@needle-tools/engine 3.32.26-alpha → 3.32.27-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.
@@ -4370,7 +4370,7 @@ void main() {
4370
4370
  `;a+=r(o);const l=Object.keys(n);let c="";for(let u=0;u<l.length;u++){const d=l[u],p=n[d];if(Ig.has(p)){c+="";continue}Ig.set(p,!0),c+=d+":"+s(p,o+1),u<l.length-1&&(c+=", "),c.length>=60&&(c+=`
4371
4371
  `,c+=r(o),a+=c,c="")}return a+=c,a+=`
4372
4372
  }`,a}return n}function r(n){let o="";for(let a=0;a<n;a++)o+=" ";return o}}const qJ=te("nodevlogs");function rs(i,e=Do.Log){Kl(e,i)}function ns(i){rs(i,Do.Warn)}function $L(i){rs(i,Do.Error)}let $E;function wt(){return qJ?!1:$E!==void 0?$E:vn()}function YJ(i){$E=i}const Hu=new Np,Kr=new w,mh=new w,Yi=new Ie,e3={X:new w(1,0,0),Y:new w(0,1,0),Z:new w(0,0,1)},eM={type:"change"},t3={type:"mouseDown"},i3={type:"mouseUp",mode:null},s3={type:"objectChange"};class JJ extends Ae{constructor(e,t){super(),t===void 0&&(console.warn('THREE.TransformControls: The second parameter "domElement" is now mandatory.'),t=document),this.isTransformControls=!0,this.visible=!1,this.domElement=t,this.domElement.style.touchAction="none";const s=new iM;this._gizmo=s,this.add(s);const r=new iK;this._plane=r,this.add(r);const n=this;function o(v,b){let _=b;Object.defineProperty(n,v,{get:function(){return _!==void 0?_:b},set:function(S){_!==S&&(_=S,r[v]=S,s[v]=S,n.dispatchEvent({type:v+"-changed",value:S}),n.dispatchEvent(eM))}}),n[v]=b,r[v]=b,s[v]=b}o("camera",e),o("object",void 0),o("enabled",!0),o("axis",null),o("mode","translate"),o("translationSnap",null),o("rotationSnap",null),o("scaleSnap",null),o("space","world"),o("size",1),o("dragging",!1),o("showX",!0),o("showY",!0),o("showZ",!0);const a=new w,l=new w,c=new Ie,u=new Ie,d=new w,p=new Ie,f=new w,m=new w,A=new w,y=0,g=new w;o("worldPosition",a),o("worldPositionStart",l),o("worldQuaternion",c),o("worldQuaternionStart",u),o("cameraPosition",d),o("cameraQuaternion",p),o("pointStart",f),o("pointEnd",m),o("rotationAxis",A),o("rotationAngle",y),o("eye",g),this._offset=new w,this._startNorm=new w,this._endNorm=new w,this._cameraScale=new w,this._parentPosition=new w,this._parentQuaternion=new Ie,this._parentQuaternionInv=new Ie,this._parentScale=new w,this._worldScaleStart=new w,this._worldQuaternionInv=new Ie,this._worldScale=new w,this._positionStart=new w,this._quaternionStart=new Ie,this._scaleStart=new w,this._getPointer=KJ.bind(this),this._onPointerDown=$J.bind(this),this._onPointerHover=ZJ.bind(this),this._onPointerMove=eK.bind(this),this._onPointerUp=tK.bind(this),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointermove",this._onPointerHover),this.domElement.addEventListener("pointerup",this._onPointerUp)}updateMatrixWorld(){this.object!==void 0&&(this.object.updateMatrixWorld(),this.object.parent===null?console.error("TransformControls: The attached 3D object must be a part of the scene graph."):this.object.parent.matrixWorld.decompose(this._parentPosition,this._parentQuaternion,this._parentScale),this.object.matrixWorld.decompose(this.worldPosition,this.worldQuaternion,this._worldScale),this._parentQuaternionInv.copy(this._parentQuaternion).invert(),this._worldQuaternionInv.copy(this.worldQuaternion).invert()),this.camera.updateMatrixWorld(),this.camera.matrixWorld.decompose(this.cameraPosition,this.cameraQuaternion,this._cameraScale),this.camera.isOrthographicCamera?this.camera.getWorldDirection(this.eye).negate():this.eye.copy(this.cameraPosition).sub(this.worldPosition).normalize(),super.updateMatrixWorld(this)}pointerHover(e){if(this.object===void 0||this.dragging===!0)return;Hu.setFromCamera(e,this.camera);const t=tM(this._gizmo.picker[this.mode],Hu);t?this.axis=t.object.name:this.axis=null}pointerDown(e){if(!(this.object===void 0||this.dragging===!0||e.button!==0)&&this.axis!==null){Hu.setFromCamera(e,this.camera);const t=tM(this._plane,Hu,!0);t&&(this.object.updateMatrixWorld(),this.object.parent.updateMatrixWorld(),this._positionStart.copy(this.object.position),this._quaternionStart.copy(this.object.quaternion),this._scaleStart.copy(this.object.scale),this.object.matrixWorld.decompose(this.worldPositionStart,this.worldQuaternionStart,this._worldScaleStart),this.pointStart.copy(t.point).sub(this.worldPositionStart)),this.dragging=!0,t3.mode=this.mode,this.dispatchEvent(t3)}}pointerMove(e){const t=this.axis,s=this.mode,r=this.object;let n=this.space;if(s==="scale"?n="local":(t==="E"||t==="XYZE"||t==="XYZ")&&(n="world"),r===void 0||t===null||this.dragging===!1||e.button!==-1)return;Hu.setFromCamera(e,this.camera);const o=tM(this._plane,Hu,!0);if(o){if(this.pointEnd.copy(o.point).sub(this.worldPositionStart),s==="translate")this._offset.copy(this.pointEnd).sub(this.pointStart),n==="local"&&t!=="XYZ"&&this._offset.applyQuaternion(this._worldQuaternionInv),t.indexOf("X")===-1&&(this._offset.x=0),t.indexOf("Y")===-1&&(this._offset.y=0),t.indexOf("Z")===-1&&(this._offset.z=0),n==="local"&&t!=="XYZ"?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),r.position.copy(this._offset).add(this._positionStart),this.translationSnap&&(n==="local"&&(r.position.applyQuaternion(Yi.copy(this._quaternionStart).invert()),t.search("X")!==-1&&(r.position.x=Math.round(r.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(r.position.y=Math.round(r.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(r.position.z=Math.round(r.position.z/this.translationSnap)*this.translationSnap),r.position.applyQuaternion(this._quaternionStart)),n==="world"&&(r.parent&&r.position.add(Kr.setFromMatrixPosition(r.parent.matrixWorld)),t.search("X")!==-1&&(r.position.x=Math.round(r.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(r.position.y=Math.round(r.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(r.position.z=Math.round(r.position.z/this.translationSnap)*this.translationSnap),r.parent&&r.position.sub(Kr.setFromMatrixPosition(r.parent.matrixWorld))));else if(s==="scale"){if(t.search("XYZ")!==-1){let a=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(a*=-1),mh.set(a,a,a)}else Kr.copy(this.pointStart),mh.copy(this.pointEnd),Kr.applyQuaternion(this._worldQuaternionInv),mh.applyQuaternion(this._worldQuaternionInv),mh.divide(Kr),t.search("X")===-1&&(mh.x=1),t.search("Y")===-1&&(mh.y=1),t.search("Z")===-1&&(mh.z=1);r.scale.copy(this._scaleStart).multiply(mh),this.scaleSnap&&(t.search("X")!==-1&&(r.scale.x=Math.round(r.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Y")!==-1&&(r.scale.y=Math.round(r.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Z")!==-1&&(r.scale.z=Math.round(r.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(s==="rotate"){this._offset.copy(this.pointEnd).sub(this.pointStart);const a=20/this.worldPosition.distanceTo(Kr.setFromMatrixPosition(this.camera.matrixWorld));let l=!1;t==="XYZE"?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(Kr.copy(this.rotationAxis).cross(this.eye))*a):(t==="X"||t==="Y"||t==="Z")&&(this.rotationAxis.copy(e3[t]),Kr.copy(e3[t]),n==="local"&&Kr.applyQuaternion(this.worldQuaternion),Kr.cross(this.eye),Kr.length()===0?l=!0:this.rotationAngle=this._offset.dot(Kr.normalize())*a),(t==="E"||l)&&(this.rotationAxis.copy(this.eye),this.rotationAngle=this.pointEnd.angleTo(this.pointStart),this._startNorm.copy(this.pointStart).normalize(),this._endNorm.copy(this.pointEnd).normalize(),this.rotationAngle*=this._endNorm.cross(this._startNorm).dot(this.eye)<0?1:-1),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),n==="local"&&t!=="E"&&t!=="XYZE"?(r.quaternion.copy(this._quaternionStart),r.quaternion.multiply(Yi.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),r.quaternion.copy(Yi.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),r.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(eM),this.dispatchEvent(s3)}}pointerUp(e){e.button===0&&(this.dragging&&this.axis!==null&&(i3.mode=this.mode,this.dispatchEvent(i3)),this.dragging=!1,this.axis=null)}dispose(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerHover),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.traverse(function(e){e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()})}attach(e){return this.object=e,this.visible=!0,this}detach(){return this.object=void 0,this.visible=!1,this.axis=null,this}reset(){this.enabled&&this.dragging&&(this.object.position.copy(this._positionStart),this.object.quaternion.copy(this._quaternionStart),this.object.scale.copy(this._scaleStart),this.dispatchEvent(eM),this.dispatchEvent(s3),this.pointStart.copy(this.pointEnd))}getRaycaster(){return Hu}getMode(){return this.mode}setMode(e){this.mode=e}setTranslationSnap(e){this.translationSnap=e}setRotationSnap(e){this.rotationSnap=e}setScaleSnap(e){this.scaleSnap=e}setSize(e){this.size=e}setSpace(e){this.space=e}}function KJ(i){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:i.button};{const e=this.domElement.getBoundingClientRect();return{x:(i.clientX-e.left)/e.width*2-1,y:-(i.clientY-e.top)/e.height*2+1,button:i.button}}}function ZJ(i){if(this.enabled)switch(i.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(i));break}}function $J(i){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(i.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(i)),this.pointerDown(this._getPointer(i)))}function eK(i){this.enabled&&this.pointerMove(this._getPointer(i))}function tK(i){this.enabled&&(this.domElement.releasePointerCapture(i.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(i)))}function tM(i,e,t){const s=e.intersectObject(i,!0);for(let r=0;r<s.length;r++)if(s[r].object.visible||t)return s[r];return!1}const Db=new zr,Di=new w(0,1,0),r3=new w(0,0,0),n3=new Te,kb=new Ie,Ob=new Ie,Ja=new w,o3=new Te,Rg=new w(1,0,0),Wu=new w(0,1,0),Pg=new w(0,0,1),Lb=new w,Bg=new w,Dg=new w;class iM extends Ae{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const e=new ni({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),t=new xs({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),s=e.clone();s.opacity=.15;const r=t.clone();r.opacity=.5;const n=e.clone();n.color.setHex(16711680);const o=e.clone();o.color.setHex(65280);const a=e.clone();a.color.setHex(255);const l=e.clone();l.color.setHex(16711680),l.opacity=.5;const c=e.clone();c.color.setHex(65280),c.opacity=.5;const u=e.clone();u.color.setHex(255),u.opacity=.5;const d=e.clone();d.opacity=.25;const p=e.clone();p.color.setHex(16776960),p.opacity=.25,e.clone().color.setHex(16776960);const f=e.clone();f.color.setHex(7895160);const m=new Ts(0,.04,.1,12);m.translate(0,.05,0);const A=new Ni(.08,.08,.08);A.translate(0,.04,0);const y=new vt;y.setAttribute("position",new ot([0,0,0,1,0,0],3));const g=new Ts(.0075,.0075,.5,3);g.translate(0,.25,0);function v(F,H){const O=new zc(F,.0075,3,64,H*Math.PI*2);return O.rotateY(Math.PI/2),O.rotateX(Math.PI/2),O}function b(){const F=new vt;return F.setAttribute("position",new ot([0,0,0,1,1,1],3)),F}const _={X:[[new ge(m,n),[.5,0,0],[0,0,-Math.PI/2]],[new ge(m,n),[-.5,0,0],[0,0,Math.PI/2]],[new ge(g,n),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new ge(m,o),[0,.5,0]],[new ge(m,o),[0,-.5,0],[Math.PI,0,0]],[new ge(g,o)]],Z:[[new ge(m,a),[0,0,.5],[Math.PI/2,0,0]],[new ge(m,a),[0,0,-.5],[-Math.PI/2,0,0]],[new ge(g,a),null,[Math.PI/2,0,0]]],XYZ:[[new ge(new Nc(.1,0),d.clone()),[0,0,0]]],XY:[[new ge(new Ni(.15,.15,.01),u.clone()),[.15,.15,0]]],YZ:[[new ge(new Ni(.15,.15,.01),l.clone()),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new ge(new Ni(.15,.15,.01),c.clone()),[.15,0,.15],[-Math.PI/2,0,0]]]},S={X:[[new ge(new Ts(.2,0,.6,4),s),[.3,0,0],[0,0,-Math.PI/2]],[new ge(new Ts(.2,0,.6,4),s),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new ge(new Ts(.2,0,.6,4),s),[0,.3,0]],[new ge(new Ts(.2,0,.6,4),s),[0,-.3,0],[0,0,Math.PI]]],Z:[[new ge(new Ts(.2,0,.6,4),s),[0,0,.3],[Math.PI/2,0,0]],[new ge(new Ts(.2,0,.6,4),s),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new ge(new Nc(.2,0),s)]],XY:[[new ge(new Ni(.2,.2,.01),s),[.15,.15,0]]],YZ:[[new ge(new Ni(.2,.2,.01),s),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new ge(new Ni(.2,.2,.01),s),[.15,0,.15],[-Math.PI/2,0,0]]]},I={START:[[new ge(new Nc(.01,2),r),null,null,null,"helper"]],END:[[new ge(new Nc(.01,2),r),null,null,null,"helper"]],DELTA:[[new ws(b(),r),null,null,null,"helper"]],X:[[new ws(y,r.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new ws(y,r.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new ws(y,r.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},T={XYZE:[[new ge(v(.5,1),f),null,[0,Math.PI/2,0]]],X:[[new ge(v(.5,.5),n)]],Y:[[new ge(v(.5,.5),o),null,[0,0,-Math.PI/2]]],Z:[[new ge(v(.5,.5),a),null,[0,Math.PI/2,0]]],E:[[new ge(v(.75,1),p),null,[0,Math.PI/2,0]]]},R={AXIS:[[new ws(y,r.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},E={XYZE:[[new ge(new ka(.25,10,8),s)]],X:[[new ge(new zc(.5,.1,4,24),s),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new ge(new zc(.5,.1,4,24),s),[0,0,0],[Math.PI/2,0,0]]],Z:[[new ge(new zc(.5,.1,4,24),s),[0,0,0],[0,0,-Math.PI/2]]],E:[[new ge(new zc(.75,.1,2,24),s)]]},C={X:[[new ge(A,n),[.5,0,0],[0,0,-Math.PI/2]],[new ge(g,n),[0,0,0],[0,0,-Math.PI/2]],[new ge(A,n),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new ge(A,o),[0,.5,0]],[new ge(g,o)],[new ge(A,o),[0,-.5,0],[0,0,Math.PI]]],Z:[[new ge(A,a),[0,0,.5],[Math.PI/2,0,0]],[new ge(g,a),[0,0,0],[Math.PI/2,0,0]],[new ge(A,a),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new ge(new Ni(.15,.15,.01),u),[.15,.15,0]]],YZ:[[new ge(new Ni(.15,.15,.01),l),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new ge(new Ni(.15,.15,.01),c),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new ge(new Ni(.1,.1,.1),d.clone())]]},j={X:[[new ge(new Ts(.2,0,.6,4),s),[.3,0,0],[0,0,-Math.PI/2]],[new ge(new Ts(.2,0,.6,4),s),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new ge(new Ts(.2,0,.6,4),s),[0,.3,0]],[new ge(new Ts(.2,0,.6,4),s),[0,-.3,0],[0,0,Math.PI]]],Z:[[new ge(new Ts(.2,0,.6,4),s),[0,0,.3],[Math.PI/2,0,0]],[new ge(new Ts(.2,0,.6,4),s),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new ge(new Ni(.2,.2,.01),s),[.15,.15,0]]],YZ:[[new ge(new Ni(.2,.2,.01),s),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new ge(new Ni(.2,.2,.01),s),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new ge(new Ni(.2,.2,.2),s),[0,0,0]]]},N={X:[[new ws(y,r.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new ws(y,r.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new ws(y,r.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function q(F){const H=new Ae;for(const O in F)for(let z=F[O].length;z--;){const Q=F[O][z][0].clone(),$=F[O][z][1],K=F[O][z][2],se=F[O][z][3],be=F[O][z][4];Q.name=O,Q.tag=be,$&&Q.position.set($[0],$[1],$[2]),K&&Q.rotation.set(K[0],K[1],K[2]),se&&Q.scale.set(se[0],se[1],se[2]),Q.updateMatrix();const Re=Q.geometry.clone();Re.applyMatrix4(Q.matrix),Q.geometry=Re,Q.renderOrder=1/0,Q.position.set(0,0,0),Q.rotation.set(0,0,0),Q.scale.set(1,1,1),H.add(Q)}return H}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=q(_)),this.add(this.gizmo.rotate=q(T)),this.add(this.gizmo.scale=q(C)),this.add(this.picker.translate=q(S)),this.add(this.picker.rotate=q(E)),this.add(this.picker.scale=q(j)),this.add(this.helper.translate=q(I)),this.add(this.helper.rotate=q(R)),this.add(this.helper.scale=q(N)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}updateMatrixWorld(e){const t=(this.mode==="scale"?"local":this.space)==="local"?this.worldQuaternion:Ob;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 s=[];s=s.concat(this.picker[this.mode].children),s=s.concat(this.gizmo[this.mode].children),s=s.concat(this.helper[this.mode].children);for(let r=0;r<s.length;r++){const n=s[r];n.visible=!0,n.rotation.set(0,0,0),n.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),n.scale.set(1,1,1).multiplyScalar(o*this.size/4),n.tag==="helper"){n.visible=!1,n.name==="AXIS"?(n.visible=!!this.axis,this.axis==="X"&&(Yi.setFromEuler(Db.set(0,0,0)),n.quaternion.copy(t).multiply(Yi),Math.abs(Di.copy(Rg).applyQuaternion(t).dot(this.eye))>.9&&(n.visible=!1)),this.axis==="Y"&&(Yi.setFromEuler(Db.set(0,0,Math.PI/2)),n.quaternion.copy(t).multiply(Yi),Math.abs(Di.copy(Wu).applyQuaternion(t).dot(this.eye))>.9&&(n.visible=!1)),this.axis==="Z"&&(Yi.setFromEuler(Db.set(0,Math.PI/2,0)),n.quaternion.copy(t).multiply(Yi),Math.abs(Di.copy(Pg).applyQuaternion(t).dot(this.eye))>.9&&(n.visible=!1)),this.axis==="XYZE"&&(Yi.setFromEuler(Db.set(0,Math.PI/2,0)),Di.copy(this.rotationAxis),n.quaternion.setFromRotationMatrix(n3.lookAt(r3,Di,Wu)),n.quaternion.multiply(Yi),n.visible=this.dragging),this.axis==="E"&&(n.visible=!1)):n.name==="START"?(n.position.copy(this.worldPositionStart),n.visible=this.dragging):n.name==="END"?(n.position.copy(this.worldPosition),n.visible=this.dragging):n.name==="DELTA"?(n.position.copy(this.worldPositionStart),n.quaternion.copy(this.worldQuaternionStart),Kr.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),Kr.applyQuaternion(this.worldQuaternionStart.clone().invert()),n.scale.copy(Kr),n.visible=this.dragging):(n.quaternion.copy(t),this.dragging?n.position.copy(this.worldPositionStart):n.position.copy(this.worldPosition),this.axis&&(n.visible=this.axis.search(n.name)!==-1));continue}n.quaternion.copy(t),this.mode==="translate"||this.mode==="scale"?(n.name==="X"&&Math.abs(Di.copy(Rg).applyQuaternion(t).dot(this.eye))>.99&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1),n.name==="Y"&&Math.abs(Di.copy(Wu).applyQuaternion(t).dot(this.eye))>.99&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1),n.name==="Z"&&Math.abs(Di.copy(Pg).applyQuaternion(t).dot(this.eye))>.99&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1),n.name==="XY"&&Math.abs(Di.copy(Pg).applyQuaternion(t).dot(this.eye))<.2&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1),n.name==="YZ"&&Math.abs(Di.copy(Rg).applyQuaternion(t).dot(this.eye))<.2&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1),n.name==="XZ"&&Math.abs(Di.copy(Wu).applyQuaternion(t).dot(this.eye))<.2&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1)):this.mode==="rotate"&&(kb.copy(t),Di.copy(this.eye).applyQuaternion(Yi.copy(t).invert()),n.name.search("E")!==-1&&n.quaternion.setFromRotationMatrix(n3.lookAt(this.eye,r3,Wu)),n.name==="X"&&(Yi.setFromAxisAngle(Rg,Math.atan2(-Di.y,Di.z)),Yi.multiplyQuaternions(kb,Yi),n.quaternion.copy(Yi)),n.name==="Y"&&(Yi.setFromAxisAngle(Wu,Math.atan2(Di.x,Di.z)),Yi.multiplyQuaternions(kb,Yi),n.quaternion.copy(Yi)),n.name==="Z"&&(Yi.setFromAxisAngle(Pg,Math.atan2(Di.y,Di.x)),Yi.multiplyQuaternions(kb,Yi),n.quaternion.copy(Yi))),n.visible=n.visible&&(n.name.indexOf("X")===-1||this.showX),n.visible=n.visible&&(n.name.indexOf("Y")===-1||this.showY),n.visible=n.visible&&(n.name.indexOf("Z")===-1||this.showZ),n.visible=n.visible&&(n.name.indexOf("E")===-1||this.showX&&this.showY&&this.showZ),n.material._color=n.material._color||n.material.color.clone(),n.material._opacity=n.material._opacity||n.material.opacity,n.material.color.copy(n.material._color),n.material.opacity=n.material._opacity,this.enabled&&this.axis&&(n.name===this.axis||this.axis.split("").some(function(a){return n.name===a}))&&(n.material.color.setHex(16776960),n.material.opacity=1)}super.updateMatrixWorld(e)}}class iK extends ge{constructor(){super(new Ks(1e5,1e5,2,2),new ni({visible:!1,wireframe:!0,side:gi,transparent:!0,opacity:.1,toneMapped:!1})),this.isTransformControlsPlane=!0,this.type="TransformControlsPlane"}updateMatrixWorld(e){let t=this.space;switch(this.position.copy(this.worldPosition),this.mode==="scale"&&(t="local"),Lb.copy(Rg).applyQuaternion(t==="local"?this.worldQuaternion:Ob),Bg.copy(Wu).applyQuaternion(t==="local"?this.worldQuaternion:Ob),Dg.copy(Pg).applyQuaternion(t==="local"?this.worldQuaternion:Ob),Di.copy(Bg),this.mode){case"translate":case"scale":switch(this.axis){case"X":Di.copy(this.eye).cross(Lb),Ja.copy(Lb).cross(Di);break;case"Y":Di.copy(this.eye).cross(Bg),Ja.copy(Bg).cross(Di);break;case"Z":Di.copy(this.eye).cross(Dg),Ja.copy(Dg).cross(Di);break;case"XY":Ja.copy(Dg);break;case"YZ":Ja.copy(Lb);break;case"XZ":Di.copy(Dg),Ja.copy(Bg);break;case"XYZ":case"E":Ja.set(0,0,0);break}break;case"rotate":default:Ja.set(0,0,0)}Ja.length()===0?this.quaternion.copy(this.cameraQuaternion):(o3.lookAt(Kr.set(0,0,0),Ja,Di),this.quaternion.setFromRotationMatrix(o3)),super.updateMatrixWorld(e)}}const sK=te("debugpatch");function Fb(i,e,t,s){const r=sK===e;if(!t&&!s)return;const n=e+"___needle";nK(i,e,t,s);const o=Object.getOwnPropertyDescriptor(i,e),a=i[e];r&&console.log("Patch",i.constructor.name,e,o,a),o?(r&&console.log("Apply patch with existing descriptor",i.constructor.name,e,o),typeof o.value=="function"&&(i[e]=l3(o.value,i,e))):(r&&console.log("Create patch with new property",i.constructor.name,e,o),Object.defineProperty(i,e,{set:function(l){if(typeof l=="function")this[n]=l3(l,i,e);else{const c=this[n];c3(i,e,this,c,l),this[n]=l,h3(i,e,this,c,l)}},get:function(){const l=this[n];return typeof l=="function"&&l[n]?l[n]:l}}))}function rK(i,e,t){const s=rM(i,e);if(s)for(let r=s.length-1;r>=0;r--){const n=s[r];n.prefix===t&&(n.prefix=null),n.postfix===t&&(n.postfix=null),!n.prefix&&!n.postfix&&s.splice(r,1)}}const a3=Symbol("Needle:Patches:WrappedFunction");function l3(i,e,t){if(i[a3])return i;const s=function(...r){c3(e,t,this,...r);const n=i.apply(this,r);return h3(e,t,this,n,...r),n};return s[a3]=!0,s}const Ub="Needle:Patches";function sM(){return globalThis[Ub]||(globalThis[Ub]=new WeakMap),globalThis[Ub]}function rM(i,e){const t=sM().get(i);return t?t.get(e):null}function nK(i,e,t,s){let r=sM().get(i);r||(r=new Map,sM().set(i,r));let n=r.get(e);n||(n=[],r.set(e,n)),n.push({prefix:t,postfix:s})}function c3(i,e,t,...s){var r;if(!t)return;const n=rM(i,e);if(n)for(const o of n)(r=o.prefix)==null||r.call(t,...s)}function h3(i,e,t,s,...r){var n;if(!t)return;const o=rM(i,e);if(o)for(const a of o)(n=a.postfix)==null||n.call(t,s,...r)}const u3=Symbol("gltf-loader-internal-usage-tracker"),oK=te("debugusers"),Nb=class{constructor(i){h(this,"parser"),h(this,"_getDependency"),h(this,"_loadingId"),h(this,"_loadedObjects",new Set),this.parser=i,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(i){return Nb._loadingProcesses>0}beforeRoot(){Nb._loadingProcesses++;const i=this,e=this._getDependency;return this.parser.getDependency=function(t,s){const r=e.call(this,t,s);return r.then(n=>(n&&(i._loadedObjects.add(n),n[u3]=i._loadingId),n)),r},null}afterRoot(i){Nb._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const e of this._loadedObjects)delete e[u3],e instanceof Ae&&(e.parent||e instanceof ge&&(oK&&console.warn("> GLTF LOADER: Mesh not used in scene!",e),e.material=null,e.geometry=null));return null}};let nM=Nb;h(nM,"_loadingProcesses",0);class d3{constructor(){window.addEventListener("unhandledrejection",e=>{var t;if(e.defaultPrevented)return;const s=(t=e?.reason)==null?void 0:t.path;if(s){const r=s[0];r&&r.tagName==="IMG"&&(console.warn(`Could not load image:
4373
- `+r.src),e.preventDefault())}})}}const zb=te("trackresources");function p3(){return zb==="dispose"}let Xu=!0;zb===0&&(Xu=!1);function aK(i){Xu=i}function f3(){return Xu}const m3=Symbol("disposable");function oM(i,e){i&&(i[m3]=e,qu&&console.warn("Set disposable",e,i))}const g3=Symbol("disposed");function lK(i){return i[g3]===!0}function Li(i){var e;if(i){if(i[m3]===!1){qu&&console.warn("Object is marked as not disposable",i);return}if(i[g3]=!0,i instanceof qr)Li(i.environment),Li(i.background),Li(i.customDepthMaterial),Li(i.customDistanceMaterial);else if(i instanceof da)Li(i.geometry),Li(i.material),Li(i.skeleton),Li(i.bindMatrix),Li(i.bindMatrixInverse),Li(i.customDepthMaterial),Li(i.customDistanceMaterial),i.geometry=null,i.material=null;else if(i instanceof ge)Li(i.geometry),Li(i.material),Li(i.customDepthMaterial),Li(i.customDistanceMaterial),i.geometry=null,i.material=null;else if(i instanceof vt){Jp(i);for(const t of Object.keys(i.attributes)){const s=i.attributes[t];Li(s)}}else if(i instanceof Ze||i instanceof Dn)qu&&console.warn("BufferAttribute dispose not supported",i.count);else if(i instanceof Array)for(const t of i)t instanceof Ot&&Li(t);else if(i instanceof Ot){Jp(i);for(const s of Object.keys(i)){const r=i[s];r instanceof Dt&&(Li(r),i[s]=null)}const t=i.uniforms;if(t)for(const s of Object.keys(t)){const r=t[s];r instanceof Dt?(Li(r),t[s]=null):r instanceof _e&&(Li(r.value),r.value=null)}}else i instanceof Dt?(Jp(i),Jp(i.source),((e=i.source)==null?void 0:e.data)instanceof ImageBitmap&&Jp(i.source.data)):i instanceof gm?(Jp(i.boneTexture),i.boneTexture=null):i instanceof $m||!(i instanceof Ae)&&qu&&console.warn("Unknown object type",i)}}function Jp(i){i&&((qu||p3()||zb)&&console.warn("\u{1F9E8} FREE",i),i instanceof ImageBitmap?i.close():i instanceof Fl?i.data=null:i.dispose())}function v3(i){(i instanceof ge||i instanceof da)&&(i.material=null,i.geometry=null)}const cK=new Set;function aM(i,e,t=null,s){if(s||(s=cK,s.clear()),!i)return s;const r=i[kg];if(r)for(const n of r)s.has(n)||t?.call(null,n)!==!1&&(s.add(n),e&&aM(n,!0,t,s));return s}function hK(i){return i[Og]}const qu=te("debugresourceusers")||te("debugmemory"),kg=Symbol("needle-resource-users"),Og=Symbol("needle-resource-users-count");function yn(i,e){Fb(i,e,function(t,s){Xu&&(jb(kg,this,t,!1),jb(kg,this,s,!0))})}Xu&&(yn(ge.prototype,"material"),yn(ge.prototype,"geometry"),yn(Ot.prototype,"map"),yn(Ot.prototype,"bumpMap"),yn(Ot.prototype,"alphaMap"),yn(Ot.prototype,"normalMap"),yn(Ot.prototype,"displacementMap"),yn(Ot.prototype,"roughnessMap"),yn(Ot.prototype,"metalnessMap"),yn(Ot.prototype,"emissiveMap"),yn(Ot.prototype,"specularMap"),yn(Ot.prototype,"envMap"),yn(Ot.prototype,"lightMap"),yn(Ot.prototype,"aoMap"),yn(Ot.prototype,"gradientMap"));function uK(i){if(Xu===!1)return;const e=i[kg];if(e)for(const t of e)jb(kg,t,i,!1)}Xu&&Fb(Ot.prototype,"dispose",function(){uK(this)});let lM=0;function jb(i,e,t,s){if(lM>0)return;if(Array.isArray(t)){for(const n of t)jb(i,e,n,s);return}if(!t)return;let r=t[i];if(r||(r=new Set),s){if(e&&!r.has(e)){r.add(e);let n=t[Og]||0;n+=1,t[Og]=n,qu&&console.warn(`\u{1F7E2} Added user of "${t.type}"`,e,t,n,"users:",r)}}else if(e&&r.has(e)){r.delete(e);let n=t[Og]||0;n>0&&(n-=1,t[Og]=n),qu&&console.warn(`\u{1F534} Removed user of "${t.type}"`,e,t,n,"users:",r),n<=0&&(nM.isLoading(t)||(zb&&console.warn(`\u{1F534} Removed all user of "${t.type}"`,t),p3()&&Li(t)))}t[i]=r}try{Fb(Hl.prototype,"render",function(){lM++},function(){lM--})}catch(i){console.warn("Could not wrap WebGLRenderer.render",i)}var Lg=(i=>(i.Added="component-added",i.Removing="removing-component",i))(Lg||{});const A3=te("debugcomponentevents");class Fg{static addComponentLifecylceEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.set(e,[]);let s=this.eventListeners.get(e);s||(s=[]),s.push(t),this.eventListeners.set(e,s),A3&&console.log("Added event listener for "+e,this.eventListeners)}static removeComponentLifecylceEventListener(e,t){const s=this.eventListeners.get(e);if(!s)return;const r=s.indexOf(t);r<0||s.splice(r,1)}static dispatchComponentLifecycleEvent(e,t){const s=this.eventListeners.get(e);if(A3&&console.log("Dispatching event "+e,s),!!s)for(const r of s)r(t)}}h(Fg,"eventListeners",new Map);const y3=te("debugdefines");Kp('if(!globalThis[""3.32.26-alpha""]) globalThis[""3.32.26-alpha""] = "0.0.0";'),Kp('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";'),Kp('if(!globalThis[""Sat Feb 24 2024 00:31:01 GMT+0800 (Pacific Standard Time)""]) globalThis[""Sat Feb 24 2024 00:31:01 GMT+0800 (Pacific Standard Time)""] = "unknown";'),Kp('globalThis["__NEEDLE_ENGINE_VERSION__"] = "3.32.26-alpha";'),Kp('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),Kp('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Sat Feb 24 2024 00:31:01 GMT+0800 (Pacific Standard Time)";');const rc="3.32.26-alpha",Gb="undefined",dK="Sat Feb 24 2024 00:31:01 GMT+0800 (Pacific Standard Time)";y3&&console.log(`Engine version: ${rc} (generator: ${Gb})
4373
+ `+r.src),e.preventDefault())}})}}const zb=te("trackresources");function p3(){return zb==="dispose"}let Xu=!0;zb===0&&(Xu=!1);function aK(i){Xu=i}function f3(){return Xu}const m3=Symbol("disposable");function oM(i,e){i&&(i[m3]=e,qu&&console.warn("Set disposable",e,i))}const g3=Symbol("disposed");function lK(i){return i[g3]===!0}function Li(i){var e;if(i){if(i[m3]===!1){qu&&console.warn("Object is marked as not disposable",i);return}if(i[g3]=!0,i instanceof qr)Li(i.environment),Li(i.background),Li(i.customDepthMaterial),Li(i.customDistanceMaterial);else if(i instanceof da)Li(i.geometry),Li(i.material),Li(i.skeleton),Li(i.bindMatrix),Li(i.bindMatrixInverse),Li(i.customDepthMaterial),Li(i.customDistanceMaterial),i.geometry=null,i.material=null;else if(i instanceof ge)Li(i.geometry),Li(i.material),Li(i.customDepthMaterial),Li(i.customDistanceMaterial),i.geometry=null,i.material=null;else if(i instanceof vt){Jp(i);for(const t of Object.keys(i.attributes)){const s=i.attributes[t];Li(s)}}else if(i instanceof Ze||i instanceof Dn)qu&&console.warn("BufferAttribute dispose not supported",i.count);else if(i instanceof Array)for(const t of i)t instanceof Ot&&Li(t);else if(i instanceof Ot){Jp(i);for(const s of Object.keys(i)){const r=i[s];r instanceof Dt&&(Li(r),i[s]=null)}const t=i.uniforms;if(t)for(const s of Object.keys(t)){const r=t[s];r instanceof Dt?(Li(r),t[s]=null):r instanceof _e&&(Li(r.value),r.value=null)}}else i instanceof Dt?(Jp(i),Jp(i.source),((e=i.source)==null?void 0:e.data)instanceof ImageBitmap&&Jp(i.source.data)):i instanceof gm?(Jp(i.boneTexture),i.boneTexture=null):i instanceof $m||!(i instanceof Ae)&&qu&&console.warn("Unknown object type",i)}}function Jp(i){i&&((qu||p3()||zb)&&console.warn("\u{1F9E8} FREE",i),i instanceof ImageBitmap?i.close():i instanceof Fl?i.data=null:i.dispose())}function v3(i){(i instanceof ge||i instanceof da)&&(i.material=null,i.geometry=null)}const cK=new Set;function aM(i,e,t=null,s){if(s||(s=cK,s.clear()),!i)return s;const r=i[kg];if(r)for(const n of r)s.has(n)||t?.call(null,n)!==!1&&(s.add(n),e&&aM(n,!0,t,s));return s}function hK(i){return i[Og]}const qu=te("debugresourceusers")||te("debugmemory"),kg=Symbol("needle-resource-users"),Og=Symbol("needle-resource-users-count");function yn(i,e){Fb(i,e,function(t,s){Xu&&(jb(kg,this,t,!1),jb(kg,this,s,!0))})}Xu&&(yn(ge.prototype,"material"),yn(ge.prototype,"geometry"),yn(Ot.prototype,"map"),yn(Ot.prototype,"bumpMap"),yn(Ot.prototype,"alphaMap"),yn(Ot.prototype,"normalMap"),yn(Ot.prototype,"displacementMap"),yn(Ot.prototype,"roughnessMap"),yn(Ot.prototype,"metalnessMap"),yn(Ot.prototype,"emissiveMap"),yn(Ot.prototype,"specularMap"),yn(Ot.prototype,"envMap"),yn(Ot.prototype,"lightMap"),yn(Ot.prototype,"aoMap"),yn(Ot.prototype,"gradientMap"));function uK(i){if(Xu===!1)return;const e=i[kg];if(e)for(const t of e)jb(kg,t,i,!1)}Xu&&Fb(Ot.prototype,"dispose",function(){uK(this)});let lM=0;function jb(i,e,t,s){if(lM>0)return;if(Array.isArray(t)){for(const n of t)jb(i,e,n,s);return}if(!t)return;let r=t[i];if(r||(r=new Set),s){if(e&&!r.has(e)){r.add(e);let n=t[Og]||0;n+=1,t[Og]=n,qu&&console.warn(`\u{1F7E2} Added user of "${t.type}"`,e,t,n,"users:",r)}}else if(e&&r.has(e)){r.delete(e);let n=t[Og]||0;n>0&&(n-=1,t[Og]=n),qu&&console.warn(`\u{1F534} Removed user of "${t.type}"`,e,t,n,"users:",r),n<=0&&(nM.isLoading(t)||(zb&&console.warn(`\u{1F534} Removed all user of "${t.type}"`,t),p3()&&Li(t)))}t[i]=r}try{Fb(Hl.prototype,"render",function(){lM++},function(){lM--})}catch(i){console.warn("Could not wrap WebGLRenderer.render",i)}var Lg=(i=>(i.Added="component-added",i.Removing="removing-component",i))(Lg||{});const A3=te("debugcomponentevents");class Fg{static addComponentLifecylceEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.set(e,[]);let s=this.eventListeners.get(e);s||(s=[]),s.push(t),this.eventListeners.set(e,s),A3&&console.log("Added event listener for "+e,this.eventListeners)}static removeComponentLifecylceEventListener(e,t){const s=this.eventListeners.get(e);if(!s)return;const r=s.indexOf(t);r<0||s.splice(r,1)}static dispatchComponentLifecycleEvent(e,t){const s=this.eventListeners.get(e);if(A3&&console.log("Dispatching event "+e,s),!!s)for(const r of s)r(t)}}h(Fg,"eventListeners",new Map);const y3=te("debugdefines");Kp('if(!globalThis[""3.32.27-alpha""]) globalThis[""3.32.27-alpha""] = "0.0.0";'),Kp('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";'),Kp('if(!globalThis[""Mon Feb 26 2024 22:30:25 GMT+0800 (Pacific Standard Time)""]) globalThis[""Mon Feb 26 2024 22:30:25 GMT+0800 (Pacific Standard Time)""] = "unknown";'),Kp('globalThis["__NEEDLE_ENGINE_VERSION__"] = "3.32.27-alpha";'),Kp('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),Kp('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Mon Feb 26 2024 22:30:25 GMT+0800 (Pacific Standard Time)";');const rc="3.32.27-alpha",Gb="undefined",dK="Mon Feb 26 2024 22:30:25 GMT+0800 (Pacific Standard Time)";y3&&console.log(`Engine version: ${rc} (generator: ${Gb})
4374
4374
  Project built at ${dK}`);const nc="needle_isActiveInHierarchy",Yu="builtin_components",Ug="needle_editor_guid";function Kp(i){try{(0,eval)(i)}catch(e){y3&&console.error(e)}}const Ng=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),b3=Symbol("isUsingInstancing"),_3=Symbol("instancingRenderer"),cM=Symbol("instancingAutoUpdateBounds");class Fa{static isUsingInstancing(e){return e[b3]===!0}static getRenderer(e){return e[_3]||null}setAutoUpdateBounds(e,t){const s=Fa.getRenderer(e);s&&(s[cM]=t)}static markDirty(e,t=!0){if(e&&(this.isUsingInstancing(e)&&(e[Ng]=!0,e.matrixWorldNeedsUpdate=!0),t))for(const s of e.children)Fa.markDirty(s,!0)}}function Ju(i,e){try{e?i(e):i()}catch(t){return console.error(t),!1}return!0}const hM=te("debugnewscripts"),pK=te("debughierarchy"),Ji=[];function fK(){return Ji.length>0}function Qb(i){if(!(i.new_scripts.length<=0)){if(hM&&console.log("Register new components",i.new_scripts.length,[...i.new_scripts],i.alias?"element: "+i.alias:i.hash,i),i.new_scripts_pre_setup_callbacks.length>0){for(const e of i.new_scripts_pre_setup_callbacks)e&&e();i.new_scripts_pre_setup_callbacks.length=0}Ji.length=0,i.new_scripts.length>0&&Ji.push(...i.new_scripts),i.new_scripts.length=0;for(let e=0;e<Ji.length;e++)try{const t=Ji[e];if(t.isComponent!==!0){(wt()||hM)&&console.error(`Registered script is not a Needle Engine component.
4375
4375
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
4376
4376
  `,t),Ji.splice(e,1),e--;continue}if(t.destroyed)continue;if(!t.gameObject){console.error("MISSING GAMEOBJECT - will ignore",t),Ji.splice(e,1),e--;continue}t.context=i,zg(t.gameObject),uM(t,i)}catch(t){console.error(t),oc(Ji[e],i),Ji.splice(e,1),e--}for(let e=0;e<Ji.length;e++)try{const t=Ji[e];if(t.destroyed){oc(Ji[e],i),Ji.splice(e,1),e--;continue}if(t.registering)try{t.registering()}catch(s){console.error(s)}t.__internalAwake!==void 0&&(t.gameObject||console.error("MISSING GAMEOBJECT",t,t.gameObject),zg(t.gameObject),t.activeAndEnabled&&Ju(t.__internalAwake.bind(t)))}catch(t){console.error(t),oc(Ji[e],i),Ji.splice(e,1),e--}for(let e=0;e<Ji.length;e++)try{const t=Ji[e];if(t.destroyed||t.enabled===!1||(zg(t.gameObject),t.activeAndEnabled===!1))continue;t.__internalEnable!==void 0&&(t.enabled=!0,Ju(t.__internalEnable.bind(t)))}catch(t){console.error(t),oc(Ji[e],i),Ji.splice(e,1),e--}for(let e=0;e<Ji.length;e++)try{const t=Ji[e];if(t.destroyed||!t.gameObject)continue;i.new_script_start.push(t)}catch(t){console.error(t),oc(Ji[e],i),Ji.splice(e,1),e--}Ji.length=0;for(const e of i.new_scripts_post_setup_callbacks)e&&e();i.new_scripts_post_setup_callbacks.length=0}}function mK(i){i&&(i.__internalDisable(!0),oc(i,i.context))}function x3(i,e){for(let t=0;t<i.new_script_start.length;t++)try{const s=i.new_script_start[t];if(e!==void 0&&s.gameObject!==e||s.destroyed||s.activeAndEnabled===!1)continue;Ju(s.__internalAwake.bind(s)),s.enabled&&(Ju(s.__internalEnable.bind(s)),Ju(s.__internalStart.bind(s)),i.new_script_start.splice(t,1),t--)}catch(s){console.error(s),oc(i.new_script_start[t],i),i.new_script_start.splice(t,1),t--}}function uM(i,e){e.scripts.indexOf(i)===-1&&(e.scripts.push(i),i.earlyUpdate&&e.scripts_earlyUpdate.push(i),i.update&&e.scripts_update.push(i),i.lateUpdate&&e.scripts_lateUpdate.push(i),i.onBeforeRender&&e.scripts_onBeforeRender.push(i),i.onAfterRender&&e.scripts_onAfterRender.push(i),i.onPausedChanged&&e.scripts_pausedChanged.push(i),dM(i,null)&&e.new_scripts_xr.push(i),dM(i,"immersive-vr")&&e.scripts_immersive_vr.push(i),dM(i,"immersive-ar")&&e.scripts_immersive_ar.push(i))}function oc(i,e){jo(i,e.new_scripts),jo(i,e.new_script_start),jo(i,e.scripts),jo(i,e.scripts_earlyUpdate),jo(i,e.scripts_update),jo(i,e.scripts_lateUpdate),jo(i,e.scripts_onBeforeRender),jo(i,e.scripts_onAfterRender),jo(i,e.scripts_pausedChanged),jo(i,e.new_scripts_xr),jo(i,e.scripts_immersive_vr),jo(i,e.scripts_immersive_ar),e.stopAllCoroutinesFrom(i)}function jo(i,e){const t=e.indexOf(i);t>=0&&e.splice(t,1)}function dM(i,e){var t;if(i){const s=i;if(s.onBeforeXR||s.onEnterXR||s.onUpdateXR||s.onLeaveXR||s.onXRControllerAdded||s.onXRControllerRemoved)return!(e!=null&&((t=s.supportsXR)==null?void 0:t.call(s,e))===!1)}return!1}function Vb(i){if(i||(i=_i.Current.scene),!i){console.trace("Invalid call - no current context.");return}const e=lf(i);w3(i,e,!0)||(hM||wt()?console.error(`Error updating hierarchy
@@ -4916,7 +4916,7 @@ in script ${r}.ts
4916
4916
  *
4917
4917
  * @author Feross Aboukhadijeh <https://feross.org>
4918
4918
  * @license MIT
4919
- */var W$=function(i){return i!=null&&(oF(i)||X$(i)||!!i._isBuffer)};function oF(i){return!!i.constructor&&typeof i.constructor.isBuffer=="function"&&i.constructor.isBuffer(i)}function X$(i){return typeof i.readFloatLE=="function"&&typeof i.slice=="function"&&oF(i.slice(0,0))}(function(){var i=H$,e=nF.utf8,t=W$,s=nF.bin,r=function(n,o){n.constructor==String?o&&o.encoding==="binary"?n=s.stringToBytes(n):n=e.stringToBytes(n):t(n)?n=Array.prototype.slice.call(n,0):!Array.isArray(n)&&n.constructor!==Uint8Array&&(n=n.toString());for(var a=i.bytesToWords(n),l=n.length*8,c=1732584193,u=-271733879,d=-1732584194,p=271733878,f=0;f<a.length;f++)a[f]=(a[f]<<8|a[f]>>>24)&16711935|(a[f]<<24|a[f]>>>8)&4278255360;a[l>>>5]|=128<<l%32,a[(l+64>>>9<<4)+14]=l;for(var m=r._ff,A=r._gg,y=r._hh,g=r._ii,f=0;f<a.length;f+=16){var v=c,b=u,_=d,S=p;c=m(c,u,d,p,a[f+0],7,-680876936),p=m(p,c,u,d,a[f+1],12,-389564586),d=m(d,p,c,u,a[f+2],17,606105819),u=m(u,d,p,c,a[f+3],22,-1044525330),c=m(c,u,d,p,a[f+4],7,-176418897),p=m(p,c,u,d,a[f+5],12,1200080426),d=m(d,p,c,u,a[f+6],17,-1473231341),u=m(u,d,p,c,a[f+7],22,-45705983),c=m(c,u,d,p,a[f+8],7,1770035416),p=m(p,c,u,d,a[f+9],12,-1958414417),d=m(d,p,c,u,a[f+10],17,-42063),u=m(u,d,p,c,a[f+11],22,-1990404162),c=m(c,u,d,p,a[f+12],7,1804603682),p=m(p,c,u,d,a[f+13],12,-40341101),d=m(d,p,c,u,a[f+14],17,-1502002290),u=m(u,d,p,c,a[f+15],22,1236535329),c=A(c,u,d,p,a[f+1],5,-165796510),p=A(p,c,u,d,a[f+6],9,-1069501632),d=A(d,p,c,u,a[f+11],14,643717713),u=A(u,d,p,c,a[f+0],20,-373897302),c=A(c,u,d,p,a[f+5],5,-701558691),p=A(p,c,u,d,a[f+10],9,38016083),d=A(d,p,c,u,a[f+15],14,-660478335),u=A(u,d,p,c,a[f+4],20,-405537848),c=A(c,u,d,p,a[f+9],5,568446438),p=A(p,c,u,d,a[f+14],9,-1019803690),d=A(d,p,c,u,a[f+3],14,-187363961),u=A(u,d,p,c,a[f+8],20,1163531501),c=A(c,u,d,p,a[f+13],5,-1444681467),p=A(p,c,u,d,a[f+2],9,-51403784),d=A(d,p,c,u,a[f+7],14,1735328473),u=A(u,d,p,c,a[f+12],20,-1926607734),c=y(c,u,d,p,a[f+5],4,-378558),p=y(p,c,u,d,a[f+8],11,-2022574463),d=y(d,p,c,u,a[f+11],16,1839030562),u=y(u,d,p,c,a[f+14],23,-35309556),c=y(c,u,d,p,a[f+1],4,-1530992060),p=y(p,c,u,d,a[f+4],11,1272893353),d=y(d,p,c,u,a[f+7],16,-155497632),u=y(u,d,p,c,a[f+10],23,-1094730640),c=y(c,u,d,p,a[f+13],4,681279174),p=y(p,c,u,d,a[f+0],11,-358537222),d=y(d,p,c,u,a[f+3],16,-722521979),u=y(u,d,p,c,a[f+6],23,76029189),c=y(c,u,d,p,a[f+9],4,-640364487),p=y(p,c,u,d,a[f+12],11,-421815835),d=y(d,p,c,u,a[f+15],16,530742520),u=y(u,d,p,c,a[f+2],23,-995338651),c=g(c,u,d,p,a[f+0],6,-198630844),p=g(p,c,u,d,a[f+7],10,1126891415),d=g(d,p,c,u,a[f+14],15,-1416354905),u=g(u,d,p,c,a[f+5],21,-57434055),c=g(c,u,d,p,a[f+12],6,1700485571),p=g(p,c,u,d,a[f+3],10,-1894986606),d=g(d,p,c,u,a[f+10],15,-1051523),u=g(u,d,p,c,a[f+1],21,-2054922799),c=g(c,u,d,p,a[f+8],6,1873313359),p=g(p,c,u,d,a[f+15],10,-30611744),d=g(d,p,c,u,a[f+6],15,-1560198380),u=g(u,d,p,c,a[f+13],21,1309151649),c=g(c,u,d,p,a[f+4],6,-145523070),p=g(p,c,u,d,a[f+11],10,-1120210379),d=g(d,p,c,u,a[f+2],15,718787259),u=g(u,d,p,c,a[f+9],21,-343485551),c=c+v>>>0,u=u+b>>>0,d=d+_>>>0,p=p+S>>>0}return i.endian([c,u,d,p])};r._ff=function(n,o,a,l,c,u,d){var p=n+(o&a|~o&l)+(c>>>0)+d;return(p<<u|p>>>32-u)+o},r._gg=function(n,o,a,l,c,u,d){var p=n+(o&l|a&~l)+(c>>>0)+d;return(p<<u|p>>>32-u)+o},r._hh=function(n,o,a,l,c,u,d){var p=n+(o^a^l)+(c>>>0)+d;return(p<<u|p>>>32-u)+o},r._ii=function(n,o,a,l,c,u,d){var p=n+(a^(o|~l))+(c>>>0)+d;return(p<<u|p>>>32-u)+o},r._blocksize=16,r._digestsize=16,sF.exports=function(n,o){if(n==null)throw new Error("Illegal argument "+n);var a=i.wordsToBytes(r(n,o));return o&&o.asBytes?a:o&&o.asString?s.bytesToString(a):i.bytesToHex(a)}})();var q$=sF.exports;const Y$=t_(q$);class OM{constructor(e,t,s,r){h(this,"success"),h(this,"filename"),h(this,"hash"),h(this,"size"),h(this,"url"),this.success=e,this.filename=t,this.hash=s,this.size=r}}async function aF(i,e){const t=await i.arrayBuffer(),s=LM(t),r=i.name.split(".").pop(),n=s+"."+r,o=i.name.split(".").shift();console.assert(o!==void 0);const a={alias:o,filename:n},l=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(a)})).json();if(l.success||console.warn("exists check did fail"),l.exists)return console.log("file already exists",s),new OM(!0,n,s,i.size);console.log("begin uploading file",o,i.size);const c=new FormData;c.append("file",i);const u={};u.filesize=i.size,o&&(u.alias=o);const d=await(await fetch(e+"/upload/file",{method:"POST",body:c,headers:u})).json();if(d?.success===!1)return d.message!==void 0?console.error("Upload failed:",d.message):console.error("Upload failed"),null;console.assert(d.hash_sum===s,"hash sum did not match","received:",d.hash_sum,"expected:",s),d.success&&console.log("successfully uploaded",s,d.id);const p=new OM(d.success,n,s,i.size);return p.url=e,p}function LM(i){return Y$(new Uint8Array(i))}async function FM(i,e,t,s,r=!1){try{const n=await fetch(s+"/download/file",{method:"POST",body:i});if(n.status!==200)return console.error("download failed",n),null;const o=await n.blob(),a=await o.arrayBuffer();r||console.assert(o.size===t,"size mismatch","expected:",t,"got:",o.size);const l=LM(a);return r||console.assert(l===e,"hash mismatch, downloaded file is invalid"),o.arrayBuffer()}catch(n){console.error(n)}return null}async function lF(i,e){var t;const s=await fetch(i),r=(t=s.body)==null?void 0:t.getReader(),n=s.headers.get("Content-Length"),o=n?parseInt(n):0;if(!r)return null;let a=0;const l=[];for(;;){const{done:d,value:p}=await r.read();if(p&&(l.push(p),a+=p.length,e.call(null,new ProgressEvent("progress",{loaded:a,total:o}))),d)break}const c=new Uint8Array(a);let u=0;for(const d of l)c.set(d,u),u+=d.length;return c}const yh=te("debugaddressables");class cF{constructor(e){h(this,"_context"),h(this,"_assetReferences",{}),this._context=e,this._context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){}findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.uri&&(this._assetReferences[e.uri]?console.warn("Asset reference already registered",e):this._assetReferences[e.uri]=e),e}dispose(){for(const e in this._assetReferences){const t=this._assetReferences[e];t?.unload()}this._assetReferences={}}unregisterAssetReference(e){e.uri&&delete this._assetReferences[e.uri]}}const UM=Symbol("assetReference"),Vg=class{constructor(i,e,t=null){h(this,"_loading"),h(this,"_asset"),h(this,"_glbRoot"),h(this,"_url"),h(this,"_progressListeners",[]),h(this,"_hash"),h(this,"_hashedUri"),h(this,"_isLoadingRawBinary",!1),h(this,"_rawBinary"),this._url=i,this._hash=e,i.includes("?v=")?this._hashedUri=i:this._hashedUri=e?i+"?v="+e:i,t!==null&&(this.asset=t),DN(this._url,this.onResolvePrefab.bind(this))}static getOrCreate(i,e,t){if(typeof i=="string"){if(!t&&(t=Lt.Current,!t))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.')}else t=i.context,i=i.sourceId;const s=Jl(i,e);yh&&console.log("GetOrCreate Addressable from",i,e,"FinalPath=",s);const r=t.addressables,n=r.findAssetReference(s);if(n)return n;const o=new Vg(s,t.hash);return r.registerAssetReference(o),o}get asset(){return this._glbRoot??this._asset}set asset(i){this._asset=i}get uri(){return this._url}get rawAsset(){return this._asset}async onResolvePrefab(i){return i===this.uri&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||od(this.asset)===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(yh&&console.log("Unload",this.asset),this.asset.scene&&Ca(this.asset.scene,!0,!0),Ca(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loading=void 0,Lt.Current&&Lt.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,yh&&console.log("Preload",this._hashedUri);const i=await lF(this._hashedUri,e=>{this.raiseProgressEvent(e)});return this._rawBinary=i?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(i){if(yh&&console.log("loadAssetAsync",this.uri),!this.mustLoad)return this.asset;if(i&&this._progressListeners.push(i),this._loading!==void 0)return this._loading.then(s=>this.asset);const e=Lt.Current;this._rawBinary?(this._loading=aa().parseSync(e,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(yh&&console.log("Load async",this.uri),this._loading=aa().loadSync(e,this._hashedUri,this.uri,null,s=>{this.raiseProgressEvent(s)}));const t=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(t),this._loading=void 0,t)return t[UM]=this,this._glbRoot&&(this._glbRoot[UM]=this),this.asset&&(this.asset[UM]=this),Qb(e),t.scene!==void 0&&(this.asset=t),this.asset}async instantiate(i){return this.onInstantiate(i,!1)}async instantiateSynced(i,e=!0){return this.onInstantiate(i,!0,e)}beginListenDownload(i){this._progressListeners.indexOf(i)<0&&this._progressListeners.push(i)}endListenDownload(i){const e=this._progressListeners.indexOf(i);e>=0&&this._progressListeners.splice(e,1)}raiseProgressEvent(i){for(const e of this._progressListeners)e(this,i)}async onInstantiate(i,e=!1,t){const s=Lt.Current,r=new Oa;if(i instanceof Ae?r.parent=i:i&&r.cloneAssign(i),r.parent||(r.parent=s.scene),this.mustLoad&&await this.loadAssetAsync(),yh&&console.log("Instantiate",this.uri,"parent:",i),this.asset){yh&&console.log("Add to scene",this.asset);let n=Vg.currentlyInstantiating.get(this.uri);if(n!==void 0&&n>=1e4)return console.error("Recursive or too many instantiations of "+this.uri+" in the same frame ("+n+")"),null;try{if(n===void 0&&(n=0),n+=1,Vg.currentlyInstantiating.set(this.uri,n),e){r.context=s;const o=this.asset;o.guid=this.uri;const a=PT(o,r,void 0,t);if(a)return a}else{const o=cf(this.asset,r);if(o)return o}}finally{s.post_render_callbacks.push(()=>{n===void 0||n<0?n=0:n-=1,Vg.currentlyInstantiating.set(this.uri,n)})}}else yh&&console.warn("Failed to load asset",this.uri);return null}tryGetActualGameObjectRoot(i){if(i&&i.scene){const e=i.scene;return e.isGroup&&e.children.length===1&&e.children[0].name+"glb"===e.name?e.children[0]:e}return null}};let ai=Vg;h(ai,"currentlyInstantiating",new Map);class J$ extends Za{constructor(){super([ai],"AssetReferenceSerializer")}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){if(typeof e=="string")return t.context?t.gltfId?ai.getOrCreate(t.gltfId,e,t.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(e instanceof Ae){if(!t.context)return console.error("Missing context"),null;if(!t.gltfId)return console.error("Missing source id"),null;const s=e,r=t.context,n=s.guid??s.uuid,o=r.addressables.findAssetReference(n);if(o)return o;const a=new ai(n,void 0,s);return r.addressables.registerAssetReference(a),a}return null}}new J$;const K$=Promise.resolve(null),i_=class{constructor(i){h(this,"url"),h(this,"_bitmap"),h(this,"_bitmapObject"),h(this,"loader",null),this.url=i}static getOrCreate(i){let e=i_.imageReferences.get(i);return e||(e=new i_(i),i_.imageReferences.set(i,e)),e}dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const i=new Image;return i.src=this.url,i}createTexture(){return this.url?(this.loader||(this.loader=new Yl),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url)):K$}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((i,e)=>{const t=document.createElement("img");t.addEventListener("load",()=>{this._bitmap=createImageBitmap(t).then(s=>(this._bitmapObject=s,i(s),s))}),t.addEventListener("error",s=>{console.error("Failed to load image:"+this.url,s),i(null)}),t.src=this.url}),this._bitmap)}};let s_=i_;h(s_,"imageReferences",new Map);class hF extends Za{constructor(){super([s_],"ImageReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const s=Jl(t.gltfId,e);return s_.getOrCreate(s)}}}new hF;const r_=class{constructor(i){h(this,"url"),h(this,"res"),this.url=i}static getOrCreate(i){let e=r_.cache.get(i);return e||(e=new r_(i),r_.cache.set(i,e)),e}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(i=>i.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(i=>i.text())}};let n_=r_;h(n_,"cache",new Map);class uF extends Za{constructor(){super([n_],"FileReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const s=Jl(t.gltfId,e);return n_.getOrCreate(s)}}}new uF;const ir={Handedness:Object.freeze({NONE:"none",LEFT:"left",RIGHT:"right"}),ComponentState:Object.freeze({DEFAULT:"default",TOUCHED:"touched",PRESSED:"pressed"}),ComponentProperty:Object.freeze({BUTTON:"button",X_AXIS:"xAxis",Y_AXIS:"yAxis",STATE:"state"}),ComponentType:Object.freeze({TRIGGER:"trigger",SQUEEZE:"squeeze",TOUCHPAD:"touchpad",THUMBSTICK:"thumbstick",BUTTON:"button"}),ButtonTouchThreshold:.05,AxisTouchThreshold:.1,VisualResponseProperty:Object.freeze({TRANSFORM:"transform",VISIBILITY:"visibility"})};async function dF(i){const e=await fetch(i);if(e.ok)return e.json();throw new Error(e.statusText)}async function Z$(i){if(!i)throw new Error("No basePath supplied");return await dF(`${i}/profilesList.json`)}async function $$(i,e,t=null,s=!0){if(!i)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No basePath supplied");const r=await Z$(e);let n;if(i.profiles.some(l=>{const c=r[l];return c&&(n={profileId:l,profilePath:`${e}/${c.path}`,deprecated:!!c.deprecated}),!!n}),!n){if(!t)throw new Error("No matching profile name found");const l=r[t];if(!l)throw new Error(`No matching profile name found and default profile "${t}" missing.`);n={profileId:t,profilePath:`${e}/${l.path}`,deprecated:!!l.deprecated}}const o=await dF(n.profilePath);let a;if(s){let l;if(i.handedness==="any"?l=o.layouts[Object.keys(o.layouts)[0]]:l=o.layouts[i.handedness],!l)throw new Error(`No matching handedness, ${i.handedness}, in profile ${n.profileId}`);l.assetPath&&(a=n.profilePath.replace("profile.json",l.assetPath))}return{profile:o,assetPath:a}}const eee={xAxis:0,yAxis:0,button:0,state:ir.ComponentState.DEFAULT};function tee(i=0,e=0){let t=i,s=e;if(Math.sqrt(i*i+e*e)>1){const r=Math.atan2(e,i);t=Math.cos(r),s=Math.sin(r)}return{normalizedXAxis:t*.5+.5,normalizedYAxis:s*.5+.5}}let iee=class{constructor(i){this.componentProperty=i.componentProperty,this.states=i.states,this.valueNodeName=i.valueNodeName,this.valueNodeProperty=i.valueNodeProperty,this.valueNodeProperty===ir.VisualResponseProperty.TRANSFORM&&(this.minNodeName=i.minNodeName,this.maxNodeName=i.maxNodeName),this.value=0,this.updateFromComponent(eee)}updateFromComponent({xAxis:i,yAxis:e,button:t,state:s}){const{normalizedXAxis:r,normalizedYAxis:n}=tee(i,e);switch(this.componentProperty){case ir.ComponentProperty.X_AXIS:this.value=this.states.includes(s)?r:.5;break;case ir.ComponentProperty.Y_AXIS:this.value=this.states.includes(s)?n:.5;break;case ir.ComponentProperty.BUTTON:this.value=this.states.includes(s)?t:0;break;case ir.ComponentProperty.STATE:this.valueNodeProperty===ir.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(s):this.value=this.states.includes(s)?1:0;break;default:throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}},see=class{constructor(i,e){if(!i||!e||!e.visualResponses||!e.gamepadIndices||Object.keys(e.gamepadIndices).length===0)throw new Error("Invalid arguments supplied");this.id=i,this.type=e.type,this.rootNodeName=e.rootNodeName,this.touchPointNodeName=e.touchPointNodeName,this.visualResponses={},Object.keys(e.visualResponses).forEach(t=>{const s=new iee(e.visualResponses[t]);this.visualResponses[t]=s}),this.gamepadIndices=Object.assign({},e.gamepadIndices),this.values={state:ir.ComponentState.DEFAULT,button:this.gamepadIndices.button!==void 0?0:void 0,xAxis:this.gamepadIndices.xAxis!==void 0?0:void 0,yAxis:this.gamepadIndices.yAxis!==void 0?0:void 0}}get data(){return{id:this.id,...this.values}}updateFromGamepad(i){if(this.values.state=ir.ComponentState.DEFAULT,this.gamepadIndices.button!==void 0&&i.buttons.length>this.gamepadIndices.button){const e=i.buttons[this.gamepadIndices.button];this.values.button=e.value,this.values.button=this.values.button<0?0:this.values.button,this.values.button=this.values.button>1?1:this.values.button,e.pressed||this.values.button===1?this.values.state=ir.ComponentState.PRESSED:(e.touched||this.values.button>ir.ButtonTouchThreshold)&&(this.values.state=ir.ComponentState.TOUCHED)}this.gamepadIndices.xAxis!==void 0&&i.axes.length>this.gamepadIndices.xAxis&&(this.values.xAxis=i.axes[this.gamepadIndices.xAxis],this.values.xAxis=this.values.xAxis<-1?-1:this.values.xAxis,this.values.xAxis=this.values.xAxis>1?1:this.values.xAxis,this.values.state===ir.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>ir.AxisTouchThreshold&&(this.values.state=ir.ComponentState.TOUCHED)),this.gamepadIndices.yAxis!==void 0&&i.axes.length>this.gamepadIndices.yAxis&&(this.values.yAxis=i.axes[this.gamepadIndices.yAxis],this.values.yAxis=this.values.yAxis<-1?-1:this.values.yAxis,this.values.yAxis=this.values.yAxis>1?1:this.values.yAxis,this.values.state===ir.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>ir.AxisTouchThreshold&&(this.values.state=ir.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(e=>{e.updateFromComponent(this.values)})}},ree=class{constructor(i,e,t){if(!i)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No profile supplied");this.xrInputSource=i,this.assetUrl=t,this.id=e.profileId,this.layoutDescription=e.layouts[i.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(s=>{const r=this.layoutDescription.components[s];this.components[s]=new see(s,r)}),this.updateFromGamepad()}get gripSpace(){return this.xrInputSource.gripSpace}get targetRaySpace(){return this.xrInputSource.targetRaySpace}get data(){const i=[];return Object.values(this.components).forEach(e=>{i.push(e.data)}),i}updateFromGamepad(){Object.values(this.components).forEach(i=>{i.updateFromGamepad(this.xrInputSource.gamepad)})}};class Ei extends we{constructor(e,t,s,r){super(e,t,s),h(this,"alpha",1),this.alpha=r}get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return super.copy(e),"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){const s=e;return s.alpha&&(this.alpha=st.lerp(this.alpha,s.alpha,t)),super.lerp(e,t)}lerpColors(e,t,s){const r=e,n=t;return r.alpha&&n.alpha&&(this.alpha=st.lerp(r.alpha,n.alpha,s)),super.lerpColors(e,t,s)}multiply(e){const t=e;return t.alpha&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}fromArray(e,t=0){return this.alpha=e[t+3],super.fromArray(e,t)}}const bn=new w,pF=new w,fF=new Ie,nee=te("debuggizmos"),cc=8947848,$a=class{static isGizmo(i){return i[zM]!==void 0}static DrawLabel(i,e,t=.05,s=0,r,n,o){var a;if(!$a.enabled)return null;r||(r=cc);const l=((a=mt.active)==null?void 0:a.rigScale)??1,c=Ds.getTextLabel(s,e,t*l,r,n);return o instanceof Ae&&o.add(c),c.position.x=i.x,c.position.y=i.y,c.position.z=i.z,c}static DrawRay(i,e,t=cc,s=0,r=!0){if(!$a.enabled)return;const n=Ds.getLine(s),o=n.geometry.getAttribute("position");o.setXYZ(0,i.x,i.y,i.z),bn.set(e.x,e.y,e.z).multiplyScalar(999999999),o.setXYZ(1,i.x+bn.x,i.y+bn.y,i.z+bn.z),o.needsUpdate=!0,n.material.color.set(t),n.material.depthTest=r,n.material.depthWrite=!1}static DrawDirection(i,e,t=cc,s=0,r=!0,n=1){if(!$a.enabled)return;const o=Ds.getLine(s),a=o.geometry.getAttribute("position");a.setXYZ(0,i.x,i.y,i.z),e.w!==void 0?(bn.set(0,0,-n),fF.set(e.x,e.y,e.z,e.w),bn.applyQuaternion(fF)):(bn.set(e.x,e.y,e.z),bn.multiplyScalar(n)),a.setXYZ(1,i.x+bn.x,i.y+bn.y,i.z+bn.z),a.needsUpdate=!0,o.material.color.set(t),o.material.depthTest=r,o.material.depthWrite=!1}static DrawLine(i,e,t=cc,s=0,r=!0){if(!$a.enabled)return;const n=Ds.getLine(s),o=n.geometry.getAttribute("position");o.setXYZ(0,i.x,i.y,i.z),o.setXYZ(1,e.x,e.y,e.z),o.needsUpdate=!0,n.material.color.set(t),n.material.depthTest=r,n.material.depthWrite=!1}static DrawWireSphere(i,e,t=cc,s=0,r=!0){if(!$a.enabled)return;const n=Ds.getSphere(e,s,!0);Qu(n,i.x,i.y,i.z),n.material.color.set(t),n.material.depthTest=r,n.material.depthWrite=!1}static DrawSphere(i,e,t=cc,s=0,r=!0){if(!$a.enabled)return;const n=Ds.getSphere(e,s,!1);Qu(n,i.x,i.y,i.z),n.material.color.set(t),n.material.depthTest=r,n.material.depthWrite=!1}static DrawWireBox(i,e,t=cc,s=0,r=!0){if(!$a.enabled)return;const n=Ds.getBox(s);n.position.set(i.x,i.y,i.z),n.scale.set(e.x,e.y,e.z),n.material.color.set(t),n.material.depthTest=r,n.material.wireframe=!0,n.material.depthWrite=!1}static DrawWireBox3(i,e=cc,t=0,s=!0){if(!$a.enabled)return;const r=Ds.getBox(t);r.position.copy(i.getCenter(bn)),r.scale.copy(i.getSize(bn)),r.material.color.set(e),r.material.depthTest=s,r.material.wireframe=!0,r.material.depthWrite=!1}static DrawArrow(i,e,t=cc,s=0,r=!0,n=!1){if(!$a.enabled)return;const o=Ds.getArrowHead(s);o.position.set(e.x,e.y,e.z),o.quaternion.setFromUnitVectors(this._up.set(0,1,0),bn.set(e.x,e.y,e.z).sub(pF.set(i.x,i.y,i.z)).normalize());const a=bn.set(e.x,e.y,e.z).sub(pF.set(i.x,i.y,i.z)).length()*.1;o.scale.set(a,a,a),o.material.color.set(t),o.material.depthTest=r,o.material.wireframe=n,this.DrawLine(i,e,t,s,r)}};let Tt=$a;h(Tt,"enabled",!0),h(Tt,"_up",new w(0,1,0));const oee=new Ni(1,1,1);function NM(i=null){const e=new we(i??14540253),t=new pC(oee);return new io(t,new xs({color:e}))}const zM=Symbol("GizmoCache");class Ds{static ensureFont(){let e=zn.FontLibrary.getFontFamily(this.familyName);if(!e){e=zn.FontLibrary.addFontFamily(this.familyName);const t=e.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png");t?.addEventListener("ready",()=>{zn.update()})}}static getTextLabel(e,t,s,r,n){this.ensureFont();let o=this.textLabelCache.pop(),a=1;n&&typeof n=="string"&&n?.length>=8&&n.startsWith("#")?(a=parseInt(n.substring(7),16)/255,n=n.substring(0,7),nee&&console.log(n,a)):typeof n=="object"&&n.a!==void 0&&(a=n.a);const l={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:s,color:r,lineHeight:1,backgroundColor:n??void 0,backgroundOpacity:a,textContent:t,borderRadius:.5*s,padding:.8*s,whiteSpace:"pre"};if(o)o.set(l);else{o=new VE(l);const c=this,u=o;u.setText=function(d){this.set({textContent:d}),c.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(Lt.Current,o,e,this.textLabelCache),o}static getBox(e){let t=this.boxesCache.pop();if(!t){const s=new Ni(1,1,1);t=new ge(s)}return this.registerTimedObject(Lt.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new ws;let s=t.geometry.getAttribute("position");s||(s=new Ze(new Float32Array(2*3),3),t.geometry.setAttribute("position",s))}return t.frustumCulled=!1,this.registerTimedObject(Lt.Current,t,e,this.linesCache),t}static getSphere(e,t,s){let r=this.spheresCache.pop();return r||(r=new ge(new ka(1,8,8))),r.scale.set(e,e,e),r.material.wireframe=s,this.registerTimedObject(Lt.Current,r,t,this.spheresCache),r}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new ge(new Ts(0,.5,1,8))),this.registerTimedObject(Lt.Current,t,e,this.arrowHeadsCache),t}static registerTimedObject(e,t,s,r){const n=this.contextBeforeRenderCallbacks.get(e),o=this.contextPostRenderCallbacks.get(e);if(n){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==n){const a=e.pre_render_callbacks.indexOf(n);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(n)}}else{const a=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,a),e.pre_render_callbacks.push(a)}if(o){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==o){const a=e.post_render_callbacks.indexOf(o);a>=0&&e.post_render_callbacks.splice(a,1),e.post_render_callbacks.push(o)}}else{const a=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,a),e.post_render_callbacks.push(a)}t.traverse(a=>{a.layers.disableAll(),a.layers.enable(2)}),t.renderOrder=999999,t[zM]=r,this.timedObjectsBuffer.push(t),this.timesBuffer.push(Lt.Current.time.realtimeSinceStartup+s),e.scene.add(t)}static onBeforeRender(e,t){this.tmuiNeedsUpdate&&zn.update();for(let s=0;s<t.length;s++){const r=t[s];if(e.mainCamera&&r instanceof zn.MeshUIBaseElement){if(od(r))continue;const n=e.isInVR,o=!1,a=!n;Ib(r,e.mainCamera,o,a)}}}static onPostRender(e,t,s){const r=e.time.realtimeSinceStartup;for(let n=t.length-1;n>=0;n--){const o=t[n];r>s[n]&&(t.splice(n,1),s.splice(n,1),o.removeFromParent(),od(o)!=!0&&o[zM].push(o))}}}h(Ds,"familyName","needle-gizmos"),h(Ds,"linesCache",[]),h(Ds,"spheresCache",[]),h(Ds,"boxesCache",[]),h(Ds,"arrowHeadsCache",[]),h(Ds,"textLabelCache",[]),h(Ds,"timedObjectsBuffer",new Array),h(Ds,"timesBuffer",new Array),h(Ds,"contextPostRenderCallbacks",new Map),h(Ds,"contextBeforeRenderCallbacks",new Map),h(Ds,"tmuiNeedsUpdate",!1);const br=te("debuginput");var o_=(i=>(i.Mouse="mouse",i.Touch="touch",i.Controller="controller",i.Hand="hand",i))(o_||{}),Ki=(i=>(i.PointerDown="pointerdown",i.PointerUp="pointerup",i.PointerMove="pointermove",i.KeyDown="keydown",i.KeyUp="keyup",i.KeyPressed="keypress",i))(Ki||{});class hc extends PointerEvent{constructor(e,t,s){super(e,s),h(this,"deviceIndex"),h(this,"origin"),h(this,"source"),h(this,"mode"),h(this,"ray"),h(this,"space"),h(this,"isClick",!1),h(this,"isDoubleClick",!1),h(this,"_used",!1),h(this,"_pointerid"),h(this,"_pointerType"),h(this,"_type"),h(this,"_immediatePropagationStopped",!1),h(this,"_propagationStopped",!1),this._pointerid=s.pointerId,this._pointerType=s.pointerType,this._type=e,this.deviceIndex=s.deviceIndex,this.origin=s.origin,this.source=t,this.mode=s.mode,this.ray=s.ray,this.space=s.device}get used(){return this._used}use(){this._used=!0}get pointerId(){return this._pointerid}get pointerType(){return this._pointerType}get type(){return this._type}get immediatePropagationStopped(){return this._immediatePropagationStopped}get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){var e;this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}stopPropagation(){var e;this._propagationStopped=!0,super.stopPropagation(),(e=this.source)==null||e.stopPropagation()}}class Hg extends KeyboardEvent{constructor(e,t,s){super(e,s),h(this,"source"),this.source=t}stopImmediatePropagation(){var e;super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}}class aee{constructor(e){h(this,"key"),h(this,"keyType"),h(this,"source"),this.key=e.key,this.keyType=e.type,this.source=e}}var el=(i=>(i[i.Early=-100]="Early",i[i.Default=0]="Default",i[i.Late=100]="Late",i))(el||{});class mF{constructor(e){h(this,"_eventListeners",{}),h(this,"_doubleClickTimeThreshold",.2),h(this,"_longPressTimeThreshold",1),h(this,"_specialCursorTrigger",0),h(this,"context"),h(this,"_pointerDown",[!1]),h(this,"_pointerUp",[!1]),h(this,"_pointerClick",[!1]),h(this,"_pointerDoubleClick",[!1]),h(this,"_pointerPressed",[!1]),h(this,"_pointerPositions",[new ee]),h(this,"_pointerPositionsLastFrame",[new ee]),h(this,"_pointerPositionsDelta",[new ee]),h(this,"_pointerPositionsRC",[new ee]),h(this,"_pointerPositionDown",[new ee]),h(this,"_pointerDownTime",[]),h(this,"_pointerUpTime",[]),h(this,"_pointerUpTimestamp",[]),h(this,"_pointerIds",[]),h(this,"_pointerTypes",[""]),h(this,"_mouseWheelChanged",[!1]),h(this,"_mouseWheelDeltaY",[0]),h(this,"_pointerEvent",[]),h(this,"_pointerUsed",[]),h(this,"_pointerSpace",[]),h(this,"_pressedStack",new Map),h(this,"_htmlEventSource"),h(this,"onLostFocus",()=>{for(const t in this.keysPressed)this.keysPressed[t].pressed=!1}),h(this,"onEndOfFrame",()=>{for(let t=0;t<this._pointerUp.length;t++)this._pointerUp[t]=!1;for(let t=0;t<this._pointerDown.length;t++)this._pointerDown[t]=!1;for(let t=0;t<this._pointerClick.length;t++)this._pointerClick[t]=!1;for(let t=0;t<this._pointerDoubleClick.length;t++)this._pointerDoubleClick[t]=!1;for(const t of this._pointerPositionsDelta)t.set(0,0);for(let t=0;t<this._mouseWheelChanged.length;t++)this._mouseWheelChanged[t]=!1;for(let t=0;t<this._mouseWheelDeltaY.length;t++)this._mouseWheelDeltaY[t]=0}),h(this,"onContextMenu",t=>{this.canReceiveInput(t)!==!1&&t instanceof PointerEvent&&t.pointerType}),h(this,"keysPressed",{}),h(this,"onKeyDown",t=>{if(br&&console.log(`key down ${t.code}, ${this.context.application.hasFocus}`,t),!this.context.application.hasFocus)return;const s=this.keysPressed[t.code];if(s&&s.pressed)return;this.keysPressed[t.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:t.key,code:t.code};const r=new Hg("keydown",t,t);this.onDispatchEvent(r)}),h(this,"onKeyPressed",t=>{if(!this.context.application.hasFocus)return;const s=this.keysPressed[t.code];if(!s)return;s.pressed=!0,s.frame=this.context.time.frameCount+1;const r=new Hg("keypress",t,t);this.onDispatchEvent(r)}),h(this,"onKeyUp",t=>{if(!this.context.application.hasFocus)return;const s=this.keysPressed[t.code];if(!s)return;s.pressed=!1,s.frame=this.context.time.frameCount+1;const r=new Hg("keyup",t,t);this.onDispatchEvent(r)}),h(this,"onMouseWheel",t=>{if(this.canReceiveInput(t)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const s=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=s+t.deltaY}),h(this,"onTouchStartWindow",t=>{this.context.isInAR&&this.onTouchStart(t)}),h(this,"onTouchStart",t=>{if(!(t.changedTouches.length<=0)&&this.canReceiveInput(t)!==!1)for(let s=0;s<t.changedTouches.length;s++){const r=t.changedTouches[s],n=this.getPointerIndex(r.identifier);br&&rs(`touch start #${n}, identifier:${r.identifier}`);const o=this.getAndUpdateSpatialObjectForScreenPosition(n,r.clientX,r.clientY),a=new hc("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:r.clientX,clientY:r.clientY,pointerType:"touch",buttonName:"unknown",device:o,pressure:r.force});this.onDown(a)}}),h(this,"onTouchMove",t=>{if(!(t.changedTouches.length<=0))for(let s=0;s<t.changedTouches.length;s++){const r=t.changedTouches[s],n=this.getPointerIndex(r.identifier),o=this.getAndUpdateSpatialObjectForScreenPosition(n,r.clientX,r.clientY),a=new hc("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:r.clientX,clientY:r.clientY,pointerType:"touch",buttonName:"unknown",device:o,pressure:r.force});this.onMove(a)}}),h(this,"onTouchUp",t=>{if(!(t.changedTouches.length<=0))for(let s=0;s<t.changedTouches.length;s++){const r=t.changedTouches[s],n=this.getPointerIndex(r.identifier);if(!this.isNewEvent(t.timeStamp,n,this._pointerUpTimestamp))continue;const o=this.createPointerEventFromTouch("pointerup",r.identifier,r.clientX,r.clientY,r.force,t);this.onUp(o),this._pointerIds.splice(this._pointerIds.indexOf(n),1)}}),h(this,"onTouchCancel",t=>{}),h(this,"onMouseDown",t=>{if(this.onDownButton(0,t.button),this.context.isInVR||t.defaultPrevented||this.canReceiveInput(t)===!1)return;const s=t.button;let r="none";switch(s){case 0:r="left";break;case 1:r="middle";break;case 2:r="right";break}const n=0+s,o=this.getAndUpdateSpatialObjectForScreenPosition(n,t.clientX,t.clientY),a=new hc("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:s,clientX:t.clientX,clientY:t.clientY,pointerType:"mouse",buttonName:r,device:o,pressure:1});this.onDown(a)}),h(this,"onMouseMove",t=>{if(this.context.isInVR||t.defaultPrevented)return;const s=this.getFirstPressedButtonForPointer(0),r=s??0,n=0+r,o=this.getAndUpdateSpatialObjectForScreenPosition(n,t.clientX,t.clientY),a=s!==void 0?1:0,l=new hc("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:r,clientX:t.clientX,clientY:t.clientY,pointerType:"mouse",buttonName:"none",device:o,pressure:a});this.onMove(l)}),h(this,"onMouseUp",t=>{if(this.onReleaseButton(0,t.button),this.context.isInVR)return;const s=t.button;if(!this.isNewEvent(t.timeStamp,s,this._pointerUpTimestamp))return;let r="none";switch(s){case 0:r="left";break;case 1:r="middle";break;case 2:r="right";break}const n=0+s;if(t.defaultPrevented)return;const o=this.getAndUpdateSpatialObjectForScreenPosition(n,t.clientX,t.clientY),a=new hc("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:s,clientX:t.clientX,clientY:t.clientY,pointerType:"mouse",buttonName:r,device:o,pressure:0});this.onUp(a)}),h(this,"tempNearPlaneVector",new w),h(this,"tempFarPlaneVector",new w),h(this,"tempLookMatrix",new Te),this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(e,t,s=0){this._eventListeners[e]||(this._eventListeners[e]=[]);const r=this._eventListeners[e],n=r.find(o=>o.priority===s);n?n.listeners.push(t):(r.push({priority:s,listeners:[t]}),r.sort((o,a)=>o.priority-a.priority))}removeEventListener(e,t,s){if(!this._eventListeners[e])return;const r=this._eventListeners[e];if(s!==void 0){const n=r.find(a=>a.priority===s);if(!n)return;const o=n.listeners.indexOf(t);o>=0&&n.listeners.splice(o,1)}else for(const n of r){const o=n.listeners.indexOf(t);o>=0&&n.listeners.splice(o,1)}}dispatchEvent(e){let t=!1;if(e instanceof Hg){const s=this._eventListeners[e.type];if(s)for(const r of s)for(const n of r.listeners)n(e)}if(e instanceof hc){const s=this._eventListeners[e.type];if(s)for(const r of s){if(t)break;for(const n of r.listeners){if(e.immediatePropagationStopped){t=!0,br&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(t=!0,br&&console.log("propagationStopped",e.type));n(e)}}}}get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}setCursorPointer(){this._specialCursorTrigger+=1,this.context.domElement.style.cursor="pointer"}setCursorNormal(){this._specialCursorTrigger-=1,this._specialCursorTrigger=Math.max(0,this._specialCursorTrigger),this._specialCursorTrigger===0&&(this.context.domElement.style.cursor="default")}setPointerUsed(e,t=!0){if(e>=this._pointerUsed.length){if(e>=this._pointerIds.length)return;for(;this._pointerUsed.length<=e;)this._pointerUsed.push(!1)}this._pointerUsed[e]=t}getPointerUsed(e){return e>=this._pointerUsed.length?!1:this._pointerUsed[e]}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}*foreachPointerId(e){for(let t=0;t<this._pointerTypes.length;t++)if(this._pointerIsActive(t)){if(e!==void 0){const s=this._pointerTypes[t];if(Array.isArray(e)){let r=!1;for(const n of e)if(s===n){r=!0;break}if(!r)continue}else if(e!==s)continue}yield t}}*foreachTouchId(){for(let e=0;e<this._pointerTypes.length;e++)this._pointerTypes[e]==="touch"&&this._pointerIsActive[e]&&(yield e)}_pointerIsActive(e){return e<0?!1:this._pointerPressed[e]||this._pointerDown[e]||this._pointerUp[e]}onDownButton(e,t){let s=this._pressedStack.get(e);s||(s=[],this._pressedStack.set(e,s)),s.push(t)}onReleaseButton(e,t){const s=this._pressedStack.get(e);if(!s)return;const r=s.indexOf(t);r>=0&&s.splice(r,1)}getFirstPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[0]}getLatestPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[t.length-1]}getKeyDown(){for(const e in this.keysPressed){const t=this.keysPressed[e];if(t.startFrame===this.context.time.frameCount)return t.key}return null}getKeyPressed(){for(const e in this.keysPressed){const t=this.keysPressed[e];if(t.pressed)return t.key}return null}isKeyDown(e){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const s=this.getCodeForCommonKeyName(e);if(s!==null){for(const r of s)if(this.isKeyDown(r))return!0;return!1}return((t=this.keysPressed[e])==null?void 0:t.startFrame)===this.context.time.frameCount&&this.keysPressed[e].pressed}isKeyUp(e){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const s=this.getCodeForCommonKeyName(e);if(s!==null){for(const r of s)if(this.isKeyUp(r))return!0;return!1}return((t=this.keysPressed[e])==null?void 0:t.frame)===this.context.time.frameCount&&!this.keysPressed[e].pressed}isKeyPressed(e){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const s=this.getCodeForCommonKeyName(e);if(s!==null){for(const r of s)if(this.isKeyPressed(r))return!0;return!1}return(t=this.keysPressed[e])==null?void 0:t.pressed}getCodeForCommonKeyName(e){if(e.length===1){if(e>="0"&&e<="9")return["Digit"+e];if(e>="a"&&e<="z")return["Key"+e.toUpperCase()];if(e==" ")return["Space"]}switch(e){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(e){switch(e.type){case"pointerdown":br&&rs("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":br&&rs("Create Pointer move"),this.onMove(e);break;case"pointerup":br&&rs("Create Pointer up"),this.onUp(e),this.onReleaseButton(e.deviceIndex,e.button);break}}convertScreenspaceToRaycastSpace(e){e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1}bindEvents(){this.unbindEvents(),this._htmlEventSource=this.context.renderer.domElement,window.addEventListener("contextmenu",this.onContextMenu),this._htmlEventSource.addEventListener("touchstart",this.onTouchStart,!1),window.addEventListener("touchstart",this.onTouchStartWindow),window.addEventListener("touchmove",this.onTouchMove,{passive:!0}),window.addEventListener("touchend",this.onTouchUp,!1),window.addEventListener("touchcancel",this.onTouchCancel,!1),this._htmlEventSource.addEventListener("mousedown",this.onMouseDown),window.addEventListener("mousemove",this.onMouseMove,!1),window.addEventListener("mouseup",this.onMouseUp,!1),this._htmlEventSource.addEventListener("wheel",this.onMouseWheel,{passive:!0}),window.addEventListener("keydown",this.onKeyDown,!1),window.addEventListener("keypress",this.onKeyPressed,!1),window.addEventListener("keyup",this.onKeyUp,!1),window.addEventListener("blur",this.onLostFocus)}unbindEvents(){var e,t,s;window.removeEventListener("contextmenu",this.onContextMenu),(e=this._htmlEventSource)==null||e.removeEventListener("touchstart",this.onTouchStart,!1),window.removeEventListener("touchstart",this.onTouchStartWindow),window.removeEventListener("touchmove",this.onTouchMove,!1),window.removeEventListener("touchend",this.onTouchUp,!1),window.removeEventListener("touchcancel",this.onTouchCancel,!1),(t=this._htmlEventSource)==null||t.removeEventListener("mousedown",this.onMouseDown,!1),window.removeEventListener("mousemove",this.onMouseMove,!1),window.removeEventListener("mouseup",this.onMouseUp,!1),(s=this._htmlEventSource)==null||s.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}dispose(){const e=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);e>=0&&this.context.post_render_callbacks.splice(e,1),this.unbindEvents()}canReceiveInput(e){var t;return!!(e.target===((t=this.context.renderer)==null?void 0:t.domElement)||e.target===this.context.domElement||this.context.isInAR&&e.target===document.body&&Uu())}createPointerEventFromTouch(e,t,s,r,n,o){const a=this.getPointerIndex(t);br&&rs(`touch up #${a}, identifier:${t}`);const l=this.getAndUpdateSpatialObjectForScreenPosition(a,s,r);return new hc(e,o,{origin:this,mode:"screen",deviceIndex:0,pointerId:a,button:0,clientX:s,clientY:r,pointerType:"touch",buttonName:"unknown",device:l,pressure:n})}getAndUpdateSpatialObjectForScreenPosition(e,t,s){let r=this._pointerSpace[e];r||(r=new Ae,this._pointerSpace[e]=r),this._pointerSpace[e]=r;const n=this.context.mainCamera;if(n){const o=this.tempNearPlaneVector.set(t,s,-1);this.convertScreenspaceToRaycastSpace(o);const a=this.tempFarPlaneVector.set(o.x,o.y,1);o.unproject(n),a.unproject(n),this.tempLookMatrix.lookAt(a,o,n.worldUp),r.position.set(o.x,o.y,o.z),r.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return r}isNewEvent(e,t,s){for(;s.length<=t;)s.push(-1);return e===s[t]?!1:(s[t]=e,!0)}isInRect(e){if(this.context.isInXR)return!0;const t=this.context.domElement.getBoundingClientRect(),s=e.clientX,r=e.clientY,n=s>=t.x&&s<=t.right&&r>=t.y&&r<=t.bottom;return br&&!n&&console.log("Not in rect",t,s,r),n}onDown(e){const t=e.pointerId;if(this.getPointerPressed(t)&&console.warn(`pointerId is already pressed: ${t}`,br?e:""),br&&console.log(e.pointerType,"DOWN",t),!!this.isInRect(e)&&!this.isMouseEventFromTouch(e)){for(this.setPointerState(t,this._pointerPressed,!0),this.setPointerState(t,this._pointerDown,!0),this.setPointerStateT(t,this._pointerEvent,e.source);t>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[t]=e.pointerType;t>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new ee);for(this._pointerPositionDown[t].set(e.clientX,e.clientY);t>=this._pointerPositions.length;)this._pointerPositions.push(new ee);this._pointerPositions[t].set(e.clientX,e.clientY),t>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t]=this.context.time.time,this.updatePointerPosition(e),this.onDispatchEvent(e)}}onMove(e){const t=e.pointerId,s=this.getPointerPressed(t);s===!1&&!this.isInRect(e)||e.pointerType==="touch"&&!s||this.isMouseEventFromTouch(e)||(br&&console.log(e.pointerType,"MOVE",t,"hasSpace="+e.space!=null),this.updatePointerPosition(e),this.setPointerStateT(t,this._pointerEvent,e.source),this.onDispatchEvent(e))}onUp(e){const t=e.pointerId;if(!this.getPointerPressed(t)){br&&console.log(e.pointerType,"UP",t,"was not down");return}if(this.isMouseEventFromTouch(e))return;for(br&&console.log(e.pointerType,"UP",t),this.setPointerState(t,this._pointerPressed,!1),this.setPointerStateT(t,this._pointerEvent,e.source),this.setPointerState(t,this._pointerUp,!0);t>=this._pointerUsed.length;)this._pointerUsed.push(!1);if(this.setPointerState(t,this._pointerUsed,!1),this.updatePointerPosition(e),!this._pointerPositionDown[t]){br&&ns("Received pointer up event without matching down event for button: "+t),console.warn("Received pointer up event without matching down event for button: "+t);return}const s=e.clientX-this._pointerPositionDown[t].x,r=e.clientY-this._pointerPositionDown[t].y;if(t>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),Math.abs(s)<5&&Math.abs(r)<5){br&&console.log("CLICK",t),this.setPointerState(t,this._pointerClick,!0),e.isClick=!0;const n=this._pointerUpTime[t],o=this.context.time.time-n;o<this._doubleClickTimeThreshold&&o>0&&(this.setPointerState(t,this._pointerDoubleClick,!0),e.isDoubleClick=!0)}this._pointerUpTime[t]=this.context.time.time,this.onDispatchEvent(e)}isMouseEventFromTouch(e){var t;if(e.pointerType==="mouse"){const s=this._pointerUpTimestamp.map((r,n)=>({timestamp:r,index:n})).sort((r,n)=>r.timestamp-n.timestamp).at(-1);if(s&&this._pointerTypes[s.index]==="touch"&&s.timestamp>0&&((t=e.source)==null?void 0:t.timeStamp)!==void 0){const r=e.source.timeStamp-s.timestamp;if(r<320&&r>=0)return br&&console.log("Ignoring mouse.down for touch.up"),!0}}return!1}updatePointerPosition(e){const t=e.pointerId;for(;t>=this._pointerPositions.length;)this._pointerPositions.push(new ee);for(;t>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new ee);for(;t>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new ee);const s=this._pointerPositionsLastFrame[t];s.copy(this._pointerPositions[t]);const r=this._pointerPositionsDelta[t];let n=e.clientX-s.x,o=e.clientY-s.y;if(e.source instanceof MouseEvent||e.source instanceof TouchEvent){const u=e.source;n===0&&u.movementX!==0&&(n=u.movementX||0),o===0&&u.movementY!==0&&(o=u.movementY||0)}r.x+=n,r.y+=o,this._pointerPositions[t].x=e.clientX,this._pointerPositions[t].y=e.clientY;const a=e.clientX,l=e.clientY;for(;t>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new ee);const c=this._pointerPositionsRC[t];c.set(a,l),this.convertScreenspaceToRaycastSpace(c)}getPointerIndex(e){const t=this._pointerIds;let s=-1;for(let r=0;r<t.length;r++){if(t[r]===e)return r;s===-1&&t[r]===-1&&(s=r)}return s!==-1?(t[s]=e,s):(t.push(e),t.length-1)}setPointerState(e,t,s){t[e]=s}setPointerStateT(e,t,s){return t[e]=s,s}onDispatchEvent(e){const t=Lt.Current;try{Lt.Current=this.context,this.dispatchEvent(e)}finally{Lt.Current=t}}}const a_=new Te().makeRotationY(Math.PI),_a=new Ie().setFromAxisAngle(new w(0,1,0),Math.PI),lee=te("debugwebxr");class cee{constructor(){if(h(this,"priority",-1e5),h(this,"gameObject"),this.gameObject=new Ae,this.gameObject.name="Implicit XR Rig",lee){const e=NM(16733661);e.position.y+=.5,this.gameObject.add(e)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const bh=te("debugwebxr"),Wg=te("debugcustomgesture");let jM=!1;const hee="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",uee="generic-trigger";class GM{constructor(e,t,s){h(this,"xr"),h(this,"inputSource"),h(this,"index",0),h(this,"emitEvents",!0),h(this,"_connected",!0),h(this,"_isTracking",!1),h(this,"_hitTestSource"),h(this,"_handJointPoses",new Map),h(this,"_gripPosition",new w),h(this,"_gripQuaternion",new Ie),h(this,"_linearVelocity",new w),h(this,"_rayPosition",new w),h(this,"_rayQuaternion",new Ie),h(this,"_gripWorldPosition",new w),h(this,"_gripWorldQuaternion",new Ie),h(this,"_rayWorldPosition",new w),h(this,"_rayWorldQuaternion",new Ie),h(this,"_ray"),h(this,"_object"),h(this,"_debugAxesHelper",new Ro(.2)),h(this,"_needleGamepadButtons",{}),h(this,"_buttonMap",new Map),h(this,"_motioncontroller"),h(this,"_layout"),h(this,"getMotionController"),h(this,"_selectButtonIndex"),h(this,"_squeezeButtonIndex"),h(this,"onSelectStart",a=>{var l,c,u,d;if(this.inputSource!==a.inputSource)return;const p=(l=this._layout)==null?void 0:l.selectComponentId,f=(d=(u=(c=this._layout)==null?void 0:c.components[p])==null?void 0:u.gamepadIndices)==null?void 0:d.button;if(f!==void 0&&(this._selectButtonIndex=f),!Wg){if(!jM){jM=!0;const m=this.getGesture("pinch");if(m!=null&&m.pressed){console.warn("Select start event was received but the pinch gesture is already down. This might happen the first time you start pinching",this.index,this.side);return}}bh&&Tt.DrawDirection(this.rayWorldPosition,Bs(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(Ki.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,a)}}),h(this,"onSelectEnd",a=>{Wg||this.inputSource===a.inputSource&&this.emitPointerEvent(Ki.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,a)}),h(this,"onSequeezeStart",a=>{var l,c,u;this.inputSource===a.inputSource&&(this._squeezeButtonIndex=(u=(c=(l=this._layout)==null?void 0:l.components["xr-standard-squeeze"])==null?void 0:c.gamepadIndices)==null?void 0:u.button,this._squeezeButtonIndex!==void 0&&(bh&&Tt.DrawDirection(this.rayWorldPosition,Bs(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(Ki.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,a)))}),h(this,"onSequeezeEnd",a=>{this.inputSource===a.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(Ki.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,a)}),h(this,"states",{}),h(this,"_didMoveLastFrame",!1),h(this,"_lastPointerMovePosition",new w),h(this,"_lastPointerMoveQuaternion",new Ie),h(this,"pointerInit");var r,n,o;this.xr=e,this.inputSource=t,this.index=s,this._object=new Ae,bh&&this._object.add(this._debugAxesHelper),this.xr.context.scene.add(this._object),this._ray=new Zn,this.pointerInit={origin:this,pointerType:this.hand?"hand":"controller",deviceIndex:this.index,pointerId:-1,mode:this.inputSource.targetRayMode,ray:this._ray,device:this._object,buttonName:"none"},this.initialize(),this.subscribeEvents(),this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&((o=(n=(r=this.xr.session).requestHitTestSourceForTransientInput)==null?void 0:n.call(r,{profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null||o.then(a=>this._hitTestSource=a))}get context(){return this.xr.context}get connected(){return this._connected}get isTracking(){return this._isTracking}get gamepad(){return this.inputSource.gamepad}get isHand(){return this.inputSource.hand!=null}get hand(){return this.inputSource.hand}get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.inputSource.handedness}get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get hitTestSource(){return this._hitTestSource}getHitTest(){return this.xr.getHitTest(this)}getHandJointPose(e){var t,s;if(!this.hand||!((t=this.xr.frame)!=null&&t.getJointPose)||!this.xr.referenceSpace)return null;let r=(s=this._handJointPoses)==null?void 0:s.get(e);return r||(r=this.xr.frame.getJointPose(e,this.xr.referenceSpace),r&&this._handJointPoses.set(e,r),r)}get gripPosition(){return Bs(this._gripPosition).applyMatrix4(a_)}get gripQuaternion(){return Gu(this._gripQuaternion).premultiply(_a)}get gripLinearVelocity(){return Bs(this._linearVelocity).applyQuaternion(_a)}get rayPosition(){return Bs(this._rayPosition).applyMatrix4(a_)}get rayQuaternion(){return Gu(this._rayQuaternion).premultiply(_a)}get gripWorldPosition(){return Bs(this._gripWorldPosition)}get gripWorldQuaternion(){return Gu(this._gripWorldQuaternion)}get rayWorldPosition(){return Bs(this._rayWorldPosition)}updateRayWorldPosition(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent;this._rayWorldPosition.copy(this._rayPosition),t&&this._rayWorldPosition.applyMatrix4(t.matrixWorld)}get rayWorldQuaternion(){return Gu(this._rayWorldQuaternion)}updateRayWorldQuaternion(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent,s=t?Ri(t):void 0;this._rayWorldQuaternion.copy(this._rayQuaternion).multiply(_a),s&&this._rayWorldQuaternion.premultiply(s)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(Bs(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}get object(){return this._object}async getModelUrl(){var e;return(e=this.getMotionController)==null?void 0:e.then(t=>t?.assetUrl||null)}onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){var e;Tt.DrawWireSphere(this.rayWorldPosition,.02),Tt.DrawDirection(this.rayWorldPosition,Bs(0,0,10).applyQuaternion(this.rayWorldQuaternion));const t=this.gripWorldPosition.sub(this.object.worldForward.multiplyScalar(.1)),s=this.inputSource.profiles.join(`
4919
+ */var W$=function(i){return i!=null&&(oF(i)||X$(i)||!!i._isBuffer)};function oF(i){return!!i.constructor&&typeof i.constructor.isBuffer=="function"&&i.constructor.isBuffer(i)}function X$(i){return typeof i.readFloatLE=="function"&&typeof i.slice=="function"&&oF(i.slice(0,0))}(function(){var i=H$,e=nF.utf8,t=W$,s=nF.bin,r=function(n,o){n.constructor==String?o&&o.encoding==="binary"?n=s.stringToBytes(n):n=e.stringToBytes(n):t(n)?n=Array.prototype.slice.call(n,0):!Array.isArray(n)&&n.constructor!==Uint8Array&&(n=n.toString());for(var a=i.bytesToWords(n),l=n.length*8,c=1732584193,u=-271733879,d=-1732584194,p=271733878,f=0;f<a.length;f++)a[f]=(a[f]<<8|a[f]>>>24)&16711935|(a[f]<<24|a[f]>>>8)&4278255360;a[l>>>5]|=128<<l%32,a[(l+64>>>9<<4)+14]=l;for(var m=r._ff,A=r._gg,y=r._hh,g=r._ii,f=0;f<a.length;f+=16){var v=c,b=u,_=d,S=p;c=m(c,u,d,p,a[f+0],7,-680876936),p=m(p,c,u,d,a[f+1],12,-389564586),d=m(d,p,c,u,a[f+2],17,606105819),u=m(u,d,p,c,a[f+3],22,-1044525330),c=m(c,u,d,p,a[f+4],7,-176418897),p=m(p,c,u,d,a[f+5],12,1200080426),d=m(d,p,c,u,a[f+6],17,-1473231341),u=m(u,d,p,c,a[f+7],22,-45705983),c=m(c,u,d,p,a[f+8],7,1770035416),p=m(p,c,u,d,a[f+9],12,-1958414417),d=m(d,p,c,u,a[f+10],17,-42063),u=m(u,d,p,c,a[f+11],22,-1990404162),c=m(c,u,d,p,a[f+12],7,1804603682),p=m(p,c,u,d,a[f+13],12,-40341101),d=m(d,p,c,u,a[f+14],17,-1502002290),u=m(u,d,p,c,a[f+15],22,1236535329),c=A(c,u,d,p,a[f+1],5,-165796510),p=A(p,c,u,d,a[f+6],9,-1069501632),d=A(d,p,c,u,a[f+11],14,643717713),u=A(u,d,p,c,a[f+0],20,-373897302),c=A(c,u,d,p,a[f+5],5,-701558691),p=A(p,c,u,d,a[f+10],9,38016083),d=A(d,p,c,u,a[f+15],14,-660478335),u=A(u,d,p,c,a[f+4],20,-405537848),c=A(c,u,d,p,a[f+9],5,568446438),p=A(p,c,u,d,a[f+14],9,-1019803690),d=A(d,p,c,u,a[f+3],14,-187363961),u=A(u,d,p,c,a[f+8],20,1163531501),c=A(c,u,d,p,a[f+13],5,-1444681467),p=A(p,c,u,d,a[f+2],9,-51403784),d=A(d,p,c,u,a[f+7],14,1735328473),u=A(u,d,p,c,a[f+12],20,-1926607734),c=y(c,u,d,p,a[f+5],4,-378558),p=y(p,c,u,d,a[f+8],11,-2022574463),d=y(d,p,c,u,a[f+11],16,1839030562),u=y(u,d,p,c,a[f+14],23,-35309556),c=y(c,u,d,p,a[f+1],4,-1530992060),p=y(p,c,u,d,a[f+4],11,1272893353),d=y(d,p,c,u,a[f+7],16,-155497632),u=y(u,d,p,c,a[f+10],23,-1094730640),c=y(c,u,d,p,a[f+13],4,681279174),p=y(p,c,u,d,a[f+0],11,-358537222),d=y(d,p,c,u,a[f+3],16,-722521979),u=y(u,d,p,c,a[f+6],23,76029189),c=y(c,u,d,p,a[f+9],4,-640364487),p=y(p,c,u,d,a[f+12],11,-421815835),d=y(d,p,c,u,a[f+15],16,530742520),u=y(u,d,p,c,a[f+2],23,-995338651),c=g(c,u,d,p,a[f+0],6,-198630844),p=g(p,c,u,d,a[f+7],10,1126891415),d=g(d,p,c,u,a[f+14],15,-1416354905),u=g(u,d,p,c,a[f+5],21,-57434055),c=g(c,u,d,p,a[f+12],6,1700485571),p=g(p,c,u,d,a[f+3],10,-1894986606),d=g(d,p,c,u,a[f+10],15,-1051523),u=g(u,d,p,c,a[f+1],21,-2054922799),c=g(c,u,d,p,a[f+8],6,1873313359),p=g(p,c,u,d,a[f+15],10,-30611744),d=g(d,p,c,u,a[f+6],15,-1560198380),u=g(u,d,p,c,a[f+13],21,1309151649),c=g(c,u,d,p,a[f+4],6,-145523070),p=g(p,c,u,d,a[f+11],10,-1120210379),d=g(d,p,c,u,a[f+2],15,718787259),u=g(u,d,p,c,a[f+9],21,-343485551),c=c+v>>>0,u=u+b>>>0,d=d+_>>>0,p=p+S>>>0}return i.endian([c,u,d,p])};r._ff=function(n,o,a,l,c,u,d){var p=n+(o&a|~o&l)+(c>>>0)+d;return(p<<u|p>>>32-u)+o},r._gg=function(n,o,a,l,c,u,d){var p=n+(o&l|a&~l)+(c>>>0)+d;return(p<<u|p>>>32-u)+o},r._hh=function(n,o,a,l,c,u,d){var p=n+(o^a^l)+(c>>>0)+d;return(p<<u|p>>>32-u)+o},r._ii=function(n,o,a,l,c,u,d){var p=n+(a^(o|~l))+(c>>>0)+d;return(p<<u|p>>>32-u)+o},r._blocksize=16,r._digestsize=16,sF.exports=function(n,o){if(n==null)throw new Error("Illegal argument "+n);var a=i.wordsToBytes(r(n,o));return o&&o.asBytes?a:o&&o.asString?s.bytesToString(a):i.bytesToHex(a)}})();var q$=sF.exports;const Y$=t_(q$);class OM{constructor(e,t,s,r){h(this,"success"),h(this,"filename"),h(this,"hash"),h(this,"size"),h(this,"url"),this.success=e,this.filename=t,this.hash=s,this.size=r}}async function aF(i,e){const t=await i.arrayBuffer(),s=LM(t),r=i.name.split(".").pop(),n=s+"."+r,o=i.name.split(".").shift();console.assert(o!==void 0);const a={alias:o,filename:n},l=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(a)})).json();if(l.success||console.warn("exists check did fail"),l.exists)return console.log("file already exists",s),new OM(!0,n,s,i.size);console.log("begin uploading file",o,i.size);const c=new FormData;c.append("file",i);const u={};u.filesize=i.size,o&&(u.alias=o);const d=await(await fetch(e+"/upload/file",{method:"POST",body:c,headers:u})).json();if(d?.success===!1)return d.message!==void 0?console.error("Upload failed:",d.message):console.error("Upload failed"),null;console.assert(d.hash_sum===s,"hash sum did not match","received:",d.hash_sum,"expected:",s),d.success&&console.log("successfully uploaded",s,d.id);const p=new OM(d.success,n,s,i.size);return p.url=e,p}function LM(i){return Y$(new Uint8Array(i))}async function FM(i,e,t,s,r=!1){try{const n=await fetch(s+"/download/file",{method:"POST",body:i});if(n.status!==200)return console.error("download failed",n),null;const o=await n.blob(),a=await o.arrayBuffer();r||console.assert(o.size===t,"size mismatch","expected:",t,"got:",o.size);const l=LM(a);return r||console.assert(l===e,"hash mismatch, downloaded file is invalid"),o.arrayBuffer()}catch(n){console.error(n)}return null}async function lF(i,e){var t;const s=await fetch(i),r=(t=s.body)==null?void 0:t.getReader(),n=s.headers.get("Content-Length"),o=n?parseInt(n):0;if(!r)return null;let a=0;const l=[];for(;;){const{done:d,value:p}=await r.read();if(p&&(l.push(p),a+=p.length,e.call(null,new ProgressEvent("progress",{loaded:a,total:o}))),d)break}const c=new Uint8Array(a);let u=0;for(const d of l)c.set(d,u),u+=d.length;return c}const yh=te("debugaddressables");class cF{constructor(e){h(this,"_context"),h(this,"_assetReferences",{}),this._context=e,this._context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){}findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.uri&&(this._assetReferences[e.uri]?console.warn("Asset reference already registered",e):this._assetReferences[e.uri]=e),e}dispose(){for(const e in this._assetReferences){const t=this._assetReferences[e];t?.unload()}this._assetReferences={}}unregisterAssetReference(e){e.uri&&delete this._assetReferences[e.uri]}}const UM=Symbol("assetReference"),Vg=class{constructor(i,e,t=null){h(this,"_loading"),h(this,"_asset"),h(this,"_glbRoot"),h(this,"_url"),h(this,"_progressListeners",[]),h(this,"_hash"),h(this,"_hashedUri"),h(this,"_isLoadingRawBinary",!1),h(this,"_rawBinary"),this._url=i,this._hash=e,i.includes("?v=")?this._hashedUri=i:this._hashedUri=e?i+"?v="+e:i,t!==null&&(this.asset=t),DN(this._url,this.onResolvePrefab.bind(this))}static getOrCreate(i,e,t){if(typeof i=="string"){if(!t&&(t=Lt.Current,!t))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.')}else t=i.context,i=i.sourceId;const s=Jl(i,e);yh&&console.log("GetOrCreate Addressable from",i,e,"FinalPath=",s);const r=t.addressables,n=r.findAssetReference(s);if(n)return n;const o=new Vg(s,t.hash);return r.registerAssetReference(o),o}get asset(){return this._glbRoot??this._asset}set asset(i){this._asset=i}get uri(){return this._url}get rawAsset(){return this._asset}async onResolvePrefab(i){return i===this.uri&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||od(this.asset)===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(yh&&console.log("Unload",this.asset),this.asset.scene&&Ca(this.asset.scene,!0,!0),Ca(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loading=void 0,Lt.Current&&Lt.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,yh&&console.log("Preload",this._hashedUri);const i=await lF(this._hashedUri,e=>{this.raiseProgressEvent(e)});return this._rawBinary=i?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(i){if(yh&&console.log("loadAssetAsync",this.uri),!this.mustLoad)return this.asset;if(i&&this._progressListeners.push(i),this._loading!==void 0)return this._loading.then(s=>this.asset);const e=Lt.Current;this._rawBinary?(this._loading=aa().parseSync(e,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(yh&&console.log("Load async",this.uri),this._loading=aa().loadSync(e,this._hashedUri,this.uri,null,s=>{this.raiseProgressEvent(s)}));const t=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(t),this._loading=void 0,t)return t[UM]=this,this._glbRoot&&(this._glbRoot[UM]=this),this.asset&&(this.asset[UM]=this),Qb(e),t.scene!==void 0&&(this.asset=t),this.asset}async instantiate(i){return this.onInstantiate(i,!1)}async instantiateSynced(i,e=!0){return this.onInstantiate(i,!0,e)}beginListenDownload(i){this._progressListeners.indexOf(i)<0&&this._progressListeners.push(i)}endListenDownload(i){const e=this._progressListeners.indexOf(i);e>=0&&this._progressListeners.splice(e,1)}raiseProgressEvent(i){for(const e of this._progressListeners)e(this,i)}async onInstantiate(i,e=!1,t){const s=Lt.Current,r=new Oa;if(i instanceof Ae?r.parent=i:i&&r.cloneAssign(i),r.parent||(r.parent=s.scene),this.mustLoad&&await this.loadAssetAsync(),yh&&console.log("Instantiate",this.uri,"parent:",i),this.asset){yh&&console.log("Add to scene",this.asset);let n=Vg.currentlyInstantiating.get(this.uri);if(n!==void 0&&n>=1e4)return console.error("Recursive or too many instantiations of "+this.uri+" in the same frame ("+n+")"),null;try{if(n===void 0&&(n=0),n+=1,Vg.currentlyInstantiating.set(this.uri,n),e){r.context=s;const o=this.asset;o.guid=this.uri;const a=PT(o,r,void 0,t);if(a)return a}else{const o=cf(this.asset,r);if(o)return o}}finally{s.post_render_callbacks.push(()=>{n===void 0||n<0?n=0:n-=1,Vg.currentlyInstantiating.set(this.uri,n)})}}else yh&&console.warn("Failed to load asset",this.uri);return null}tryGetActualGameObjectRoot(i){if(i&&i.scene){const e=i.scene;return e.isGroup&&e.children.length===1&&e.children[0].name+"glb"===e.name?e.children[0]:e}return null}};let ai=Vg;h(ai,"currentlyInstantiating",new Map);class J$ extends Za{constructor(){super([ai],"AssetReferenceSerializer")}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){if(typeof e=="string")return t.context?t.gltfId?ai.getOrCreate(t.gltfId,e,t.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(e instanceof Ae){if(!t.context)return console.error("Missing context"),null;if(!t.gltfId)return console.error("Missing source id"),null;const s=e,r=t.context,n=s.guid??s.uuid,o=r.addressables.findAssetReference(n);if(o)return o;const a=new ai(n,void 0,s);return r.addressables.registerAssetReference(a),a}return null}}new J$;const K$=Promise.resolve(null),i_=class{constructor(i){h(this,"url"),h(this,"_bitmap"),h(this,"_bitmapObject"),h(this,"loader",null),this.url=i}static getOrCreate(i){let e=i_.imageReferences.get(i);return e||(e=new i_(i),i_.imageReferences.set(i,e)),e}dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const i=new Image;return i.src=this.url,i}createTexture(){return this.url?(this.loader||(this.loader=new Yl),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url)):K$}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((i,e)=>{const t=document.createElement("img");t.addEventListener("load",()=>{this._bitmap=createImageBitmap(t).then(s=>(this._bitmapObject=s,i(s),s))}),t.addEventListener("error",s=>{console.error("Failed to load image:"+this.url,s),i(null)}),t.src=this.url}),this._bitmap)}};let s_=i_;h(s_,"imageReferences",new Map);class hF extends Za{constructor(){super([s_],"ImageReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const s=Jl(t.gltfId,e);return s_.getOrCreate(s)}}}new hF;const r_=class{constructor(i){h(this,"url"),h(this,"res"),this.url=i}static getOrCreate(i){let e=r_.cache.get(i);return e||(e=new r_(i),r_.cache.set(i,e)),e}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(i=>i.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(i=>i.text())}};let n_=r_;h(n_,"cache",new Map);class uF extends Za{constructor(){super([n_],"FileReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const s=Jl(t.gltfId,e);return n_.getOrCreate(s)}}}new uF;const ir={Handedness:Object.freeze({NONE:"none",LEFT:"left",RIGHT:"right"}),ComponentState:Object.freeze({DEFAULT:"default",TOUCHED:"touched",PRESSED:"pressed"}),ComponentProperty:Object.freeze({BUTTON:"button",X_AXIS:"xAxis",Y_AXIS:"yAxis",STATE:"state"}),ComponentType:Object.freeze({TRIGGER:"trigger",SQUEEZE:"squeeze",TOUCHPAD:"touchpad",THUMBSTICK:"thumbstick",BUTTON:"button"}),ButtonTouchThreshold:.05,AxisTouchThreshold:.1,VisualResponseProperty:Object.freeze({TRANSFORM:"transform",VISIBILITY:"visibility"})};async function dF(i){const e=await fetch(i);if(e.ok)return e.json();throw new Error(e.statusText)}async function Z$(i){if(!i)throw new Error("No basePath supplied");return await dF(`${i}/profilesList.json`)}async function $$(i,e,t=null,s=!0){if(!i)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No basePath supplied");const r=await Z$(e);let n;if(i.profiles.some(l=>{const c=r[l];return c&&(n={profileId:l,profilePath:`${e}/${c.path}`,deprecated:!!c.deprecated}),!!n}),!n){if(!t)throw new Error("No matching profile name found");const l=r[t];if(!l)throw new Error(`No matching profile name found and default profile "${t}" missing.`);n={profileId:t,profilePath:`${e}/${l.path}`,deprecated:!!l.deprecated}}const o=await dF(n.profilePath);let a;if(s){let l;if(i.handedness==="any"?l=o.layouts[Object.keys(o.layouts)[0]]:l=o.layouts[i.handedness],!l)throw new Error(`No matching handedness, ${i.handedness}, in profile ${n.profileId}`);l.assetPath&&(a=n.profilePath.replace("profile.json",l.assetPath))}return{profile:o,assetPath:a}}const eee={xAxis:0,yAxis:0,button:0,state:ir.ComponentState.DEFAULT};function tee(i=0,e=0){let t=i,s=e;if(Math.sqrt(i*i+e*e)>1){const r=Math.atan2(e,i);t=Math.cos(r),s=Math.sin(r)}return{normalizedXAxis:t*.5+.5,normalizedYAxis:s*.5+.5}}let iee=class{constructor(i){this.componentProperty=i.componentProperty,this.states=i.states,this.valueNodeName=i.valueNodeName,this.valueNodeProperty=i.valueNodeProperty,this.valueNodeProperty===ir.VisualResponseProperty.TRANSFORM&&(this.minNodeName=i.minNodeName,this.maxNodeName=i.maxNodeName),this.value=0,this.updateFromComponent(eee)}updateFromComponent({xAxis:i,yAxis:e,button:t,state:s}){const{normalizedXAxis:r,normalizedYAxis:n}=tee(i,e);switch(this.componentProperty){case ir.ComponentProperty.X_AXIS:this.value=this.states.includes(s)?r:.5;break;case ir.ComponentProperty.Y_AXIS:this.value=this.states.includes(s)?n:.5;break;case ir.ComponentProperty.BUTTON:this.value=this.states.includes(s)?t:0;break;case ir.ComponentProperty.STATE:this.valueNodeProperty===ir.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(s):this.value=this.states.includes(s)?1:0;break;default:throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}},see=class{constructor(i,e){if(!i||!e||!e.visualResponses||!e.gamepadIndices||Object.keys(e.gamepadIndices).length===0)throw new Error("Invalid arguments supplied");this.id=i,this.type=e.type,this.rootNodeName=e.rootNodeName,this.touchPointNodeName=e.touchPointNodeName,this.visualResponses={},Object.keys(e.visualResponses).forEach(t=>{const s=new iee(e.visualResponses[t]);this.visualResponses[t]=s}),this.gamepadIndices=Object.assign({},e.gamepadIndices),this.values={state:ir.ComponentState.DEFAULT,button:this.gamepadIndices.button!==void 0?0:void 0,xAxis:this.gamepadIndices.xAxis!==void 0?0:void 0,yAxis:this.gamepadIndices.yAxis!==void 0?0:void 0}}get data(){return{id:this.id,...this.values}}updateFromGamepad(i){if(this.values.state=ir.ComponentState.DEFAULT,this.gamepadIndices.button!==void 0&&i.buttons.length>this.gamepadIndices.button){const e=i.buttons[this.gamepadIndices.button];this.values.button=e.value,this.values.button=this.values.button<0?0:this.values.button,this.values.button=this.values.button>1?1:this.values.button,e.pressed||this.values.button===1?this.values.state=ir.ComponentState.PRESSED:(e.touched||this.values.button>ir.ButtonTouchThreshold)&&(this.values.state=ir.ComponentState.TOUCHED)}this.gamepadIndices.xAxis!==void 0&&i.axes.length>this.gamepadIndices.xAxis&&(this.values.xAxis=i.axes[this.gamepadIndices.xAxis],this.values.xAxis=this.values.xAxis<-1?-1:this.values.xAxis,this.values.xAxis=this.values.xAxis>1?1:this.values.xAxis,this.values.state===ir.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>ir.AxisTouchThreshold&&(this.values.state=ir.ComponentState.TOUCHED)),this.gamepadIndices.yAxis!==void 0&&i.axes.length>this.gamepadIndices.yAxis&&(this.values.yAxis=i.axes[this.gamepadIndices.yAxis],this.values.yAxis=this.values.yAxis<-1?-1:this.values.yAxis,this.values.yAxis=this.values.yAxis>1?1:this.values.yAxis,this.values.state===ir.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>ir.AxisTouchThreshold&&(this.values.state=ir.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(e=>{e.updateFromComponent(this.values)})}},ree=class{constructor(i,e,t){if(!i)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No profile supplied");this.xrInputSource=i,this.assetUrl=t,this.id=e.profileId,this.layoutDescription=e.layouts[i.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(s=>{const r=this.layoutDescription.components[s];this.components[s]=new see(s,r)}),this.updateFromGamepad()}get gripSpace(){return this.xrInputSource.gripSpace}get targetRaySpace(){return this.xrInputSource.targetRaySpace}get data(){const i=[];return Object.values(this.components).forEach(e=>{i.push(e.data)}),i}updateFromGamepad(){Object.values(this.components).forEach(i=>{i.updateFromGamepad(this.xrInputSource.gamepad)})}};class Ei extends we{constructor(e,t,s,r){super(e,t,s),h(this,"alpha",1),this.alpha=r}get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return super.copy(e),"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){const s=e;return s.alpha&&(this.alpha=st.lerp(this.alpha,s.alpha,t)),super.lerp(e,t)}lerpColors(e,t,s){const r=e,n=t;return r.alpha&&n.alpha&&(this.alpha=st.lerp(r.alpha,n.alpha,s)),super.lerpColors(e,t,s)}multiply(e){const t=e;return t.alpha&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}fromArray(e,t=0){return this.alpha=e[t+3],super.fromArray(e,t)}}const bn=new w,pF=new w,fF=new Ie,nee=te("debuggizmos"),cc=8947848,$a=class{static isGizmo(i){return i[zM]!==void 0}static DrawLabel(i,e,t=.05,s=0,r,n,o){var a;if(!$a.enabled)return null;r||(r=cc);const l=((a=mt.active)==null?void 0:a.rigScale)??1,c=Ds.getTextLabel(s,e,t*l,r,n);return o instanceof Ae&&o.add(c),c.position.x=i.x,c.position.y=i.y,c.position.z=i.z,c}static DrawRay(i,e,t=cc,s=0,r=!0){if(!$a.enabled)return;const n=Ds.getLine(s),o=n.geometry.getAttribute("position");o.setXYZ(0,i.x,i.y,i.z),bn.set(e.x,e.y,e.z).multiplyScalar(999999999),o.setXYZ(1,i.x+bn.x,i.y+bn.y,i.z+bn.z),o.needsUpdate=!0,n.material.color.set(t),n.material.depthTest=r,n.material.depthWrite=!1}static DrawDirection(i,e,t=cc,s=0,r=!0,n=1){if(!$a.enabled)return;const o=Ds.getLine(s),a=o.geometry.getAttribute("position");a.setXYZ(0,i.x,i.y,i.z),e.w!==void 0?(bn.set(0,0,-n),fF.set(e.x,e.y,e.z,e.w),bn.applyQuaternion(fF)):(bn.set(e.x,e.y,e.z),bn.multiplyScalar(n)),a.setXYZ(1,i.x+bn.x,i.y+bn.y,i.z+bn.z),a.needsUpdate=!0,o.material.color.set(t),o.material.depthTest=r,o.material.depthWrite=!1}static DrawLine(i,e,t=cc,s=0,r=!0){if(!$a.enabled)return;const n=Ds.getLine(s),o=n.geometry.getAttribute("position");o.setXYZ(0,i.x,i.y,i.z),o.setXYZ(1,e.x,e.y,e.z),o.needsUpdate=!0,n.material.color.set(t),n.material.depthTest=r,n.material.depthWrite=!1}static DrawWireSphere(i,e,t=cc,s=0,r=!0){if(!$a.enabled)return;const n=Ds.getSphere(e,s,!0);Qu(n,i.x,i.y,i.z),n.material.color.set(t),n.material.depthTest=r,n.material.depthWrite=!1}static DrawSphere(i,e,t=cc,s=0,r=!0){if(!$a.enabled)return;const n=Ds.getSphere(e,s,!1);Qu(n,i.x,i.y,i.z),n.material.color.set(t),n.material.depthTest=r,n.material.depthWrite=!1}static DrawWireBox(i,e,t=cc,s=0,r=!0){if(!$a.enabled)return;const n=Ds.getBox(s);n.position.set(i.x,i.y,i.z),n.scale.set(e.x,e.y,e.z),n.material.color.set(t),n.material.depthTest=r,n.material.wireframe=!0,n.material.depthWrite=!1}static DrawWireBox3(i,e=cc,t=0,s=!0){if(!$a.enabled)return;const r=Ds.getBox(t);r.position.copy(i.getCenter(bn)),r.scale.copy(i.getSize(bn)),r.material.color.set(e),r.material.depthTest=s,r.material.wireframe=!0,r.material.depthWrite=!1}static DrawArrow(i,e,t=cc,s=0,r=!0,n=!1){if(!$a.enabled)return;const o=Ds.getArrowHead(s);o.position.set(e.x,e.y,e.z),o.quaternion.setFromUnitVectors(this._up.set(0,1,0),bn.set(e.x,e.y,e.z).sub(pF.set(i.x,i.y,i.z)).normalize());const a=bn.set(e.x,e.y,e.z).sub(pF.set(i.x,i.y,i.z)).length()*.1;o.scale.set(a,a,a),o.material.color.set(t),o.material.depthTest=r,o.material.wireframe=n,this.DrawLine(i,e,t,s,r)}};let Tt=$a;h(Tt,"enabled",!0),h(Tt,"_up",new w(0,1,0));const oee=new Ni(1,1,1);function NM(i=null){const e=new we(i??14540253),t=new pC(oee);return new io(t,new xs({color:e}))}const zM=Symbol("GizmoCache");class Ds{static ensureFont(){let e=zn.FontLibrary.getFontFamily(this.familyName);if(!e){e=zn.FontLibrary.addFontFamily(this.familyName);const t=e.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png");t?.addEventListener("ready",()=>{zn.update()})}}static getTextLabel(e,t,s,r,n){this.ensureFont();let o=this.textLabelCache.pop(),a=1;n&&typeof n=="string"&&n?.length>=8&&n.startsWith("#")?(a=parseInt(n.substring(7),16)/255,n=n.substring(0,7),nee&&console.log(n,a)):typeof n=="object"&&n.a!==void 0&&(a=n.a);const l={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:s,color:r,lineHeight:1,backgroundColor:n??void 0,backgroundOpacity:a,textContent:t,borderRadius:.5*s,padding:.8*s,whiteSpace:"pre"};if(o)o.set(l);else{o=new VE(l);const c=this,u=o;u.setText=function(d){this.set({textContent:d}),c.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(Lt.Current,o,e,this.textLabelCache),o}static getBox(e){let t=this.boxesCache.pop();if(!t){const s=new Ni(1,1,1);t=new ge(s)}return this.registerTimedObject(Lt.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new ws;let s=t.geometry.getAttribute("position");s||(s=new Ze(new Float32Array(2*3),3),t.geometry.setAttribute("position",s))}return t.frustumCulled=!1,this.registerTimedObject(Lt.Current,t,e,this.linesCache),t}static getSphere(e,t,s){let r=this.spheresCache.pop();return r||(r=new ge(new ka(1,8,8))),r.scale.set(e,e,e),r.material.wireframe=s,this.registerTimedObject(Lt.Current,r,t,this.spheresCache),r}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new ge(new Ts(0,.5,1,8))),this.registerTimedObject(Lt.Current,t,e,this.arrowHeadsCache),t}static registerTimedObject(e,t,s,r){const n=this.contextBeforeRenderCallbacks.get(e),o=this.contextPostRenderCallbacks.get(e);if(n){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==n){const a=e.pre_render_callbacks.indexOf(n);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(n)}}else{const a=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,a),e.pre_render_callbacks.push(a)}if(o){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==o){const a=e.post_render_callbacks.indexOf(o);a>=0&&e.post_render_callbacks.splice(a,1),e.post_render_callbacks.push(o)}}else{const a=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,a),e.post_render_callbacks.push(a)}t.traverse(a=>{a.layers.disableAll(),a.layers.enable(2)}),t.renderOrder=999999,t[zM]=r,this.timedObjectsBuffer.push(t),this.timesBuffer.push(Lt.Current.time.realtimeSinceStartup+s),e.scene.add(t)}static onBeforeRender(e,t){this.tmuiNeedsUpdate&&zn.update();for(let s=0;s<t.length;s++){const r=t[s];if(e.mainCamera&&r instanceof zn.MeshUIBaseElement){if(od(r))continue;const n=e.isInVR,o=!1,a=!n;Ib(r,e.mainCamera,o,a)}}}static onPostRender(e,t,s){const r=e.time.realtimeSinceStartup;for(let n=t.length-1;n>=0;n--){const o=t[n];r>s[n]&&(t.splice(n,1),s.splice(n,1),o.removeFromParent(),od(o)!=!0&&o[zM].push(o))}}}h(Ds,"familyName","needle-gizmos"),h(Ds,"linesCache",[]),h(Ds,"spheresCache",[]),h(Ds,"boxesCache",[]),h(Ds,"arrowHeadsCache",[]),h(Ds,"textLabelCache",[]),h(Ds,"timedObjectsBuffer",new Array),h(Ds,"timesBuffer",new Array),h(Ds,"contextPostRenderCallbacks",new Map),h(Ds,"contextBeforeRenderCallbacks",new Map),h(Ds,"tmuiNeedsUpdate",!1);const br=te("debuginput");var o_=(i=>(i.Mouse="mouse",i.Touch="touch",i.Controller="controller",i.Hand="hand",i))(o_||{}),Ki=(i=>(i.PointerDown="pointerdown",i.PointerUp="pointerup",i.PointerMove="pointermove",i.KeyDown="keydown",i.KeyUp="keyup",i.KeyPressed="keypress",i))(Ki||{});class hc extends PointerEvent{constructor(e,t,s){super(e,s),h(this,"deviceIndex"),h(this,"origin"),h(this,"source"),h(this,"mode"),h(this,"ray"),h(this,"space"),h(this,"isClick",!1),h(this,"isDoubleClick",!1),h(this,"_used",!1),h(this,"_pointerid"),h(this,"_pointerType"),h(this,"_type"),h(this,"_immediatePropagationStopped",!1),h(this,"_propagationStopped",!1),this._pointerid=s.pointerId,this._pointerType=s.pointerType,this._type=e,this.deviceIndex=s.deviceIndex,this.origin=s.origin,this.source=t,this.mode=s.mode,this.ray=s.ray,this.space=s.device}get used(){return this._used}use(){this._used=!0}get pointerId(){return this._pointerid}get pointerType(){return this._pointerType}get type(){return this._type}get immediatePropagationStopped(){return this._immediatePropagationStopped}get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){var e;this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}stopPropagation(){var e;this._propagationStopped=!0,super.stopPropagation(),(e=this.source)==null||e.stopPropagation()}}class Hg extends KeyboardEvent{constructor(e,t,s){super(e,s),h(this,"source"),this.source=t}stopImmediatePropagation(){var e;super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}}class aee{constructor(e){h(this,"key"),h(this,"keyType"),h(this,"source"),this.key=e.key,this.keyType=e.type,this.source=e}}var el=(i=>(i[i.Early=-100]="Early",i[i.Default=0]="Default",i[i.Late=100]="Late",i))(el||{});class mF{constructor(e){h(this,"_eventListeners",{}),h(this,"_doubleClickTimeThreshold",.2),h(this,"_longPressTimeThreshold",1),h(this,"_specialCursorTrigger",0),h(this,"context"),h(this,"_pointerDown",[!1]),h(this,"_pointerUp",[!1]),h(this,"_pointerClick",[!1]),h(this,"_pointerDoubleClick",[!1]),h(this,"_pointerPressed",[!1]),h(this,"_pointerPositions",[new ee]),h(this,"_pointerPositionsLastFrame",[new ee]),h(this,"_pointerPositionsDelta",[new ee]),h(this,"_pointerPositionsRC",[new ee]),h(this,"_pointerPositionDown",[new ee]),h(this,"_pointerDownTime",[]),h(this,"_pointerUpTime",[]),h(this,"_pointerUpTimestamp",[]),h(this,"_pointerIds",[]),h(this,"_pointerTypes",[""]),h(this,"_mouseWheelChanged",[!1]),h(this,"_mouseWheelDeltaY",[0]),h(this,"_pointerEvent",[]),h(this,"_pointerUsed",[]),h(this,"_pointerSpace",[]),h(this,"_pressedStack",new Map),h(this,"_htmlEventSource"),h(this,"onLostFocus",()=>{for(const t in this.keysPressed)this.keysPressed[t].pressed=!1}),h(this,"onEndOfFrame",()=>{for(let t=0;t<this._pointerUp.length;t++)this._pointerUp[t]=!1;for(let t=0;t<this._pointerDown.length;t++)this._pointerDown[t]=!1;for(let t=0;t<this._pointerClick.length;t++)this._pointerClick[t]=!1;for(let t=0;t<this._pointerDoubleClick.length;t++)this._pointerDoubleClick[t]=!1;for(const t of this._pointerPositionsDelta)t.set(0,0);for(let t=0;t<this._mouseWheelChanged.length;t++)this._mouseWheelChanged[t]=!1;for(let t=0;t<this._mouseWheelDeltaY.length;t++)this._mouseWheelDeltaY[t]=0}),h(this,"onContextMenu",t=>{this.canReceiveInput(t)!==!1&&t instanceof PointerEvent&&t.pointerType}),h(this,"keysPressed",{}),h(this,"onKeyDown",t=>{if(br&&console.log(`key down ${t.code}, ${this.context.application.hasFocus}`,t),!this.context.application.hasFocus)return;const s=this.keysPressed[t.code];if(s&&s.pressed)return;this.keysPressed[t.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:t.key,code:t.code};const r=new Hg("keydown",t,t);this.onDispatchEvent(r)}),h(this,"onKeyPressed",t=>{if(!this.context.application.hasFocus)return;const s=this.keysPressed[t.code];if(!s)return;s.pressed=!0,s.frame=this.context.time.frameCount+1;const r=new Hg("keypress",t,t);this.onDispatchEvent(r)}),h(this,"onKeyUp",t=>{if(!this.context.application.hasFocus)return;const s=this.keysPressed[t.code];if(!s)return;s.pressed=!1,s.frame=this.context.time.frameCount+1;const r=new Hg("keyup",t,t);this.onDispatchEvent(r)}),h(this,"onMouseWheel",t=>{if(this.canReceiveInput(t)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const s=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=s+t.deltaY}),h(this,"onTouchStartWindow",t=>{this.context.isInAR&&this.onTouchStart(t)}),h(this,"onTouchStart",t=>{if(!(t.changedTouches.length<=0)&&this.canReceiveInput(t)!==!1)for(let s=0;s<t.changedTouches.length;s++){const r=t.changedTouches[s],n=this.getPointerIndex(r.identifier);br&&rs(`touch start #${n}, identifier:${r.identifier}`);const o=this.getAndUpdateSpatialObjectForScreenPosition(n,r.clientX,r.clientY),a=new hc("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:r.clientX,clientY:r.clientY,pointerType:"touch",buttonName:"unknown",device:o,pressure:r.force});this.onDown(a)}}),h(this,"onTouchMove",t=>{if(!(t.changedTouches.length<=0))for(let s=0;s<t.changedTouches.length;s++){const r=t.changedTouches[s],n=this.getPointerIndex(r.identifier),o=this.getAndUpdateSpatialObjectForScreenPosition(n,r.clientX,r.clientY),a=new hc("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:r.clientX,clientY:r.clientY,pointerType:"touch",buttonName:"unknown",device:o,pressure:r.force});this.onMove(a)}}),h(this,"onTouchUp",t=>{if(!(t.changedTouches.length<=0))for(let s=0;s<t.changedTouches.length;s++){const r=t.changedTouches[s],n=this.getPointerIndex(r.identifier);if(!this.isNewEvent(t.timeStamp,n,this._pointerUpTimestamp))continue;const o=this.createPointerEventFromTouch("pointerup",r.identifier,r.clientX,r.clientY,r.force,t);this.onUp(o),this._pointerIds.splice(this._pointerIds.indexOf(n),1)}}),h(this,"onTouchCancel",t=>{}),h(this,"onMouseDown",t=>{if(this.onDownButton(0,t.button),this.context.isInVR||t.defaultPrevented||this.canReceiveInput(t)===!1)return;const s=t.button;let r="none";switch(s){case 0:r="left";break;case 1:r="middle";break;case 2:r="right";break}const n=0+s,o=this.getAndUpdateSpatialObjectForScreenPosition(n,t.clientX,t.clientY),a=new hc("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:s,clientX:t.clientX,clientY:t.clientY,pointerType:"mouse",buttonName:r,device:o,pressure:1});this.onDown(a)}),h(this,"onMouseMove",t=>{if(this.context.isInVR||t.defaultPrevented)return;const s=this.getFirstPressedButtonForPointer(0),r=s??0,n=0+r,o=this.getAndUpdateSpatialObjectForScreenPosition(n,t.clientX,t.clientY),a=s!==void 0?1:0,l=new hc("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:r,clientX:t.clientX,clientY:t.clientY,pointerType:"mouse",buttonName:"none",device:o,pressure:a});this.onMove(l)}),h(this,"onMouseUp",t=>{if(this.onReleaseButton(0,t.button),this.context.isInVR)return;const s=t.button;if(!this.isNewEvent(t.timeStamp,s,this._pointerUpTimestamp))return;let r="none";switch(s){case 0:r="left";break;case 1:r="middle";break;case 2:r="right";break}const n=0+s;if(t.defaultPrevented)return;const o=this.getAndUpdateSpatialObjectForScreenPosition(n,t.clientX,t.clientY),a=new hc("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:s,clientX:t.clientX,clientY:t.clientY,pointerType:"mouse",buttonName:r,device:o,pressure:0});this.onUp(a)}),h(this,"tempNearPlaneVector",new w),h(this,"tempFarPlaneVector",new w),h(this,"tempLookMatrix",new Te),this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(e,t,s){this._eventListeners[e]||(this._eventListeners[e]=[]);let r=0;s?.queue!=null&&(r=s.queue);const n=this._eventListeners[e],o=n.find(a=>a.priority===r);o?o.listeners.push(t):(n.push({priority:r,listeners:[t]}),n.sort((a,l)=>a.priority-l.priority))}removeEventListener(e,t,s){if(!this._eventListeners[e])return;const r=this._eventListeners[e];if(s?.queue!=null){const n=r.find(a=>a.priority===s.queue);if(!n)return;const o=n.listeners.indexOf(t);o>=0&&n.listeners.splice(o,1)}else for(const n of r){const o=n.listeners.indexOf(t);o>=0&&n.listeners.splice(o,1)}}dispatchEvent(e){let t=!1;if(e instanceof Hg){const s=this._eventListeners[e.type];if(s)for(const r of s)for(const n of r.listeners)n(e)}if(e instanceof hc){const s=this._eventListeners[e.type];if(s)for(const r of s){if(t)break;for(const n of r.listeners){if(e.immediatePropagationStopped){t=!0,br&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(t=!0,br&&console.log("propagationStopped",e.type));n(e)}}}}get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}setCursorPointer(){this._specialCursorTrigger+=1,this.context.domElement.style.cursor="pointer"}setCursorNormal(){this._specialCursorTrigger-=1,this._specialCursorTrigger=Math.max(0,this._specialCursorTrigger),this._specialCursorTrigger===0&&(this.context.domElement.style.cursor="default")}setPointerUsed(e,t=!0){if(e>=this._pointerUsed.length){if(e>=this._pointerIds.length)return;for(;this._pointerUsed.length<=e;)this._pointerUsed.push(!1)}this._pointerUsed[e]=t}getPointerUsed(e){return e>=this._pointerUsed.length?!1:this._pointerUsed[e]}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}*foreachPointerId(e){for(let t=0;t<this._pointerTypes.length;t++)if(this._pointerIsActive(t)){if(e!==void 0){const s=this._pointerTypes[t];if(Array.isArray(e)){let r=!1;for(const n of e)if(s===n){r=!0;break}if(!r)continue}else if(e!==s)continue}yield t}}*foreachTouchId(){for(let e=0;e<this._pointerTypes.length;e++)this._pointerTypes[e]==="touch"&&this._pointerIsActive[e]&&(yield e)}_pointerIsActive(e){return e<0?!1:this._pointerPressed[e]||this._pointerDown[e]||this._pointerUp[e]}onDownButton(e,t){let s=this._pressedStack.get(e);s||(s=[],this._pressedStack.set(e,s)),s.push(t)}onReleaseButton(e,t){const s=this._pressedStack.get(e);if(!s)return;const r=s.indexOf(t);r>=0&&s.splice(r,1)}getFirstPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[0]}getLatestPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[t.length-1]}getKeyDown(){for(const e in this.keysPressed){const t=this.keysPressed[e];if(t.startFrame===this.context.time.frameCount)return t.key}return null}getKeyPressed(){for(const e in this.keysPressed){const t=this.keysPressed[e];if(t.pressed)return t.key}return null}isKeyDown(e){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const s=this.getCodeForCommonKeyName(e);if(s!==null){for(const r of s)if(this.isKeyDown(r))return!0;return!1}return((t=this.keysPressed[e])==null?void 0:t.startFrame)===this.context.time.frameCount&&this.keysPressed[e].pressed}isKeyUp(e){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const s=this.getCodeForCommonKeyName(e);if(s!==null){for(const r of s)if(this.isKeyUp(r))return!0;return!1}return((t=this.keysPressed[e])==null?void 0:t.frame)===this.context.time.frameCount&&!this.keysPressed[e].pressed}isKeyPressed(e){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const s=this.getCodeForCommonKeyName(e);if(s!==null){for(const r of s)if(this.isKeyPressed(r))return!0;return!1}return(t=this.keysPressed[e])==null?void 0:t.pressed}getCodeForCommonKeyName(e){if(e.length===1){if(e>="0"&&e<="9")return["Digit"+e];if(e>="a"&&e<="z")return["Key"+e.toUpperCase()];if(e==" ")return["Space"]}switch(e){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(e){switch(e.type){case"pointerdown":br&&rs("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":br&&rs("Create Pointer move"),this.onMove(e);break;case"pointerup":br&&rs("Create Pointer up"),this.onUp(e),this.onReleaseButton(e.deviceIndex,e.button);break}}convertScreenspaceToRaycastSpace(e){e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1}bindEvents(){this.unbindEvents(),this._htmlEventSource=this.context.renderer.domElement,window.addEventListener("contextmenu",this.onContextMenu),this._htmlEventSource.addEventListener("touchstart",this.onTouchStart,!1),window.addEventListener("touchstart",this.onTouchStartWindow),window.addEventListener("touchmove",this.onTouchMove,{passive:!0}),window.addEventListener("touchend",this.onTouchUp,!1),window.addEventListener("touchcancel",this.onTouchCancel,!1),this._htmlEventSource.addEventListener("mousedown",this.onMouseDown),window.addEventListener("mousemove",this.onMouseMove,!1),window.addEventListener("mouseup",this.onMouseUp,!1),this._htmlEventSource.addEventListener("wheel",this.onMouseWheel,{passive:!0}),window.addEventListener("keydown",this.onKeyDown,!1),window.addEventListener("keypress",this.onKeyPressed,!1),window.addEventListener("keyup",this.onKeyUp,!1),window.addEventListener("blur",this.onLostFocus)}unbindEvents(){var e,t,s;window.removeEventListener("contextmenu",this.onContextMenu),(e=this._htmlEventSource)==null||e.removeEventListener("touchstart",this.onTouchStart,!1),window.removeEventListener("touchstart",this.onTouchStartWindow),window.removeEventListener("touchmove",this.onTouchMove,!1),window.removeEventListener("touchend",this.onTouchUp,!1),window.removeEventListener("touchcancel",this.onTouchCancel,!1),(t=this._htmlEventSource)==null||t.removeEventListener("mousedown",this.onMouseDown,!1),window.removeEventListener("mousemove",this.onMouseMove,!1),window.removeEventListener("mouseup",this.onMouseUp,!1),(s=this._htmlEventSource)==null||s.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}dispose(){const e=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);e>=0&&this.context.post_render_callbacks.splice(e,1),this.unbindEvents()}canReceiveInput(e){var t;return!!(e.target===((t=this.context.renderer)==null?void 0:t.domElement)||e.target===this.context.domElement||this.context.isInAR&&e.target===document.body&&Uu())}createPointerEventFromTouch(e,t,s,r,n,o){const a=this.getPointerIndex(t);br&&rs(`touch up #${a}, identifier:${t}`);const l=this.getAndUpdateSpatialObjectForScreenPosition(a,s,r);return new hc(e,o,{origin:this,mode:"screen",deviceIndex:0,pointerId:a,button:0,clientX:s,clientY:r,pointerType:"touch",buttonName:"unknown",device:l,pressure:n})}getAndUpdateSpatialObjectForScreenPosition(e,t,s){let r=this._pointerSpace[e];r||(r=new Ae,this._pointerSpace[e]=r),this._pointerSpace[e]=r;const n=this.context.mainCamera;if(n){const o=this.tempNearPlaneVector.set(t,s,-1);this.convertScreenspaceToRaycastSpace(o);const a=this.tempFarPlaneVector.set(o.x,o.y,1);o.unproject(n),a.unproject(n),this.tempLookMatrix.lookAt(a,o,n.worldUp),r.position.set(o.x,o.y,o.z),r.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return r}isNewEvent(e,t,s){for(;s.length<=t;)s.push(-1);return e===s[t]?!1:(s[t]=e,!0)}isInRect(e){if(this.context.isInXR)return!0;const t=this.context.domElement.getBoundingClientRect(),s=e.clientX,r=e.clientY,n=s>=t.x&&s<=t.right&&r>=t.y&&r<=t.bottom;return br&&!n&&console.log("Not in rect",t,s,r),n}onDown(e){const t=e.pointerId;if(this.getPointerPressed(t)&&console.warn(`pointerId is already pressed: ${t}`,br?e:""),br&&console.log(e.pointerType,"DOWN",t),!!this.isInRect(e)&&!this.isMouseEventFromTouch(e)){for(this.setPointerState(t,this._pointerPressed,!0),this.setPointerState(t,this._pointerDown,!0),this.setPointerStateT(t,this._pointerEvent,e.source);t>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[t]=e.pointerType;t>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new ee);for(this._pointerPositionDown[t].set(e.clientX,e.clientY);t>=this._pointerPositions.length;)this._pointerPositions.push(new ee);this._pointerPositions[t].set(e.clientX,e.clientY),t>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t]=this.context.time.time,this.updatePointerPosition(e),this.onDispatchEvent(e)}}onMove(e){const t=e.pointerId,s=this.getPointerPressed(t);s===!1&&!this.isInRect(e)||e.pointerType==="touch"&&!s||this.isMouseEventFromTouch(e)||(br&&console.log(e.pointerType,"MOVE",t,"hasSpace="+e.space!=null),this.updatePointerPosition(e),this.setPointerStateT(t,this._pointerEvent,e.source),this.onDispatchEvent(e))}onUp(e){const t=e.pointerId;if(!this.getPointerPressed(t)){br&&console.log(e.pointerType,"UP",t,"was not down");return}if(this.isMouseEventFromTouch(e))return;for(br&&console.log(e.pointerType,"UP",t),this.setPointerState(t,this._pointerPressed,!1),this.setPointerStateT(t,this._pointerEvent,e.source),this.setPointerState(t,this._pointerUp,!0);t>=this._pointerUsed.length;)this._pointerUsed.push(!1);if(this.setPointerState(t,this._pointerUsed,!1),this.updatePointerPosition(e),!this._pointerPositionDown[t]){br&&ns("Received pointer up event without matching down event for button: "+t),console.warn("Received pointer up event without matching down event for button: "+t);return}const s=e.clientX-this._pointerPositionDown[t].x,r=e.clientY-this._pointerPositionDown[t].y;if(t>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),Math.abs(s)<5&&Math.abs(r)<5){br&&console.log("CLICK",t),this.setPointerState(t,this._pointerClick,!0),e.isClick=!0;const n=this._pointerUpTime[t],o=this.context.time.time-n;o<this._doubleClickTimeThreshold&&o>0&&(this.setPointerState(t,this._pointerDoubleClick,!0),e.isDoubleClick=!0)}this._pointerUpTime[t]=this.context.time.time,this.onDispatchEvent(e)}isMouseEventFromTouch(e){var t;if(e.pointerType==="mouse"){const s=this._pointerUpTimestamp.map((r,n)=>({timestamp:r,index:n})).sort((r,n)=>r.timestamp-n.timestamp).at(-1);if(s&&this._pointerTypes[s.index]==="touch"&&s.timestamp>0&&((t=e.source)==null?void 0:t.timeStamp)!==void 0){const r=e.source.timeStamp-s.timestamp;if(r<320&&r>=0)return br&&console.log("Ignoring mouse.down for touch.up"),!0}}return!1}updatePointerPosition(e){const t=e.pointerId;for(;t>=this._pointerPositions.length;)this._pointerPositions.push(new ee);for(;t>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new ee);for(;t>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new ee);const s=this._pointerPositionsLastFrame[t];s.copy(this._pointerPositions[t]);const r=this._pointerPositionsDelta[t];let n=e.clientX-s.x,o=e.clientY-s.y;if(e.source instanceof MouseEvent||e.source instanceof TouchEvent){const u=e.source;n===0&&u.movementX!==0&&(n=u.movementX||0),o===0&&u.movementY!==0&&(o=u.movementY||0)}r.x+=n,r.y+=o,this._pointerPositions[t].x=e.clientX,this._pointerPositions[t].y=e.clientY;const a=e.clientX,l=e.clientY;for(;t>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new ee);const c=this._pointerPositionsRC[t];c.set(a,l),this.convertScreenspaceToRaycastSpace(c)}getPointerIndex(e){const t=this._pointerIds;let s=-1;for(let r=0;r<t.length;r++){if(t[r]===e)return r;s===-1&&t[r]===-1&&(s=r)}return s!==-1?(t[s]=e,s):(t.push(e),t.length-1)}setPointerState(e,t,s){t[e]=s}setPointerStateT(e,t,s){return t[e]=s,s}onDispatchEvent(e){const t=Lt.Current;try{Lt.Current=this.context,this.dispatchEvent(e)}finally{Lt.Current=t}}}const a_=new Te().makeRotationY(Math.PI),_a=new Ie().setFromAxisAngle(new w(0,1,0),Math.PI),lee=te("debugwebxr");class cee{constructor(){if(h(this,"priority",-1e5),h(this,"gameObject"),this.gameObject=new Ae,this.gameObject.name="Implicit XR Rig",lee){const e=NM(16733661);e.position.y+=.5,this.gameObject.add(e)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const bh=te("debugwebxr"),Wg=te("debugcustomgesture");let jM=!1;const hee="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",uee="generic-trigger";class GM{constructor(e,t,s){h(this,"xr"),h(this,"inputSource"),h(this,"index",0),h(this,"emitEvents",!0),h(this,"_connected",!0),h(this,"_isTracking",!1),h(this,"_hitTestSource"),h(this,"_handJointPoses",new Map),h(this,"_gripPosition",new w),h(this,"_gripQuaternion",new Ie),h(this,"_linearVelocity",new w),h(this,"_rayPosition",new w),h(this,"_rayQuaternion",new Ie),h(this,"_gripWorldPosition",new w),h(this,"_gripWorldQuaternion",new Ie),h(this,"_rayWorldPosition",new w),h(this,"_rayWorldQuaternion",new Ie),h(this,"_ray"),h(this,"_object"),h(this,"_debugAxesHelper",new Ro(.2)),h(this,"_needleGamepadButtons",{}),h(this,"_buttonMap",new Map),h(this,"_motioncontroller"),h(this,"_layout"),h(this,"getMotionController"),h(this,"_selectButtonIndex"),h(this,"_squeezeButtonIndex"),h(this,"onSelectStart",a=>{var l,c,u,d;if(this.inputSource!==a.inputSource)return;const p=(l=this._layout)==null?void 0:l.selectComponentId,f=(d=(u=(c=this._layout)==null?void 0:c.components[p])==null?void 0:u.gamepadIndices)==null?void 0:d.button;if(f!==void 0&&(this._selectButtonIndex=f),!Wg){if(!jM){jM=!0;const m=this.getGesture("pinch");if(m!=null&&m.pressed){console.warn("Select start event was received but the pinch gesture is already down. This might happen the first time you start pinching",this.index,this.side);return}}bh&&Tt.DrawDirection(this.rayWorldPosition,Bs(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(Ki.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,a)}}),h(this,"onSelectEnd",a=>{Wg||this.inputSource===a.inputSource&&this.emitPointerEvent(Ki.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,a)}),h(this,"onSequeezeStart",a=>{var l,c,u;this.inputSource===a.inputSource&&(this._squeezeButtonIndex=(u=(c=(l=this._layout)==null?void 0:l.components["xr-standard-squeeze"])==null?void 0:c.gamepadIndices)==null?void 0:u.button,this._squeezeButtonIndex!==void 0&&(bh&&Tt.DrawDirection(this.rayWorldPosition,Bs(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(Ki.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,a)))}),h(this,"onSequeezeEnd",a=>{this.inputSource===a.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(Ki.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,a)}),h(this,"states",{}),h(this,"_didMoveLastFrame",!1),h(this,"_lastPointerMovePosition",new w),h(this,"_lastPointerMoveQuaternion",new Ie),h(this,"pointerInit");var r,n,o;this.xr=e,this.inputSource=t,this.index=s,this._object=new Ae,bh&&this._object.add(this._debugAxesHelper),this.xr.context.scene.add(this._object),this._ray=new Zn,this.pointerInit={origin:this,pointerType:this.hand?"hand":"controller",deviceIndex:this.index,pointerId:-1,mode:this.inputSource.targetRayMode,ray:this._ray,device:this._object,buttonName:"none"},this.initialize(),this.subscribeEvents(),this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&((o=(n=(r=this.xr.session).requestHitTestSourceForTransientInput)==null?void 0:n.call(r,{profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null||o.then(a=>this._hitTestSource=a))}get context(){return this.xr.context}get connected(){return this._connected}get isTracking(){return this._isTracking}get gamepad(){return this.inputSource.gamepad}get isHand(){return this.inputSource.hand!=null}get hand(){return this.inputSource.hand}get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.inputSource.handedness}get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get hitTestSource(){return this._hitTestSource}getHitTest(){return this.xr.getHitTest(this)}getHandJointPose(e){var t,s;if(!this.hand||!((t=this.xr.frame)!=null&&t.getJointPose)||!this.xr.referenceSpace)return null;let r=(s=this._handJointPoses)==null?void 0:s.get(e);return r||(r=this.xr.frame.getJointPose(e,this.xr.referenceSpace),r&&this._handJointPoses.set(e,r),r)}get gripPosition(){return Bs(this._gripPosition).applyMatrix4(a_)}get gripQuaternion(){return Gu(this._gripQuaternion).premultiply(_a)}get gripLinearVelocity(){return Bs(this._linearVelocity).applyQuaternion(_a)}get rayPosition(){return Bs(this._rayPosition).applyMatrix4(a_)}get rayQuaternion(){return Gu(this._rayQuaternion).premultiply(_a)}get gripWorldPosition(){return Bs(this._gripWorldPosition)}get gripWorldQuaternion(){return Gu(this._gripWorldQuaternion)}get rayWorldPosition(){return Bs(this._rayWorldPosition)}updateRayWorldPosition(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent;this._rayWorldPosition.copy(this._rayPosition),t&&this._rayWorldPosition.applyMatrix4(t.matrixWorld)}get rayWorldQuaternion(){return Gu(this._rayWorldQuaternion)}updateRayWorldQuaternion(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent,s=t?Ri(t):void 0;this._rayWorldQuaternion.copy(this._rayQuaternion).multiply(_a),s&&this._rayWorldQuaternion.premultiply(s)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(Bs(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}get object(){return this._object}async getModelUrl(){var e;return(e=this.getMotionController)==null?void 0:e.then(t=>t?.assetUrl||null)}onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){var e;Tt.DrawWireSphere(this.rayWorldPosition,.02),Tt.DrawDirection(this.rayWorldPosition,Bs(0,0,10).applyQuaternion(this.rayWorldQuaternion));const t=this.gripWorldPosition.sub(this.object.worldForward.multiplyScalar(.1)),s=this.inputSource.profiles.join(`
4920
4920
  `);let r=`Controller[${this.index}] ${this.side}
4921
4921
  C:${this.connected?"yes":"no"} T:${this.isTracking?"yes":"no"} Hand:${this.inputSource.hand?"yes":"no"}`;this.inputSource.hand&&(r+=`
4922
4922
  Pinch: ${(e=this.getGesture("pinch"))==null?void 0:e.value.toFixed(3)}`),r+=`
@@ -5540,7 +5540,7 @@ Texture:`,s),this.setLightmapDebugMaterial()),this.applyLightmap())}updateLightm
5540
5540
  gl_FragColor = lightMapTexel;
5541
5541
  gl_FragColor.a = 1.;
5542
5542
  }
5543
- `,defines:{USE_LIGHTMAP:""}})}}var ooe=Object.defineProperty,aoe=Object.getOwnPropertyDescriptor,Tc=(i,e,t,s)=>{for(var r=s>1?void 0:s?aoe(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&ooe(e,t,r),r};const Ix=te("debugrenderer"),loe=te("debugskinnedmesh"),jz=te("noInstancing"),a0=te("debuginstancing"),coe=te("debugprogressive"),hoe=te("noprogressive"),uoe=te("wireframe");class o2{constructor(){h(this,"path",null),h(this,"asset",null),h(this,"default")}}class doe{constructor(e,t){h(this,"_renderer"),h(this,"_targets",[]),h(this,"_indexMapMaxIndex"),h(this,"_indexMap"),h(this,"_changed",!1),this._renderer=e;const s=this.setMaterial.bind(this),r=this.getMaterial.bind(this),n=e.gameObject;if(this._targets=[],n)switch(n.type){case"Group":this._targets=[...n.children];break;case"SkinnedMesh":case"Mesh":this._targets.push(n);break}let o=!1,a,l=0;for(let c=0;c<this._targets.length;c++){const u=this._targets[c];if(!u)continue;const d=u.material;if(d){d.shadowSide=d.side;for(let p=0;p<t.length;p++){const f=t[p];if(!f){o=!0;continue}if(d.name===f.name){a===void 0&&(a=new Map),a.set(p,c),l=Math.max(l,p);break}}}}if(o){this._indexMapMaxIndex=l,this._indexMap=a;const c=`Renderer ${e.name} was initialized with missing materials - this may lead to unexpected behaviour when trying to access sharedMaterials by index.`;console.warn(c),vn()&&ns("Found renderer with missing materials: please check the console for details.")}return new Proxy(this,{get(c,u){if(typeof u=="string"){const d=parseInt(u);if(!isNaN(d))return r(d)}return c[u]},set(c,u,d){return typeof u=="string"&&s(d,Number.parseInt(u)),Reflect.set(c,u,d)?(d instanceof Ot&&(c.changed=!0),!0):!1}})}get changed(){return this._changed}set changed(e){e===!0&&Ix&&console.warn("SharedMaterials have changed: "+this._renderer.name,this),this._changed=e}is(e){return this._renderer===e}get length(){return this._indexMapMaxIndex!==void 0?this._indexMapMaxIndex+1:this._targets.length}*[Symbol.iterator](){for(let e=0;e<this.length;e++)yield this.getMaterial(e)}resolveIndex(e){const t=this._indexMap;return t&&t.has(e)?t.get(e):e}setMaterial(e,t){if(t=this.resolveIndex(t),t<0||t>=this._targets.length)return;const s=this._targets[t];!s||s.material===void 0||(s.material=e,this.changed=!0)}getMaterial(e){if(e=this.resolveIndex(e),e<0)return null;const t=this._targets;if(e>=t.length)return null;const s=t[e];return s?s.material:null}}const Gz=class extends Be{constructor(){super(...arguments),h(this,"receiveShadows",!1),h(this,"shadowCastingMode",0),h(this,"lightmapIndex",-1),h(this,"lightmapScaleOffset",new $e(1,1,0,0)),h(this,"enableInstancing"),h(this,"renderOrder"),h(this,"allowOcclusionWhenDynamic",!0),h(this,"probeAnchor"),h(this,"reflectionProbeUsage",0),h(this,"_lightmaps"),h(this,"_sharedMeshes",[]),h(this,"_sharedMaterials"),h(this,"_originalMaterials"),h(this,"_lightmapTextureOverride"),h(this,"allowProgressiveLoading",!0),h(this,"_isInstancingEnabled",!1),h(this,"handles"),h(this,"onBeforeRenderThree",(i,e,t,s,r,n)=>{var o;if(r.envMapIntensity!==void 0){const a=this.hasLightmap?Math.PI:1,l=((o=this.context.mainCameraComponent)==null?void 0:o.environmentIntensity)??1;r.envMapIntensity=Math.max(0,l*this.context.sceneLighting.environmentIntensity/a)}if(this._lightmaps)for(const a of this._lightmaps)a.updateLightmapUniforms(r)}),h(this,"_reflectionProbe",null)}static setVisible(i,e){Uf(i,e)}get sharedMesh(){if(this.gameObject.type==="Mesh")return this.gameObject;if(this.gameObject.type==="SkinnesMesh")return this.gameObject;if(this.gameObject.type==="Group")return this.gameObject.children[0]}get sharedMeshes(){if(this.destroyed||!this.gameObject)return this._sharedMeshes;if(this._sharedMeshes.length=0,this.gameObject.type==="Group")for(const i of this.gameObject.children)(i.type==="Mesh"||i.type==="SkinnedMesh")&&this._sharedMeshes.push(i);else(this.gameObject.type==="Mesh"||this.gameObject.type==="SkinnedMesh")&&this._sharedMeshes.push(this.gameObject);return this._sharedMeshes}get sharedMaterial(){return this.sharedMaterials[0]}set sharedMaterial(i){this.sharedMaterials[0]!==i&&(this.sharedMaterials[0]=i,this.applyLightmapping())}get material(){return this.sharedMaterials[0]}set material(i){this.sharedMaterial=i}set sharedMaterials(i){if(!this._originalMaterials)this._originalMaterials=i;else if(i){let e=!1;for(let t=0;t<this._sharedMaterials.length;t++){const s=t<i.length?i[t]:null;s&&s instanceof Ot?this.sharedMaterials[t]=s:e||(e=!0,console.warn("Can not assign null as material: "+this.name,s))}}}get sharedMaterials(){return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._originalMaterials||(this._originalMaterials=[]),this._sharedMaterials=new doe(this,this._originalMaterials)),this._sharedMaterials}static get shouldSuppressInstancing(){return jz}get lightmap(){var i;return(i=this._lightmaps)!=null&&i.length?this._lightmaps[0].lightmap:null}set lightmap(i){var e;if(this._lightmapTextureOverride=i,i===void 0&&(i=this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex)),(e=this._lightmaps)!=null&&e.length)for(const t of this._lightmaps)t.lightmap=i}get hasLightmap(){return this.lightmap!=null}registering(){this.enabled||this.setVisibility(!1)}awake(){if(Ix&&console.log("Renderer ",this.name,this),this.clearInstancingState(),this.probeAnchor&&Ix&&this.probeAnchor.add(new Ro(.2)),this._reflectionProbe=null,this.isMultiMaterialObject(this.gameObject)){for(const i of this.gameObject.children)this.context.addBeforeRenderListener(i,this.onBeforeRenderThree),i.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let i=0;for(let e=0;e<this.gameObject.children.length;e++){const t=this.gameObject.children[e];if(!(!this.isMeshOrSkinnedMesh(t)||re.getComponent(t,Gz))){if(this.renderOrder.length<=i){console.warn("Incorrect renderOrder element count",this,this.renderOrder.length+" but expected "+this.gameObject.children.length,"Index: "+i,"ChildElement:",t);continue}t.renderOrder=this.renderOrder[i],i+=1}}}}else this.isMeshOrSkinnedMesh(this.gameObject)?(this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree),this.renderOrder!==void 0&&this.renderOrder.length>0&&(this.gameObject.renderOrder=this.renderOrder[0])):this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree);if(this.applyLightmapping(),uoe)for(let i=0;i<this.sharedMaterials.length;i++){const e=this.sharedMaterials[i];e&&(e.wireframe=!0)}}applyLightmapping(){var i;if(this.lightmapIndex>=0){const e=this.gameObject.type,t=this._lightmapTextureOverride!==void 0?this._lightmapTextureOverride:this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex);if(t){if(this._lightmaps||(this._lightmaps=[]),e==="Mesh"){const s=this.gameObject.material;if(s!=null&&s.isMeshBasicMaterial)s&&console.warn("Lightmapping is not supported on MeshBasicMaterial",s.name);else{if(this._lightmaps.length<=0){const r=new o0(this.gameObject,this.context);this._lightmaps.push(r)}this._lightmaps[0].init(this.lightmapIndex,this.lightmapScaleOffset,t)}}else if(this.isMultiMaterialObject(this.gameObject)&&this.sharedMaterials.length>0)for(let s=0;s<this.gameObject.children.length;s++){const r=this.gameObject.children[s];if(!((i=r.material)!=null&&i.isMeshBasicMaterial)){let n;s>=this._lightmaps.length?(n=new o0(r,this.context),this._lightmaps.push(n)):n=this._lightmaps[s],n.init(this.lightmapIndex,this.lightmapScaleOffset,t)}}}else Ix&&console.warn("Lightmap not found",this.sourceId,this.lightmapIndex)}}clearInstancingState(){this._isInstancingEnabled=!1,this.handles=void 0}setInstancingEnabled(i){if(this._isInstancingEnabled===i)return i&&(this.handles===void 0||this.handles!=null&&this.handles.length>0);if(this._isInstancingEnabled=i,i){if(this.handles===void 0){if(this.handles=foe.setup(this,this.gameObject,this.context,null,{rend:this,foundMeshes:0,useMatrixWorldAutoUpdate:this.useInstanceMatrixWorldAutoUpdate()}),this.handles)return re.markAsInstancedRendered(this.gameObject,!0),!0}else if(this.handles!==null){for(const e of this.handles)e.updateInstanceMatrix(!0),e.add();return re.markAsInstancedRendered(this.gameObject,!0),!0}}else{if(this.handles)for(const e of this.handles)e.remove();return!0}return!1}useInstanceMatrixWorldAutoUpdate(){return!0}start(){if(this.enableInstancing&&!jz&&(this.setInstancingEnabled(!0),Fa.markDirty(this.gameObject)),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.isMultiMaterialObject(this.gameObject))for(let i=0;i<this.gameObject.children.length;i++){const e=this.gameObject.children[i];e.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this.sharedMeshes,this.setVisibility(!0),this._isInstancingEnabled?this.setInstancingEnabled(!0):this.enabled&&this.applyStencil(),this.updateReflectionProbe()}onDisable(){this.setVisibility(!1),this.handles&&this.handles.length>0&&this.setInstancingEnabled(!1)}onDestroy(){if(this.handles=null,this.isMultiMaterialObject(this.gameObject))for(const i of this.gameObject.children)this.context.removeBeforeRenderListener(i,this.onBeforeRenderThree);else this.context.removeBeforeRenderListener(this.gameObject,this.onBeforeRenderThree)}applyStencil(){s2.applyStencil(this)}onBeforeRender(){var i,e;if(this.gameObject){if(this.isMultiMaterialObject(this.gameObject)&&((i=this.gameObject.children)==null?void 0:i.length)>0)for(const t of this.gameObject.children)this.applySettings(t);else this.applySettings(this.gameObject);if(this.sharedMaterials.changed&&(this.sharedMaterials.changed=!1,this.applyLightmapping()),(e=this.handles)!=null&&e.length&&this.gameObject[Ng]===!0){a0&&console.log("UPDATE INSTANCED MATRICES",this.context.time.frame),this.gameObject[Ng]=!1;for(let t=this.handles.length-1;t>=0;t--)this.handles[t].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this.handles&&this.handles.length<=0&&re.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this.handles)for(let t=0;t<this.handles.length;t++){const s=this.handles[t];Uf(s.object,!1)}for(const t of this.sharedMaterials)t&&this.loadProgressiveTextures(t);this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onSet(this)}}onAfterRender(){if(this._isInstancingEnabled&&this.handles)for(let i=0;i<this.handles.length;i++){const e=this.handles[i];Uf(e.object,!0)}this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onUnset(this)}loadProgressiveTextures(i){return!hoe&&i&&i._didRequestTextureLOD===void 0&&this.allowProgressiveLoading?(i._didRequestTextureLOD=0,coe&&console.log("Load material LOD",i.name),Hn.assignTextureLOD(this.context,this.sourceId,i)):Promise.resolve(!0)}applySettings(i){i.receiveShadow=this.receiveShadows,this.shadowCastingMode==1?i.castShadow=!0:i.castShadow=!1}updateReflectionProbe(){if(this._reflectionProbe=null,this.reflectionProbeUsage!==0){if(!this.probeAnchor)return;this.startCoroutine(this._updateReflectionProbe(),Os.LateUpdate)}}*_updateReflectionProbe(){const i=this.probeAnchor||this.gameObject,e=!!this.probeAnchor;this._reflectionProbe=Nf.get(i,this.context,e,this.probeAnchor)}setVisibility(i){if(!this.isMultiMaterialObject(this.gameObject))Uf(this.gameObject,i);else for(const e of this.gameObject.children)this.isMeshOrSkinnedMesh(e)&&Uf(e,i)}isMultiMaterialObject(i){return i.type==="Group"}isMeshOrSkinnedMesh(i){return i.type==="Mesh"||i.type==="SkinnedMesh"}};let As=Gz;Tc([x()],As.prototype,"receiveShadows",2),Tc([x()],As.prototype,"shadowCastingMode",2),Tc([x()],As.prototype,"lightmapIndex",2),Tc([x($e)],As.prototype,"lightmapScaleOffset",2),Tc([x()],As.prototype,"enableInstancing",2),Tc([x()],As.prototype,"renderOrder",2),Tc([x()],As.prototype,"allowOcclusionWhenDynamic",2),Tc([x(Ae)],As.prototype,"probeAnchor",2),Tc([x()],As.prototype,"reflectionProbeUsage",2);class l0 extends As{}class a2 extends l0{awake(){var e;super.awake(),this.allowOcclusionWhenDynamic=!1,(e=this.gameObject.parent)==null||e.updateWorldMatrix(!1,!0)}onBeforeRender(){if(super.onBeforeRender(),loe&&this.gameObject instanceof da&&this.gameObject.boundingSphere){const e=Bs(this.gameObject.boundingSphere.center).applyMatrix4(this.gameObject.matrixWorld);Tt.DrawWireSphere(e,this.gameObject.boundingSphere.radius,"red")}}}class poe{constructor(){h(this,"objs",[])}setup(e,t,s,r,n,o=0){e.applySettings(t);const a=this.tryCreateOrAddInstance(t,s,n);if(a)e.loadProgressiveTextures(a.instancer.material),r===null&&(r=[]),r.push(a);else if(o<=0&&t.type!=="Mesh"){const l=o+1;for(const c of t.children)r=this.setup(e,c,s,r,n,l)}return o===0&&n.useMatrixWorldAutoUpdate&&r&&r.length>=0&&this.autoUpdateInstanceMatrix(t),r}tryCreateOrAddInstance(e,t,s){if(e.type==="Mesh"){const r=s.foundMeshes;if(s.foundMeshes+=1,!s.rend.enableInstancing||r>=s.rend.enableInstancing.length||!s.rend.enableInstancing[r])return null;const n=e,o=n.geometry,a=n.material;for(const c of this.objs)if(!c.isFull()&&c.geo===o&&c.material===a)return c.addInstance(n);const l=new Vz(e.name,o,a,200,t);return this.objs.push(l),l.addInstance(n)}return null}autoUpdateInstanceMatrix(e){const t=e.matrixWorld.multiplyMatrices.bind(e.matrixWorld),s=e.matrixWorld.clone(),r=(n,o)=>{const a=t(n,o);return(e[Ng]||s.equals(a)===!1)&&(s.copy(a),e[Ng]=!0),a};e.matrixWorld.multiplyMatrices=r}}const foe=new poe;class moe{constructor(e,t,s){h(this,"instanceIndex",-1),h(this,"object"),h(this,"instancer"),this.instanceIndex=e,this.object=t,this.instancer=s,t[_3]=s,re.markAsInstancedRendered(t,!0)}get name(){return this.object.name}updateInstanceMatrix(e=!1){this.instanceIndex<0||(this.object.updateWorldMatrix(!0,e),this.instancer.updateInstance(this.object.matrixWorld,this.instanceIndex))}setMatrix(e){this.instanceIndex<0||this.instancer.updateInstance(e,this.instanceIndex)}add(){this.instanceIndex>=0||this.instancer.add(this)}remove(){this.instanceIndex<0||this.instancer.remove(this)}}const Qz=class{constructor(i,e,t,s,r){h(this,"name",""),h(this,"geo"),h(this,"material"),h(this,"context"),h(this,"inst"),h(this,"handles",[]),h(this,"maxCount"),h(this,"_needUpdateBounds",!1),h(this,"onBeforeRender",()=>{this.inst.layers.enableAll(),this._needUpdateBounds&&this.inst[cM]===!0&&(a0&&console.log("Update instancing bounds",this.name,this.inst.matrixWorldNeedsUpdate),this.updateBounds())}),h(this,"onAfterRender",()=>{this.inst.layers.disableAll()}),this.name=i,this.geo=e,this.material=t,this.context=r,this.maxCount=s,a0&&(t=new ni({color:this.randomColor()})),this.inst=new Cy(e,t,s),this.inst[cM]=!0,this.inst.count=0,this.inst.visible=!0,this.context.scene.add(this.inst),t instanceof cg&&(t.defines.USE_INSTANCING=!0,t.needsUpdate=!0),r.pre_render_callbacks.push(this.onBeforeRender),r.post_render_callbacks.push(this.onAfterRender)}get mesh(){return this.inst}get visible(){return this.inst.visible}set visible(i){this.inst.visible=i}get castShadow(){return this.inst.castShadow}set castShadow(i){this.inst.castShadow=i}set receiveShadow(i){this.inst.receiveShadow=i}updateBounds(i=!0,e=!0){this._needUpdateBounds=!1,i&&this.inst.computeBoundingBox(),e&&this.inst.computeBoundingSphere()}get currentCount(){return this.inst.count}isFull(){return this.currentCount>=this.maxCount}randomColor(){return new we(Math.random(),Math.random(),Math.random())}addInstance(i){if(this.currentCount>=this.maxCount)return console.error("TOO MANY INSTANCES - resize is not yet implemented!",this.inst.count),null;const e=new moe(-1,i,this);return i.castShadow===!0&&this.inst.castShadow===!1&&(this.inst.castShadow=!0),i.receiveShadow===!0&&this.inst.receiveShadow===!1&&(this.inst.receiveShadow=!0),this.add(e),e}add(i){i.instanceIndex<0&&(i.instanceIndex=this.currentCount,i.instanceIndex>=this.handles.length?this.handles.push(i):this.handles[i.instanceIndex]=i),i.object.updateWorldMatrix(!0,!0),this.inst.setMatrixAt(i.instanceIndex,i.object.matrixWorld),this.inst.instanceMatrix.needsUpdate=!0,this.inst.count+=1,this._needUpdateBounds=!0,this.inst.count>0&&(this.inst.visible=!0),a0&&console.log("Added",this.name,this.inst.count)}remove(i){if(!(!i||i.instanceIndex<0||i.instanceIndex>=this.handles.length||this.inst.count<=0)){if(this.handles[i.instanceIndex]!==i){console.error("instance handle is not part of renderer, was it removed before?",i.instanceIndex,this.name);const e=this.handles.indexOf(i);if(e<0)return;i.instanceIndex=e}if(this.handles[i.instanceIndex]=null,this.inst.setMatrixAt(i.instanceIndex,Qz.nullMatrix),!(i.instanceIndex>=this.currentCount-1)&&this.currentCount>0){const e=this.handles[this.currentCount-1];e&&(e.instanceIndex=i.instanceIndex,e.updateInstanceMatrix(),this.handles[i.instanceIndex]=e,this.handles[this.currentCount-1]=null)}this.inst.count>0&&(this.inst.count-=1),i.instanceIndex=-1,this._needUpdateBounds=!0,this.inst.count<=0&&(this.inst.visible=!1),this.inst.instanceMatrix.needsUpdate=!0,a0&&console.log("Removed",this.name,this.inst.count)}}updateInstance(i,e){this.inst.setMatrixAt(e,i),this.inst.instanceMatrix.needsUpdate=!0,this._needUpdateBounds=!0}};let Vz=Qz;h(Vz,"nullMatrix",new Te);var goe=Object.defineProperty,voe=Object.getOwnPropertyDescriptor,as=(i,e,t,s)=>{for(var r=s>1?void 0:s?voe(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&goe(e,t,r),r};const Hz=te("debugusdzbehaviours");function c0(i){i&&(i.getComponentInParent(Dv)||(wt()&&console.warn("Create Raycaster on "+i.name+" because no raycaster was found in the hierarchy"),i.addNewComponent(ao)))}class Cd extends Be{constructor(){super(...arguments),h(this,"object"),h(this,"target"),h(this,"duration",1),h(this,"relativeMotion",!1),h(this,"coroutine",null),h(this,"targetPos",new w),h(this,"targetRot",new Ie),h(this,"targetScale",new w)}start(){c0(this.gameObject)}onPointerClick(e){e.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 e=Rt(this.object).clone(),t=Rt(this.target).clone(),s=Ri(this.object).clone(),r=Ri(this.target).clone(),n=ss(this.object).clone(),o=ss(this.target).clone(),a=e.distanceTo(t),l=s.angleTo(r),c=n.distanceTo(o);if(a<.01&&l<.01&&c<.01){Jr(this.object,t),zo(this.object,r),Cg(this.object,o),this.coroutine=null;return}let u=0,d=0;for(;u<1;)u+=this.context.time.deltaTime/this.duration,u>1&&(u=1),d=u<.5?4*u*u*u:1-Math.pow(-2*u+2,3)/2,this.targetPos.lerpVectors(e,t,d),this.targetRot.slerpQuaternions(s,r,d),this.targetScale.lerpVectors(n,o,d),Jr(this.object,this.targetPos),zo(this.object,this.targetRot),Cg(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const e=this.object.position.clone(),t=this.object.quaternion.clone(),s=this.object.scale.clone(),r=this.target.position.clone(),n=this.target.quaternion.clone(),o=this.target.scale.clone();r.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(r),this.targetRot.copy(this.object.quaternion).multiply(n),this.targetScale.copy(this.object.scale).multiply(o);let a=0,l=0;for(;a<1;)a+=this.context.time.deltaTime/this.duration,a>1&&(a=1),l=a<.5?4*a*a*a:1-Math.pow(-2*a+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,l),this.object.quaternion.slerpQuaternions(t,this.targetRot,l),this.object.scale.lerpVectors(s,this.targetScale,l),yield;this.coroutine=null}beforeCreateDocument(e){var t;if(this.target&&this.object&&this.gameObject){const s=new Cr("Move to "+((t=this.target)==null?void 0:t.name),Er.tapTrigger(this.gameObject),di.transformAction(this.object,this.target,this.duration,this.relativeMotion?hI.Relative:hI.Absolute));e.addBehavior(s)}}}as([x(Ae)],Cd.prototype,"object",2),as([x(Ae)],Cd.prototype,"target",2),as([x()],Cd.prototype,"duration",2),as([x()],Cd.prototype,"relativeMotion",2);var Rx;const Ic=(Rx=class extends Be{constructor(){super(...arguments),h(this,"materialToSwitch"),h(this,"variantMaterial"),h(this,"fadeDuration",0),h(this,"_objectsWithThisMaterial",[]),h(this,"selfModel"),h(this,"targetModels")}awake(){if(this.variantMaterial&&this.materialToSwitch){const i=re.findObjectsOfType(As);for(const e of i)for(let t=0;t<e.sharedMaterials.length;t++){const s=e.sharedMaterials[t];if(s===this.materialToSwitch){if(e.gameObject instanceof ge)this._objectsWithThisMaterial.push(e.gameObject);else if(e.gameObject instanceof fn)for(const r of e.gameObject.children)r instanceof ge&&r.material===s&&this._objectsWithThisMaterial.push(r);break}}}}start(){c0(this.gameObject)}onPointerClick(i){if(i.use(),!!this.variantMaterial)for(let e=0;e<this._objectsWithThisMaterial.length;e++){const t=this._objectsWithThisMaterial[e];t.material=this.variantMaterial}}async beforeCreateDocument(i,e){this.targetModels=[],Ic._materialTriggersPerId={},Ic.variantSwitchIndex=0,this.materialToSwitch&&await Hn.assignTextureLOD(this.context,this.sourceId,this.materialToSwitch,0),this.variantMaterial&&await Hn.assignTextureLOD(this.context,this.sourceId,this.variantMaterial,0)}createBehaviours(i,e,t){this._objectsWithThisMaterial.find(s=>s.uuid===e.uuid)&&this.targetModels.push(e),this.gameObject.uuid===e.uuid&&(this.selfModel=e,this.materialToSwitch&&(Ic._materialTriggersPerId[this.materialToSwitch.uuid]||(Ic._materialTriggersPerId[this.materialToSwitch.uuid]=[]),Ic._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(i,e){if(!this.materialToSwitch)return;const t=Ic._materialTriggersPerId[this.materialToSwitch.uuid];if(t){const s={};for(const r of t){const n=r.createVariants();n&&n.length>0&&(s[r.selfModel.uuid]=n)}for(const r of t){const n=[];for(const o in s)o!==r.selfModel.uuid&&n.push(...s[o]);r.createAndAttachBehaviors(i,s[r.selfModel.uuid],n)}}delete Ic._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(i,e,t){const s=[],r=[],n=Math.max(0,this.fadeDuration);r.push(di.fadeAction([...this.targetModels,...t],n,!1)),s.push(di.fadeAction(e,n,!1)),r.push(di.fadeAction(e,n,!0)),i.addBehavior(new Cr("Select_"+this.selfModel.name,Er.tapTrigger(this.selfModel),di.parallel(...r))),i.addBehavior(new Cr("StartHidden_"+this.selfModel.name,Er.sceneStartTrigger(),di.parallel(...s)))}createVariants(){if(!this.variantMaterial)return null;const i=[];for(const e of this.targetModels){const t=e.clone();t.name+=" variant_"+this.variantMaterial.name+"_"+Ic.variantSwitchIndex++,t.name=t.name.replace(/\s/g,"_"),t.material=this.variantMaterial,t.geometry=e.geometry,t.matrix=e.matrix,(!e.parent||!e.parent.isEmpty())&&Wo.createEmptyParent(e),e.parent&&e.parent.add(t),i.push(t)}return i}},h(Rx,"_materialTriggersPerId",{}),h(Rx,"variantSwitchIndex",0),Rx);let zf=Ic;as([x(Ot)],zf.prototype,"materialToSwitch",2),as([x(Ot)],zf.prototype,"variantMaterial",2),as([x()],zf.prototype,"fadeDuration",2);var jf;const ls=(jf=class extends Be{constructor(){super(...arguments),h(this,"target"),h(this,"toggleOnClick",!1),h(this,"targetState",!0),h(this,"hideSelf",!0),h(this,"selfModel"),h(this,"selfModelClone"),h(this,"targetModel"),h(this,"toggleModel"),h(this,"stateBeforeCreatingDocument",!1),h(this,"targetStateBeforeCreatingDocument",!1)}start(){c0(this.gameObject)}onPointerClick(i){i.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}createBehaviours(i,e,t){e.uuid===this.gameObject.uuid&&(this.selfModel=e,this.selfModelClone=e.clone())}beforeCreateDocument(){this.target&&(this.gameObject[ls.wasVisible]===void 0&&(this.gameObject[ls.wasVisible]=this.gameObject.activeSelf),this.target[ls.wasVisible]===void 0&&(this.target[ls.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[ls.wasVisible],this.targetStateBeforeCreatingDocument=this.target[ls.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(i,e){if(!this.target)return;this.targetModel=e.document.findById(this.target.uuid);const t=this.selfModel;if(this.selfModel&&this.targetModel){let s=this.selfModel,r=this.targetState;if(this.toggleOnClick)if(r=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&k4.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[ls.toggleClone]){const a=this.selfModelClone.clone();a.matrix.identity(),a.name+="_toggle"+ls.clonedToggleIndex++,t.add(a),this.gameObject[ls.toggleClone]=a,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[ls.toggleClone];if(!this.gameObject[ls.reverseToggleClone]){const a=this.selfModelClone.clone();a.matrix.identity(),a.name+="_toggleReverse"+ls.clonedToggleIndex++,t.add(a),this.gameObject[ls.reverseToggleClone]=a}this.toggleModel=this.gameObject[ls.reverseToggleClone],(!this.toggleModel.geometry||!o.geometry)&&console.error("triggers without childs and without geometry won't work!",this,t.geometry),s=o,t.geometry=null,t.material=null}if(this.toggleModel){if(this.toggleOnClick){const o=[];o.push(di.fadeAction(s,0,!1)),o.push(di.fadeAction(this.toggleModel,0,!0)),o.push(di.fadeAction(this.targetModel,0,r)),i.addBehavior(new Cr("Toggle_"+s.name+"_toggleTo"+(r?"On":"Off"),Er.tapTrigger(s),di.parallel(...o)));const a=[];a.push(di.fadeAction(this.toggleModel,0,!1)),a.push(di.fadeAction(s,0,!0)),a.push(di.fadeAction(this.targetModel,0,!r)),i.addBehavior(new Cr("Toggle_"+s.name+"_toggleTo"+(r?"Off":"On"),Er.tapTrigger(this.toggleModel),di.parallel(...a)))}}else{const o=[];this.hideSelf&&o.push(di.fadeAction(s,0,!1)),o.push(di.fadeAction(this.targetModel,0,r)),i.addBehavior(new Cr("Toggle_"+s.name+"_toggleTo"+(r?"On":"Off"),Er.tapTrigger(s),di.parallel(...o)))}const n=new Array;this.targetStateBeforeCreatingDocument||n.push(this.targetModel),this.stateBeforeCreatingDocument||n.push(t),this.toggleModel&&n.push(this.toggleModel),i.addBehavior(new Cr("HideOnStart_"+this.gameObject.name,Er.sceneStartTrigger(),di.fadeAction(n,0,!1)))}}afterSerialize(i,e){this.gameObject[ls.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[ls.wasVisible],delete this.gameObject[ls.wasVisible]),this.target&&this.target[ls.wasVisible]!==void 0&&(this.target.visible=this.target[ls.wasVisible],delete this.target[ls.wasVisible]),delete this.gameObject[ls.toggleClone],delete this.gameObject[ls.reverseToggleClone]}},h(jf,"clonedToggleIndex",0),h(jf,"wasVisible",Symbol("usdz_SetActiveOnClick_wasVisible")),h(jf,"toggleClone",Symbol("clone for toggling")),h(jf,"reverseToggleClone",Symbol("clone for reverse toggling")),jf);let Ed=ls;as([x(Ae)],Ed.prototype,"target",2),as([x()],Ed.prototype,"toggleOnClick",2),as([x()],Ed.prototype,"targetState",2),as([x()],Ed.prototype,"hideSelf",2);class l2 extends Be{start(){this.gameObject.visible=!1}createBehaviours(e,t,s){t.uuid===this.gameObject.uuid&&e.addBehavior(new Cr("HideOnStart_"+this.gameObject.name,Er.sceneStartTrigger(),di.fadeAction(t,0,!1)))}beforeCreateDocument(){this.gameObject.visible=!0}afterCreateDocument(){this.gameObject.visible=!1}}class Gf extends Be{constructor(){super(...arguments),h(this,"target"),h(this,"duration",.5),h(this,"motionType",cI.bounce)}beforeCreateDocument(){}createBehaviours(e,t,s){if(this.target&&t.uuid===this.gameObject.uuid){const r=new Cr("emphasize "+this.name,Er.tapTrigger(this.gameObject),di.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(r)}}afterCreateDocument(e,t){}}as([x()],Gf.prototype,"target",2),as([x()],Gf.prototype,"duration",2),as([x()],Gf.prototype,"motionType",2);class Vh extends Be{constructor(){super(...arguments),h(this,"target"),h(this,"clip",""),h(this,"toggleOnClick",!1)}start(){c0(this.gameObject)}ensureAudioSource(){if(!this.target){const e=this.gameObject.addNewComponent(os);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1)}}onPointerClick(e){var t;e.use(),!(!((t=this.target)!=null&&t.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(e,t,s){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const r=this.clip?this.clip:this.target?this.target.clip:void 0;if(!r||typeof r!="string")return;const n=this.target?this.target.gameObject:this.gameObject,o=cu.getName(r),a=this.target?this.target.volume:1,l=this.target&&this.target.spatialBlend==0?pI.NonSpatial:pI.Spatial;let c=!1;if(this.gameObject.traverse(u=>{u instanceof ge&&u.visible&&(c=!0)}),c){let u=di.playAudioAction(n,"audio/"+o,dI.Play,a,l);this.toggleOnClick&&(u.multiplePerformOperation=Y4.Stop),this.target&&this.target.loop&&(u=di.sequence(u).makeLooping());const d=new Cr("playAudio "+this.name,Er.tapTrigger(this.gameObject),u);e.addBehavior(d)}if(this.target&&this.target.playOnAwake&&this.target.enabled){let u=di.playAudioAction(n,"audio/"+o,dI.Play,a,l);this.target.loop&&(u=di.sequence(u).makeLooping());const d=new Cr("playAudioOnStart"+(this.name?"_"+this.name:""),Er.sceneStartTrigger(),u);e.addBehavior(d)}}}async afterSerialize(e,t){if(!this.target&&!this.clip)return;const s=this.clip?this.clip:this.target?this.target.clip:void 0;if(!s||typeof s!="string")return;const r="audio/"+cu.getName(s);if(t.files[r])return;const n=await(await(await fetch(s)).blob()).arrayBuffer(),o=new Uint8Array(n);t.files[r]=o}}as([x(os)],Vh.prototype,"target",2),as([x(URL)],Vh.prototype,"clip",2),as([x()],Vh.prototype,"toggleOnClick",2);var Px;const Hh=(Px=class extends Be{constructor(){super(...arguments),h(this,"animator"),h(this,"stateName"),h(this,"trigger","tap"),h(this,"selfModel"),h(this,"stateAnimationModel"),h(this,"animationSequence",new Array),h(this,"animationLoopAfterSequence",new Array)}get target(){var i;return(i=this.animator)==null?void 0:i.gameObject}start(){c0(this.gameObject)}onPointerClick(i){var e;i.use(),this.target&&this.stateName&&((e=this.animator)==null||e.play(this.stateName,0,0,.1))}createBehaviours(i,e,t){e.uuid===this.gameObject.uuid&&(this.selfModel=e)}afterSerialize(){if(Hh.rootsWithExclusivePlayback.size>1){const i='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.';wt()&&ns(i),console.warn(i,...Hh.rootsWithExclusivePlayback)}Hh.animationActions=[],Hh.rootsWithExclusivePlayback=new Set}afterCreateDocument(i,e){if(!this.animationSequence||!this.stateAnimationModel||!this.target)return;const t=e.document,s=e.extensions.find(o=>o instanceof Qv);if(!s)return;const r=s.getClipCount(this.target)>1;r&&(wt()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+s.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),Hh.rootsWithExclusivePlayback.add(this.target));const n=(o,a)=>{let l=Hh.animationActions.find(c=>c.affectedObjects==o&&c.start==a.start&&c.duration==a.duration);return l||(l=di.startAnimationAction(o,a.start,a.duration),Hh.animationActions.push(l)),l};t.traverse(o=>{var a,l;if(o.uuid===((a=this.target)==null?void 0:a.uuid)){const c=di.sequence();if(this.animationSequence!==void 0)for(const d of this.animationSequence)c.addAction(n(o,d));if(this.animationLoopAfterSequence!==void 0){const d=c.actions.length==0?c:di.sequence();for(const p of this.animationLoopAfterSequence)d.addAction(n(o,p));d.makeLooping(),c!==d&&c.addAction(d)}const u=new Cr("tap "+this.name+" for "+this.stateName+" on "+((l=this.target)==null?void 0:l.name),this.trigger=="tap"?Er.tapTrigger(this.selfModel):Er.sceneStartTrigger(),c);r&&u.makeExclusive(!0),i.addBehavior(u)}})}createAnimation(i,e,t){var s,r,n,o;if(!this.target||!this.animator)return;const a=(s=this.animator)==null?void 0:s.runtimeAnimatorController;let l=a?.findState(this.stateName),c=[],u=[];if(a&&l){const p=new Array;p.push(l);let f=!1;for(;p.length<100;){if(!l||l===null||!l.transitions||l.transitions.length===0){(r=l.motion)!=null&&r.isLooping&&(f=!0);break}const m=l.transitions.find(y=>y.conditions.length===0),A=m?a.getState(m.destinationState,0):null;if(A&&p.includes(A)){l=A,f=!0;break}else if(m){if(l=A,!l)break;p.push(l)}else{f=((n=l.motion)==null?void 0:n.isLooping)??!1;break}}if(f&&l){const m=p.indexOf(l);c=p.slice(0,m),u=p.slice(m),Hz&&console.log("found loop from "+this.stateName,"states until loop",c,"states looping",u)}else c=p,u=[],Hz&&console.log("found no loop from "+this.stateName,"states",c)}if(c=c.filter(p=>{var f,m,A;return((f=p.motion)==null?void 0:f.clip)&&((A=(m=p.motion)==null?void 0:m.clip.tracks)==null?void 0:A.length)>0}),u=u.filter(p=>{var f,m,A;return((f=p.motion)==null?void 0:f.clip)&&((A=(m=p.motion)==null?void 0:m.clip.tracks)==null?void 0:A.length)>0}),c.length===0&&u.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}this.stateAnimationModel=e;const d=(p,f)=>{var m,A,y;if(!this.target)return;if(!((m=p.motion)!=null&&m.clip)){console.warn("No clip found for state "+p.name+" on "+((A=this.animator)==null?void 0:A.name)+", can't export animation data");return}const g=i.registerAnimation(this.target,p.motion.clip);g?f.push(g):console.warn("Couldn't register animation for state "+p.name+" on "+((y=this.animator)==null?void 0:y.name))};if(c.length>0){this.animationSequence=new Array;for(const p of c)d(p,this.animationSequence)}if(u.length>0){this.animationLoopAfterSequence=new Array;for(const p of u)d(p,this.animationLoopAfterSequence)}}},h(Px,"animationActions",[]),h(Px,"rootsWithExclusivePlayback",new Set),Px);let Qf=Hh;as([x(Ir)],Qf.prototype,"animator",2),as([x()],Qf.prototype,"stateName",2);class Vf extends Be{constructor(){super(...arguments),h(this,"target")}getType(){}getDuration(){}}as([x(Ae)],Vf.prototype,"target",2);class h0 extends Be{constructor(){super(...arguments),h(this,"target")}}as([x(Vf)],h0.prototype,"target",2);class u0 extends Vf{constructor(){super(...arguments),h(this,"type",1),h(this,"duration",1)}getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}as([x()],u0.prototype,"type",2),as([x()],u0.prototype,"duration",2);class c2 extends h0{}var Aoe=Object.defineProperty,yoe=Object.getOwnPropertyDescriptor,Rc=(i,e,t,s)=>{for(var r=s>1?void 0:s?yoe(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Aoe(e,t,r),r};const Wz=te("debugcharactercontroller");class Md extends Be{constructor(){super(...arguments),h(this,"center",new w(0,0,0)),h(this,"radius",.5),h(this,"height",2),h(this,"_rigidbody",null),h(this,"_activeGroundCollisions"),h(this,"_contactVelocity",new w)}get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(zi),this._rigidbody||(this._rigidbody=this.gameObject.addNewComponent(zi)),this.rigidbody)}awake(){this._activeGroundCollisions=new Set}onEnable(){const e=this.rigidbody;let t=this.gameObject.getComponent(zh);t||(t=this.gameObject.addNewComponent(zh)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height;const s=new w(0,0,1),r=new w(1,0,0),n=new w(0,1,0),o=this.gameObject.getWorldDirection(new w);o.y=0;const a=r.dot(o)<0?-1:1,l=s.angleTo(o)*a;this.gameObject.setRotationFromAxisAngle(n,l),e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}onCollisionEnter(e){(e.contacts.length==0||e.contacts.some(t=>t.normal.y>.2))&&(this._activeGroundCollisions.add(e),Wz&&console.log(`Collision(${this._activeGroundCollisions.size}): ${e.contacts.map(t=>t.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(e){this._activeGroundCollisions.delete(e),Wz&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}get contactVelocity(){var e;this._contactVelocity.set(0,0,0);for(const t of this._activeGroundCollisions){const s=(e=this.context.physics.engine)==null?void 0:e.getLinearVelocity(t.collider);s&&(this._contactVelocity.x+=s.x,this._contactVelocity.y+=s.y,this._contactVelocity.z+=s.z)}return this._contactVelocity}}Rc([x(w)],Md.prototype,"center",2),Rc([x()],Md.prototype,"radius",2),Rc([x()],Md.prototype,"height",2);class Pc extends Be{constructor(){super(...arguments),h(this,"controller"),h(this,"movementSpeed",2),h(this,"rotationSpeed",2),h(this,"jumpForce",1),h(this,"doubleJumpForce",2),h(this,"animator"),h(this,"lookForward",!0),h(this,"lookInput",new ee(0,0)),h(this,"moveInput",new ee(0,0)),h(this,"jumpInput",!1),h(this,"_currentSpeed",new w(0,0,0)),h(this,"_currentAngularSpeed",new w(0,0,0)),h(this,"_temp",new w(0,0,0)),h(this,"_jumpCount",0),h(this,"_currentRotation"),h(this,"_raycastOptions",new Qo)}awake(){this._currentRotation=new Ie}update(){const e=this.context.input;e.isKeyPressed("KeyW")?this.moveInput.y+=1:e.isKeyPressed("KeyS")&&(this.moveInput.y-=1),e.isKeyPressed("KeyD")?this.lookInput.x+=1:e.isKeyPressed("KeyA")&&(this.lookInput.x-=1),this.jumpInput||(this.jumpInput=e.isKeyDown("Space"))}move(e){this.moveInput.add(e)}look(e){this.lookInput.add(e)}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(e,t,s){var r,n,o,a,l,c,u,d,p,f,m;if((r=this.controller)!=null&&r.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&((n=this.animator)==null||n.setBool("doubleJump",!1))),this._currentSpeed.z+=e.y*this.movementSpeed*this.context.time.deltaTime,(o=this.animator)==null||o.setBool("running",e.length()>.01),(l=this.animator)==null||l.setBool("jumping",((a=this.controller)==null?void 0:a.isGrounded)===!0&&s),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+=st.toRadians(-t.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const A=this.context.mainCameraComponent.forward;A.y=0,A.normalize(),this._currentRotation.setFromUnitVectors(new w(0,0,1),A),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&&s&&this.jumpForce>0){let A=(c=this.controller)==null?void 0:c.isGrounded;if(this.doubleJumpForce>0&&!((u=this.controller)!=null&&u.isGrounded)&&this._jumpCount===1&&(A=!0,(d=this.animator)==null||d.setBool("doubleJump",!0)),A){this._jumpCount+=1;const y=this.controller.rigidbody,g=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;y.applyImpulse(new w(0,1,0).multiplyScalar(g))}}if(this.controller){const A=(p=this.controller)==null?void 0:p.rigidbody.getVelocity().y;if(A<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new Zn),this._raycastOptions.ray.origin.copy(Rt(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const y=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const g=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(y),(g.length&&g[0].distance>2||A<-10)&&((f=this.animator)==null||f.setBool("falling",!0))}else(m=this.animator)==null||m.setBool("falling",!1)}}}Rc([x(Md)],Pc.prototype,"controller",2),Rc([x()],Pc.prototype,"movementSpeed",2),Rc([x()],Pc.prototype,"rotationSpeed",2),Rc([x()],Pc.prototype,"jumpForce",2),Rc([x()],Pc.prototype,"doubleJumpForce",2),Rc([x(Ir)],Pc.prototype,"animator",2);var boe=Object.defineProperty,_oe=Object.getOwnPropertyDescriptor,xoe=(i,e,t,s)=>{for(var r=s>1?void 0:s?_oe(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&boe(e,t,r),r};class d0 extends nn{constructor(){super(...arguments),h(this,"intensity")}get typeName(){return"ChromaticAberration"}init(){this.intensity.defaultValue=0}onCreateEffect(){const e=new j3;return e.offset=new ee(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=t=>t*.02,this.intensity.onValueChanged=t=>{e.offset.x=-t,e.offset.y=t},e}}xoe([x(Bt)],d0.prototype,"intensity",2),Ko("ChromaticAberration",d0);const p0=new vt;p0.setAttribute("position",new Ze(new Float32Array([-1,-1,3,-1,-1,3]),2)),p0.setAttribute("uv",new Ze(new Float32Array([0,0,2,0,0,2]),2)),p0.boundingSphere=new _s,p0.computeBoundingSphere=function(){};const woe=new Vl;class Td{constructor(e){this._mesh=new ge(p0,e),this._mesh.frustumCulled=!1}render(e){e.render(this._mesh,woe)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}dispose(){this._mesh.material.dispose(),this._mesh.geometry.dispose()}}const Soe={uniforms:{sceneDiffuse:{value:null},sceneDepth:{value:null},sceneNormal:{value:null},projMat:{value:new Te},viewMat:{value:new Te},projViewMat:{value:new Te},projectionMatrixInv:{value:new Te},viewMatrixInv:{value:new Te},cameraPos:{value:new w},resolution:{value:new ee},time:{value:0},samples:{value:[]},bluenoise:{value:null},distanceFalloff:{value:1},radius:{value:5},near:{value:.1},far:{value:1e3},logDepth:{value:!1},ortho:{value:!1},screenSpaceRadius:{value:!1},frame:{value:0}},depthWrite:!1,depthTest:!1,vertexShader:`
5543
+ `,defines:{USE_LIGHTMAP:""}})}}var ooe=Object.defineProperty,aoe=Object.getOwnPropertyDescriptor,Tc=(i,e,t,s)=>{for(var r=s>1?void 0:s?aoe(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&ooe(e,t,r),r};const Ix=te("debugrenderer"),loe=te("debugskinnedmesh"),jz=te("noInstancing"),a0=te("debuginstancing"),coe=te("debugprogressive"),hoe=te("noprogressive"),uoe=te("wireframe");class o2{constructor(){h(this,"path",null),h(this,"asset",null),h(this,"default")}}class doe{constructor(e,t){h(this,"_renderer"),h(this,"_targets",[]),h(this,"_indexMapMaxIndex"),h(this,"_indexMap"),h(this,"_changed",!1),this._renderer=e;const s=this.setMaterial.bind(this),r=this.getMaterial.bind(this),n=e.gameObject;if(this._targets=[],n)switch(n.type){case"Group":this._targets=[...n.children];break;case"SkinnedMesh":case"Mesh":this._targets.push(n);break}let o=!1,a,l=0;for(let c=0;c<this._targets.length;c++){const u=this._targets[c];if(!u)continue;const d=u.material;if(d){d.shadowSide=d.side;for(let p=0;p<t.length;p++){const f=t[p];if(!f){o=!0;continue}if(d.name===f.name){a===void 0&&(a=new Map),a.set(p,c),l=Math.max(l,p);break}}}}if(o){this._indexMapMaxIndex=l,this._indexMap=a;const c=`Renderer ${e.name} was initialized with missing materials - this may lead to unexpected behaviour when trying to access sharedMaterials by index.`;console.warn(c),vn()&&ns("Found renderer with missing materials: please check the console for details.")}return new Proxy(this,{get(c,u){if(typeof u=="string"){const d=parseInt(u);if(!isNaN(d))return r(d)}return c[u]},set(c,u,d){return typeof u=="string"&&s(d,Number.parseInt(u)),Reflect.set(c,u,d)?(d instanceof Ot&&(c.changed=!0),!0):!1}})}get changed(){return this._changed}set changed(e){e===!0&&Ix&&console.warn("SharedMaterials have changed: "+this._renderer.name,this),this._changed=e}is(e){return this._renderer===e}get length(){return this._indexMapMaxIndex!==void 0?this._indexMapMaxIndex+1:this._targets.length}*[Symbol.iterator](){for(let e=0;e<this.length;e++)yield this.getMaterial(e)}resolveIndex(e){const t=this._indexMap;return t&&t.has(e)?t.get(e):e}setMaterial(e,t){if(t=this.resolveIndex(t),t<0||t>=this._targets.length)return;const s=this._targets[t];!s||s.material===void 0||(s.material=e,this.changed=!0)}getMaterial(e){if(e=this.resolveIndex(e),e<0)return null;const t=this._targets;if(e>=t.length)return null;const s=t[e];return s?s.material:null}}const Gz=class extends Be{constructor(){super(...arguments),h(this,"receiveShadows",!1),h(this,"shadowCastingMode",0),h(this,"lightmapIndex",-1),h(this,"lightmapScaleOffset",new $e(1,1,0,0)),h(this,"enableInstancing"),h(this,"renderOrder"),h(this,"allowOcclusionWhenDynamic",!0),h(this,"probeAnchor"),h(this,"reflectionProbeUsage",0),h(this,"_lightmaps"),h(this,"_sharedMeshes",[]),h(this,"_sharedMaterials"),h(this,"_originalMaterials"),h(this,"_lightmapTextureOverride"),h(this,"allowProgressiveLoading",!0),h(this,"_isInstancingEnabled",!1),h(this,"handles"),h(this,"onBeforeRenderThree",(i,e,t,s,r,n)=>{var o;if(r.envMapIntensity!==void 0){const a=this.hasLightmap?Math.PI:1,l=((o=this.context.mainCameraComponent)==null?void 0:o.environmentIntensity)??1;r.envMapIntensity=Math.max(0,l*this.context.sceneLighting.environmentIntensity/a)}if(this._lightmaps)for(const a of this._lightmaps)a.updateLightmapUniforms(r)}),h(this,"_reflectionProbe",null)}static setVisible(i,e){Uf(i,e)}get sharedMesh(){if(this.gameObject.type==="Mesh")return this.gameObject;if(this.gameObject.type==="SkinnesMesh")return this.gameObject;if(this.gameObject.type==="Group")return this.gameObject.children[0]}get sharedMeshes(){if(this.destroyed||!this.gameObject)return this._sharedMeshes;if(this._sharedMeshes.length=0,this.gameObject.type==="Group")for(const i of this.gameObject.children)(i.type==="Mesh"||i.type==="SkinnedMesh")&&this._sharedMeshes.push(i);else(this.gameObject.type==="Mesh"||this.gameObject.type==="SkinnedMesh")&&this._sharedMeshes.push(this.gameObject);return this._sharedMeshes}get sharedMaterial(){return this.sharedMaterials[0]}set sharedMaterial(i){this.sharedMaterials[0]!==i&&(this.sharedMaterials[0]=i,this.applyLightmapping())}get material(){return this.sharedMaterials[0]}set material(i){this.sharedMaterial=i}set sharedMaterials(i){if(!this._originalMaterials)this._originalMaterials=i;else if(i){let e=!1;for(let t=0;t<this._sharedMaterials.length;t++){const s=t<i.length?i[t]:null;s&&s instanceof Ot?this.sharedMaterials[t]=s:e||(e=!0,console.warn("Can not assign null as material: "+this.name,s))}}}get sharedMaterials(){return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._originalMaterials||(this._originalMaterials=[]),this._sharedMaterials=new doe(this,this._originalMaterials)),this._sharedMaterials}static get shouldSuppressInstancing(){return jz}get lightmap(){var i;return(i=this._lightmaps)!=null&&i.length?this._lightmaps[0].lightmap:null}set lightmap(i){var e;if(this._lightmapTextureOverride=i,i===void 0&&(i=this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex)),(e=this._lightmaps)!=null&&e.length)for(const t of this._lightmaps)t.lightmap=i}get hasLightmap(){return this.lightmap!=null}registering(){this.enabled||this.setVisibility(!1)}awake(){if(Ix&&console.log("Renderer ",this.name,this),this.clearInstancingState(),this.probeAnchor&&Ix&&this.probeAnchor.add(new Ro(.2)),this._reflectionProbe=null,this.isMultiMaterialObject(this.gameObject)){for(const i of this.gameObject.children)this.context.addBeforeRenderListener(i,this.onBeforeRenderThree),i.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let i=0;for(let e=0;e<this.gameObject.children.length;e++){const t=this.gameObject.children[e];if(!(!this.isMeshOrSkinnedMesh(t)||re.getComponent(t,Gz))){if(this.renderOrder.length<=i){console.warn("Incorrect renderOrder element count",this,this.renderOrder.length+" but expected "+this.gameObject.children.length,"Index: "+i,"ChildElement:",t);continue}t.renderOrder=this.renderOrder[i],i+=1}}}}else this.isMeshOrSkinnedMesh(this.gameObject)?(this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree),this.renderOrder!==void 0&&this.renderOrder.length>0&&(this.gameObject.renderOrder=this.renderOrder[0])):this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree);if(this.applyLightmapping(),uoe)for(let i=0;i<this.sharedMaterials.length;i++){const e=this.sharedMaterials[i];e&&(e.wireframe=!0)}}applyLightmapping(){var i;if(this.lightmapIndex>=0){const e=this.gameObject.type,t=this._lightmapTextureOverride!==void 0?this._lightmapTextureOverride:this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex);if(t){if(this._lightmaps||(this._lightmaps=[]),e==="Mesh"){const s=this.gameObject.material;if(s!=null&&s.isMeshBasicMaterial)s&&console.warn("Lightmapping is not supported on MeshBasicMaterial",s.name);else{if(this._lightmaps.length<=0){const r=new o0(this.gameObject,this.context);this._lightmaps.push(r)}this._lightmaps[0].init(this.lightmapIndex,this.lightmapScaleOffset,t)}}else if(this.isMultiMaterialObject(this.gameObject)&&this.sharedMaterials.length>0)for(let s=0;s<this.gameObject.children.length;s++){const r=this.gameObject.children[s];if(!((i=r.material)!=null&&i.isMeshBasicMaterial)){let n;s>=this._lightmaps.length?(n=new o0(r,this.context),this._lightmaps.push(n)):n=this._lightmaps[s],n.init(this.lightmapIndex,this.lightmapScaleOffset,t)}}}else Ix&&console.warn("Lightmap not found",this.sourceId,this.lightmapIndex)}}clearInstancingState(){this._isInstancingEnabled=!1,this.handles=void 0}setInstancingEnabled(i){if(this._isInstancingEnabled===i)return i&&(this.handles===void 0||this.handles!=null&&this.handles.length>0);if(this._isInstancingEnabled=i,i){if(this.handles===void 0){if(this.handles=foe.setup(this,this.gameObject,this.context,null,{rend:this,foundMeshes:0,useMatrixWorldAutoUpdate:this.useInstanceMatrixWorldAutoUpdate()}),this.handles)return re.markAsInstancedRendered(this.gameObject,!0),!0}else if(this.handles!==null){for(const e of this.handles)e.updateInstanceMatrix(!0),e.add();return re.markAsInstancedRendered(this.gameObject,!0),!0}}else{if(this.handles)for(const e of this.handles)e.remove();return!0}return!1}useInstanceMatrixWorldAutoUpdate(){return!0}start(){if(this.enableInstancing&&!jz&&(this.setInstancingEnabled(!0),Fa.markDirty(this.gameObject)),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.isMultiMaterialObject(this.gameObject))for(let i=0;i<this.gameObject.children.length;i++){const e=this.gameObject.children[i];e.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this.sharedMeshes,this.setVisibility(!0),this._isInstancingEnabled?this.setInstancingEnabled(!0):this.enabled&&this.applyStencil(),this.updateReflectionProbe()}onDisable(){this.setVisibility(!1),this.handles&&this.handles.length>0&&this.setInstancingEnabled(!1)}onDestroy(){if(this.handles=null,this.isMultiMaterialObject(this.gameObject))for(const i of this.gameObject.children)this.context.removeBeforeRenderListener(i,this.onBeforeRenderThree);else this.context.removeBeforeRenderListener(this.gameObject,this.onBeforeRenderThree)}applyStencil(){s2.applyStencil(this)}onBeforeRender(){var i,e;if(this.gameObject){if(this.isMultiMaterialObject(this.gameObject)&&((i=this.gameObject.children)==null?void 0:i.length)>0)for(const t of this.gameObject.children)this.applySettings(t);else this.applySettings(this.gameObject);if(this.sharedMaterials.changed&&(this.sharedMaterials.changed=!1,this.applyLightmapping()),(e=this.handles)!=null&&e.length&&this.gameObject[Ng]===!0){a0&&console.log("UPDATE INSTANCED MATRICES",this.context.time.frame),this.gameObject[Ng]=!1;for(let t=this.handles.length-1;t>=0;t--)this.handles[t].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this.handles&&this.handles.length<=0&&re.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this.handles)for(let t=0;t<this.handles.length;t++){const s=this.handles[t];Uf(s.object,!1)}for(const t of this.sharedMaterials)t&&this.loadProgressiveTextures(t);this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onSet(this)}}onAfterRender(){if(this._isInstancingEnabled&&this.handles)for(let i=0;i<this.handles.length;i++){const e=this.handles[i];Uf(e.object,!0)}this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onUnset(this)}loadProgressiveTextures(i){return!hoe&&i&&i._didRequestTextureLOD===void 0&&this.allowProgressiveLoading?(i._didRequestTextureLOD=0,coe&&console.log("Load material LOD",i.name),Hn.assignTextureLOD(this.context,this.sourceId,i)):Promise.resolve(!0)}applySettings(i){i.receiveShadow=this.receiveShadows,this.shadowCastingMode==1?i.castShadow=!0:i.castShadow=!1}updateReflectionProbe(){if(this._reflectionProbe=null,this.reflectionProbeUsage!==0){if(!this.probeAnchor)return;this.startCoroutine(this._updateReflectionProbe(),Os.LateUpdate)}}*_updateReflectionProbe(){const i=this.probeAnchor||this.gameObject,e=!!this.probeAnchor;this._reflectionProbe=Nf.get(i,this.context,e,this.probeAnchor)}setVisibility(i){if(!this.isMultiMaterialObject(this.gameObject))Uf(this.gameObject,i);else for(const e of this.gameObject.children)this.isMeshOrSkinnedMesh(e)&&Uf(e,i)}isMultiMaterialObject(i){return i.type==="Group"}isMeshOrSkinnedMesh(i){return i.type==="Mesh"||i.type==="SkinnedMesh"}};let As=Gz;Tc([x()],As.prototype,"receiveShadows",2),Tc([x()],As.prototype,"shadowCastingMode",2),Tc([x()],As.prototype,"lightmapIndex",2),Tc([x($e)],As.prototype,"lightmapScaleOffset",2),Tc([x()],As.prototype,"enableInstancing",2),Tc([x()],As.prototype,"renderOrder",2),Tc([x()],As.prototype,"allowOcclusionWhenDynamic",2),Tc([x(Ae)],As.prototype,"probeAnchor",2),Tc([x()],As.prototype,"reflectionProbeUsage",2);class l0 extends As{}class a2 extends l0{awake(){var e;super.awake(),this.allowOcclusionWhenDynamic=!1,(e=this.gameObject.parent)==null||e.updateWorldMatrix(!1,!0)}onBeforeRender(){if(super.onBeforeRender(),loe&&this.gameObject instanceof da&&this.gameObject.boundingSphere){const e=Bs(this.gameObject.boundingSphere.center).applyMatrix4(this.gameObject.matrixWorld);Tt.DrawWireSphere(e,this.gameObject.boundingSphere.radius,"red")}}}class poe{constructor(){h(this,"objs",[])}setup(e,t,s,r,n,o=0){e.applySettings(t);const a=this.tryCreateOrAddInstance(t,s,n);if(a)e.loadProgressiveTextures(a.instancer.material),r===null&&(r=[]),r.push(a);else if(o<=0&&t.type!=="Mesh"){const l=o+1;for(const c of t.children)r=this.setup(e,c,s,r,n,l)}return o===0&&n.useMatrixWorldAutoUpdate&&r&&r.length>=0&&this.autoUpdateInstanceMatrix(t),r}tryCreateOrAddInstance(e,t,s){if(e.type==="Mesh"){const r=s.foundMeshes;if(s.foundMeshes+=1,!s.rend.enableInstancing||r>=s.rend.enableInstancing.length||!s.rend.enableInstancing[r])return null;const n=e,o=n.geometry,a=n.material;for(const c of this.objs)if(!c.isFull()&&c.geo===o&&c.material===a)return c.addInstance(n);const l=new Vz(e.name,o,a,200,t);return this.objs.push(l),l.addInstance(n)}return null}autoUpdateInstanceMatrix(e){const t=e.matrixWorld.multiplyMatrices.bind(e.matrixWorld),s=e.matrixWorld.clone(),r=(n,o)=>{const a=t(n,o);return(e[Ng]||s.equals(a)===!1)&&(s.copy(a),e[Ng]=!0),a};e.matrixWorld.multiplyMatrices=r}}const foe=new poe;class moe{constructor(e,t,s){h(this,"instanceIndex",-1),h(this,"object"),h(this,"instancer"),this.instanceIndex=e,this.object=t,this.instancer=s,t[_3]=s,re.markAsInstancedRendered(t,!0)}get name(){return this.object.name}updateInstanceMatrix(e=!1){this.instanceIndex<0||(this.object.updateWorldMatrix(!0,e),this.instancer.updateInstance(this.object.matrixWorld,this.instanceIndex))}setMatrix(e){this.instanceIndex<0||this.instancer.updateInstance(e,this.instanceIndex)}add(){this.instanceIndex>=0||this.instancer.add(this)}remove(){this.instanceIndex<0||this.instancer.remove(this)}}const Qz=class{constructor(i,e,t,s,r){h(this,"name",""),h(this,"geo"),h(this,"material"),h(this,"context"),h(this,"inst"),h(this,"handles",[]),h(this,"maxCount"),h(this,"_needUpdateBounds",!1),h(this,"onBeforeRender",()=>{this.inst.layers.enableAll(),this._needUpdateBounds&&this.inst[cM]===!0&&(a0&&console.log("Update instancing bounds",this.name,this.inst.matrixWorldNeedsUpdate),this.updateBounds())}),h(this,"onAfterRender",()=>{this.inst.layers.disableAll()}),this.name=i,this.geo=e,this.material=t,this.context=r,this.maxCount=s,a0&&(t=new ni({color:this.randomColor()})),this.inst=new Cy(e,t,s),this.inst[cM]=!0,this.inst.count=0,this.inst.visible=!0,this.context.scene.add(this.inst),t instanceof cg&&(t.defines.USE_INSTANCING=!0,t.needsUpdate=!0),r.pre_render_callbacks.push(this.onBeforeRender),r.post_render_callbacks.push(this.onAfterRender)}get mesh(){return this.inst}get visible(){return this.inst.visible}set visible(i){this.inst.visible=i}get castShadow(){return this.inst.castShadow}set castShadow(i){this.inst.castShadow=i}set receiveShadow(i){this.inst.receiveShadow=i}updateBounds(i=!0,e=!0){this._needUpdateBounds=!1,i&&this.inst.computeBoundingBox(),e&&this.inst.computeBoundingSphere()}get currentCount(){return this.inst.count}isFull(){return this.currentCount>=this.maxCount}randomColor(){return new we(Math.random(),Math.random(),Math.random())}addInstance(i){if(this.currentCount>=this.maxCount)return console.error("TOO MANY INSTANCES - resize is not yet implemented!",this.inst.count),null;const e=new moe(-1,i,this);return i.castShadow===!0&&this.inst.castShadow===!1&&(this.inst.castShadow=!0),i.receiveShadow===!0&&this.inst.receiveShadow===!1&&(this.inst.receiveShadow=!0),this.add(e),e}add(i){i.instanceIndex<0&&(i.instanceIndex=this.currentCount,i.instanceIndex>=this.handles.length?this.handles.push(i):this.handles[i.instanceIndex]=i),i.object.updateWorldMatrix(!0,!0),this.inst.setMatrixAt(i.instanceIndex,i.object.matrixWorld),this.inst.instanceMatrix.needsUpdate=!0,this.inst.count+=1,this._needUpdateBounds=!0,this.inst.count>0&&(this.inst.visible=!0),a0&&console.log("Added",this.name,this.inst.count)}remove(i){if(!(!i||i.instanceIndex<0||i.instanceIndex>=this.handles.length||this.inst.count<=0)){if(this.handles[i.instanceIndex]!==i){console.error("instance handle is not part of renderer, was it removed before?",i.instanceIndex,this.name);const e=this.handles.indexOf(i);if(e<0)return;i.instanceIndex=e}if(this.handles[i.instanceIndex]=null,this.inst.setMatrixAt(i.instanceIndex,Qz.nullMatrix),!(i.instanceIndex>=this.currentCount-1)&&this.currentCount>0){const e=this.handles[this.currentCount-1];e&&(e.instanceIndex=i.instanceIndex,e.updateInstanceMatrix(),this.handles[i.instanceIndex]=e,this.handles[this.currentCount-1]=null)}this.inst.count>0&&(this.inst.count-=1),i.instanceIndex=-1,this._needUpdateBounds=!0,this.inst.count<=0&&(this.inst.visible=!1),this.inst.instanceMatrix.needsUpdate=!0,a0&&console.log("Removed",this.name,this.inst.count)}}updateInstance(i,e){this.inst.setMatrixAt(e,i),this.inst.instanceMatrix.needsUpdate=!0,this._needUpdateBounds=!0}};let Vz=Qz;h(Vz,"nullMatrix",new Te);var goe=Object.defineProperty,voe=Object.getOwnPropertyDescriptor,as=(i,e,t,s)=>{for(var r=s>1?void 0:s?voe(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&goe(e,t,r),r};const Hz=te("debugusdzbehaviours");function c0(i){i&&(i.getComponentInParent(Dv)||(wt()&&console.warn("Create Raycaster on "+i.name+" because no raycaster was found in the hierarchy"),i.addNewComponent(ao)))}class Cd extends Be{constructor(){super(...arguments),h(this,"object"),h(this,"target"),h(this,"duration",1),h(this,"relativeMotion",!1),h(this,"coroutine",null),h(this,"targetPos",new w),h(this,"targetRot",new Ie),h(this,"targetScale",new w)}start(){c0(this.gameObject)}onPointerClick(e){e.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 e=Rt(this.object).clone(),t=Rt(this.target).clone(),s=Ri(this.object).clone(),r=Ri(this.target).clone(),n=ss(this.object).clone(),o=ss(this.target).clone(),a=e.distanceTo(t),l=s.angleTo(r),c=n.distanceTo(o);if(a<.01&&l<.01&&c<.01){Jr(this.object,t),zo(this.object,r),Cg(this.object,o),this.coroutine=null;return}let u=0,d=0;for(;u<1;)u+=this.context.time.deltaTime/this.duration,u>1&&(u=1),d=u<.5?4*u*u*u:1-Math.pow(-2*u+2,3)/2,this.targetPos.lerpVectors(e,t,d),this.targetRot.slerpQuaternions(s,r,d),this.targetScale.lerpVectors(n,o,d),Jr(this.object,this.targetPos),zo(this.object,this.targetRot),Cg(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const e=this.object.position.clone(),t=this.object.quaternion.clone(),s=this.object.scale.clone(),r=this.target.position.clone(),n=this.target.quaternion.clone(),o=this.target.scale.clone();r.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(r),this.targetRot.copy(this.object.quaternion).multiply(n),this.targetScale.copy(this.object.scale).multiply(o);let a=0,l=0;for(;a<1;)a+=this.context.time.deltaTime/this.duration,a>1&&(a=1),l=a<.5?4*a*a*a:1-Math.pow(-2*a+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,l),this.object.quaternion.slerpQuaternions(t,this.targetRot,l),this.object.scale.lerpVectors(s,this.targetScale,l),yield;this.coroutine=null}beforeCreateDocument(e){var t;if(this.target&&this.object&&this.gameObject){const s=new Cr("Move to "+((t=this.target)==null?void 0:t.name),Er.tapTrigger(this.gameObject),di.transformAction(this.object,this.target,this.duration,this.relativeMotion?hI.Relative:hI.Absolute));e.addBehavior(s)}}}as([x(Ae)],Cd.prototype,"object",2),as([x(Ae)],Cd.prototype,"target",2),as([x()],Cd.prototype,"duration",2),as([x()],Cd.prototype,"relativeMotion",2);var Rx;const Ic=(Rx=class extends Be{constructor(){super(...arguments),h(this,"materialToSwitch"),h(this,"variantMaterial"),h(this,"fadeDuration",0),h(this,"_objectsWithThisMaterial",[]),h(this,"selfModel"),h(this,"targetModels")}awake(){if(this.variantMaterial&&this.materialToSwitch){const i=re.findObjectsOfType(As);for(const e of i)for(let t=0;t<e.sharedMaterials.length;t++){const s=e.sharedMaterials[t];if(s===this.materialToSwitch){if(e.gameObject instanceof ge)this._objectsWithThisMaterial.push(e.gameObject);else if(e.gameObject instanceof fn)for(const r of e.gameObject.children)r instanceof ge&&r.material===s&&this._objectsWithThisMaterial.push(r);break}}}}start(){c0(this.gameObject)}onPointerClick(i){if(i.use(),!!this.variantMaterial)for(let e=0;e<this._objectsWithThisMaterial.length;e++){const t=this._objectsWithThisMaterial[e];t.material=this.variantMaterial}}async beforeCreateDocument(i,e){this.targetModels=[],Ic._materialTriggersPerId={},Ic.variantSwitchIndex=0,this.materialToSwitch&&await Hn.assignTextureLOD(this.context,this.sourceId,this.materialToSwitch,0),this.variantMaterial&&await Hn.assignTextureLOD(this.context,this.sourceId,this.variantMaterial,0)}createBehaviours(i,e,t){this._objectsWithThisMaterial.find(s=>s.uuid===e.uuid)&&this.targetModels.push(e),this.gameObject.uuid===e.uuid&&(this.selfModel=e,this.materialToSwitch&&(Ic._materialTriggersPerId[this.materialToSwitch.uuid]||(Ic._materialTriggersPerId[this.materialToSwitch.uuid]=[]),Ic._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(i,e){if(!this.materialToSwitch)return;const t=Ic._materialTriggersPerId[this.materialToSwitch.uuid];if(t){const s={};for(const r of t){const n=r.createVariants();n&&n.length>0&&(s[r.selfModel.uuid]=n)}for(const r of t){const n=[];for(const o in s)o!==r.selfModel.uuid&&n.push(...s[o]);r.createAndAttachBehaviors(i,s[r.selfModel.uuid],n)}}delete Ic._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(i,e,t){const s=[],r=[],n=Math.max(0,this.fadeDuration);r.push(di.fadeAction([...this.targetModels,...t],n,!1)),s.push(di.fadeAction(e,n,!1)),r.push(di.fadeAction(e,n,!0)),i.addBehavior(new Cr("Select_"+this.selfModel.name,Er.tapTrigger(this.selfModel),di.parallel(...r))),i.addBehavior(new Cr("StartHidden_"+this.selfModel.name,Er.sceneStartTrigger(),di.parallel(...s)))}createVariants(){if(!this.variantMaterial)return null;const i=[];for(const e of this.targetModels){const t=e.clone();t.name+=" variant_"+this.variantMaterial.name+"_"+Ic.variantSwitchIndex++,t.name=t.name.replace(/\s/g,"_"),t.material=this.variantMaterial,t.geometry=e.geometry,t.matrix=e.matrix,(!e.parent||!e.parent.isEmpty())&&Wo.createEmptyParent(e),e.parent&&e.parent.add(t),i.push(t)}return i}},h(Rx,"_materialTriggersPerId",{}),h(Rx,"variantSwitchIndex",0),Rx);let zf=Ic;as([x(Ot)],zf.prototype,"materialToSwitch",2),as([x(Ot)],zf.prototype,"variantMaterial",2),as([x()],zf.prototype,"fadeDuration",2);var jf;const ls=(jf=class extends Be{constructor(){super(...arguments),h(this,"target"),h(this,"toggleOnClick",!1),h(this,"targetState",!0),h(this,"hideSelf",!0),h(this,"selfModel"),h(this,"selfModelClone"),h(this,"targetModel"),h(this,"toggleModel"),h(this,"stateBeforeCreatingDocument",!1),h(this,"targetStateBeforeCreatingDocument",!1)}start(){c0(this.gameObject)}onPointerClick(i){i.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}createBehaviours(i,e,t){e.uuid===this.gameObject.uuid&&(this.selfModel=e,this.selfModelClone=e.clone())}beforeCreateDocument(){this.target&&(this.gameObject[ls.wasVisible]===void 0&&(this.gameObject[ls.wasVisible]=this.gameObject.activeSelf),this.target[ls.wasVisible]===void 0&&(this.target[ls.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[ls.wasVisible],this.targetStateBeforeCreatingDocument=this.target[ls.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(i,e){if(!this.target)return;this.targetModel=e.document.findById(this.target.uuid);const t=this.selfModel;if(this.selfModel&&this.targetModel){let s=this.selfModel,r=this.targetState;if(this.toggleOnClick)if(r=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&k4.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[ls.toggleClone]){const a=this.selfModelClone.clone();a.matrix.identity(),a.name+="_toggle"+ls.clonedToggleIndex++,t.add(a),this.gameObject[ls.toggleClone]=a,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[ls.toggleClone];if(!this.gameObject[ls.reverseToggleClone]){const a=this.selfModelClone.clone();a.matrix.identity(),a.name+="_toggleReverse"+ls.clonedToggleIndex++,t.add(a),this.gameObject[ls.reverseToggleClone]=a}this.toggleModel=this.gameObject[ls.reverseToggleClone],(!this.toggleModel.geometry||!o.geometry)&&console.error("triggers without childs and without geometry won't work!",this,t.geometry),s=o,t.geometry=null,t.material=null}if(this.toggleModel){if(this.toggleOnClick){const o=[];o.push(di.fadeAction(s,0,!1)),o.push(di.fadeAction(this.toggleModel,0,!0)),o.push(di.fadeAction(this.targetModel,0,r)),i.addBehavior(new Cr("Toggle_"+s.name+"_toggleTo"+(r?"On":"Off"),Er.tapTrigger(s),di.parallel(...o)));const a=[];a.push(di.fadeAction(this.toggleModel,0,!1)),a.push(di.fadeAction(s,0,!0)),a.push(di.fadeAction(this.targetModel,0,!r)),i.addBehavior(new Cr("Toggle_"+s.name+"_toggleTo"+(r?"Off":"On"),Er.tapTrigger(this.toggleModel),di.parallel(...a)))}}else{const o=[];this.hideSelf&&o.push(di.fadeAction(s,0,!1)),o.push(di.fadeAction(this.targetModel,0,r)),i.addBehavior(new Cr("Toggle_"+s.name+"_toggleTo"+(r?"On":"Off"),Er.tapTrigger(s),di.parallel(...o)))}const n=new Array;this.targetStateBeforeCreatingDocument||n.push(this.targetModel),this.stateBeforeCreatingDocument||n.push(t),this.toggleModel&&n.push(this.toggleModel),i.addBehavior(new Cr("HideOnStart_"+this.gameObject.name,Er.sceneStartTrigger(),di.fadeAction(n,0,!1)))}}afterSerialize(i,e){this.gameObject[ls.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[ls.wasVisible],delete this.gameObject[ls.wasVisible]),this.target&&this.target[ls.wasVisible]!==void 0&&(this.target.visible=this.target[ls.wasVisible],delete this.target[ls.wasVisible]),delete this.gameObject[ls.toggleClone],delete this.gameObject[ls.reverseToggleClone]}},h(jf,"clonedToggleIndex",0),h(jf,"wasVisible",Symbol("usdz_SetActiveOnClick_wasVisible")),h(jf,"toggleClone",Symbol("clone for toggling")),h(jf,"reverseToggleClone",Symbol("clone for reverse toggling")),jf);let Ed=ls;as([x(Ae)],Ed.prototype,"target",2),as([x()],Ed.prototype,"toggleOnClick",2),as([x()],Ed.prototype,"targetState",2),as([x()],Ed.prototype,"hideSelf",2);class l2 extends Be{start(){this.gameObject.visible=!1}createBehaviours(e,t,s){t.uuid===this.gameObject.uuid&&e.addBehavior(new Cr("HideOnStart_"+this.gameObject.name,Er.sceneStartTrigger(),di.fadeAction(t,0,!1)))}beforeCreateDocument(){this.gameObject.visible=!0}afterCreateDocument(){this.gameObject.visible=!1}}class Gf extends Be{constructor(){super(...arguments),h(this,"target"),h(this,"duration",.5),h(this,"motionType",cI.bounce)}beforeCreateDocument(){}createBehaviours(e,t,s){if(this.target&&t.uuid===this.gameObject.uuid){const r=new Cr("emphasize "+this.name,Er.tapTrigger(this.gameObject),di.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(r)}}afterCreateDocument(e,t){}}as([x()],Gf.prototype,"target",2),as([x()],Gf.prototype,"duration",2),as([x()],Gf.prototype,"motionType",2);class Vh extends Be{constructor(){super(...arguments),h(this,"target"),h(this,"clip",""),h(this,"toggleOnClick",!1)}start(){c0(this.gameObject)}ensureAudioSource(){if(!this.target){const e=this.gameObject.addNewComponent(os);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1)}}onPointerClick(e){var t;e.use(),!(!((t=this.target)!=null&&t.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(e,t,s){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const r=this.clip?this.clip:this.target?this.target.clip:void 0;if(!r||typeof r!="string")return;const n=this.target?this.target.gameObject:this.gameObject,o=cu.getName(r),a=this.target?this.target.volume:1,l=this.target&&this.target.spatialBlend==0?pI.NonSpatial:pI.Spatial;let c=!1;if(this.gameObject.traverse(u=>{u instanceof ge&&u.visible&&(c=!0)}),c=!0,c){let u=di.playAudioAction(n,"audio/"+o,dI.Play,a,l);this.toggleOnClick&&(u.multiplePerformOperation=Y4.Stop),this.target&&this.target.loop&&(u=di.sequence(u).makeLooping());const d=new Cr("playAudio "+this.name,Er.tapTrigger(this.gameObject),u);e.addBehavior(d)}if(this.target&&this.target.playOnAwake&&this.target.enabled){let u=di.playAudioAction(n,"audio/"+o,dI.Play,a,l);this.target.loop&&(u=di.sequence(u).makeLooping());const d=new Cr("playAudioOnStart"+(this.name?"_"+this.name:""),Er.sceneStartTrigger(),u);e.addBehavior(d)}}}async afterSerialize(e,t){if(!this.target&&!this.clip)return;const s=this.clip?this.clip:this.target?this.target.clip:void 0;if(!s||typeof s!="string")return;const r="audio/"+cu.getName(s);if(t.files[r])return;const n=await(await(await fetch(s)).blob()).arrayBuffer(),o=new Uint8Array(n);t.files[r]=o}}as([x(os)],Vh.prototype,"target",2),as([x(URL)],Vh.prototype,"clip",2),as([x()],Vh.prototype,"toggleOnClick",2);var Px;const Hh=(Px=class extends Be{constructor(){super(...arguments),h(this,"animator"),h(this,"stateName"),h(this,"trigger","tap"),h(this,"selfModel"),h(this,"stateAnimationModel"),h(this,"animationSequence",new Array),h(this,"animationLoopAfterSequence",new Array)}get target(){var i;return(i=this.animator)==null?void 0:i.gameObject}start(){c0(this.gameObject)}onPointerClick(i){var e;i.use(),this.target&&this.stateName&&((e=this.animator)==null||e.play(this.stateName,0,0,.1))}createBehaviours(i,e,t){e.uuid===this.gameObject.uuid&&(this.selfModel=e)}afterSerialize(){if(Hh.rootsWithExclusivePlayback.size>1){const i='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.';wt()&&ns(i),console.warn(i,...Hh.rootsWithExclusivePlayback)}Hh.animationActions=[],Hh.rootsWithExclusivePlayback=new Set}afterCreateDocument(i,e){if(!this.animationSequence||!this.stateAnimationModel||!this.target)return;const t=e.document,s=e.extensions.find(o=>o instanceof Qv);if(!s)return;const r=s.getClipCount(this.target)>1;r&&(wt()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+s.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),Hh.rootsWithExclusivePlayback.add(this.target));const n=(o,a)=>{let l=Hh.animationActions.find(c=>c.affectedObjects==o&&c.start==a.start&&c.duration==a.duration);return l||(l=di.startAnimationAction(o,a.start,a.duration),Hh.animationActions.push(l)),l};t.traverse(o=>{var a,l;if(o.uuid===((a=this.target)==null?void 0:a.uuid)){const c=di.sequence();if(this.animationSequence!==void 0)for(const d of this.animationSequence)c.addAction(n(o,d));if(this.animationLoopAfterSequence!==void 0){const d=c.actions.length==0?c:di.sequence();for(const p of this.animationLoopAfterSequence)d.addAction(n(o,p));d.makeLooping(),c!==d&&c.addAction(d)}const u=new Cr("tap "+this.name+" for "+this.stateName+" on "+((l=this.target)==null?void 0:l.name),this.trigger=="tap"?Er.tapTrigger(this.selfModel):Er.sceneStartTrigger(),c);r&&u.makeExclusive(!0),i.addBehavior(u)}})}createAnimation(i,e,t){var s,r,n,o;if(!this.target||!this.animator)return;const a=(s=this.animator)==null?void 0:s.runtimeAnimatorController;let l=a?.findState(this.stateName),c=[],u=[];if(a&&l){const p=new Array;p.push(l);let f=!1;for(;p.length<100;){if(!l||l===null||!l.transitions||l.transitions.length===0){(r=l.motion)!=null&&r.isLooping&&(f=!0);break}const m=l.transitions.find(y=>y.conditions.length===0),A=m?a.getState(m.destinationState,0):null;if(A&&p.includes(A)){l=A,f=!0;break}else if(m){if(l=A,!l)break;p.push(l)}else{f=((n=l.motion)==null?void 0:n.isLooping)??!1;break}}if(f&&l){const m=p.indexOf(l);c=p.slice(0,m),u=p.slice(m),Hz&&console.log("found loop from "+this.stateName,"states until loop",c,"states looping",u)}else c=p,u=[],Hz&&console.log("found no loop from "+this.stateName,"states",c)}if(c=c.filter(p=>{var f,m,A;return((f=p.motion)==null?void 0:f.clip)&&((A=(m=p.motion)==null?void 0:m.clip.tracks)==null?void 0:A.length)>0}),u=u.filter(p=>{var f,m,A;return((f=p.motion)==null?void 0:f.clip)&&((A=(m=p.motion)==null?void 0:m.clip.tracks)==null?void 0:A.length)>0}),c.length===0&&u.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}this.stateAnimationModel=e;const d=(p,f)=>{var m,A,y;if(!this.target)return;if(!((m=p.motion)!=null&&m.clip)){console.warn("No clip found for state "+p.name+" on "+((A=this.animator)==null?void 0:A.name)+", can't export animation data");return}const g=i.registerAnimation(this.target,p.motion.clip);g?f.push(g):console.warn("Couldn't register animation for state "+p.name+" on "+((y=this.animator)==null?void 0:y.name))};if(c.length>0){this.animationSequence=new Array;for(const p of c)d(p,this.animationSequence)}if(u.length>0){this.animationLoopAfterSequence=new Array;for(const p of u)d(p,this.animationLoopAfterSequence)}}},h(Px,"animationActions",[]),h(Px,"rootsWithExclusivePlayback",new Set),Px);let Qf=Hh;as([x(Ir)],Qf.prototype,"animator",2),as([x()],Qf.prototype,"stateName",2);class Vf extends Be{constructor(){super(...arguments),h(this,"target")}getType(){}getDuration(){}}as([x(Ae)],Vf.prototype,"target",2);class h0 extends Be{constructor(){super(...arguments),h(this,"target")}}as([x(Vf)],h0.prototype,"target",2);class u0 extends Vf{constructor(){super(...arguments),h(this,"type",1),h(this,"duration",1)}getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}as([x()],u0.prototype,"type",2),as([x()],u0.prototype,"duration",2);class c2 extends h0{}var Aoe=Object.defineProperty,yoe=Object.getOwnPropertyDescriptor,Rc=(i,e,t,s)=>{for(var r=s>1?void 0:s?yoe(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Aoe(e,t,r),r};const Wz=te("debugcharactercontroller");class Md extends Be{constructor(){super(...arguments),h(this,"center",new w(0,0,0)),h(this,"radius",.5),h(this,"height",2),h(this,"_rigidbody",null),h(this,"_activeGroundCollisions"),h(this,"_contactVelocity",new w)}get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(zi),this._rigidbody||(this._rigidbody=this.gameObject.addNewComponent(zi)),this.rigidbody)}awake(){this._activeGroundCollisions=new Set}onEnable(){const e=this.rigidbody;let t=this.gameObject.getComponent(zh);t||(t=this.gameObject.addNewComponent(zh)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height;const s=new w(0,0,1),r=new w(1,0,0),n=new w(0,1,0),o=this.gameObject.getWorldDirection(new w);o.y=0;const a=r.dot(o)<0?-1:1,l=s.angleTo(o)*a;this.gameObject.setRotationFromAxisAngle(n,l),e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}onCollisionEnter(e){(e.contacts.length==0||e.contacts.some(t=>t.normal.y>.2))&&(this._activeGroundCollisions.add(e),Wz&&console.log(`Collision(${this._activeGroundCollisions.size}): ${e.contacts.map(t=>t.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(e){this._activeGroundCollisions.delete(e),Wz&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}get contactVelocity(){var e;this._contactVelocity.set(0,0,0);for(const t of this._activeGroundCollisions){const s=(e=this.context.physics.engine)==null?void 0:e.getLinearVelocity(t.collider);s&&(this._contactVelocity.x+=s.x,this._contactVelocity.y+=s.y,this._contactVelocity.z+=s.z)}return this._contactVelocity}}Rc([x(w)],Md.prototype,"center",2),Rc([x()],Md.prototype,"radius",2),Rc([x()],Md.prototype,"height",2);class Pc extends Be{constructor(){super(...arguments),h(this,"controller"),h(this,"movementSpeed",2),h(this,"rotationSpeed",2),h(this,"jumpForce",1),h(this,"doubleJumpForce",2),h(this,"animator"),h(this,"lookForward",!0),h(this,"lookInput",new ee(0,0)),h(this,"moveInput",new ee(0,0)),h(this,"jumpInput",!1),h(this,"_currentSpeed",new w(0,0,0)),h(this,"_currentAngularSpeed",new w(0,0,0)),h(this,"_temp",new w(0,0,0)),h(this,"_jumpCount",0),h(this,"_currentRotation"),h(this,"_raycastOptions",new Qo)}awake(){this._currentRotation=new Ie}update(){const e=this.context.input;e.isKeyPressed("KeyW")?this.moveInput.y+=1:e.isKeyPressed("KeyS")&&(this.moveInput.y-=1),e.isKeyPressed("KeyD")?this.lookInput.x+=1:e.isKeyPressed("KeyA")&&(this.lookInput.x-=1),this.jumpInput||(this.jumpInput=e.isKeyDown("Space"))}move(e){this.moveInput.add(e)}look(e){this.lookInput.add(e)}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(e,t,s){var r,n,o,a,l,c,u,d,p,f,m;if((r=this.controller)!=null&&r.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&((n=this.animator)==null||n.setBool("doubleJump",!1))),this._currentSpeed.z+=e.y*this.movementSpeed*this.context.time.deltaTime,(o=this.animator)==null||o.setBool("running",e.length()>.01),(l=this.animator)==null||l.setBool("jumping",((a=this.controller)==null?void 0:a.isGrounded)===!0&&s),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+=st.toRadians(-t.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const A=this.context.mainCameraComponent.forward;A.y=0,A.normalize(),this._currentRotation.setFromUnitVectors(new w(0,0,1),A),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&&s&&this.jumpForce>0){let A=(c=this.controller)==null?void 0:c.isGrounded;if(this.doubleJumpForce>0&&!((u=this.controller)!=null&&u.isGrounded)&&this._jumpCount===1&&(A=!0,(d=this.animator)==null||d.setBool("doubleJump",!0)),A){this._jumpCount+=1;const y=this.controller.rigidbody,g=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;y.applyImpulse(new w(0,1,0).multiplyScalar(g))}}if(this.controller){const A=(p=this.controller)==null?void 0:p.rigidbody.getVelocity().y;if(A<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new Zn),this._raycastOptions.ray.origin.copy(Rt(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const y=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const g=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(y),(g.length&&g[0].distance>2||A<-10)&&((f=this.animator)==null||f.setBool("falling",!0))}else(m=this.animator)==null||m.setBool("falling",!1)}}}Rc([x(Md)],Pc.prototype,"controller",2),Rc([x()],Pc.prototype,"movementSpeed",2),Rc([x()],Pc.prototype,"rotationSpeed",2),Rc([x()],Pc.prototype,"jumpForce",2),Rc([x()],Pc.prototype,"doubleJumpForce",2),Rc([x(Ir)],Pc.prototype,"animator",2);var boe=Object.defineProperty,_oe=Object.getOwnPropertyDescriptor,xoe=(i,e,t,s)=>{for(var r=s>1?void 0:s?_oe(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&boe(e,t,r),r};class d0 extends nn{constructor(){super(...arguments),h(this,"intensity")}get typeName(){return"ChromaticAberration"}init(){this.intensity.defaultValue=0}onCreateEffect(){const e=new j3;return e.offset=new ee(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=t=>t*.02,this.intensity.onValueChanged=t=>{e.offset.x=-t,e.offset.y=t},e}}xoe([x(Bt)],d0.prototype,"intensity",2),Ko("ChromaticAberration",d0);const p0=new vt;p0.setAttribute("position",new Ze(new Float32Array([-1,-1,3,-1,-1,3]),2)),p0.setAttribute("uv",new Ze(new Float32Array([0,0,2,0,0,2]),2)),p0.boundingSphere=new _s,p0.computeBoundingSphere=function(){};const woe=new Vl;class Td{constructor(e){this._mesh=new ge(p0,e),this._mesh.frustumCulled=!1}render(e){e.render(this._mesh,woe)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}dispose(){this._mesh.material.dispose(),this._mesh.geometry.dispose()}}const Soe={uniforms:{sceneDiffuse:{value:null},sceneDepth:{value:null},sceneNormal:{value:null},projMat:{value:new Te},viewMat:{value:new Te},projViewMat:{value:new Te},projectionMatrixInv:{value:new Te},viewMatrixInv:{value:new Te},cameraPos:{value:new w},resolution:{value:new ee},time:{value:0},samples:{value:[]},bluenoise:{value:null},distanceFalloff:{value:1},radius:{value:5},near:{value:.1},far:{value:1e3},logDepth:{value:!1},ortho:{value:!1},screenSpaceRadius:{value:!1},frame:{value:0}},depthWrite:!1,depthTest:!1,vertexShader:`
5544
5544
  varying vec2 vUv;
5545
5545
  void main() {
5546
5546
  vUv = uv;
@@ -6159,7 +6159,7 @@ void main() {
6159
6159
  void main() {
6160
6160
  vec2 uv = vUv - vec2(0.5) / resolution;
6161
6161
  vec2 pixelSize = vec2(1.0) / resolution;
6162
- vec2[4] uvSamples;
6162
+ highp vec2[4] uvSamples;
6163
6163
  uvSamples[0] = uv;
6164
6164
  uvSamples[1] = uv + vec2(pixelSize.x, 0.0);
6165
6165
  uvSamples[2] = uv + vec2(0.0, pixelSize.y);
@@ -6300,7 +6300,7 @@ void main() {
6300
6300
  }`};var joe=Object.defineProperty,Goe=Object.getOwnPropertyDescriptor,b0=(i,e,t,s)=>{for(var r=s>1?void 0:s?Goe(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&joe(e,t,r),r};const f2=te("debugcontactshadows");class Jh extends Be{constructor(){super(...arguments),h(this,"darkness",.5),h(this,"opacity",.5),h(this,"blur",4),h(this,"occludeBelowGround",!0),h(this,"backfaceShadows",!0),h(this,"shadowCamera"),h(this,"shadowGroup"),h(this,"renderTarget"),h(this,"renderTargetBlur"),h(this,"plane"),h(this,"occluderMesh"),h(this,"blurPlane"),h(this,"depthMaterial"),h(this,"horizontalBlurMaterial"),h(this,"verticalBlurMaterial")}awake(){f2&&console.log("Create ContactShadows on "+this.gameObject.name,this);const e=512;this.shadowGroup=new fn,this.gameObject.add(this.shadowGroup),this.renderTarget=new qt(e,e),this.renderTarget.texture.generateMipmaps=!1,this.renderTargetBlur=new qt(e,e),this.renderTargetBlur.texture.generateMipmaps=!1;const t=new Ks(1,1).rotateX(Math.PI/2);if(this.gameObject instanceof ge){f2&&console.log("ContactShadows: use existing mesh",this.gameObject),this.plane=this.gameObject;const s=this.plane.material=this.plane.material.clone();s.map=this.renderTarget.texture,s.opacity=this.opacity}else{const s=new ni({map:this.renderTarget.texture,opacity:this.opacity,color:0,transparent:!0,depthWrite:!1});this.plane=new ge(t,s),this.plane.scale.y=-1,this.gameObject.add(this.plane)}this.plane&&(this.plane.renderOrder=1),this.occludeBelowGround&&(this.occluderMesh=new ge(this.plane.geometry,new ni({depthWrite:!0,stencilWrite:!0,colorWrite:!1})).translateY(-1e-4),this.occluderMesh.renderOrder=-100,this.gameObject.add(this.occluderMesh)),this.blurPlane=new ge(t),this.blurPlane.visible=!1,this.shadowGroup.add(this.blurPlane),this.shadowCamera=new Vl(-1/2,1/2,1/2,-1/2,0,1),this.shadowCamera.rotation.x=Math.PI/2,this.shadowGroup.add(this.shadowCamera),this.depthMaterial=new qm,this.depthMaterial.userData.darkness={value:this.darkness},this.depthMaterial.blending=M1,this.depthMaterial.blendEquation=xA,this.backfaceShadows&&(this.depthMaterial.side=gi),this.depthMaterial.onBeforeCompile=s=>{this.depthMaterial&&(s.uniforms.darkness=this.depthMaterial.userData.darkness,s.fragmentShader=`
6301
6301
  uniform float darkness;
6302
6302
  ${s.fragmentShader.replace("gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );","gl_FragColor = vec4( vec3( 1.0 ), ( 1.0 - fragCoordZ ) * darkness * opacity * (gl_FrontFacing ? 1.0 : 0.66) );")}
6303
- `)},this.depthMaterial.depthTest=!1,this.depthMaterial.depthWrite=!1,this.horizontalBlurMaterial=new Mt(Noe),this.horizontalBlurMaterial.depthTest=!1,this.verticalBlurMaterial=new Mt(zoe),this.verticalBlurMaterial.depthTest=!1,this.shadowGroup.visible=!1}onDestroy(){var e,t,s,r,n,o,a,l;(e=this.renderTarget)==null||e.dispose(),(t=this.renderTargetBlur)==null||t.dispose(),(s=this.depthMaterial)==null||s.dispose(),(r=this.horizontalBlurMaterial)==null||r.dispose(),(n=this.verticalBlurMaterial)==null||n.dispose(),(o=this.blurPlane)==null||o.geometry.dispose(),(a=this.plane)==null||a.geometry.dispose(),(l=this.occluderMesh)==null||l.geometry.dispose()}onBeforeRender(e){const t=this.context.scene,s=this.context.renderer,r=s.getRenderTarget();if(!this.renderTarget||!this.renderTargetBlur||!this.depthMaterial||!this.shadowCamera||!this.blurPlane||!this.shadowGroup||!this.plane||!this.horizontalBlurMaterial||!this.verticalBlurMaterial){f2&&console.error("ContactShadows: not initialized yet");return}this.shadowGroup.visible=!0,this.occluderMesh&&(this.occluderMesh.visible=!1);const n=this.plane.visible;this.plane.visible=!1,this.gameObject instanceof ge&&(this.gameObject.visible=!1,Uf(this.gameObject,!1));const o=t.background;t.background=null,t.overrideMaterial=this.depthMaterial;const a=s.getClearAlpha();s.setClearAlpha(0),s.setRenderTarget(this.renderTarget),s.render(t,this.shadowCamera),t.overrideMaterial=null,this.blurShadow(this.blur),this.blurShadow(this.blur*.4),this.shadowGroup.visible=!1,this.occluderMesh&&(this.occluderMesh.visible=!0),this.plane.visible=n,s.setRenderTarget(r),s.setClearAlpha(a),t.background=o}blurShadow(e){if(!this.blurPlane||!this.shadowCamera||!this.renderTarget||!this.renderTargetBlur||!this.horizontalBlurMaterial||!this.verticalBlurMaterial)return;this.blurPlane.visible=!0,this.blurPlane.material=this.horizontalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTarget.texture,this.horizontalBlurMaterial.uniforms.h.value=e*1/256;const t=this.context.renderer,s=t.getRenderTarget();t.setRenderTarget(this.renderTargetBlur),t.render(this.blurPlane,this.shadowCamera),this.blurPlane.material=this.verticalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTargetBlur.texture,this.verticalBlurMaterial.uniforms.v.value=e*1/256,t.setRenderTarget(this.renderTarget),t.render(this.blurPlane,this.shadowCamera),this.blurPlane.visible=!1,t.setRenderTarget(s)}}b0([x()],Jh.prototype,"darkness",2),b0([x()],Jh.prototype,"opacity",2),b0([x()],Jh.prototype,"blur",2),b0([x()],Jh.prototype,"occludeBelowGround",2),b0([x()],Jh.prototype,"backfaceShadows",2);var Qoe=Object.defineProperty,Voe=Object.getOwnPropertyDescriptor,_0=(i,e,t,s)=>{for(var r=s>1?void 0:s?Voe(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Qoe(e,t,r),r};const Zz=te("debugwebxr"),Hoe=new Te().makeRotationY(Math.PI);class go extends Be{constructor(){super(...arguments),h(this,"_arScale",1),h(this,"invertForward",!1),h(this,"customReticle"),h(this,"useXRAnchor",!1),h(this,"arTouchTransform",!1),h(this,"_isPlacing",!0),h(this,"_startOffset",new Te),h(this,"_createdPlacementObject",null),h(this,"_reparentedComponents",[]),h(this,"_placementScene",new qr),h(this,"_reticle",[]),h(this,"_hits",[]),h(this,"_placementStartTime",-1),h(this,"_rigPlacementMatrix"),h(this,"_anchor",null),h(this,"userInput"),h(this,"onPlaceScene",e=>{var t;if(this._isPlacing==!1)return;let s=this._reticle[0],r=this._hits[0];if(e.origin instanceof GM){const n=this._reticle[e.origin.index];n&&(s=n,r=this._hits[e.origin.index])}if(!s){console.warn("No reticle to place...");return}if(!s.visible){console.warn("Reticle is not visible (can not place)");return}if((t=mt.active)!=null&&t.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}e.stopImmediatePropagation(),e.use(),this._isPlacing=!1,this.context.input.removeEventListener("pointerup",this.onPlaceScene),this.onRevertSceneChanges(),this.onApplyPose(s),this.useXRAnchor&&this.onCreateAnchor(mt.active,r)})}get arScale(){return this._arScale}set arScale(e){e!==this._arScale&&(this._arScale=e,this.onScaleChanged())}onEnable(){var e;(e=this.customReticle)==null||e.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){Zz&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new Ae;this._createdPlacementObject=t,t.name="AR Session Root",this._placementScene.name="AR Placement Scene",this._placementScene.children.length=0;for(let s=this.context.scene.children.length-1;s>=0;s--){const r=this.context.scene.children[s];this._placementScene.add(r)}this.context.scene.add(t),this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),re.addComponent(t,this);for(const s of this._reticle)Ca(s);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,el.Early)}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,el.Early),this.onRevertSceneChanges(),this._anchor=null,this._rigPlacementMatrix=void 0}onUpdateXR(e){var t,s,r,n;if(e.xr.isTrackingImages){for(const o of this._reticle)o.visible=!1;return}if(this._isPlacing){const o=(t=e.xr.rig)==null?void 0:t.gameObject;o&&o.parent!==this.context.scene&&this.context.scene.add(o);let a=!1;if(e.xr.isPassThrough&&e.xr.controllers.length>0)for(const l of e.xr.controllers){const c=l.getHitTest();c&&(a=!0,this.updateReticleAndHits(e.xr,l.index,c,e.xr.rigScale))}if(!a){const l=e.xr.getHitTest();l&&this.updateReticleAndHits(e.xr,0,l,e.xr.rigScale)}}else{if(this._anchor&&e.xr.referenceSpace){const o=e.xr.frame.getPose(this._anchor.anchorSpace,e.xr.referenceSpace);if(o&&this.context.time.frame%20===0){const a=e.xr.convertSpace(o.transform),l=this._reticle[0];l&&(l.position.copy(a.position),l.quaternion.copy(a.quaternion),this.onApplyPose(l))}}if(this.arTouchTransform?(this.userInput||(this.userInput=new Gx(this.context)),(s=this.userInput)==null||s.enable()):(r=this.userInput)==null||r.disable(),this.arTouchTransform&&(n=this.userInput)!=null&&n.hasChanged){if(e.xr.rig){const o=e.xr.rig.gameObject;this.userInput.applyMatrixTo(o.matrix,!0),o.matrix.decompose(o.position,o.quaternion,o.scale),this.userInput.factor=o.scale.x}this.userInput.reset()}}}updateReticleAndHits(e,t,s,r){this._hits[t]=s.hit;let n=this._reticle[t];if(!n){if(this.customReticle)if(this.customReticle.asset)n=cf(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else n=new ge(new $d(.07,.09,32).rotateX(-Math.PI/2),new ni({side:gi})),n.name="AR Placement Reticle";if(Zz){const o=new Ro(1);o.position.y+=.01,n.add(o)}this._reticle[t]=n,n.matrixAutoUpdate=!1,n.visible=!1}n.position.lerp(s.position,this.context.time.deltaTime/.1),n.quaternion.slerp(s.quaternion,this.context.time.deltaTime/.05),n.scale.set(r,r,r),this.customReticle&&this.applyViewBasedTransform(n),n.updateMatrix(),n.visible=!0,n.parent!==this.context.scene&&this.context.scene.add(n),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup)}onScaleChanged(){}onRevertSceneChanges(){var e;for(const t of this._reticle)t&&(t.visible=!1,t?.removeFromParent());this._reticle.length=0;for(let t=this._placementScene.children.length-1;t>=0;t--){const s=this._placementScene.children[t];this.context.scene.add(s)}(e=this._createdPlacementObject)==null||e.removeFromParent();for(const t of this._reparentedComponents)re.addComponent(t.originalObject,t.comp)}async onCreateAnchor(e,t){if(t.createAnchor===void 0){console.warn("Hit does not support creating an anchor",t),wt()&&ns("Hit does not support creating an anchor");return}else{const s=await t.createAnchor(e.viewerPose.transform);e.running&&s&&(this._anchor=s)}}applyViewBasedTransform(e){const t=this.context.mainCamera,s=e,r=t.worldPosition,n=s.worldPosition;r.y=n.y,e.lookAt(r)}onApplyPose(e){var t,s,r,n;const o=(s=(t=mt.active)==null?void 0:t.rig)==null?void 0:s.gameObject;if((r=mt.active)!=null&&r.rigScale,o){const a=o.parent||this.context.scene;this._rigPlacementMatrix?(n=this._rigPlacementMatrix)==null||n.decompose(o.position,o.quaternion,o.scale):this._rigPlacementMatrix=o.matrix.clone(),this.applyViewBasedTransform(e),e.updateMatrix(),this.context.scene.add(e),e.attach(o),e.removeFromParent(),o.scale.set(this.arScale,this.arScale,this.arScale),o.position.multiplyScalar(this.arScale),o.updateMatrix(),this.invertForward&&o.matrix.premultiply(Hoe),o.matrix.premultiply(this._startOffset),o.matrix.decompose(o.position,o.quaternion,o.scale),a.add(o)}}}_0([x()],go.prototype,"arScale",1),_0([x()],go.prototype,"invertForward",2),_0([x(ai)],go.prototype,"customReticle",2),_0([x()],go.prototype,"useXRAnchor",2),_0([x()],go.prototype,"arTouchTransform",2);const m2=class{constructor(i){h(this,"oneFingerDrag",!0),h(this,"twoFingerRotate",!0),h(this,"twoFingerScale",!0),h(this,"factor",1),h(this,"context"),h(this,"offset"),h(this,"plane"),h(this,"_scale",1),h(this,"_hasChanged",!1),h(this,"_enabled",!1),h(this,"currentlyUsedPointerIds",new Set),h(this,"currentlyUnusedPointerIds",new Set),h(this,"onPointerDownEarly",e=>{this.isActive&&e.stopPropagation()}),h(this,"onPointerDownLate",e=>{e.used?this.currentlyUsedPointerIds.add(e.pointerId):this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.add(e.pointerId)}),h(this,"onPointerUpEarly",e=>{this.currentlyUsedPointerIds.delete(e.pointerId),this.currentlyUnusedPointerIds.delete(e.pointerId)}),h(this,"prev",new Map),h(this,"_didMultitouch",!1),h(this,"touchStart",e=>{for(let t=0;t<e.changedTouches.length;t++){const s=e.changedTouches[t];this.prev.has(s.identifier)||this.prev.set(s.identifier,{x:0,z:0,screenx:0,screeny:0});const r=this.prev.get(s.identifier);if(r){const n=this.getPositionOnPlane(s.clientX,s.clientY);r.x=n.x,r.z=n.z,r.screenx=s.clientX,r.screeny=s.clientY}}}),h(this,"touchEnd",e=>{e.touches.length<=0&&(this._didMultitouch=!1)}),h(this,"touchMove",e=>{if(!e.defaultPrevented&&this.isActive){if(e.touches.length===1){if(this._didMultitouch)return;const t=e.touches[0],s=this.prev.get(t.identifier);if(!s)return;const r=this.getPositionOnPlane(t.clientX,t.clientY),n=r.x-s.x,o=r.z-s.z;if(n===0&&o===0)return;this.oneFingerDrag&&this.addMovement(n,o),s.x=r.x,s.z=r.z,s.screenx=t.clientX,s.screeny=t.clientY;return}else if(e.touches.length===2){this._didMultitouch=!0;const t=e.touches[0],s=e.touches[1],r=this.prev.get(t.identifier),n=this.prev.get(s.identifier);if(!r||!n)return;if(this.twoFingerRotate){const o=Math.atan2(t.clientY-s.clientY,t.clientX-s.clientX),a=Math.atan2(r.screeny-n.screeny,r.screenx-n.screenx),l=o-a;Math.abs(l)>.001&&this.addRotation(l)}if(this.twoFingerScale){const o=t.clientX-s.clientX,a=t.clientY-s.clientY,l=Math.sqrt(o*o+a*a),c=r.screenx-n.screenx,u=r.screeny-n.screeny,d=Math.sqrt(c*c+u*u),p=l-d;Math.abs(p)>2&&this.addScale(p)}r.screenx=t.clientX,r.screeny=t.clientY,n.screenx=s.clientX,n.screeny=s.clientY}}}),h(this,"_raycaster",new Np),h(this,"_intersection",new w),h(this,"_screenPos",new w),h(this,"_tempMatrix",new Te),this.context=i,this.offset=new Te,this.plane=new pn,this.plane.setFromNormalAndCoplanarPoint(m2.up,m2.zero)}reset(){this._scale=1,this.offset.identity()}get hasChanged(){return this._hasChanged}applyMatrixTo(i,e){this._hasChanged=!1,e?(this.offset.invert(),i.premultiply(this.offset)):i.multiply(this.offset)}get isActive(){return this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.size>0}enable(){this._enabled||(this._enabled=!0,this.context.input.addEventListener("pointerdown",this.onPointerDownEarly,el.Early),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,el.Late),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,el.Early),window.addEventListener("touchstart",this.touchStart,{passive:!1}),window.addEventListener("touchmove",this.touchMove,{passive:!1}),window.addEventListener("touchend",this.touchEnd,{passive:!1}))}disable(){this._enabled&&(this._enabled=!1,this.context.input.removeEventListener("pointerdown",this.onPointerDownEarly,el.Early),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,el.Late),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,el.Early),window.removeEventListener("touchstart",this.touchStart),window.removeEventListener("touchmove",this.touchMove),window.removeEventListener("touchend",this.touchEnd))}getPositionOnPlane(i,e){const t=this.context.mainCamera;return this._screenPos.x=i/window.innerWidth*2-1,this._screenPos.y=-(e/window.innerHeight)*2+1,this._screenPos.z=1,this._screenPos.unproject(t),this._raycaster.set(t.position,this._screenPos.sub(t.position)),this._raycaster.ray.intersectPlane(this.plane,this._intersection),this._intersection}addMovement(i,e){i/=this._scale,e/=this._scale,i*=this.factor,e*=this.factor,this.offset.elements[12]+=i,this.offset.elements[14]+=e,(i!==0||e!==0)&&(this._hasChanged=!0)}addScale(i){i/=window.innerWidth,i*=-1,this._scale*=1+i,this._tempMatrix.makeScale(1-i,1-i,1-i),this.offset.premultiply(this._tempMatrix),i!==0&&(this._hasChanged=!0)}addRotation(i){i*=-1,this._tempMatrix.makeRotationY(i),this.offset.premultiply(this._tempMatrix),i!==0&&(this._hasChanged=!0)}};let Gx=m2;h(Gx,"up",new w(0,1,0)),h(Gx,"zero",new w(0,0,0)),h(Gx,"one",new w(1,1,1));const $z=class{constructor(){h(this,"_quicklookButton"),h(this,"_arButton"),h(this,"_vrButton"),h(this,"_sendToQuestButton"),h(this,"_qrButton")}static create(){return new $z}static getOrCreate(){return this._instance||(this._instance=this.create()),this._instance}get isSecureConnection(){return window.location.protocol==="https:"}get quicklookButton(){return this._quicklookButton}get arButton(){return this._arButton}get vrButton(){return this._vrButton}get sendToQuestButton(){return this._sendToQuestButton}get qrButton(){return this._qrButton}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const i=document.createElement("button");return this._quicklookButton=i,i.dataset.needle="quicklook-button",i.innerText="Open in Quicklook",i.addEventListener("click",()=>{const e=re.findObjectOfType(Ys);e?(i.classList.add("this-mode-is-requested"),e.exportAsync().then(()=>{i.classList.remove("this-mode-is-requested")}).catch(t=>{i.classList.remove("this-mode-is-requested"),console.error(t)})):console.warn("No USDZExporter component found in the scene")}),this.hideElementDuringXRSession(i),i}createARButton(i){var e;if(this._arButton)return this._arButton;const t="immersive-ar",s=document.createElement("button");return this._arButton=s,s.classList.add("webxr-button"),s.dataset.needle="webxr-ar-button",s.innerText="Enter AR",s.title="Click to start a WebXR session in AR",s.addEventListener("click",()=>mt.start(t,i)),this.updateSessionSupported(s,t),this.listenToXRSessionState(s,t),this.hideElementDuringXRSession(s),this.isSecureConnection||(s.disabled=!0,s.title="WebXR requires a secure connection (HTTPS)"),Uu()||(e=navigator.xr)==null||e.addEventListener("devicechange",()=>this.updateSessionSupported(s,t)),s}createVRButton(i){var e;if(this._vrButton)return this._vrButton;const t="immersive-vr",s=document.createElement("button");return this._vrButton=s,s.classList.add("webxr-button"),s.dataset.needle="webxr-vr-button",s.innerText="Enter VR",s.title="Click to start a WebXR session in VR",s.addEventListener("click",()=>mt.start(t,i)),this.updateSessionSupported(s,t),this.listenToXRSessionState(s,t),this.hideElementDuringXRSession(s),this.isSecureConnection||(s.disabled=!0,s.title="WebXR requires a secure connection (HTTPS)"),Uu()||(e=navigator.xr)==null||e.addEventListener("devicechange",()=>this.updateSessionSupported(s,t)),s}createSendToQuestButton(){var i;if(this._sendToQuestButton)return this._sendToQuestButton;const e="https://oculus.com/open_url/?url=",t=document.createElement("button");return this._sendToQuestButton=t,t.dataset.needle="webxr-sendtoquest-button",t.innerText="Open on Quest",t.title="Click to send this page to the Oculus Browser on your Quest",t.addEventListener("click",()=>{const s=encodeURIComponent(window.location.href);window.open(e+s)}),this.listenToXRSessionState(t),this.hideElementDuringXRSession(t),Uu()||(i=navigator.xr)==null||i.addEventListener("devicechange",()=>{var s;(s=navigator.xr)!=null&&s.isSessionSupported("immersive-vr")?t.style.display="none":t.style.display=""}),t}createQRCode(){if(this._qrButton)return this._qrButton;const i=document.createElement("button");this._qrButton=i,i.innerText="QR Code",i.title="Scan this QR code with your phone to open this page",this.hideElementDuringXRSession(i);const e=document.createElement("div");e.style.position="fixed",e.style.display="inline-block",e.style.padding="1rem",e.style.backgroundColor="white",e.style.borderRadius="0.4rem",e.style.cursor="pointer",e.style.zIndex="1000",e.style.boxShadow="0 0 12px rgba(0, 0, 0, 0.2)";const t=document.createElement("div");t.classList.add("qr-code-container"),e.appendChild(t),i.addEventListener("click",()=>{if(e.parentNode)return r();s()});async function s(){await n(),document.body.appendChild(e);const o=t.getBoundingClientRect(),a=i.getBoundingClientRect();e.style.left=a.left+a.width*.5-o.width*.5+"px",a.top<o.height?e.style.top=`calc(${a.bottom}px + ${e.style.padding} * .6)`:e.style.top=`calc(${a.top-o.height}px - ${e.style.padding} * 2.5)`,setTimeout(()=>window.addEventListener("click",r,{once:!0})),window.addEventListener("resize",r),window.addEventListener("scroll",r),document.body.appendChild(e)}function r(){var o;(o=e.parentNode)==null||o.removeChild(e),window.removeEventListener("click",r),window.removeEventListener("resize",r),window.removeEventListener("scroll",r)}async function n(){const o=await Kk({text:window.location.href,width:200,height:200});t.innerHTML="",t.appendChild(o)}return i.addEventListener("pointerenter",()=>{n()},{once:!0}),i}updateSessionSupported(i,e){if(!("xr"in navigator)){i.style.display="none";return}mt.isSessionSupported(e).then(t=>{i.style.display=t?"":"none",wt()&&!t&&console.warn(e+" is not supported on this device - make sure your server runs using HTTPS and you have a device connected that supports "+e)})}hideElementDuringXRSession(i){mt.onXRSessionStart(e=>{i["previous-display"]=i.style.display,i.style.display="none"}),mt.onXRSessionEnd(e=>{i["previous-display"]!=null&&(i.style.display=i["previous-display"])})}listenToXRSessionState(i,e){e&&(mt.onSessionRequestStart(t=>{t.mode===e?i.classList.add("this-mode-is-requested"):(i["was-disabled"]=i.disabled,i.disabled=!0,i.classList.add("other-mode-is-requested"))}),mt.onSessionRequestEnd(t=>{i.classList.remove("this-mode-is-requested"),i.classList.remove("other-mode-is-requested"),i.disabled=i["was-disabled"]}))}};let Hf=$z;h(Hf,"_instance");var Woe=Object.defineProperty,Xoe=Object.getOwnPropertyDescriptor,Dc=(i,e,t,s)=>{for(var r=s>1?void 0:s?Xoe(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Woe(e,t,r),r};const Rd=te("debugtext");var qs=(i=>(i[i.UpperLeft=0]="UpperLeft",i[i.UpperCenter=1]="UpperCenter",i[i.UpperRight=2]="UpperRight",i[i.MiddleLeft=3]="MiddleLeft",i[i.MiddleCenter=4]="MiddleCenter",i[i.MiddleRight=5]="MiddleRight",i[i.LowerLeft=6]="LowerLeft",i[i.LowerCenter=7]="LowerCenter",i[i.LowerRight=8]="LowerRight",i))(qs||{}),e5=(i=>(i[i.Normal=0]="Normal",i[i.Bold=1]="Bold",i[i.Italic=2]="Italic",i[i.BoldAndItalic=3]="BoldAndItalic",i))(e5||{});class Rn extends xd{constructor(){super(...arguments),h(this,"alignment",0),h(this,"verticalOverflow",0),h(this,"horizontalOverflow",0),h(this,"lineSpacing",1),h(this,"supportRichText",!1),h(this,"font"),h(this,"fontStyle",0),h(this,"sRGBTextColor",new we(1,0,1)),h(this,"_text",""),h(this,"_fontSize",12),h(this,"_textMeshUi",null),h(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(e){var t;super.setAlphaFactor(e),(t=this.uiObject)==null||t.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){var t;this._fontSize=e,(t=this.uiObject)==null||t.set({fontSize:e})}onColorChanged(){var e;this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),(e=this.uiObject)==null||e.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(e){this.updateOverflow()}updateOverflow(){var e;const t=(e=this.uiObject)==null?void 0:e._overflow;t&&(t._needsUpdate=!0,this.markDirty())}onCreate(e){Rd&&console.log(this),this.horizontalOverflow==1&&(e.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,e.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,e.lineHeight=this.lineSpacing,delete e.backgroundOpacity,delete e.backgroundColor,Rd&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),Rd&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=t.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}getTextOpts(){const e=this.fontSize,t={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.setFont(t,this.fontStyle),t}onEnable(){var e;super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),(e=this.canvas)==null||e.registerEventReceiver(this)}onDisable(){var e;super.onDisable(),(e=this.canvas)==null||e.unregisterEventReceiver(this)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 0:case 3:case 6:e.textAlign="left";break;case 1:case 4:case 7:e.textAlign="center";break;case 2:case 5:case 8:e.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:e.alignItems="start";break;case 3:case 4:case 5:e.alignItems="center";break;case 6:case 7:case 8:e.alignItems="end";break}return e}feedText(e,t){var s,r,n;if(Rd&&console.log("feedText",this.uiObject,e,t),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!t||e.length===0)this.uiObject.textContent=e;else{let o=this.getNextTag(e);if(o){if(o.startIndex>0){for(let c=this.uiObject.children.length-1;c>=0;c--){const u=this.uiObject.children[c];u.isUI&&(this.uiObject.remove(u),u.clear())}const l=new Mb({textContent:e.substring(0,o.startIndex),color:"inherit"});this.uiObject.add(l)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const a=[];for(;o;){const l=this.getNextTag(e,o.endIndex),c={fontFamily:(s=this.uiObject)==null?void 0:s.get("fontFamily"),color:"inherit",textContent:""};if(l){c.textContent=this.getText(e,o,l),this.handleTag(o,c,a);const u=new Mb(c);(r=this.uiObject)==null||r.add(u)}else{c.textContent=e.substring(o.endIndex),this.handleTag(o,c,a);const u=new Mb(c);(n=this.uiObject)==null||n.add(u)}o=l}}}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,s={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let r=!1;if(this._textMeshUi)for(let n=0;n<this._textMeshUi.length;n++){if(e[n]===!0)continue;r=!0;const o=this._textMeshUi[n];o.textContent&&(sx(o,s),e[n]=!0)}if(!r)break;yield}}handleTag(e,t,s){if(!e.isEndTag){if(e.type.includes("color")){const r=new g2(e,{color:t.color});if(s.push(r),e.type.length>6){const n=parseInt("0x"+e.type.substring(7));t.color=n}else t.color=new we(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const r=new g2(e,{fontWeight:700});s.push(r)}else if(e.type=="i"){this.setFont(t,2);const r=new g2(e,{fontStyle:"italic"});s.push(r)}}}getText(e,t,s){return e.substring(t.endIndex,s.startIndex)}getNextTag(e,t=0){const s=e.indexOf("<",t),r=e.indexOf(">",s);if(s>=0&&r>=0){const n=e.substring(s+1,r);return{type:n,startIndex:s,endIndex:r+1,isEndTag:n.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;const s=this.font,r=this.getFamilyNameWithCorrectSuffix(s,t);Rd&&console.log("Selected font family:"+r);let n=QE.getFontFamily(r);switch(n||(n=QE.addFontFamily(r)),e.fontFamily=n,t){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal";break;case 2:e.fontWeight=400,e.fontStyle="italic";break;case 3:e.fontStyle="italic",e.fontWeight=400}let o=n.getVariant(e.fontWeight,e.fontStyle);if(!o){let a=r;a!=null&&a.endsWith("-msdf.json")||(a+="-msdf.json");let l=r;l!=null&&l.endsWith(".png")||(l+=".png"),o=n.addVariant(e.fontWeight,e.fontStyle,a,l),o?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,t){var s;const r=e.lastIndexOf("-");if(r<0)return e;const n=(s=e.substring(r+1))==null?void 0:s.toLowerCase();if(qoe.includes(n))return Rd&&console.warn("Unsupported font style: "+n),e;const o=e.lastIndexOf("/");let a=e;o>=0&&(a=a.substring(o+1));const l=a[0]===a[0].toUpperCase(),c=e.substring(0,r);switch(Rd&&console.log("Select font: ",e,e5[t],a,l,c),t){case 0:return l?c+"-Regular":c+"-regular";case 1:return l?c+"-Bold":c+"-bold";case 2:return l?c+"-Italic":c+"-italic";case 3:return l?c+"-BoldItalic":c+"-bolditalic";default:return e}}}Dc([x()],Rn.prototype,"alignment",2),Dc([x()],Rn.prototype,"verticalOverflow",2),Dc([x()],Rn.prototype,"horizontalOverflow",2),Dc([x()],Rn.prototype,"lineSpacing",2),Dc([x()],Rn.prototype,"supportRichText",2),Dc([x(URL)],Rn.prototype,"font",2),Dc([x()],Rn.prototype,"fontStyle",2),Dc([x()],Rn.prototype,"text",1),Dc([x()],Rn.prototype,"fontSize",1);class g2{constructor(e,t){h(this,"tag"),h(this,"previousValues"),this.tag=e,this.previousValues=t}}const qoe=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class Kh{constructor(e){h(this,"id"),h(this,"content",""),h(this,"font",[]),h(this,"pointSize",144),h(this,"width"),h(this,"height"),h(this,"depth"),h(this,"wrapMode"),h(this,"horizontalAlignment"),h(this,"verticalAlignment"),h(this,"material"),this.id=e}static getId(){return this.global_id++}setDepth(e){return this.depth=e,this}setPointSize(e){return this.pointSize=e,this}setHorizontalAlignment(e){return this.horizontalAlignment=e,this}setVerticalAlignment(e){return this.verticalAlignment=e,this}writeTo(e,t){var s;t.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),t.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),t.closeBlock(")"),t.beginBlock(),this.content&&t.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(s=this.font)==null||s.push("sans-serif"));const r=this.font.map(n=>`"${n}"`).join(", ");t.appendLine(`string[] font = [ ${r} ]`),t.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&t.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&t.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&t.appendLine(`double depth = ${this.depth}`),this.wrapMode&&t.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&t.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&t.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&t.appendLine(`rel material:binding = </StageRoot/Materials/${nI(this.material)}>`),t.closeBlock()}}h(Kh,"global_id",0);class Qx{static singleLine(e,t,s){const r=new Kh("text_"+Kh.getId());return r.content=e,t&&(r.pointSize=t),s&&(r.depth=s),r}static multiLine(e,t,s,r,n,o){const a=new Kh("text_"+Kh.getId());return a.content=e,a.width=t,a.height=s,a.horizontalAlignment=r,a.verticalAlignment=n,o!==void 0&&(a.wrapMode=o),a}}const Yoe=new Te().makeRotationY(Math.PI),Joe=new Te().makeScale(-1,1,-1);class x0{get extensionName(){return"text"}onExportObject(e,t,s){}exportText(e,t,s){const r=re.getComponent(e,Rn);if(!r)return;const n=re.getComponent(e,Tn);let o=100,a=100;n&&(o=n.width,a=n.height),t.matrix=Yoe.clone(),n&&t.matrix.premultiply(Joe);const l=r.color.clone();t.material=new Un({color:l,emissive:l}),t.addEventListener("serialize",(c,u)=>{let d=r.text;d=d.replace(/\r/g,""),d=d.replace(/\n/g,"\\n");const p=Qx.multiLine(d,o,a,"center","bottom","flowing");this.setTextAlignment(p,r.alignment),this.setOverflow(p,r),t.material&&(p.material=t.material),p.pointSize=this.convertToTextSize(r.fontSize),p.depth=.001,p.writeTo(void 0,c)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case qs.LowerLeft:case qs.MiddleLeft:case qs.UpperLeft:e.horizontalAlignment="left";break;case qs.LowerCenter:case qs.MiddleCenter:case qs.UpperCenter:e.horizontalAlignment="center";break;case qs.LowerRight:case qs.MiddleRight:case qs.UpperRight:e.horizontalAlignment="right";break}switch(t){case qs.LowerLeft:case qs.LowerCenter:case qs.LowerRight:e.verticalAlignment="bottom";break;case qs.MiddleLeft:case qs.MiddleCenter:case qs.MiddleRight:e.verticalAlignment="middle";break;case qs.UpperLeft:case qs.UpperCenter:case qs.UpperRight:e.verticalAlignment="top";break}}}class Vx{get extensionName(){return"tmui"}onExportObject(e,t,s){const r=re.getComponent(e,Br);if(r&&r.activeAndEnabled&&r.renderMode===Oz.WorldSpace){const n=new x0,o=re.getComponent(e,Tn),a=re.getComponent(e,Qh);if(o){o.width,o.height;const l=Wo.createEmpty(),c=o.shadowComponent;if(t.add(l),c){const u=c.matrix;l.matrix.copy(u);const d=new Map,p=new Map;d.set(c,l),p.set(c,a?a.alpha:1),c.traverse(f=>{if(f===c)return;const m=Wo.createEmpty();m.matrix.copy(f.matrix);const A=f.parent,y=!!A&&typeof A.textContent=="string"&&A.textContent.length>0;let g=p.get(A)||1;const v=re.getComponent(f,Qh);if(v&&(g*=v.alpha),f instanceof ge&&y){const _=f[qo];_?n.exportText(_.gameObject,m,s):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",f)}if(f instanceof ge&&!y){const _=f.geometry.clone();_.scale(1,1,-1),this.flipWindingOrder(_),m.geometry=_;const S=new we,I=f.material.opacity;S.copy(f.material.color),m.material=new ni({color:S,opacity:I*g,map:f.material.map,transparent:!0})}d.set(f,m),p.set(f,g);const b=d.get(A);if(!b){console.error("Error when exporting UI: shadow component parent not found!",f,f.parent);return}b.add(m)})}}}}flipWindingOrder(e){const t=e.index.array;for(let s=0,r=t.length/3;s<r;s++){const n=t[s*3];t[s*3]=t[s*3+2],t[s*3+2]=n}e.index.needsUpdate=!0}}const Hx=te("debugusdz");function Koe(i,e){var t;const s=[],r=re.getComponentsInChildren(i,Ir),n=re.getComponentsInChildren(i,oo),o=new Array;if(e.injectImplicitBehaviours)for(const a of r){if(!a||!a.runtimeAnimatorController)continue;const l=a.runtimeAnimatorController.activeState;if(!l||!l.motion||!l.motion.clip||((t=l.motion.clip.tracks)==null?void 0:t.length)<1)continue;const c=new Qf;c.animator=a,c.stateName=l.name,c.trigger="start",c.name="PlayAnimationOnClick_implicitAtStart_"+c.stateName;const u=new Ae;re.addComponent(u,c),o.push(u),i.add(u)}else for(const a of r){if(!a||!a.runtimeAnimatorController)continue;Hx&&console.log(a);const l=[];for(const c of a.runtimeAnimatorController.enumerateActions()){Hx&&console.log(c);const u=c.getClip();l.includes(u)||l.push(u)}s.push({root:a.gameObject,clips:l})}for(const a of n){Hx&&console.log(a);const l=[];for(const c of a.animations)l.includes(c)||l.push(c);s.push({root:a.gameObject,clips:l})}Hx&&console.log("USDZ Animation Clips",s);for(const a of s)for(const l of a.clips)e.registerAnimation(a.root,l);return o}function Zoe(i,e){const t=re.getComponentsInChildren(i,os),s=re.getComponentsInChildren(i,Vh),r=new Array;for(const n of s){if(!n.target)continue;const o=t.indexOf(n.target);o>-1&&t.splice(o,1)}for(const n of t){if(!n||!n.clip||n.volume<=0)continue;const o=new Vh;o.target=n,o.name="PlayAudioOnClick_implicitAtStart_";const a=new Ae;re.addComponent(a,o),console.log("implicit PlayAudioOnStart",a,o),r.push(a),i.add(a)}return r}function t5(i){const e=i.domElement.shadowRoot.querySelector("link[rel='ar']");if(e)return e;const t=document.createElement("div");t.classList.add("menu"),t.classList.add("quicklook-menu"),t.style.display="none",t.style.visibility="hidden";const s=document.createElement("button");s.id="open-in-ar",s.innerText="Open in QuickLook",t.appendChild(s);const r=document.createElement("a");r.id="needle-usdz-link",r.style.display="none",r.rel="ar",r.href="",t.appendChild(r);const n=document.createElement("img");return n.id="button",r.appendChild(n),i.domElement.shadowRoot.appendChild(t),r}var $oe=Object.defineProperty,eae=Object.getOwnPropertyDescriptor,on=(i,e,t,s)=>{for(var r=s>1?void 0:s?eae(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&$oe(e,t,r),r};const Xn=te("debugusdz");class Zh{constructor(){h(this,"callToAction"),h(this,"checkoutTitle"),h(this,"checkoutSubtitle"),h(this,"callToActionURL")}}on([x()],Zh.prototype,"callToAction",2),on([x()],Zh.prototype,"checkoutTitle",2),on([x()],Zh.prototype,"checkoutSubtitle",2),on([x()],Zh.prototype,"callToActionURL",2);var v2;const A2=(v2=class extends Be{constructor(){super(...arguments),h(this,"objectToExport"),h(this,"autoExportAnimations",!1),h(this,"autoExportAudioSources",!0),h(this,"exportFileName"),h(this,"customUsdzFile"),h(this,"customBranding"),h(this,"anchoringType","plane"),h(this,"maxTextureSize",2048),h(this,"planeAnchoringAlignment","horizontal"),h(this,"interactive",!0),h(this,"allowCreateQuicklookButton",!0),h(this,"quickLookCompatible",!0),h(this,"extensions",[]),h(this,"link"),h(this,"button"),h(this,"onClickedOpenInARElement",i=>{i.preventDefault(),this.exportAsync()}),h(this,"lastCallback")}start(){var i,e,t;Xn&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",s=>{switch(s.key){case"t":this.exportAsync();break}}),Xa()&&setTimeout(()=>{this.exportAsync()},2e3)),this.objectToExport||(this.objectToExport=this.gameObject),!((e=(i=this.objectToExport)==null?void 0:i.children)!=null&&e.length)&&!((t=this.objectToExport)!=null&&t.isMesh)&&(this.objectToExport=this.context.scene),this.interactive&&(this.extensions.push(new yx),this.extensions.push(new cu),this.extensions.push(new x0),this.extensions.push(new Vx))}onEnable(){var i;const e=Gp(),t=Qp();(Xn||e&&t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=t5(this.context),this.link.addEventListener("message",this.lastCallback)),Xn&&rs("USDZ Exporter enabled: "+this.name),(i=document.getElementById("open-in-ar"))==null||i.addEventListener("click",this.onClickedOpenInARElement)}onDisable(){var i,e,t;(i=this.button)==null||i.remove(),(e=this.link)==null||e.removeEventListener("message",this.lastCallback),Xn&&rs("USDZ Exporter disabled: "+this.name),(t=document.getElementById("open-in-ar"))==null||t.removeEventListener("click",this.onClickedOpenInARElement)}async exportAsync(){var i;let e=this.exportFileName??((i=this.objectToExport)==null?void 0:i.name)??this.name;if(e+="-"+P4(),mc()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=t5(this.context)),this.customUsdzFile){Xn&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,e);return}const t=await this.export(this.objectToExport);if(!t){console.warn("No object to export",this);return}Xn&&console.log("USDZ generation done. Downloading as "+this.link.download),this.openInQuickLook(t,e)}async export(i){if(!i)return null;ti.start("export-usdz",{onProgress:p=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:p}}))}}),ti.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),ti.report("export-usdz",{message:"Load progressive textures",autoStep:5}),ti.start("export-usdz-textures","export-usdz");const e=re.getComponentsInChildren(i,As),t=new Array;let s=0;for(const p of e)for(const f of p.sharedMaterials)if(f){const m=p.loadProgressiveTextures(f);m instanceof Promise&&t.push(new Promise((A,y)=>{m.then(()=>{s++,ti.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:s,totalSteps:t.length}),A()}).catch(g=>y(g))}))}Xn&&rs("Load textures: "+t.length),await Promise.all(t),Xn&&rs("Load textures: done"),ti.end("export-usdz-textures");const r=Mn.Global.Mask;Mn.Global.Set(cl.AR),this.applyWebARSessionRoot();const n=new vse,o=[...this.extensions],a=new Qv(this.quickLookCompatible);o.push(a);const l={self:this,exporter:n,extensions:o,object:i};ti.report("export-usdz","Invoking before-export"),this.dispatchEvent(new CustomEvent("before-export",{detail:l})),ti.report("export-usdz","auto export animations and audio sources");const c=new Array;this.autoExportAnimations&&c.push(...Koe(i,a)),this.extensions.find(p=>p.extensionName==="Audio")&&this.autoExportAudioSources&&c.push(...Zoe(i)),n.debug=Xn,n.keepObject=p=>{const f=re.getComponent(p,As);return!(f&&!f.enabled)},this.anchoringType!=="plane"&&this.anchoringType!=="none"&&this.anchoringType!=="image"&&this.anchoringType!=="face"&&(this.anchoringType="plane"),this.planeAnchoringAlignment!=="horizontal"&&this.planeAnchoringAlignment!=="vertical"&&this.planeAnchoringAlignment!=="any"&&(this.planeAnchoringAlignment="horizontal"),ti.report("export-usdz","Invoking exporter.parse");const u=await n.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:o,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize}),d=new Blob([u],{type:"vnd.usdz+zip"});for(const p of c)re.destroy(p);return ti.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:l})),Mn.Global.Set(r),ti.end("export-usdz"),d}openInQuickLook(i,e){const t=i instanceof Blob?URL.createObjectURL(i):i,s=this.buildQuicklookOverlay();Xn&&console.log("QuickLook Overlay",s);const r=s.callToAction?encodeURIComponent(s.callToAction):"",n=s.checkoutTitle?encodeURIComponent(s.checkoutTitle):"",o=s.checkoutSubtitle?encodeURIComponent(s.checkoutSubtitle):"";this.link.href=t+`#callToAction=${r}&checkoutTitle=${n}&checkoutSubtitle=${o}&callToActionURL=${s.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=e+".usdz",this.link.click()}download(i,e){A2.save(i,e)}static save(i,e){const t=document.createElement("a");t.style.display="none",document.body.appendChild(t),typeof i=="string"?t.href=i:t.href=URL.createObjectURL(i),t.download=e,t.click(),t.remove()}quicklookCallback(i){if(i?.data=="_apple_ar_quicklook_button_tapped"){Xn&&ns("Quicklook closed via call to action button");var e=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(e),!e.defaultPrevented){const t=new URLSearchParams(this.link.href);if(t){const s=t.get("callToActionURL");Xn&&rs("Quicklook url: "+s),s&&(mc()?globalThis.open(s,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",s))}}}}buildQuicklookOverlay(){var i,e,t,s,r,n;const o={};return this.customBranding&&Object.assign(o,this.customBranding),mc()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),o.callToAction="Close",o.checkoutTitle="\u{1F335} Made with Needle",o.checkoutSubtitle="_"),(((i=o.callToAction)==null?void 0:i.length)||((e=o.checkoutTitle)==null?void 0:e.length)||((t=o.checkoutSubtitle)==null?void 0:t.length))&&((s=o.callToAction)!=null&&s.length||(o.callToAction="\0"),(r=o.checkoutTitle)!=null&&r.length||(o.checkoutTitle="\0"),(n=o.checkoutSubtitle)!=null&&n.length||(o.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:o})),o}applyWebARSessionRoot(){if(!this.objectToExport)return;let i=re.getComponentInParent(this.objectToExport,go);const e=i!=null;if(i||(i=re.getComponentInChildren(this.objectToExport,go)),Xn&&console.log("applyWebARSessionRoot",i),!i){Xn&&console.warn("No WebARSessionRoot found in parent hierarchy",this.objectToExport);return}const t=e?this.objectToExport:i.gameObject,s=1/i.arScale;t.matrix.makeScale(s,s,s),i.invertForward&&t.matrix.multiply(A2.invertForwardMatrix)}createQuicklookButton(){const i=Hf.getOrCreate().createQuicklookButton();return i.parentNode||this.context.menu.appendChild(i),i}},h(v2,"invertForwardMatrix",new Te().makeRotationY(Math.PI)),v2);let Ys=A2;on([x(Ae)],Ys.prototype,"objectToExport",2),on([x()],Ys.prototype,"autoExportAnimations",2),on([x()],Ys.prototype,"autoExportAudioSources",2),on([x()],Ys.prototype,"exportFileName",2),on([x(URL)],Ys.prototype,"customUsdzFile",2),on([x(Zh)],Ys.prototype,"customBranding",2),on([x()],Ys.prototype,"anchoringType",2),on([x()],Ys.prototype,"maxTextureSize",2),on([x()],Ys.prototype,"planeAnchoringAlignment",2),on([x()],Ys.prototype,"interactive",2),on([x()],Ys.prototype,"allowCreateQuicklookButton",2),on([x()],Ys.prototype,"quickLookCompatible",2);class w0 extends Be{constructor(){super(...arguments),h(this,"isUsed",!0),h(this,"usedBy",null)}}class y2 extends Be{}const i5=te("debugdeletable");class Wx extends dl{}class b2 extends Be{constructor(){super(...arguments),h(this,"deleteBoxes",[])}awake(){this.deleteBoxes=re.findObjectsOfType(Wx,this.context)}update(){for(const e of this.deleteBoxes){const t=this.gameObject;if(e.isInBox(t)===!0){const s=re.getComponentInParent(this.gameObject,w0);s?i5&&console.warn("Can not delete object with usage marker",this.guid,s):(i5&&console.log("DESTROY",this.gameObject),O_(this.gameObject,this.context.connection))}}}}var tae=Object.defineProperty,iae=Object.getOwnPropertyDescriptor,Pd=(i,e,t,s)=>{for(var r=s>1?void 0:s?iae(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&tae(e,t,r),r};const s5=te("debugpost");class Pa extends nn{constructor(){super(...arguments),h(this,"mode"),h(this,"focusDistance"),h(this,"focalLength"),h(this,"aperture"),h(this,"gaussianMaxRadius"),h(this,"resolutionScale"),h(this,"bokehScale")}get typeName(){return"DepthOfField"}init(){s5&&console.log("DOF: INIT"),this.focalLength.valueProcessor=t=>{const s=t/300,r=2;return st.lerp(r,.01,s)};const e=20;this.aperture.valueProcessor=t=>{const s=1-t/32;return st.lerp(1,e,s)}}onCreateEffect(){if(this.mode===0){s5&&console.warn("DepthOfField: Mode is set to Off");return}const e=1/window.devicePixelRatio;if(this.resolutionScale===void 0){let s=1;Xa()&&(s=.6),this.resolutionScale=new Bt(s*e)}const t=new G3(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=s=>{t.cocMaterial.worldFocusDistance=s},this.focalLength.onValueChanged=s=>t.cocMaterial.worldFocusRange=s,this.aperture.onValueChanged=s=>t.bokehScale=s,this.resolutionScale&&(this.resolutionScale.onValueChanged=s=>t.resolution.scale=s),[t]}unapply(){}}Pd([x()],Pa.prototype,"mode",2),Pd([x(Bt)],Pa.prototype,"focusDistance",2),Pd([x(Bt)],Pa.prototype,"focalLength",2),Pd([x(Bt)],Pa.prototype,"aperture",2),Pd([x(Bt)],Pa.prototype,"gaussianMaxRadius",2),Pd([x(Bt)],Pa.prototype,"resolutionScale",2),Pd([x(Bt)],Pa.prototype,"bokehScale",2),Ko("DepthOfField",Pa);var sae=Object.defineProperty,rae=Object.getOwnPropertyDescriptor,nae=(i,e,t,s)=>{for(var r=s>1?void 0:s?rae(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&sae(e,t,r),r};class Xx extends Be{constructor(){super(...arguments),h(this,"visibleOn")}onEnable(){this.apply()}apply(){this.test()||re.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:Xa()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}nae([x()],Xx.prototype,"visibleOn",2);class _2{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}var oae=Object.defineProperty,aae=Object.getOwnPropertyDescriptor,Bd=(i,e,t,s)=>{for(var r=s>1?void 0:s?aae(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&oae(e,t,r),r};const ml=te("debugdrag");var r5=(i=>(i[i.XZPlane=0]="XZPlane",i[i.Attached=1]="Attached",i[i.HitNormal=2]="HitNormal",i[i.DynamicViewAngle=3]="DynamicViewAngle",i[i.SnapToSurfaces=4]="SnapToSurfaces",i[i.None=5]="None",i))(r5||{}),qx;const gl=(qx=class extends Be{constructor(){super(...arguments),h(this,"dragMode",3),h(this,"snapGridResolution",0),h(this,"keepRotation",!0),h(this,"xrDragMode",1),h(this,"xrKeepRotation",!1),h(this,"xrDistanceDragFactor",1),h(this,"showGizmo",!1),h(this,"targetObject",null),h(this,"orbit",null),h(this,"_dragHelper",null),h(this,"_draggingRigidbodies",[]),h(this,"_potentialDragStartEvt",null),h(this,"_dragHandlers",new Map),h(this,"_totalMovement",new w),h(this,"_marker",null),h(this,"_isDragging",!1),h(this,"_didDrag",!1)}static get HasAnySelected(){return this._active>0}setTargetObject(i){this.targetObject=i;for(const e of this._dragHandlers.values())e.setTargetObject(i)}awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new w,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._dragHelper=null,this._draggingRigidbodies=[]}start(){this.orbit=re.findObjectOfType(ji,this.context),this.gameObject.getComponentInParent(ao)||this.gameObject.addNewComponent(ao)}allowEdit(i=null){return this.context.connection.allowEditing}onPointerEnter(i){if(!this.allowEdit(this.gameObject)||i.mode!=="screen"||(i.event.mode==="tracked-pointer"?this.xrDragMode:this.dragMode)===5)return;const e=re.getComponentInParent(i.object,gl);!e||e!==this||(gl.lastHovered=i.object,this.context.domElement.style.cursor="pointer")}onPointerExit(i){this.allowEdit(this.gameObject)&&i.mode==="screen"&&gl.lastHovered===i.object&&(this.context.domElement.style.cursor="auto")}onPointerDown(i){if(!(!this.allowEdit(this.gameObject)||i.used||(i.mode==="tracked-pointer"?this.xrDragMode:this.dragMode)===5)&&(gl.lastHovered=i.object,i.button===0)){this._dragHandlers.size===0&&(this._didDrag=!1,this._totalMovement.set(0,0,0),this._potentialDragStartEvt=i),gl._active+=1;const e=new cae(this,this.targetObject||this.gameObject);if(this._dragHandlers.set(i.event.space,e),this.orbit&&(this.orbit.enabled=!1),e.onDragStart(i),this._dragHandlers.size===2){const t=this._dragHandlers.values(),s=t.next().value,r=t.next().value,n=new lae(this,this.targetObject||this.gameObject,s,r);this._dragHandlers.set(this.gameObject,n),n.onDragStart(i)}i.use()}}onPointerMove(i){(this._isDragging||this._potentialDragStartEvt!==null)&&i.use()}onPointerUp(i){if(ml&&Tt.DrawLabel(i.point??this.gameObject.worldPosition,"POINTERUP:"+i.pointerId+", "+i.button,.03,3),!this.allowEdit(this.gameObject)||i.button!==0)return;this._potentialDragStartEvt=null;const e=this._dragHandlers.get(i.event.space),t=this._dragHandlers.get(this.gameObject);t&&(t.handlerA===e||t.handlerB===e)&&(this._dragHandlers.delete(this.gameObject),t.onDragEnd(i)),e&&(gl._active>0&&(gl._active-=1),e.onDragEnd&&e.onDragEnd(i),this._dragHandlers.delete(i.event.space),this._dragHandlers.size===0&&this.onLastDragEnd(i),i.use()),gl._active===0&&this.orbit&&(this.orbit.enabled=!0)}update(){for(const i of this._dragHandlers.values())i.collectMovementInfo&&i.collectMovementInfo(),i.getTotalMovement&&this._totalMovement.add(i.getTotalMovement());if(this._potentialDragStartEvt){if(!this._didDrag)if(this._totalMovement.length()>3e-4)this._didDrag=!0;else return;const i=this._potentialDragStartEvt;this._potentialDragStartEvt=null,this.onFirstDragStart(i)}for(const i of this._dragHandlers.values())i.onDragUpdate&&i.onDragUpdate(this._dragHandlers.size);this._dragHelper&&this._dragHelper.hasSelected&&this.onAnyDragUpdate()}onFirstDragStart(i){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new o5(this.context.mainCamera);else return;if(!i||!i.object)return;const e=re.getComponentInParent(i.object,gl);if(!e||e!==this)return;const t=this.targetObject||this.gameObject;if(!t)return;this._isDragging=!0,this._dragHelper.setSelected(t,this.context),this.orbit&&(this.orbit.enabled=!1);const s=re.getComponentInChildren(t,Oh);ml&&console.log("DRAG START",s,t),s&&(s.fastMode=!0,s?.requestOwnership()),this._marker=re.addNewComponent(t,w0),this._draggingRigidbodies.length=0;const r=re.getComponentsInChildren(t,zi);r&&this._draggingRigidbodies.push(...r)}onAnyDragUpdate(){if(!this._dragHelper)return;this._dragHelper.showGizmo=this.showGizmo,this._dragHelper.onUpdate(this.context);for(const e of this._draggingRigidbodies)e.wakeUp(),e.resetVelocities(),e.resetForcesAndTorques();const i=this.targetObject||this.gameObject;Fa.markDirty(i)}onLastDragEnd(i){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;for(const t of this._draggingRigidbodies)t.setVelocity(t.smoothedVelocity);this._draggingRigidbodies.length=0;const e=this._dragHelper.selected;if(ml&&console.log("DRAG END",e,e?.visible),this._dragHelper.setSelected(null,this.context),this.orbit&&(this.orbit.enabled=!0),i!=null&&i.object){const t=re.getComponentInChildren(i.object,Oh);t&&(t.fastMode=!1)}this._marker&&this._marker.destroy()}},h(qx,"_active",0),h(qx,"lastHovered"),qx);let ta=gl;Bd([x()],ta.prototype,"dragMode",2),Bd([x()],ta.prototype,"snapGridResolution",2),Bd([x()],ta.prototype,"keepRotation",2),Bd([x()],ta.prototype,"xrDragMode",2),Bd([x()],ta.prototype,"xrKeepRotation",2),Bd([x()],ta.prototype,"xrDistanceDragFactor",2),Bd([x()],ta.prototype,"showGizmo",2);class lae{constructor(e,t,s,r){h(this,"handlerA"),h(this,"handlerB"),h(this,"context"),h(this,"settings"),h(this,"gameObject"),h(this,"_handlerAAttachmentPoint",new w),h(this,"_handlerBAttachmentPoint",new w),h(this,"_followObject"),h(this,"_manipulatorObject"),h(this,"_deviceMode"),h(this,"_followObjectStartWorldQuaternion",new Ie),h(this,"_manipulatorPosOffset",new w),h(this,"_manipulatorRotOffset",new Ie),h(this,"_manipulatorScaleOffset",new w),h(this,"_tempVec1",new w),h(this,"_tempVec2",new w),h(this,"_tempVec3",new w),h(this,"tempLookMatrix",new Te),h(this,"_initialScale",new w),h(this,"_initialDistance",0);var n,o;this.context=e.context,this.settings=e,this.gameObject=t,this.handlerA=s,this.handlerB=r,this._followObject=new Ae,this._manipulatorObject=new Ae,this.context.scene.add(this._manipulatorObject);const a=(o=(n=mt.active)==null?void 0:n.rig)==null?void 0:o.gameObject;if(!this.handlerA||!this.handlerB||!this.handlerA.hitPointInLocalSpace||!this.handlerB.hitPointInLocalSpace){console.error("Invalid: MultiTouchDragHandler needs two valid DragPointerHandlers with hitPointInLocalSpace set.");return}if(this._tempVec1.copy(this.handlerA.hitPointInLocalSpace),this._tempVec2.copy(this.handlerB.hitPointInLocalSpace),this.gameObject.localToWorld(this._tempVec1),this.gameObject.localToWorld(this._tempVec2),a&&(a.worldToLocal(this._tempVec1),a.worldToLocal(this._tempVec2)),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(ml&&console.log("Finding alternative drag attachment points since initial distance is too low: "+this._initialDistance.toFixed(2)),this.handlerA.followObject.parent.getWorldPosition(this._tempVec1),this.handlerB.followObject.parent.getWorldPosition(this._tempVec2),this._handlerAAttachmentPoint.copy(this._tempVec1),this._handlerBAttachmentPoint.copy(this._tempVec2),this.gameObject.worldToLocal(this._handlerAAttachmentPoint),this.gameObject.worldToLocal(this._handlerBAttachmentPoint),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.001&&(console.warn("Not supported right now \u2013 controller drag points for multitouch are too close!"),this._initialDistance=1)):(this._handlerAAttachmentPoint.copy(this.handlerA.hitPointInLocalSpace),this._handlerBAttachmentPoint.copy(this.handlerB.hitPointInLocalSpace)),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._initialScale.copy(t.scale),ml){this._followObject.add(new Ro(2)),this._manipulatorObject.add(new Ro(5));const l=c=>`${c.x.toFixed(2)}, ${c.y.toFixed(2)}, ${c.z.toFixed(2)}`;Tt.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),Tt.DrawLabel(this._tempVec3,"A:B "+this._initialDistance.toFixed(2)+`
6303
+ `)},this.depthMaterial.depthTest=!1,this.depthMaterial.depthWrite=!1,this.horizontalBlurMaterial=new Mt(Noe),this.horizontalBlurMaterial.depthTest=!1,this.verticalBlurMaterial=new Mt(zoe),this.verticalBlurMaterial.depthTest=!1,this.shadowGroup.visible=!1}onDestroy(){var e,t,s,r,n,o,a,l;(e=this.renderTarget)==null||e.dispose(),(t=this.renderTargetBlur)==null||t.dispose(),(s=this.depthMaterial)==null||s.dispose(),(r=this.horizontalBlurMaterial)==null||r.dispose(),(n=this.verticalBlurMaterial)==null||n.dispose(),(o=this.blurPlane)==null||o.geometry.dispose(),(a=this.plane)==null||a.geometry.dispose(),(l=this.occluderMesh)==null||l.geometry.dispose()}onBeforeRender(e){const t=this.context.scene,s=this.context.renderer,r=s.getRenderTarget();if(!this.renderTarget||!this.renderTargetBlur||!this.depthMaterial||!this.shadowCamera||!this.blurPlane||!this.shadowGroup||!this.plane||!this.horizontalBlurMaterial||!this.verticalBlurMaterial){f2&&console.error("ContactShadows: not initialized yet");return}this.shadowGroup.visible=!0,this.occluderMesh&&(this.occluderMesh.visible=!1);const n=this.plane.visible;this.plane.visible=!1,this.gameObject instanceof ge&&(this.gameObject.visible=!1,Uf(this.gameObject,!1));const o=t.background;t.background=null,t.overrideMaterial=this.depthMaterial;const a=s.getClearAlpha();s.setClearAlpha(0),s.setRenderTarget(this.renderTarget),s.render(t,this.shadowCamera),t.overrideMaterial=null,this.blurShadow(this.blur),this.blurShadow(this.blur*.4),this.shadowGroup.visible=!1,this.occluderMesh&&(this.occluderMesh.visible=!0),this.plane.visible=n,s.setRenderTarget(r),s.setClearAlpha(a),t.background=o}blurShadow(e){if(!this.blurPlane||!this.shadowCamera||!this.renderTarget||!this.renderTargetBlur||!this.horizontalBlurMaterial||!this.verticalBlurMaterial)return;this.blurPlane.visible=!0,this.blurPlane.material=this.horizontalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTarget.texture,this.horizontalBlurMaterial.uniforms.h.value=e*1/256;const t=this.context.renderer,s=t.getRenderTarget();t.setRenderTarget(this.renderTargetBlur),t.render(this.blurPlane,this.shadowCamera),this.blurPlane.material=this.verticalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTargetBlur.texture,this.verticalBlurMaterial.uniforms.v.value=e*1/256,t.setRenderTarget(this.renderTarget),t.render(this.blurPlane,this.shadowCamera),this.blurPlane.visible=!1,t.setRenderTarget(s)}}b0([x()],Jh.prototype,"darkness",2),b0([x()],Jh.prototype,"opacity",2),b0([x()],Jh.prototype,"blur",2),b0([x()],Jh.prototype,"occludeBelowGround",2),b0([x()],Jh.prototype,"backfaceShadows",2);var Qoe=Object.defineProperty,Voe=Object.getOwnPropertyDescriptor,_0=(i,e,t,s)=>{for(var r=s>1?void 0:s?Voe(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Qoe(e,t,r),r};const Zz=te("debugwebxr"),Hoe=new Te().makeRotationY(Math.PI);class go extends Be{constructor(){super(...arguments),h(this,"_arScale",1),h(this,"invertForward",!1),h(this,"customReticle"),h(this,"useXRAnchor",!1),h(this,"arTouchTransform",!1),h(this,"_isPlacing",!0),h(this,"_startOffset",new Te),h(this,"_createdPlacementObject",null),h(this,"_reparentedComponents",[]),h(this,"_placementScene",new qr),h(this,"_reticle",[]),h(this,"_hits",[]),h(this,"_placementStartTime",-1),h(this,"_rigPlacementMatrix"),h(this,"_anchor",null),h(this,"userInput"),h(this,"onPlaceScene",e=>{var t;if(this._isPlacing==!1)return;let s=this._reticle[0],r=this._hits[0];if(e.origin instanceof GM){const n=this._reticle[e.origin.index];n&&(s=n,r=this._hits[e.origin.index])}if(!s){console.warn("No reticle to place...");return}if(!s.visible){console.warn("Reticle is not visible (can not place)");return}if((t=mt.active)!=null&&t.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}e.stopImmediatePropagation(),e.use(),this._isPlacing=!1,this.context.input.removeEventListener("pointerup",this.onPlaceScene),this.onRevertSceneChanges(),this.onApplyPose(s),this.useXRAnchor&&this.onCreateAnchor(mt.active,r)})}get arScale(){return this._arScale}set arScale(e){e!==this._arScale&&(this._arScale=e,this.onScaleChanged())}onEnable(){var e;(e=this.customReticle)==null||e.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){Zz&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new Ae;this._createdPlacementObject=t,t.name="AR Session Root",this._placementScene.name="AR Placement Scene",this._placementScene.children.length=0;for(let s=this.context.scene.children.length-1;s>=0;s--){const r=this.context.scene.children[s];this._placementScene.add(r)}this.context.scene.add(t),this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),re.addComponent(t,this);for(const s of this._reticle)Ca(s);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:el.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:el.Early}),this.onRevertSceneChanges(),this._anchor=null,this._rigPlacementMatrix=void 0}onUpdateXR(e){var t,s,r,n;if(e.xr.isTrackingImages){for(const o of this._reticle)o.visible=!1;return}if(this._isPlacing){const o=(t=e.xr.rig)==null?void 0:t.gameObject;o&&o.parent!==this.context.scene&&this.context.scene.add(o);let a=!1;if(e.xr.isPassThrough&&e.xr.controllers.length>0)for(const l of e.xr.controllers){const c=l.getHitTest();c&&(a=!0,this.updateReticleAndHits(e.xr,l.index,c,e.xr.rigScale))}if(!a){const l=e.xr.getHitTest();l&&this.updateReticleAndHits(e.xr,0,l,e.xr.rigScale)}}else{if(this._anchor&&e.xr.referenceSpace){const o=e.xr.frame.getPose(this._anchor.anchorSpace,e.xr.referenceSpace);if(o&&this.context.time.frame%20===0){const a=e.xr.convertSpace(o.transform),l=this._reticle[0];l&&(l.position.copy(a.position),l.quaternion.copy(a.quaternion),this.onApplyPose(l))}}if(this.arTouchTransform?(this.userInput||(this.userInput=new Gx(this.context)),(s=this.userInput)==null||s.enable()):(r=this.userInput)==null||r.disable(),this.arTouchTransform&&(n=this.userInput)!=null&&n.hasChanged){if(e.xr.rig){const o=e.xr.rig.gameObject;this.userInput.applyMatrixTo(o.matrix,!0),o.matrix.decompose(o.position,o.quaternion,o.scale),this.userInput.factor=o.scale.x}this.userInput.reset()}}}updateReticleAndHits(e,t,s,r){this._hits[t]=s.hit;let n=this._reticle[t];if(!n){if(this.customReticle)if(this.customReticle.asset)n=cf(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else n=new ge(new $d(.07,.09,32).rotateX(-Math.PI/2),new ni({side:gi})),n.name="AR Placement Reticle";if(Zz){const o=new Ro(1);o.position.y+=.01,n.add(o)}this._reticle[t]=n,n.matrixAutoUpdate=!1,n.visible=!1}n.position.lerp(s.position,this.context.time.deltaTime/.1),n.quaternion.slerp(s.quaternion,this.context.time.deltaTime/.05),n.scale.set(r,r,r),this.customReticle&&this.applyViewBasedTransform(n),n.updateMatrix(),n.visible=!0,n.parent!==this.context.scene&&this.context.scene.add(n),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup)}onScaleChanged(){}onRevertSceneChanges(){var e;for(const t of this._reticle)t&&(t.visible=!1,t?.removeFromParent());this._reticle.length=0;for(let t=this._placementScene.children.length-1;t>=0;t--){const s=this._placementScene.children[t];this.context.scene.add(s)}(e=this._createdPlacementObject)==null||e.removeFromParent();for(const t of this._reparentedComponents)re.addComponent(t.originalObject,t.comp)}async onCreateAnchor(e,t){if(t.createAnchor===void 0){console.warn("Hit does not support creating an anchor",t),wt()&&ns("Hit does not support creating an anchor");return}else{const s=await t.createAnchor(e.viewerPose.transform);e.running&&s&&(this._anchor=s)}}applyViewBasedTransform(e){const t=this.context.mainCamera,s=e,r=t.worldPosition,n=s.worldPosition;r.y=n.y,e.lookAt(r)}onApplyPose(e){var t,s,r,n;const o=(s=(t=mt.active)==null?void 0:t.rig)==null?void 0:s.gameObject;if((r=mt.active)!=null&&r.rigScale,o){const a=o.parent||this.context.scene;this._rigPlacementMatrix?(n=this._rigPlacementMatrix)==null||n.decompose(o.position,o.quaternion,o.scale):this._rigPlacementMatrix=o.matrix.clone(),this.applyViewBasedTransform(e),e.updateMatrix(),this.context.scene.add(e),e.attach(o),e.removeFromParent(),o.scale.set(this.arScale,this.arScale,this.arScale),o.position.multiplyScalar(this.arScale),o.updateMatrix(),this.invertForward&&o.matrix.premultiply(Hoe),o.matrix.premultiply(this._startOffset),o.matrix.decompose(o.position,o.quaternion,o.scale),a.add(o)}}}_0([x()],go.prototype,"arScale",1),_0([x()],go.prototype,"invertForward",2),_0([x(ai)],go.prototype,"customReticle",2),_0([x()],go.prototype,"useXRAnchor",2),_0([x()],go.prototype,"arTouchTransform",2);const m2=class{constructor(i){h(this,"oneFingerDrag",!0),h(this,"twoFingerRotate",!0),h(this,"twoFingerScale",!0),h(this,"factor",1),h(this,"context"),h(this,"offset"),h(this,"plane"),h(this,"_scale",1),h(this,"_hasChanged",!1),h(this,"_enabled",!1),h(this,"currentlyUsedPointerIds",new Set),h(this,"currentlyUnusedPointerIds",new Set),h(this,"onPointerDownEarly",e=>{this.isActive&&e.stopPropagation()}),h(this,"onPointerDownLate",e=>{e.used?this.currentlyUsedPointerIds.add(e.pointerId):this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.add(e.pointerId)}),h(this,"onPointerUpEarly",e=>{this.currentlyUsedPointerIds.delete(e.pointerId),this.currentlyUnusedPointerIds.delete(e.pointerId)}),h(this,"prev",new Map),h(this,"_didMultitouch",!1),h(this,"touchStart",e=>{for(let t=0;t<e.changedTouches.length;t++){const s=e.changedTouches[t];this.prev.has(s.identifier)||this.prev.set(s.identifier,{x:0,z:0,screenx:0,screeny:0});const r=this.prev.get(s.identifier);if(r){const n=this.getPositionOnPlane(s.clientX,s.clientY);r.x=n.x,r.z=n.z,r.screenx=s.clientX,r.screeny=s.clientY}}}),h(this,"touchEnd",e=>{e.touches.length<=0&&(this._didMultitouch=!1)}),h(this,"touchMove",e=>{if(!e.defaultPrevented&&this.isActive){if(e.touches.length===1){if(this._didMultitouch)return;const t=e.touches[0],s=this.prev.get(t.identifier);if(!s)return;const r=this.getPositionOnPlane(t.clientX,t.clientY),n=r.x-s.x,o=r.z-s.z;if(n===0&&o===0)return;this.oneFingerDrag&&this.addMovement(n,o),s.x=r.x,s.z=r.z,s.screenx=t.clientX,s.screeny=t.clientY;return}else if(e.touches.length===2){this._didMultitouch=!0;const t=e.touches[0],s=e.touches[1],r=this.prev.get(t.identifier),n=this.prev.get(s.identifier);if(!r||!n)return;if(this.twoFingerRotate){const o=Math.atan2(t.clientY-s.clientY,t.clientX-s.clientX),a=Math.atan2(r.screeny-n.screeny,r.screenx-n.screenx),l=o-a;Math.abs(l)>.001&&this.addRotation(l)}if(this.twoFingerScale){const o=t.clientX-s.clientX,a=t.clientY-s.clientY,l=Math.sqrt(o*o+a*a),c=r.screenx-n.screenx,u=r.screeny-n.screeny,d=Math.sqrt(c*c+u*u),p=l-d;Math.abs(p)>2&&this.addScale(p)}r.screenx=t.clientX,r.screeny=t.clientY,n.screenx=s.clientX,n.screeny=s.clientY}}}),h(this,"_raycaster",new Np),h(this,"_intersection",new w),h(this,"_screenPos",new w),h(this,"_tempMatrix",new Te),this.context=i,this.offset=new Te,this.plane=new pn,this.plane.setFromNormalAndCoplanarPoint(m2.up,m2.zero)}reset(){this._scale=1,this.offset.identity()}get hasChanged(){return this._hasChanged}applyMatrixTo(i,e){this._hasChanged=!1,e?(this.offset.invert(),i.premultiply(this.offset)):i.multiply(this.offset)}get isActive(){return this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.size>0}enable(){this._enabled||(this._enabled=!0,this.context.input.addEventListener("pointerdown",this.onPointerDownEarly,{queue:el.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:el.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:el.Early}),window.addEventListener("touchstart",this.touchStart,{passive:!1}),window.addEventListener("touchmove",this.touchMove,{passive:!1}),window.addEventListener("touchend",this.touchEnd,{passive:!1}))}disable(){this._enabled&&(this._enabled=!1,this.context.input.removeEventListener("pointerdown",this.onPointerDownEarly,{queue:el.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:el.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:el.Early}),window.removeEventListener("touchstart",this.touchStart),window.removeEventListener("touchmove",this.touchMove),window.removeEventListener("touchend",this.touchEnd))}getPositionOnPlane(i,e){const t=this.context.mainCamera;return this._screenPos.x=i/window.innerWidth*2-1,this._screenPos.y=-(e/window.innerHeight)*2+1,this._screenPos.z=1,this._screenPos.unproject(t),this._raycaster.set(t.position,this._screenPos.sub(t.position)),this._raycaster.ray.intersectPlane(this.plane,this._intersection),this._intersection}addMovement(i,e){i/=this._scale,e/=this._scale,i*=this.factor,e*=this.factor,this.offset.elements[12]+=i,this.offset.elements[14]+=e,(i!==0||e!==0)&&(this._hasChanged=!0)}addScale(i){i/=window.innerWidth,i*=-1,this._scale*=1+i,this._tempMatrix.makeScale(1-i,1-i,1-i),this.offset.premultiply(this._tempMatrix),i!==0&&(this._hasChanged=!0)}addRotation(i){i*=-1,this._tempMatrix.makeRotationY(i),this.offset.premultiply(this._tempMatrix),i!==0&&(this._hasChanged=!0)}};let Gx=m2;h(Gx,"up",new w(0,1,0)),h(Gx,"zero",new w(0,0,0)),h(Gx,"one",new w(1,1,1));const $z=class{constructor(){h(this,"_quicklookButton"),h(this,"_arButton"),h(this,"_vrButton"),h(this,"_sendToQuestButton"),h(this,"_qrButton")}static create(){return new $z}static getOrCreate(){return this._instance||(this._instance=this.create()),this._instance}get isSecureConnection(){return window.location.protocol==="https:"}get quicklookButton(){return this._quicklookButton}get arButton(){return this._arButton}get vrButton(){return this._vrButton}get sendToQuestButton(){return this._sendToQuestButton}get qrButton(){return this._qrButton}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const i=document.createElement("button");return this._quicklookButton=i,i.dataset.needle="quicklook-button",i.innerText="Open in Quicklook",i.addEventListener("click",()=>{const e=re.findObjectOfType(Ys);e?(i.classList.add("this-mode-is-requested"),e.exportAsync().then(()=>{i.classList.remove("this-mode-is-requested")}).catch(t=>{i.classList.remove("this-mode-is-requested"),console.error(t)})):console.warn("No USDZExporter component found in the scene")}),this.hideElementDuringXRSession(i),i}createARButton(i){var e;if(this._arButton)return this._arButton;const t="immersive-ar",s=document.createElement("button");return this._arButton=s,s.classList.add("webxr-button"),s.dataset.needle="webxr-ar-button",s.innerText="Enter AR",s.title="Click to start a WebXR session in AR",s.addEventListener("click",()=>mt.start(t,i)),this.updateSessionSupported(s,t),this.listenToXRSessionState(s,t),this.hideElementDuringXRSession(s),this.isSecureConnection||(s.disabled=!0,s.title="WebXR requires a secure connection (HTTPS)"),Uu()||(e=navigator.xr)==null||e.addEventListener("devicechange",()=>this.updateSessionSupported(s,t)),s}createVRButton(i){var e;if(this._vrButton)return this._vrButton;const t="immersive-vr",s=document.createElement("button");return this._vrButton=s,s.classList.add("webxr-button"),s.dataset.needle="webxr-vr-button",s.innerText="Enter VR",s.title="Click to start a WebXR session in VR",s.addEventListener("click",()=>mt.start(t,i)),this.updateSessionSupported(s,t),this.listenToXRSessionState(s,t),this.hideElementDuringXRSession(s),this.isSecureConnection||(s.disabled=!0,s.title="WebXR requires a secure connection (HTTPS)"),Uu()||(e=navigator.xr)==null||e.addEventListener("devicechange",()=>this.updateSessionSupported(s,t)),s}createSendToQuestButton(){var i;if(this._sendToQuestButton)return this._sendToQuestButton;const e="https://oculus.com/open_url/?url=",t=document.createElement("button");return this._sendToQuestButton=t,t.dataset.needle="webxr-sendtoquest-button",t.innerText="Open on Quest",t.title="Click to send this page to the Oculus Browser on your Quest",t.addEventListener("click",()=>{const s=encodeURIComponent(window.location.href);window.open(e+s)}),this.listenToXRSessionState(t),this.hideElementDuringXRSession(t),Uu()||(i=navigator.xr)==null||i.addEventListener("devicechange",()=>{var s;(s=navigator.xr)!=null&&s.isSessionSupported("immersive-vr")?t.style.display="none":t.style.display=""}),t}createQRCode(){if(this._qrButton)return this._qrButton;const i=document.createElement("button");this._qrButton=i,i.innerText="QR Code",i.title="Scan this QR code with your phone to open this page",this.hideElementDuringXRSession(i);const e=document.createElement("div");e.style.position="fixed",e.style.display="inline-block",e.style.padding="1rem",e.style.backgroundColor="white",e.style.borderRadius="0.4rem",e.style.cursor="pointer",e.style.zIndex="1000",e.style.boxShadow="0 0 12px rgba(0, 0, 0, 0.2)";const t=document.createElement("div");t.classList.add("qr-code-container"),e.appendChild(t),i.addEventListener("click",()=>{if(e.parentNode)return r();s()});async function s(){await n(),document.body.appendChild(e);const o=t.getBoundingClientRect(),a=i.getBoundingClientRect();e.style.left=a.left+a.width*.5-o.width*.5+"px",a.top<o.height?e.style.top=`calc(${a.bottom}px + ${e.style.padding} * .6)`:e.style.top=`calc(${a.top-o.height}px - ${e.style.padding} * 2.5)`,setTimeout(()=>window.addEventListener("click",r,{once:!0})),window.addEventListener("resize",r),window.addEventListener("scroll",r),document.body.appendChild(e)}function r(){var o;(o=e.parentNode)==null||o.removeChild(e),window.removeEventListener("click",r),window.removeEventListener("resize",r),window.removeEventListener("scroll",r)}async function n(){const o=await Kk({text:window.location.href,width:200,height:200});t.innerHTML="",t.appendChild(o)}return i.addEventListener("pointerenter",()=>{n()},{once:!0}),i}updateSessionSupported(i,e){if(!("xr"in navigator)){i.style.display="none";return}mt.isSessionSupported(e).then(t=>{i.style.display=t?"":"none",wt()&&!t&&console.warn(e+" is not supported on this device - make sure your server runs using HTTPS and you have a device connected that supports "+e)})}hideElementDuringXRSession(i){mt.onXRSessionStart(e=>{i["previous-display"]=i.style.display,i.style.display="none"}),mt.onXRSessionEnd(e=>{i["previous-display"]!=null&&(i.style.display=i["previous-display"])})}listenToXRSessionState(i,e){e&&(mt.onSessionRequestStart(t=>{t.mode===e?i.classList.add("this-mode-is-requested"):(i["was-disabled"]=i.disabled,i.disabled=!0,i.classList.add("other-mode-is-requested"))}),mt.onSessionRequestEnd(t=>{i.classList.remove("this-mode-is-requested"),i.classList.remove("other-mode-is-requested"),i.disabled=i["was-disabled"]}))}};let Hf=$z;h(Hf,"_instance");var Woe=Object.defineProperty,Xoe=Object.getOwnPropertyDescriptor,Dc=(i,e,t,s)=>{for(var r=s>1?void 0:s?Xoe(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Woe(e,t,r),r};const Rd=te("debugtext");var qs=(i=>(i[i.UpperLeft=0]="UpperLeft",i[i.UpperCenter=1]="UpperCenter",i[i.UpperRight=2]="UpperRight",i[i.MiddleLeft=3]="MiddleLeft",i[i.MiddleCenter=4]="MiddleCenter",i[i.MiddleRight=5]="MiddleRight",i[i.LowerLeft=6]="LowerLeft",i[i.LowerCenter=7]="LowerCenter",i[i.LowerRight=8]="LowerRight",i))(qs||{}),e5=(i=>(i[i.Normal=0]="Normal",i[i.Bold=1]="Bold",i[i.Italic=2]="Italic",i[i.BoldAndItalic=3]="BoldAndItalic",i))(e5||{});class Rn extends xd{constructor(){super(...arguments),h(this,"alignment",0),h(this,"verticalOverflow",0),h(this,"horizontalOverflow",0),h(this,"lineSpacing",1),h(this,"supportRichText",!1),h(this,"font"),h(this,"fontStyle",0),h(this,"sRGBTextColor",new we(1,0,1)),h(this,"_text",""),h(this,"_fontSize",12),h(this,"_textMeshUi",null),h(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(e){var t;super.setAlphaFactor(e),(t=this.uiObject)==null||t.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){var t;this._fontSize=e,(t=this.uiObject)==null||t.set({fontSize:e})}onColorChanged(){var e;this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),(e=this.uiObject)==null||e.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(e){this.updateOverflow()}updateOverflow(){var e;const t=(e=this.uiObject)==null?void 0:e._overflow;t&&(t._needsUpdate=!0,this.markDirty())}onCreate(e){Rd&&console.log(this),this.horizontalOverflow==1&&(e.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,e.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,e.lineHeight=this.lineSpacing,delete e.backgroundOpacity,delete e.backgroundColor,Rd&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),Rd&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=t.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}getTextOpts(){const e=this.fontSize,t={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.setFont(t,this.fontStyle),t}onEnable(){var e;super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),(e=this.canvas)==null||e.registerEventReceiver(this)}onDisable(){var e;super.onDisable(),(e=this.canvas)==null||e.unregisterEventReceiver(this)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 0:case 3:case 6:e.textAlign="left";break;case 1:case 4:case 7:e.textAlign="center";break;case 2:case 5:case 8:e.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:e.alignItems="start";break;case 3:case 4:case 5:e.alignItems="center";break;case 6:case 7:case 8:e.alignItems="end";break}return e}feedText(e,t){var s,r,n;if(Rd&&console.log("feedText",this.uiObject,e,t),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!t||e.length===0)this.uiObject.textContent=e;else{let o=this.getNextTag(e);if(o){if(o.startIndex>0){for(let c=this.uiObject.children.length-1;c>=0;c--){const u=this.uiObject.children[c];u.isUI&&(this.uiObject.remove(u),u.clear())}const l=new Mb({textContent:e.substring(0,o.startIndex),color:"inherit"});this.uiObject.add(l)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const a=[];for(;o;){const l=this.getNextTag(e,o.endIndex),c={fontFamily:(s=this.uiObject)==null?void 0:s.get("fontFamily"),color:"inherit",textContent:""};if(l){c.textContent=this.getText(e,o,l),this.handleTag(o,c,a);const u=new Mb(c);(r=this.uiObject)==null||r.add(u)}else{c.textContent=e.substring(o.endIndex),this.handleTag(o,c,a);const u=new Mb(c);(n=this.uiObject)==null||n.add(u)}o=l}}}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,s={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let r=!1;if(this._textMeshUi)for(let n=0;n<this._textMeshUi.length;n++){if(e[n]===!0)continue;r=!0;const o=this._textMeshUi[n];o.textContent&&(sx(o,s),e[n]=!0)}if(!r)break;yield}}handleTag(e,t,s){if(!e.isEndTag){if(e.type.includes("color")){const r=new g2(e,{color:t.color});if(s.push(r),e.type.length>6){const n=parseInt("0x"+e.type.substring(7));t.color=n}else t.color=new we(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const r=new g2(e,{fontWeight:700});s.push(r)}else if(e.type=="i"){this.setFont(t,2);const r=new g2(e,{fontStyle:"italic"});s.push(r)}}}getText(e,t,s){return e.substring(t.endIndex,s.startIndex)}getNextTag(e,t=0){const s=e.indexOf("<",t),r=e.indexOf(">",s);if(s>=0&&r>=0){const n=e.substring(s+1,r);return{type:n,startIndex:s,endIndex:r+1,isEndTag:n.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;const s=this.font,r=this.getFamilyNameWithCorrectSuffix(s,t);Rd&&console.log("Selected font family:"+r);let n=QE.getFontFamily(r);switch(n||(n=QE.addFontFamily(r)),e.fontFamily=n,t){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal";break;case 2:e.fontWeight=400,e.fontStyle="italic";break;case 3:e.fontStyle="italic",e.fontWeight=400}let o=n.getVariant(e.fontWeight,e.fontStyle);if(!o){let a=r;a!=null&&a.endsWith("-msdf.json")||(a+="-msdf.json");let l=r;l!=null&&l.endsWith(".png")||(l+=".png"),o=n.addVariant(e.fontWeight,e.fontStyle,a,l),o?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,t){var s;const r=e.lastIndexOf("-");if(r<0)return e;const n=(s=e.substring(r+1))==null?void 0:s.toLowerCase();if(qoe.includes(n))return Rd&&console.warn("Unsupported font style: "+n),e;const o=e.lastIndexOf("/");let a=e;o>=0&&(a=a.substring(o+1));const l=a[0]===a[0].toUpperCase(),c=e.substring(0,r);switch(Rd&&console.log("Select font: ",e,e5[t],a,l,c),t){case 0:return l?c+"-Regular":c+"-regular";case 1:return l?c+"-Bold":c+"-bold";case 2:return l?c+"-Italic":c+"-italic";case 3:return l?c+"-BoldItalic":c+"-bolditalic";default:return e}}}Dc([x()],Rn.prototype,"alignment",2),Dc([x()],Rn.prototype,"verticalOverflow",2),Dc([x()],Rn.prototype,"horizontalOverflow",2),Dc([x()],Rn.prototype,"lineSpacing",2),Dc([x()],Rn.prototype,"supportRichText",2),Dc([x(URL)],Rn.prototype,"font",2),Dc([x()],Rn.prototype,"fontStyle",2),Dc([x()],Rn.prototype,"text",1),Dc([x()],Rn.prototype,"fontSize",1);class g2{constructor(e,t){h(this,"tag"),h(this,"previousValues"),this.tag=e,this.previousValues=t}}const qoe=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class Kh{constructor(e){h(this,"id"),h(this,"content",""),h(this,"font",[]),h(this,"pointSize",144),h(this,"width"),h(this,"height"),h(this,"depth"),h(this,"wrapMode"),h(this,"horizontalAlignment"),h(this,"verticalAlignment"),h(this,"material"),this.id=e}static getId(){return this.global_id++}setDepth(e){return this.depth=e,this}setPointSize(e){return this.pointSize=e,this}setHorizontalAlignment(e){return this.horizontalAlignment=e,this}setVerticalAlignment(e){return this.verticalAlignment=e,this}writeTo(e,t){var s;t.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),t.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),t.closeBlock(")"),t.beginBlock(),this.content&&t.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(s=this.font)==null||s.push("sans-serif"));const r=this.font.map(n=>`"${n}"`).join(", ");t.appendLine(`string[] font = [ ${r} ]`),t.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&t.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&t.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&t.appendLine(`double depth = ${this.depth}`),this.wrapMode&&t.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&t.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&t.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&t.appendLine(`rel material:binding = </StageRoot/Materials/${nI(this.material)}>`),t.closeBlock()}}h(Kh,"global_id",0);class Qx{static singleLine(e,t,s){const r=new Kh("text_"+Kh.getId());return r.content=e,t&&(r.pointSize=t),s&&(r.depth=s),r}static multiLine(e,t,s,r,n,o){const a=new Kh("text_"+Kh.getId());return a.content=e,a.width=t,a.height=s,a.horizontalAlignment=r,a.verticalAlignment=n,o!==void 0&&(a.wrapMode=o),a}}const Yoe=new Te().makeRotationY(Math.PI),Joe=new Te().makeScale(-1,1,-1);class x0{get extensionName(){return"text"}onExportObject(e,t,s){}exportText(e,t,s){const r=re.getComponent(e,Rn);if(!r)return;const n=re.getComponent(e,Tn);let o=100,a=100;n&&(o=n.width,a=n.height),t.matrix=Yoe.clone(),n&&t.matrix.premultiply(Joe);const l=r.color.clone();t.material=new Un({color:l,emissive:l}),t.addEventListener("serialize",(c,u)=>{let d=r.text;d=d.replace(/\r/g,""),d=d.replace(/\n/g,"\\n");const p=Qx.multiLine(d,o,a,"center","bottom","flowing");this.setTextAlignment(p,r.alignment),this.setOverflow(p,r),t.material&&(p.material=t.material),p.pointSize=this.convertToTextSize(r.fontSize),p.depth=.001,p.writeTo(void 0,c)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case qs.LowerLeft:case qs.MiddleLeft:case qs.UpperLeft:e.horizontalAlignment="left";break;case qs.LowerCenter:case qs.MiddleCenter:case qs.UpperCenter:e.horizontalAlignment="center";break;case qs.LowerRight:case qs.MiddleRight:case qs.UpperRight:e.horizontalAlignment="right";break}switch(t){case qs.LowerLeft:case qs.LowerCenter:case qs.LowerRight:e.verticalAlignment="bottom";break;case qs.MiddleLeft:case qs.MiddleCenter:case qs.MiddleRight:e.verticalAlignment="middle";break;case qs.UpperLeft:case qs.UpperCenter:case qs.UpperRight:e.verticalAlignment="top";break}}}class Vx{get extensionName(){return"tmui"}onExportObject(e,t,s){const r=re.getComponent(e,Br);if(r&&r.activeAndEnabled&&r.renderMode===Oz.WorldSpace){const n=new x0,o=re.getComponent(e,Tn),a=re.getComponent(e,Qh);if(o){o.width,o.height;const l=Wo.createEmpty(),c=o.shadowComponent;if(t.add(l),c){const u=c.matrix;l.matrix.copy(u);const d=new Map,p=new Map;d.set(c,l),p.set(c,a?a.alpha:1),c.traverse(f=>{if(f===c)return;const m=Wo.createEmpty();m.matrix.copy(f.matrix);const A=f.parent,y=!!A&&typeof A.textContent=="string"&&A.textContent.length>0;let g=p.get(A)||1;const v=re.getComponent(f,Qh);if(v&&(g*=v.alpha),f instanceof ge&&y){const _=f[qo];_?n.exportText(_.gameObject,m,s):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",f)}if(f instanceof ge&&!y){const _=f.geometry.clone();_.scale(1,1,-1),this.flipWindingOrder(_),m.geometry=_;const S=new we,I=f.material.opacity;S.copy(f.material.color),m.material=new ni({color:S,opacity:I*g,map:f.material.map,transparent:!0})}d.set(f,m),p.set(f,g);const b=d.get(A);if(!b){console.error("Error when exporting UI: shadow component parent not found!",f,f.parent);return}b.add(m)})}}}}flipWindingOrder(e){const t=e.index.array;for(let s=0,r=t.length/3;s<r;s++){const n=t[s*3];t[s*3]=t[s*3+2],t[s*3+2]=n}e.index.needsUpdate=!0}}const Hx=te("debugusdz");function Koe(i,e){var t;const s=[],r=re.getComponentsInChildren(i,Ir),n=re.getComponentsInChildren(i,oo),o=new Array;if(e.injectImplicitBehaviours)for(const a of r){if(!a||!a.runtimeAnimatorController)continue;const l=a.runtimeAnimatorController.activeState;if(!l||!l.motion||!l.motion.clip||((t=l.motion.clip.tracks)==null?void 0:t.length)<1)continue;const c=new Qf;c.animator=a,c.stateName=l.name,c.trigger="start",c.name="PlayAnimationOnClick_implicitAtStart_"+c.stateName;const u=new Ae;re.addComponent(u,c),o.push(u),i.add(u)}else for(const a of r){if(!a||!a.runtimeAnimatorController)continue;Hx&&console.log(a);const l=[];for(const c of a.runtimeAnimatorController.enumerateActions()){Hx&&console.log(c);const u=c.getClip();l.includes(u)||l.push(u)}s.push({root:a.gameObject,clips:l})}for(const a of n){Hx&&console.log(a);const l=[];for(const c of a.animations)l.includes(c)||l.push(c);s.push({root:a.gameObject,clips:l})}Hx&&console.log("USDZ Animation Clips",s);for(const a of s)for(const l of a.clips)e.registerAnimation(a.root,l);return o}function Zoe(i,e){const t=re.getComponentsInChildren(i,os),s=re.getComponentsInChildren(i,Vh),r=new Array;for(const n of s){if(!n.target)continue;const o=t.indexOf(n.target);o>-1&&t.splice(o,1)}for(const n of t){if(!n||!n.clip||n.volume<=0)continue;const o=new Vh;o.target=n,o.name="PlayAudioOnClick_implicitAtStart_";const a=new Ae;re.addComponent(a,o),console.log("implicit PlayAudioOnStart",a,o),r.push(a),i.add(a)}return r}function t5(i){const e=i.domElement.shadowRoot.querySelector("link[rel='ar']");if(e)return e;const t=document.createElement("div");t.classList.add("menu"),t.classList.add("quicklook-menu"),t.style.display="none",t.style.visibility="hidden";const s=document.createElement("button");s.id="open-in-ar",s.innerText="Open in QuickLook",t.appendChild(s);const r=document.createElement("a");r.id="needle-usdz-link",r.style.display="none",r.rel="ar",r.href="",t.appendChild(r);const n=document.createElement("img");return n.id="button",r.appendChild(n),i.domElement.shadowRoot.appendChild(t),r}var $oe=Object.defineProperty,eae=Object.getOwnPropertyDescriptor,on=(i,e,t,s)=>{for(var r=s>1?void 0:s?eae(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&$oe(e,t,r),r};const Xn=te("debugusdz");class Zh{constructor(){h(this,"callToAction"),h(this,"checkoutTitle"),h(this,"checkoutSubtitle"),h(this,"callToActionURL")}}on([x()],Zh.prototype,"callToAction",2),on([x()],Zh.prototype,"checkoutTitle",2),on([x()],Zh.prototype,"checkoutSubtitle",2),on([x()],Zh.prototype,"callToActionURL",2);var v2;const A2=(v2=class extends Be{constructor(){super(...arguments),h(this,"objectToExport"),h(this,"autoExportAnimations",!1),h(this,"autoExportAudioSources",!0),h(this,"exportFileName"),h(this,"customUsdzFile"),h(this,"customBranding"),h(this,"anchoringType","plane"),h(this,"maxTextureSize",2048),h(this,"planeAnchoringAlignment","horizontal"),h(this,"interactive",!0),h(this,"allowCreateQuicklookButton",!0),h(this,"quickLookCompatible",!0),h(this,"extensions",[]),h(this,"link"),h(this,"button"),h(this,"onClickedOpenInARElement",i=>{i.preventDefault(),this.exportAsync()}),h(this,"lastCallback")}start(){var i,e,t;Xn&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",s=>{switch(s.key){case"t":this.exportAsync();break}}),Xa()&&setTimeout(()=>{this.exportAsync()},2e3)),this.objectToExport||(this.objectToExport=this.gameObject),!((e=(i=this.objectToExport)==null?void 0:i.children)!=null&&e.length)&&!((t=this.objectToExport)!=null&&t.isMesh)&&(this.objectToExport=this.context.scene),this.interactive&&(this.extensions.push(new yx),this.extensions.push(new cu),this.extensions.push(new x0),this.extensions.push(new Vx))}onEnable(){var i;const e=Gp(),t=Qp();(Xn||e&&t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=t5(this.context),this.link.addEventListener("message",this.lastCallback)),Xn&&rs("USDZ Exporter enabled: "+this.name),(i=document.getElementById("open-in-ar"))==null||i.addEventListener("click",this.onClickedOpenInARElement)}onDisable(){var i,e,t;(i=this.button)==null||i.remove(),(e=this.link)==null||e.removeEventListener("message",this.lastCallback),Xn&&rs("USDZ Exporter disabled: "+this.name),(t=document.getElementById("open-in-ar"))==null||t.removeEventListener("click",this.onClickedOpenInARElement)}async exportAsync(){var i;let e=this.exportFileName??((i=this.objectToExport)==null?void 0:i.name)??this.name;if(e+="-"+P4(),mc()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=t5(this.context)),this.customUsdzFile){Xn&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,e);return}const t=await this.export(this.objectToExport);if(!t){console.warn("No object to export",this);return}Xn&&console.log("USDZ generation done. Downloading as "+this.link.download),this.openInQuickLook(t,e)}async export(i){if(!i)return null;ti.start("export-usdz",{onProgress:p=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:p}}))}}),ti.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),ti.report("export-usdz",{message:"Load progressive textures",autoStep:5}),ti.start("export-usdz-textures","export-usdz");const e=re.getComponentsInChildren(i,As),t=new Array;let s=0;for(const p of e)for(const f of p.sharedMaterials)if(f){const m=p.loadProgressiveTextures(f);m instanceof Promise&&t.push(new Promise((A,y)=>{m.then(()=>{s++,ti.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:s,totalSteps:t.length}),A()}).catch(g=>y(g))}))}Xn&&rs("Load textures: "+t.length),await Promise.all(t),Xn&&rs("Load textures: done"),ti.end("export-usdz-textures");const r=Mn.Global.Mask;Mn.Global.Set(cl.AR),this.applyWebARSessionRoot();const n=new vse,o=[...this.extensions],a=new Qv(this.quickLookCompatible);o.push(a);const l={self:this,exporter:n,extensions:o,object:i};ti.report("export-usdz","Invoking before-export"),this.dispatchEvent(new CustomEvent("before-export",{detail:l})),ti.report("export-usdz","auto export animations and audio sources");const c=new Array;this.autoExportAnimations&&c.push(...Koe(i,a)),this.extensions.find(p=>p.extensionName==="Audio")&&this.autoExportAudioSources&&c.push(...Zoe(i)),n.debug=Xn,n.keepObject=p=>{const f=re.getComponent(p,As);return!(f&&!f.enabled)},this.anchoringType!=="plane"&&this.anchoringType!=="none"&&this.anchoringType!=="image"&&this.anchoringType!=="face"&&(this.anchoringType="plane"),this.planeAnchoringAlignment!=="horizontal"&&this.planeAnchoringAlignment!=="vertical"&&this.planeAnchoringAlignment!=="any"&&(this.planeAnchoringAlignment="horizontal"),ti.report("export-usdz","Invoking exporter.parse");const u=await n.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:o,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize}),d=new Blob([u],{type:"model/vnd.usdz+zip"});for(const p of c)re.destroy(p);return ti.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:l})),Mn.Global.Set(r),ti.end("export-usdz"),d}openInQuickLook(i,e){const t=i instanceof Blob?URL.createObjectURL(i):i,s=this.buildQuicklookOverlay();Xn&&console.log("QuickLook Overlay",s);const r=s.callToAction?encodeURIComponent(s.callToAction):"",n=s.checkoutTitle?encodeURIComponent(s.checkoutTitle):"",o=s.checkoutSubtitle?encodeURIComponent(s.checkoutSubtitle):"";this.link.href=t+`#callToAction=${r}&checkoutTitle=${n}&checkoutSubtitle=${o}&callToActionURL=${s.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=e+".usdz",this.link.click()}download(i,e){A2.save(i,e)}static save(i,e){const t=document.createElement("a");t.style.display="none",document.body.appendChild(t),typeof i=="string"?t.href=i:t.href=URL.createObjectURL(i),t.download=e,t.click(),t.remove()}quicklookCallback(i){if(i?.data=="_apple_ar_quicklook_button_tapped"){Xn&&ns("Quicklook closed via call to action button");var e=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(e),!e.defaultPrevented){const t=new URLSearchParams(this.link.href);if(t){const s=t.get("callToActionURL");Xn&&rs("Quicklook url: "+s),s&&(mc()?globalThis.open(s,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",s))}}}}buildQuicklookOverlay(){var i,e,t,s,r,n;const o={};return this.customBranding&&Object.assign(o,this.customBranding),mc()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),o.callToAction="Close",o.checkoutTitle="\u{1F335} Made with Needle",o.checkoutSubtitle="_"),(((i=o.callToAction)==null?void 0:i.length)||((e=o.checkoutTitle)==null?void 0:e.length)||((t=o.checkoutSubtitle)==null?void 0:t.length))&&((s=o.callToAction)!=null&&s.length||(o.callToAction="\0"),(r=o.checkoutTitle)!=null&&r.length||(o.checkoutTitle="\0"),(n=o.checkoutSubtitle)!=null&&n.length||(o.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:o})),o}applyWebARSessionRoot(){if(!this.objectToExport)return;let i=re.getComponentInParent(this.objectToExport,go);const e=i!=null;if(i||(i=re.getComponentInChildren(this.objectToExport,go)),Xn&&console.log("applyWebARSessionRoot",i),!i){Xn&&console.warn("No WebARSessionRoot found in parent hierarchy",this.objectToExport);return}const t=e?this.objectToExport:i.gameObject,s=1/i.arScale;t.matrix.makeScale(s,s,s),i.invertForward&&t.matrix.multiply(A2.invertForwardMatrix)}createQuicklookButton(){const i=Hf.getOrCreate().createQuicklookButton();return i.parentNode||this.context.menu.appendChild(i),i}},h(v2,"invertForwardMatrix",new Te().makeRotationY(Math.PI)),v2);let Ys=A2;on([x(Ae)],Ys.prototype,"objectToExport",2),on([x()],Ys.prototype,"autoExportAnimations",2),on([x()],Ys.prototype,"autoExportAudioSources",2),on([x()],Ys.prototype,"exportFileName",2),on([x(URL)],Ys.prototype,"customUsdzFile",2),on([x(Zh)],Ys.prototype,"customBranding",2),on([x()],Ys.prototype,"anchoringType",2),on([x()],Ys.prototype,"maxTextureSize",2),on([x()],Ys.prototype,"planeAnchoringAlignment",2),on([x()],Ys.prototype,"interactive",2),on([x()],Ys.prototype,"allowCreateQuicklookButton",2),on([x()],Ys.prototype,"quickLookCompatible",2);class w0 extends Be{constructor(){super(...arguments),h(this,"isUsed",!0),h(this,"usedBy",null)}}class y2 extends Be{}const i5=te("debugdeletable");class Wx extends dl{}class b2 extends Be{constructor(){super(...arguments),h(this,"deleteBoxes",[])}awake(){this.deleteBoxes=re.findObjectsOfType(Wx,this.context)}update(){for(const e of this.deleteBoxes){const t=this.gameObject;if(e.isInBox(t)===!0){const s=re.getComponentInParent(this.gameObject,w0);s?i5&&console.warn("Can not delete object with usage marker",this.guid,s):(i5&&console.log("DESTROY",this.gameObject),O_(this.gameObject,this.context.connection))}}}}var tae=Object.defineProperty,iae=Object.getOwnPropertyDescriptor,Pd=(i,e,t,s)=>{for(var r=s>1?void 0:s?iae(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&tae(e,t,r),r};const s5=te("debugpost");class Pa extends nn{constructor(){super(...arguments),h(this,"mode"),h(this,"focusDistance"),h(this,"focalLength"),h(this,"aperture"),h(this,"gaussianMaxRadius"),h(this,"resolutionScale"),h(this,"bokehScale")}get typeName(){return"DepthOfField"}init(){s5&&console.log("DOF: INIT"),this.focalLength.valueProcessor=t=>{const s=t/300,r=2;return st.lerp(r,.01,s)};const e=20;this.aperture.valueProcessor=t=>{const s=1-t/32;return st.lerp(1,e,s)}}onCreateEffect(){if(this.mode===0){s5&&console.warn("DepthOfField: Mode is set to Off");return}const e=1/window.devicePixelRatio;if(this.resolutionScale===void 0){let s=1;Xa()&&(s=.6),this.resolutionScale=new Bt(s*e)}const t=new G3(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=s=>{t.cocMaterial.worldFocusDistance=s},this.focalLength.onValueChanged=s=>t.cocMaterial.worldFocusRange=s,this.aperture.onValueChanged=s=>t.bokehScale=s,this.resolutionScale&&(this.resolutionScale.onValueChanged=s=>t.resolution.scale=s),[t]}unapply(){}}Pd([x()],Pa.prototype,"mode",2),Pd([x(Bt)],Pa.prototype,"focusDistance",2),Pd([x(Bt)],Pa.prototype,"focalLength",2),Pd([x(Bt)],Pa.prototype,"aperture",2),Pd([x(Bt)],Pa.prototype,"gaussianMaxRadius",2),Pd([x(Bt)],Pa.prototype,"resolutionScale",2),Pd([x(Bt)],Pa.prototype,"bokehScale",2),Ko("DepthOfField",Pa);var sae=Object.defineProperty,rae=Object.getOwnPropertyDescriptor,nae=(i,e,t,s)=>{for(var r=s>1?void 0:s?rae(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&sae(e,t,r),r};class Xx extends Be{constructor(){super(...arguments),h(this,"visibleOn")}onEnable(){this.apply()}apply(){this.test()||re.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:Xa()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}nae([x()],Xx.prototype,"visibleOn",2);class _2{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}var oae=Object.defineProperty,aae=Object.getOwnPropertyDescriptor,Bd=(i,e,t,s)=>{for(var r=s>1?void 0:s?aae(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&oae(e,t,r),r};const ml=te("debugdrag");var r5=(i=>(i[i.XZPlane=0]="XZPlane",i[i.Attached=1]="Attached",i[i.HitNormal=2]="HitNormal",i[i.DynamicViewAngle=3]="DynamicViewAngle",i[i.SnapToSurfaces=4]="SnapToSurfaces",i[i.None=5]="None",i))(r5||{}),qx;const gl=(qx=class extends Be{constructor(){super(...arguments),h(this,"dragMode",3),h(this,"snapGridResolution",0),h(this,"keepRotation",!0),h(this,"xrDragMode",1),h(this,"xrKeepRotation",!1),h(this,"xrDistanceDragFactor",1),h(this,"showGizmo",!1),h(this,"targetObject",null),h(this,"orbit",null),h(this,"_dragHelper",null),h(this,"_draggingRigidbodies",[]),h(this,"_potentialDragStartEvt",null),h(this,"_dragHandlers",new Map),h(this,"_totalMovement",new w),h(this,"_marker",null),h(this,"_isDragging",!1),h(this,"_didDrag",!1)}static get HasAnySelected(){return this._active>0}setTargetObject(i){this.targetObject=i;for(const e of this._dragHandlers.values())e.setTargetObject(i)}awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new w,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._dragHelper=null,this._draggingRigidbodies=[]}start(){this.orbit=re.findObjectOfType(ji,this.context),this.gameObject.getComponentInParent(ao)||this.gameObject.addNewComponent(ao)}allowEdit(i=null){return this.context.connection.allowEditing}onPointerEnter(i){if(!this.allowEdit(this.gameObject)||i.mode!=="screen"||(i.event.mode==="tracked-pointer"?this.xrDragMode:this.dragMode)===5)return;const e=re.getComponentInParent(i.object,gl);!e||e!==this||(gl.lastHovered=i.object,this.context.domElement.style.cursor="pointer")}onPointerExit(i){this.allowEdit(this.gameObject)&&i.mode==="screen"&&gl.lastHovered===i.object&&(this.context.domElement.style.cursor="auto")}onPointerDown(i){if(!(!this.allowEdit(this.gameObject)||i.used||(i.mode==="tracked-pointer"?this.xrDragMode:this.dragMode)===5)&&(gl.lastHovered=i.object,i.button===0)){this._dragHandlers.size===0&&(this._didDrag=!1,this._totalMovement.set(0,0,0),this._potentialDragStartEvt=i),gl._active+=1;const e=new cae(this,this.targetObject||this.gameObject);if(this._dragHandlers.set(i.event.space,e),this.orbit&&(this.orbit.enabled=!1),e.onDragStart(i),this._dragHandlers.size===2){const t=this._dragHandlers.values(),s=t.next().value,r=t.next().value,n=new lae(this,this.targetObject||this.gameObject,s,r);this._dragHandlers.set(this.gameObject,n),n.onDragStart(i)}i.use()}}onPointerMove(i){(this._isDragging||this._potentialDragStartEvt!==null)&&i.use()}onPointerUp(i){if(ml&&Tt.DrawLabel(i.point??this.gameObject.worldPosition,"POINTERUP:"+i.pointerId+", "+i.button,.03,3),!this.allowEdit(this.gameObject)||i.button!==0)return;this._potentialDragStartEvt=null;const e=this._dragHandlers.get(i.event.space),t=this._dragHandlers.get(this.gameObject);t&&(t.handlerA===e||t.handlerB===e)&&(this._dragHandlers.delete(this.gameObject),t.onDragEnd(i)),e&&(gl._active>0&&(gl._active-=1),e.onDragEnd&&e.onDragEnd(i),this._dragHandlers.delete(i.event.space),this._dragHandlers.size===0&&this.onLastDragEnd(i),i.use()),gl._active===0&&this.orbit&&(this.orbit.enabled=!0)}update(){for(const i of this._dragHandlers.values())i.collectMovementInfo&&i.collectMovementInfo(),i.getTotalMovement&&this._totalMovement.add(i.getTotalMovement());if(this._potentialDragStartEvt){if(!this._didDrag)if(this._totalMovement.length()>3e-4)this._didDrag=!0;else return;const i=this._potentialDragStartEvt;this._potentialDragStartEvt=null,this.onFirstDragStart(i)}for(const i of this._dragHandlers.values())i.onDragUpdate&&i.onDragUpdate(this._dragHandlers.size);this._dragHelper&&this._dragHelper.hasSelected&&this.onAnyDragUpdate()}onFirstDragStart(i){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new o5(this.context.mainCamera);else return;if(!i||!i.object)return;const e=re.getComponentInParent(i.object,gl);if(!e||e!==this)return;const t=this.targetObject||this.gameObject;if(!t)return;this._isDragging=!0,this._dragHelper.setSelected(t,this.context),this.orbit&&(this.orbit.enabled=!1);const s=re.getComponentInChildren(t,Oh);ml&&console.log("DRAG START",s,t),s&&(s.fastMode=!0,s?.requestOwnership()),this._marker=re.addNewComponent(t,w0),this._draggingRigidbodies.length=0;const r=re.getComponentsInChildren(t,zi);r&&this._draggingRigidbodies.push(...r)}onAnyDragUpdate(){if(!this._dragHelper)return;this._dragHelper.showGizmo=this.showGizmo,this._dragHelper.onUpdate(this.context);for(const e of this._draggingRigidbodies)e.wakeUp(),e.resetVelocities(),e.resetForcesAndTorques();const i=this.targetObject||this.gameObject;Fa.markDirty(i)}onLastDragEnd(i){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;for(const t of this._draggingRigidbodies)t.setVelocity(t.smoothedVelocity);this._draggingRigidbodies.length=0;const e=this._dragHelper.selected;if(ml&&console.log("DRAG END",e,e?.visible),this._dragHelper.setSelected(null,this.context),this.orbit&&(this.orbit.enabled=!0),i!=null&&i.object){const t=re.getComponentInChildren(i.object,Oh);t&&(t.fastMode=!1)}this._marker&&this._marker.destroy()}},h(qx,"_active",0),h(qx,"lastHovered"),qx);let ta=gl;Bd([x()],ta.prototype,"dragMode",2),Bd([x()],ta.prototype,"snapGridResolution",2),Bd([x()],ta.prototype,"keepRotation",2),Bd([x()],ta.prototype,"xrDragMode",2),Bd([x()],ta.prototype,"xrKeepRotation",2),Bd([x()],ta.prototype,"xrDistanceDragFactor",2),Bd([x()],ta.prototype,"showGizmo",2);class lae{constructor(e,t,s,r){h(this,"handlerA"),h(this,"handlerB"),h(this,"context"),h(this,"settings"),h(this,"gameObject"),h(this,"_handlerAAttachmentPoint",new w),h(this,"_handlerBAttachmentPoint",new w),h(this,"_followObject"),h(this,"_manipulatorObject"),h(this,"_deviceMode"),h(this,"_followObjectStartWorldQuaternion",new Ie),h(this,"_manipulatorPosOffset",new w),h(this,"_manipulatorRotOffset",new Ie),h(this,"_manipulatorScaleOffset",new w),h(this,"_tempVec1",new w),h(this,"_tempVec2",new w),h(this,"_tempVec3",new w),h(this,"tempLookMatrix",new Te),h(this,"_initialScale",new w),h(this,"_initialDistance",0);var n,o;this.context=e.context,this.settings=e,this.gameObject=t,this.handlerA=s,this.handlerB=r,this._followObject=new Ae,this._manipulatorObject=new Ae,this.context.scene.add(this._manipulatorObject);const a=(o=(n=mt.active)==null?void 0:n.rig)==null?void 0:o.gameObject;if(!this.handlerA||!this.handlerB||!this.handlerA.hitPointInLocalSpace||!this.handlerB.hitPointInLocalSpace){console.error("Invalid: MultiTouchDragHandler needs two valid DragPointerHandlers with hitPointInLocalSpace set.");return}if(this._tempVec1.copy(this.handlerA.hitPointInLocalSpace),this._tempVec2.copy(this.handlerB.hitPointInLocalSpace),this.gameObject.localToWorld(this._tempVec1),this.gameObject.localToWorld(this._tempVec2),a&&(a.worldToLocal(this._tempVec1),a.worldToLocal(this._tempVec2)),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(ml&&console.log("Finding alternative drag attachment points since initial distance is too low: "+this._initialDistance.toFixed(2)),this.handlerA.followObject.parent.getWorldPosition(this._tempVec1),this.handlerB.followObject.parent.getWorldPosition(this._tempVec2),this._handlerAAttachmentPoint.copy(this._tempVec1),this._handlerBAttachmentPoint.copy(this._tempVec2),this.gameObject.worldToLocal(this._handlerAAttachmentPoint),this.gameObject.worldToLocal(this._handlerBAttachmentPoint),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.001&&(console.warn("Not supported right now \u2013 controller drag points for multitouch are too close!"),this._initialDistance=1)):(this._handlerAAttachmentPoint.copy(this.handlerA.hitPointInLocalSpace),this._handlerBAttachmentPoint.copy(this.handlerB.hitPointInLocalSpace)),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._initialScale.copy(t.scale),ml){this._followObject.add(new Ro(2)),this._manipulatorObject.add(new Ro(5));const l=c=>`${c.x.toFixed(2)}, ${c.y.toFixed(2)}, ${c.z.toFixed(2)}`;Tt.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),Tt.DrawLabel(this._tempVec3,"A:B "+this._initialDistance.toFixed(2)+`
6304
6304
  `+l(this._tempVec1)+`
6305
6305
  `+l(this._tempVec2),.03,5)}}onDragStart(e){this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.matrix.identity(),this._deviceMode=e.mode,this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this.alignManipulator(),this._manipulatorObject.attach(this._followObject),this._manipulatorPosOffset.copy(this._followObject.position),this._manipulatorRotOffset.copy(this._followObject.quaternion),this._manipulatorScaleOffset.copy(this._followObject.scale)}onDragEnd(e){if(!this.handlerA||!this.handlerB){console.error("onDragEnd called on MultiTouchDragHandler without valid handlers. This is likely a bug.");return}this.handlerA.recenter(),this.handlerB.recenter(),this._manipulatorObject.removeFromParent(),this._followObject.removeFromParent(),this._manipulatorObject.destroy(),this._followObject.destroy()}alignManipulator(){if(!this.handlerA||!this.handlerB){console.error("alignManipulator called on MultiTouchDragHandler without valid handlers. This is likely a bug.",this);return}if(!this.handlerA.followObject||!this.handlerB.followObject){console.error("alignManipulator called on MultiTouchDragHandler without valid follow objects. This is likely a bug.",this.handlerA,this.handlerB);return}this._tempVec1.copy(this._handlerAAttachmentPoint),this._tempVec2.copy(this._handlerBAttachmentPoint),this.handlerA.followObject.localToWorld(this._tempVec1),this.handlerB.followObject.localToWorld(this._tempVec2),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._manipulatorObject.position.copy(this._tempVec3);const e=this.context.mainCamera;this.tempLookMatrix.lookAt(this._tempVec3,this._tempVec2,e.worldUp),this._manipulatorObject.quaternion.setFromRotationMatrix(this.tempLookMatrix);const t=this._tempVec1.distanceTo(this._tempVec2);this._manipulatorObject.scale.copy(this._initialScale).multiplyScalar(t/this._initialDistance),this._manipulatorObject.updateMatrix(),this._manipulatorObject.updateMatrixWorld(!0),ml&&(Tt.DrawLabel(this._tempVec3.clone().add(new w(0,.2,0)),"A:B "+t.toFixed(2),.03),Tt.DrawLine(this._tempVec1,this._tempVec2,65280,0,!1))}onDragUpdate(){this.alignManipulator();const e=30,t=1;this._followObject.position.copy(this._manipulatorPosOffset),this._followObject.quaternion.copy(this._manipulatorRotOffset),this._followObject.scale.copy(this._manipulatorScaleOffset);const s=this.gameObject,r=this._followObject;r.updateMatrix(),r.updateMatrixWorld(!0);const n=this._deviceMode==="tracked-pointer"?this.settings.xrKeepRotation:this.settings.keepRotation;if(this.settings.snapGridResolution>0){const u=this._followObject.worldPosition,d=this.settings.snapGridResolution;u.x=Math.round(u.x/d)*d,u.y=Math.round(u.y/d)*d,u.z=Math.round(u.z/d)*d,this._followObject.worldPosition=u,this._followObject.updateMatrix()}n&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const o=st.clamp01(this.context.time.deltaTime*e*t),a=s.worldPosition;a.lerp(r.worldPosition,o),s.worldPosition=a;const l=s.worldQuaternion;l.slerp(r.worldQuaternion,o),s.worldQuaternion=l;const c=s.worldScale;c.lerp(r.worldScale,o),s.worldScale=c}setTargetObject(e){this.gameObject=e}}class cae{constructor(e,t){h(this,"context"),h(this,"gameObject"),h(this,"settings"),h(this,"_lastRig"),h(this,"_followObject"),h(this,"_totalMovement",new w),h(this,"_totalMovementAlongRayDirection",0),h(this,"_grabStartDistance",0),h(this,"_deviceMode"),h(this,"_followObjectStartPosition",new w),h(this,"_followObjectStartQuaternion",new Ie),h(this,"_followObjectStartWorldQuaternion",new Ie),h(this,"_lastDragPosRigSpace"),h(this,"_tempVec",new w),h(this,"_tempMat",new Te),h(this,"_hitPointInLocalSpace",new w),h(this,"_hitNormalInLocalSpace",new w),h(this,"_bottomCenter",new w),h(this,"_backCenter",new w),h(this,"_backBottomCenter",new w),h(this,"_bounds",new Ii),h(this,"_dragPlane",new pn(new w(0,1,0))),h(this,"_draggedOverObject",null),h(this,"_draggedOverObjectLastSetUp",null),h(this,"_draggedOverObjectLastNormal",new w),h(this,"_draggedOverObjectDuration",0),this.settings=e,this.context=e.context,this.gameObject=t,this._followObject=new Ae}getTotalMovement(){return this._totalMovement}get followObject(){return this._followObject}get hitPointInLocalSpace(){return this._hitPointInLocalSpace}setTargetObject(e){this.gameObject=e}recenter(){var e,t;if(!this._followObject.parent){console.warn("Error: space follow object doesn't have parent but recenter() is called. This is likely a bug");return}const s=this._followObject.parent;this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.position.set(0,0,0),this._followObject.quaternion.set(0,0,0,1),this._followObject.scale.set(1,1,1),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0),s.attach(this._followObject),this._followObjectStartPosition.copy(this._followObject.position),this._followObjectStartQuaternion.copy(this._followObject.quaternion),this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const r=this._hitPointInLocalSpace.clone();this.gameObject.localToWorld(r),this._grabStartDistance=r.distanceTo(s.worldPosition);const n=(t=(e=mt.active)==null?void 0:e.rig)==null?void 0:t.gameObject,o=n?.worldScale.x||1;this._grabStartDistance/=o,this._totalMovementAlongRayDirection=0,this._lastDragPosRigSpace=void 0,ml&&(Tt.DrawLine(r,s.worldPosition,65280,.5,!1),Tt.DrawLabel(s.worldPosition.add(new w(0,.1,0)),this._grabStartDistance.toFixed(2),.03,.5))}onDragStart(e){if(e.event.space.add(this._followObject),this._lastDragPosRigSpace=void 0,e.point&&e.normal)this._hitPointInLocalSpace.copy(e.point),this.gameObject.worldToLocal(this._hitPointInLocalSpace),this._hitNormalInLocalSpace.copy(e.normal);else if(e){const p=e.event.space,f=p.worldPosition;this.gameObject.worldToLocal(f),this._hitPointInLocalSpace.copy(f);const m=p.worldUp;this._tempMat.copy(this.gameObject.matrixWorld).invert(),m.transformDirection(this._tempMat),this._hitNormalInLocalSpace.copy(m)}this.recenter(),this._totalMovement.set(0,0,0),this._deviceMode=e.mode;const t=this._followObject.parent.worldForward,s=this._deviceMode==="tracked-pointer"?this.settings.xrDragMode:this.settings.dragMode,r=this._hitPointInLocalSpace.clone();switch(this.gameObject.localToWorld(r),s){case 0:const p=new w(0,1,0);this.gameObject.parent&&p.transformDirection(this.gameObject.parent.matrixWorld.clone().invert()),this._dragPlane.setFromNormalAndCoplanarPoint(p,r);break;case 2:const f=this._hitNormalInLocalSpace.clone();f.transformDirection(this.gameObject.matrixWorld),this._dragPlane.setFromNormalAndCoplanarPoint(f,r);break;case 1:this._dragPlane.setFromNormalAndCoplanarPoint(t,r);break;case 3:const m=new w(0,1,0),A=t,y=m.angleTo(A),g=.5;y>Math.PI/2+g||y<Math.PI/2-g?this._dragPlane.setFromNormalAndCoplanarPoint(new w(0,1,0),r):this._dragPlane.setFromNormalAndCoplanarPoint(t,r);break}const n=new Ii,o=this.gameObject.parent,a=this.gameObject.position.clone(),l=this.gameObject.quaternion.clone(),c=this.gameObject.scale.clone();o&&o.remove(this.gameObject),this.gameObject.position.set(0,0,0),this.gameObject.quaternion.set(0,0,0,1),this.gameObject.scale.set(1,1,1),n.setFromObject(this.gameObject);const u=new w;n.getCenter(u);const d=new w;n.getSize(d),this._bottomCenter.copy(u.clone().add(new w(0,-d.y/2,0))),this._backCenter.copy(u.clone().add(new w(0,0,d.z/2))),this._backBottomCenter.copy(u.clone().add(new w(0,-d.y/2,d.z/2))),this._bounds.copy(n),o&&o.add(this.gameObject),this.gameObject.position.copy(a),this.gameObject.quaternion.copy(l),this.gameObject.scale.copy(c),this._draggedOverObject=null,this._draggedOverObjectLastSetUp=null,this._draggedOverObjectLastNormal.set(0,1,0),this._draggedOverObjectDuration=0}collectMovementInfo(){var e,t;if(!this._followObject.parent)return;const s=this._followObject.parent;this._followObject.updateMatrix();const r=s.worldPosition,n=(t=(e=mt.active)==null?void 0:e.rig)==null?void 0:t.gameObject;n&&n.worldToLocal(r),(this._lastDragPosRigSpace===void 0||n!=this._lastRig)&&(this._lastDragPosRigSpace=r.clone(),this._lastRig=n),this._tempVec.copy(r).sub(this._lastDragPosRigSpace);const o=s.worldForward;if(n&&(this._tempMat.copy(n.matrixWorld).invert(),o.transformDirection(this._tempMat)),this._totalMovementAlongRayDirection+=o.dot(this._tempVec),this._tempVec.x=Math.abs(this._tempVec.x),this._tempVec.y=Math.abs(this._tempVec.y),this._tempVec.z=Math.abs(this._tempVec.z),this._totalMovement.add(this._tempVec),this._lastDragPosRigSpace.copy(r),ml){let a=r;n&&(a=a.clone(),a.transformDirection(n.matrixWorld)),Tt.DrawRay(a,o,255)}}onDragUpdate(e){if(e>1)return;const t=this.gameObject,s=this._followObject.parent;this._followObject.updateMatrix();const r=s.worldPosition,n=s.worldForward,o=this._deviceMode==="tracked-pointer",a=o?this.settings.xrKeepRotation:this.settings.keepRotation,l=o?this.settings.xrDragMode:this.settings.dragMode;if(l===5)return;const c=10;a&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let u=1,d=1;if(this._deviceMode==="tracked-pointer"&&this._grabStartDistance>.5){const y=1+this._totalMovementAlongRayDirection*(2*this.settings.xrDistanceDragFactor);u=Math.max(0,y),u=u*u*u}else this._grabStartDistance<=.5&&(d=3);this._followObject.position.copy(this._followObjectStartPosition),a||this._followObject.quaternion.copy(this._followObjectStartQuaternion),this._followObject.position.multiplyScalar(u),this._followObject.updateMatrix();const p=new Zn(r,n);if(l==4){const y=new Qo;y.ignore=[t];const g=this.context.physics.raycastFromRay(p,y);if(g.length>0){const v=g[0];if(this._draggedOverObject===v.object?this._draggedOverObjectDuration+=this.context.time.deltaTime:(this._draggedOverObject=v.object,this._draggedOverObjectDuration=0),v.face&&this._draggedOverObjectDuration>.15&&(this._draggedOverObjectLastSetUp!==this._draggedOverObject||this._draggedOverObjectLastNormal.dot(v.face.normal)<.999999)){this._draggedOverObjectLastSetUp=this._draggedOverObject,this._draggedOverObjectLastNormal.copy(v.face.normal);const b=new w,_=new w;this._bounds.getCenter(b),this._bounds.getSize(_),b.sub(_.multiplyScalar(.5).multiply(v.face.normal)),this._hitPointInLocalSpace.copy(b),this._hitNormalInLocalSpace.copy(v.face.normal),this._bounds.getCenter(b),this._bounds.getSize(_),b.add(_.multiplyScalar(.5).multiply(v.face.normal));const S=this._hitPointInLocalSpace.clone().add(b);this._followObject.localToWorld(S);const I=this._followObject.worldPosition.sub(S);this._dragPlane.setFromNormalAndCoplanarPoint(v.face.normal,v.point.sub(I))}}}if(l!==1&&p.intersectPlane(this._dragPlane,this._tempVec)){this._followObject.worldPosition=this._tempVec,this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const y=this._hitPointInLocalSpace.clone();this._followObject.localToWorld(y),ml&&Tt.DrawLine(y,this._tempVec,65535,0,!1),this._followObject.worldPosition=this._tempVec.multiplyScalar(2).sub(y),this._followObject.updateMatrix(),this._followObject.updateMatrix()}if(this.settings.snapGridResolution>0){const y=this._followObject.worldPosition,g=this.settings.snapGridResolution;y.x=Math.round(y.x/g)*g,y.y=Math.round(y.y/g)*g,y.z=Math.round(y.z/g)*g,this._followObject.worldPosition=y,this._followObject.updateMatrix()}a&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const f=st.clamp01(this.context.time.deltaTime*c*d),m=t.worldPosition;m.lerp(this._followObject.worldPosition,f),t.worldPosition=m;const A=t.worldQuaternion;if(A.slerp(this._followObject.worldQuaternion,f),t.worldQuaternion=A,ml){const y=this._hitPointInLocalSpace.clone();t.localToWorld(y),Tt.DrawSphere(y,.02,16711680);const g=this._hitNormalInLocalSpace.clone();g.applyQuaternion(A),Tt.DrawRay(y,g,16711680),Tt.DrawLabel(m.add(new w(0,.25,0)),`Distance: ${this._totalMovement.length().toFixed(2)}
6306
6306