@needle-tools/engine 2.56.0-pre → 2.56.2-pre
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/needle-engine.d.ts +3 -2
- package/dist/needle-engine.js +1 -1
- package/dist/needle-engine.js.map +2 -2
- package/dist/needle-engine.min.js +1 -1
- package/dist/needle-engine.min.js.map +2 -2
- package/dist/needle-engine.tsbuildinfo +1 -1
- package/lib/engine-components/Component.d.ts +2 -2
- package/lib/engine-components/Component.js.map +1 -1
- package/lib/engine-components/ui/Graphic.d.ts +1 -0
- package/lib/engine-components/ui/Graphic.js +4 -1
- package/lib/engine-components/ui/Graphic.js.map +1 -1
- package/lib/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -1
- package/src/engine/codegen/register_types.js +2 -2
- package/src/engine-components/Component.ts +2 -3
- package/src/engine-components/ui/Graphic.ts +5 -1
|
@@ -212,7 +212,7 @@ a:hover {
|
|
|
212
212
|
|
|
213
213
|
`;function _y(o){if(nd.has(o))return nd.get(o);{let e=document.createElement("div");e.classList.add(Ui),e.classList.add("desktop"),e.classList.add("debug-container"),e.style.position="absolute",e.style.top="0",e.style.right="5px",e.style.paddingTop="0px",e.style.maxWidth="70%",e.style.maxHeight="calc(100% - 5px)",e.style.zIndex="1000",e.style.pointerEvents="scroll",e.style.display="flex",e.style.alignItems="end",e.style.flexDirection="column",e.style.color="white",e.style.overflow="auto",o.appendChild(e),nd.set(o,e);let t=document.createElement("style");return t.innerHTML=yy,e.appendChild(t),e}}var am=Symbol("logtype"),Bl=new Map;function xy(o){o.remove();let e=o[am],t=Bl.get(e)??[];t.push(o),Bl.set(e,t)}function wy(o,e){if(Bl.has(o)){let i=Bl.get(o);if(i.length>0){let n=i.pop();return n.innerHTML=e,n}}let t=document.createElement("div");switch(t.style.marginRight="5px",t.style.padding=".5em",t.style.backgroundColor="rgba(0,0,0,.9)",t.style.marginTop="5px",t.style.marginBottom="3px",t.style.borderRadius="8px",t.style.pointerEvents="all",t.style.userSelect="text",t.style.maxWidth="250px",t.style.whiteSpace="pre-wrap",t.style["backdrop-filter"]="blur(10px)",t.style.backgroundColor="rgba(20,20,20,.8)",t.style.boxShadow="inset 0 0 80px rgba(0,0,0,.2), 0 0 5px rgba(0,0,0,.2)",t.style.border="1px solid rgba(160,160,160,.2)",t[am]=o,o){case 0:t.classList.add("log"),t.style.color="rgba(200,200,200,.7)",t.style.backgroundColor="rgba(40,40,40,.7)";break;case 1:t.classList.add("warn"),t.style.color="rgb(255, 255, 150)",t.style.backgroundColor="rgba(50,50,20,.8)";break;case 2:t.classList.add("error"),t.style.color="rgb(255, 50, 50",t.style.backgroundColor="rgba(50,20,20,.8)";break}return t.title="Open the browser console (F12) for more information",t.innerHTML=e,t}var ui=function(o,e){return function(t,i,n){Ey(t,i,n,o,e)}};function Ey(o,e,t,i,n){if(!(!n&&!i&&!o.onValidate)){if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",o,e,t),Fe("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,2);return}if(o.__internalAwake){let r=Symbol(e),s=o.__internalAwake;o.__internalAwake=function(){this[r]===void 0&&(this[r]=this[e],Object.defineProperty(this,e,{set:function(a){if(this[Xa]===!0)this[r]=a;else{i?.call(this,a);let c=this[r];this[r]=a,this.onValidate?.call(this,e,c)}},get:function(){return n?.call(this),this[r]}})),s.call(this)}}}}var Uo=P("debugloadingbar"),Cy=P("debugloadingbarrendering");var ia=0,lm;function sd(o){Uo&&console.log(o.progress.loaded.toFixed(0)+"/"+o.progress.total.toFixed(0),o);let e=o.count,t=o.progress.total;t===0||t===void 0?(lm!==o.name&&(ia=0),lm=o.name,ia+=(1-ia)*.001,Uo&&Xn("Loading "+o.name+" did not report total size")):ia=o.progress.loaded/t;let i=o.index/e+ia/e;return H.clamp01(i)}var Ul=class{loadingProgress=0;container;_progress=0;_allowCustomLoadingElement=!0;_loadingElement;_loadingTextContainer=null;_loadingBar=null;_messageContainer=null;_loadingElementOptions;constructor(e,t){this.container=e,this._loadingElementOptions=t}onLoadingBegin(e){if(Uo&&console.log("Begin Loading"),!this._loadingElement){for(let t=0;t<this.container.children.length;t++){let i=this.container.children[t];if(i.classList.contains(Ul.LoadingContainerClassName)){if(!this._allowCustomLoadingElement){Uo&&console.warn("Remove custom loading container"),this.container.removeChild(i);continue}this._loadingElement=this.createLoadingElement(i)}}this._loadingElement||(this._loadingElement=this.createLoadingElement())}this._progress=0,this.loadingProgress=0,this._loadingElement.style.display="flex",this.container.appendChild(this._loadingElement),this.smoothProgressLoop(),this.setMessage(e??"")}onLoadingUpdate(e,t){this._loadingElement?.parentElement||this.onLoadingBegin(t);let i=0;typeof e=="number"?i=e:("index"in e&&(i=sd(e)),!t&&"name"in e&&this.setMessage(e.name)),this.loadingProgress=i,t&&this.setMessage(t),this.updateDisplay()}onLoadingFinished(e){this.loadingProgress=1,this.setMessage(e??"")}setMessage(e){this._messageContainer&&(this._messageContainer.innerText=e)}_progressLoop;smoothProgressLoop(){if(this._progressLoop)return;let e=1/12,t=1-.05;Cy&&(e=1/500),this._progressLoop=setInterval(()=>{if(this.loadingProgress>=1&&this._progress>=t){this._loadingElement&&(Uo&&console.log("Hiding loading element"),this._loadingElement.style.display="none",this._loadingElement.remove()),clearInterval(this._progressLoop),this._progressLoop=null;return}this._progress=H.lerp(this._progress,this.loadingProgress,e*this.loadingProgress),this.updateDisplay()},e)}updateDisplay(){let e=this._progress,t=(e*100).toFixed(0)+"%";this._loadingBar&&(this._loadingBar.style.width=e*100+"%"),this._loadingTextContainer&&(this._loadingTextContainer.textContent=t)}createLoadingElement(e){Uo&&!e&&console.log("Creating loading element"),this._loadingElement=e||document.createElement("div"),e||(this._loadingElement.style.position="fixed",this._loadingElement.style.width="100%",this._loadingElement.style.height="100%",this._loadingElement.style.left="0",this._loadingElement.style.top="0",this._loadingElement.style.backgroundColor="#000000",this._loadingElement.style.display="flex",this._loadingElement.style.alignItems="center",this._loadingElement.style.justifyContent="center",this._loadingElement.style.zIndex="1000",this._loadingElement.style.flexDirection="column",this._loadingElement.style.pointerEvents="none",this._loadingElement.style.color="white");let t=this._loadingElementOptions?.className??Ul.LoadingContainerClassName;if(this._loadingElement.classList.add(t),this._loadingElementOptions?.additionalClasses)for(let a of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(a);let i=document.createElement("div"),n=30;i.style.display="flex",i.style.width=n+"%",i.style.height="2px",i.style.background="rgba(255,255,255,.1)",this._loadingElement.appendChild(i),this._loadingBar=document.createElement("div"),i.appendChild(this._loadingBar);let r=function(a){return H.lerp(n*.5,100-n*.5,a)+"%"};this._loadingBar.style.background=`linear-gradient(90deg, #02022B ${r(0)}, #0BA398 ${r(.4)}, #99CC33 ${r(.5)}, #D7DB0A ${r(1)})`,this._loadingBar.style.backgroundAttachment="fixed",this._loadingBar.style.width="0%",this._loadingBar.style.height="100%",this._loadingTextContainer=document.createElement("div"),this._loadingTextContainer.style.display="flex",this._loadingTextContainer.style.justifyContent="center",this._loadingTextContainer.style.marginTop=".9em",this._loadingElement.appendChild(this._loadingTextContainer);let s=document.createElement("div");return this._messageContainer=s,s.style.display="flex",s.style.fontSize=".8em",s.style.paddingTop=".5em",s.style.color="rgba(255,255,255,.5)",s.style.justifyContent="center",this._loadingElement.appendChild(s),this._loadingElement}},na=Ul;I(na,"LoadingContainerClassName","loading");import{DRACOLoader as ad}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as cm}from"three/examples/jsm/loaders/KTX2Loader.js";var ra=P("debugdecoders"),di,$n;function ld(o){o!==void 0&&typeof o=="string"&&(di||(di=new ad),ra&&console.log("Setting draco decoder path to",o),di.setDecoderPath(o))}function cd(o){o!==void 0&&typeof o=="string"&&(di||(di=new ad),ra&&console.log("Setting draco decoder type to",o),di.setDecoderConfig({type:o}))}function ud(o){o!==void 0&&typeof o=="string"&&($n||($n=new cm),ra&&console.log("Setting ktx2 transcoder path to",o),$n.setTranscoderPath(o))}function xn(o,e){di||(di=new ad,di.setDecoderPath("./include/draco/"),di.setDecoderConfig({type:"js"}),ra&&console.log("Setting draco decoder path to","./include/draco/")),$n||($n=new cm,$n.setTranscoderPath("./include/ktx2/"),ra&&console.log("Setting ktx2 transcoder path to","./include/ktx2/"),e.renderer&&$n.detectSupport(e.renderer)),o.setDRACOLoader(di),o.setKTX2Loader($n)}import{AnimationClip as Ty,MathUtils as Ry}from"three";var Go=class{_name;get name(){return this._name}_nameHash;get nameHash(){return this._nameHash}_normalizedTime;get normalizedTime(){return this._normalizedTime}_length;get length(){return this._length}_speed;get speed(){return this._speed}constructor(e,t,i,n){this._name=e.name,this._nameHash=e.hash,this._normalizedTime=t,this._length=i,this._speed=n}};function dm(o,e){return{name:"",isLooping:!1,guid:e?.generateUUID()??Ry.generateUUID(),index:-1,clip:new Ty(o,1,[])}}import{AnimationClip as Sy,AnimationMixer as Py,AxesHelper as Oy,Euler as hm,LoopOnce as ky,Quaternion as hi,Vector3 as oa}from"three";import*as Vl from"three";var Gi=P("debuganimatorcontroller"),dd=P("debugrootmotion"),fi=class{Play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}let s=this.model.layers[t].stateMachine;for(let a of s.states)if(a.name===e||a.hash===e){Gi&&console.log("transition to ",a),this.transitionTo(a,n,i);return}console.warn("Could not find "+e+" to play")}Reset(){this.setStartTransition()}SetBool(e,t){let i=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[i]===e).forEach(n=>n.value=t)}GetBool(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(i=>i[t]===e)?.value??!1}SetFloat(e,t){let i=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[i]===e).forEach(n=>n.value=t)}GetFloat(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(i=>i[t]===e)?.value??0}SetInteger(e,t){let i=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[i]===e).forEach(n=>n.value=t)}GetInteger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(i=>i[t]===e)?.value??0}SetTrigger(e){Gi&&console.log("SET TRIGGER",e);let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[t]===e).forEach(i=>i.value=!0)}ResetTrigger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[t]===e).forEach(i=>i.value=!1)}IsInTransition(){return this._activeStates.length>1}SetSpeed(e){this._speed=e}FindState(e){if(!e)return null;for(let t of this.model.layers)for(let i of t.stateMachine.states)if(i.name===e)return i;return null}normalizedStartOffset=0;_speed=1;animator;model;get context(){return this.animator?.context}bind(e){this.animator=e,this._mixer=new Py(this.animator.gameObject),this.createActions(this.animator)}clone(){let e=Us(this.model,(i,n,r)=>r==null?!0:!(r.type==="Object3D"||r.isObject3D===!0||Bp(r)||r.tracks!==void 0));return console.assert(e!==this.model),new fi(e)}update(){if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates();let e=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&this.rootMotionHandler?.onBeforeUpdate(),this._mixer.update(e),this.animator.applyRootMotion&&this.rootMotionHandler?.onAfterUpdate()}_mixer;_activeState;constructor(e){this.model=e,Gi&&console.log(this)}_activeStates=[];updateActiveStates(){for(let e=0;e<this._activeStates.length;e++){let t=this._activeStates[e],i=t.motion;if(!i.action)this._activeStates.splice(e,1),e--;else{let n=i.action;n.getEffectiveWeight()<=0&&!n.isRunning()&&(Gi&&console.debug("REMOVE",t.name,n.getEffectiveWeight(),n.isRunning(),n.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(let e of this.model.layers){let t=e.stateMachine;t.defaultState===void 0&&(Gi&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",e),t.defaultState=0);let i=t.states[t.defaultState];this.transitionTo(i,0,this.normalizedStartOffset)}}evaluateTransitions(){let t=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;t=!0}let i=this._activeState,n=i.motion.action,r=0;for(let a of i.transitions){if(++r,!a.hasExitTime&&a.conditions.length<=0)continue;let c=!0;for(let u of a.conditions)if(!this.evaluateCondition(u)){c=!1;break}if(!!c){for(let u of a.conditions){let l=this.model.parameters.find(d=>d.name===u.parameter);l?.type===9&&(l.value=!1)}if(n){let u=i.motion.clip.duration,l=u<=0?1:n.time/u;if(a.hasExitTime?l>=a.exitTime:!0){n.clampWhenFinished=!0,Gi&&console.log("transition to "+a.destinationState,a,l,a.exitTime,a.hasExitTime),this.transitionTo(a.destinationState,a.duration,a.offset);return}}else{this.transitionTo(a.destinationState,a.duration,a.offset);return}}}let s=!1;if(i.motion.isLooping&&n&&n.time>=n.getClip().duration&&(s=!0,n.reset(),n.time=0,n.play()),!s&&i&&!t&&n&&this.animator&&i.behaviours){let a=n?.getClip().duration,c=n.time/a,u=new Go(this._activeState,c,a,this._speed);for(let l of i.behaviours)l.instance&&l.instance.onStateUpdate?.call(l.instance,this.animator,u,0)}}getState(e,t){return typeof e=="number"&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState,e===void 0&&(Gi&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+t),e=0)),e=this.model.layers[t].stateMachine.states[e]),e}transitionTo(e,t,i){if(!this.animator)return;let n=0;if(e=this.getState(e,n),!e?.motion||!e.motion.clip)return;let r=this._activeState===e;if(r){let u=e.motion;!u.action_loopback&&u.clip&&(this._mixer.uncacheAction(u.clip,this.animator.gameObject),u.action_loopback=this.createAction(u.clip))}if(this._activeState?.behaviours&&this._activeState.motion.action){let u=this._activeState?.motion.clip.duration,l=this._activeState.motion.action.time/u,d=new Go(this._activeState,l,u,this._speed);for(let h of this._activeState.behaviours)h.instance?.onStateExit?.call(h.instance,this.animator,d,n)}let s=this._activeState?.motion.action;s&&s.fadeOut(t),r&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=s);let a=this._activeState;this._activeState=e;let c=e.motion?.action;if(c){i=Math.max(0,Math.min(1,i)),c.isRunning()&&c.stop(),c.reset(),c.timeScale=this._speed,c.enabled=!0;let u=e.motion.clip.duration;if(c.time=i*u,c.clampWhenFinished=!0,c.setLoop(ky,0),t>0?c.fadeIn(t):c.setEffectiveWeight(1),c.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(c),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){let l=new Go(e,i,u,this._speed);for(let d of this._activeState.behaviours)d.instance?.onStateEnter?.call(d.instance,this.animator,l,n)}}else console.warn("No action",e.motion,this);Gi&&console.log("TRANSITION FROM "+a?.name+" TO "+e.name,t,s,c,c?.getEffectiveTimeScale(),c?.getEffectiveWeight(),c?.isRunning(),c?.isScheduled(),c?.paused)}createAction(e){if(this._mixer.existingAction(e)&&this._mixer.uncacheAction(e,this.animator?.gameObject),this.animator?.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new hd(this));let i=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,i,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){let t=this.model.parameters.find(i=>i.name===e.parameter);if(!t)return!1;switch(e.mode){case 1:return t.value===!0;case 2:return t.value===!1;case 3:return t.value>e.threshold;case 4:return t.value<e.threshold;case 6:return t.value===e.threshold;case 7:return t.value!==e.threshold}return!1}createActions(e){for(let t of this.model.layers){let i=t.stateMachine;for(let n=0;n<i.states.length;n++){let r=i.states[n];r.transitions||(r.transitions=[]);for(let s of r.transitions)s.conditions||(s.conditions=[]);if(r.motion||(r.motion=dm(r.name)),this.animator&&r.motion.clips){let s=r.motion.clips?.find(a=>a.node.name===this.animator?.gameObject?.name);r.motion.clip=s?.clip}if(!r.motion.clip){let s=new Sy(void 0,void 0,[]);r.motion.clip=s}if(r.motion?.clip){let s=r.motion.clip,a=this.createAction(s);r.motion.action=a}if(r.behaviours&&Array.isArray(r.behaviours))for(let s of r.behaviours){if(!s?.typeName)continue;let a=O.get(s.typeName),c=new a;c.isStateMachineBehaviour&&(c._context=this.context??void 0,jt(c,s.properties),s.instance=c),Gi&&console.log("Created animator controller behaviour",r.name,s.typeName,s.properties,c)}}}}*enumerateActions(){for(let e of this.model.layers){let t=e.stateMachine;for(let i=0;i<t.states.length;i++){let n=t.states[i];n?.motion&&(n.motion.action&&(yield n.motion.action),n.motion.action_loopback&&(yield n.motion.action_loopback))}}}rootMotionHandler},Gl=class{track;createdInterpolant;originalEvaluate;customEvaluate;constructor(e,t){this.track=e;let i=e,n=i.createInterpolant.bind(e);i.createInterpolant=()=>(i.createInterpolant=n,this.createdInterpolant=n(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=r=>{if(!this.originalEvaluate)return;let s=this.originalEvaluate(r);return t(r,s)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}evaluate(e){this.customEvaluate&&this.customEvaluate(e)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}},we=class{set action(e){this._action=e}get action(){return this._action}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new oa;rotationChange=new hi;constructor(e,t,i,n,r){if(this.context=e,this.root=t,this.clip=i,we.firstKeyframeRotation[i.uuid]||(we.firstKeyframeRotation[i.uuid]=new Vl.Quaternion),r){let s=r.values;we.firstKeyframeRotation[i.uuid].set(s[0],s[1],s[2],s[3])}we.spaceRotation[i.uuid]||(we.spaceRotation[i.uuid]=new hi),we.effectiveSpaceRotation[i.uuid]||(we.effectiveSpaceRotation[i.uuid]=new hi),we.clipOffsetRotation[i.uuid]=new hi,r&&we.clipOffsetRotation[i.uuid].set(r.values[0],r.values[1],r.values[2],r.values[3]).invert(),this.handlePosition(i,n),this.handleRotation(i,r)}onStart(e){if(e.getClip()!==this.clip)return;let t=we.lastObjRotation[this.root.uuid];we.spaceRotation[this.clip.uuid].copy(t);{let i=new Vl.Euler().setFromQuaternion(t);console.log("START",this.clip.name,H.toDegrees(i.y))}}getClipRotationOffset(){return we.clipOffsetRotation[this.clip.uuid]}handlePosition(e,t){if(t){let i=this.root;dd&&i.add(new Oy),we.lastObjPosition[i.uuid]||(we.lastObjPosition[i.uuid]=new oa);let n=new oa,r=new oa,s=0;this.positionWrapper=new Gl(t,(a,c)=>{let u=this.action.getEffectiveWeight();if(dd&&i.position.length()>8&&i.position.set(0,i.position.y,0),a>s){n.set(c[0],c[1],c[2]),n.sub(r),n.multiplyScalar(u),n.applyQuaternion(this.getClipRotationOffset());let l=this.clip.uuid;n.applyQuaternion(we.spaceRotation[l]),this.positionChange.copy(n)}return r.fromArray(c),s=a,c[0]=0,c[1]=0,c[2]=0,c})}}handleRotation(e,t){if(t){if(dd){let a=t.values,c=new hm().setFromQuaternion(new hi(a[0],a[1],a[2],a[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",H.toDegrees(c.y));let u=t.values.length-4,l=new hi().set(a[u],a[u+1],a[u+2],a[u+3]),d=new hm().setFromQuaternion(l);console.log(e.name,t.name,"LAST ROTATION IN TRACK",H.toDegrees(d.y))}let i=this.root;we.lastObjRotation[i.uuid]||(we.lastObjRotation[i.uuid]=new hi);let n=0,r=new hi,s=new hi;this.rotationWrapper=new Gl(t,(a,c)=>(a>n&&(s.set(c[0],c[1],c[2],c[3]),r.invert(),s.multiply(r),this.rotationChange.copy(s)),r.fromArray(c),n=a,c[0]=0,c[1]=0,c[2]=0,c[3]=1,c))}}onBeforeUpdate(){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(){let e=this.action.getEffectiveWeight();this.positionChange.multiplyScalar(e),this.rotationChange.slerp(we.identityQuaternion,1-e)}},pi=we;I(pi,"lastObjPosition",{}),I(pi,"lastObjRotation",{}),I(pi,"firstKeyframeRotation",{}),I(pi,"spaceRotation",{}),I(pi,"effectiveSpaceRotation",{}),I(pi,"clipOffsetRotation",{}),I(pi,"identityQuaternion",new hi);var hd=class{controller;handler=[];root;constructor(e){this.controller=e}createClip(e,t,i){this.root=t;let n="";t&&"name"in t&&(n=t.name);let r=this.findRootTrack(i,".position"),s=this.findRootTrack(i,".quaternion"),a=new pi(this.controller.context,t,i,r,s);this.handler.push(a);let c=e.clipAction(i);return a.action=c,c}onStart(e){for(let t of this.handler)t.onStart(e)}onBeforeUpdate(){for(let e of this.handler)e.onBeforeUpdate()}summedPosition=new oa;summedRotation=new hi;onAfterUpdate(){this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(let e of this.handler)e.onAfterUpdate(),this.summedPosition.add(e.positionChange),this.summedRotation.multiply(e.rotationChange);this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation),pi.lastObjRotation[this.root.uuid].copy(this.root.quaternion)}findRootTrack(e,t){let i=e.tracks;for(let n of i)if(n.name.endsWith(t))return n;return null}};var pm=P("debuganimator"),Pe=class extends M{applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof fi?this._animatorController=e:(pm&&console.log("Assign animator controller",e,this),this._animatorController=new fi(e)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}Play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){this.runtimeAnimatorController?.Play(e,t,i,n)}Reset(){this._animatorController?.Reset()}SetBool(e,t){this.runtimeAnimatorController?.SetBool(e,t)}GetBool(e){return this.runtimeAnimatorController?.GetBool(e)??!1}SetFloat(e,t){this.runtimeAnimatorController?.SetFloat(e,t)}GetFloat(e){return this.runtimeAnimatorController?.GetFloat(e)??-1}SetInteger(e,t){this.runtimeAnimatorController?.SetInteger(e,t)}GetInteger(e){return this.runtimeAnimatorController?.GetInteger(e)??-1}SetTrigger(e){this.runtimeAnimatorController?.SetTrigger(e)}ResetTrigger(e){this.runtimeAnimatorController?.ResetTrigger(e)}IsInTransition(){return this.runtimeAnimatorController?.IsInTransition()??!1}SetSpeed(e){e!==this.speed&&(this.speed=e,this._animatorController?.SetSpeed(e))}set minMaxSpeed(e){this.speed=H.lerp(e.x,e.y,Math.random())}set minMaxOffsetNormalized(e){this.normalizedStartOffset=H.lerp(e.x,e.y,Math.random()),this.runtimeAnimatorController&&(this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset)}speed=1;normalizedStartOffset=0;_animatorController=null;awake(){if(pm&&console.log("ANIMATOR",this.name,this),!!this.gameObject&&this.runtimeAnimatorController){let e=this.runtimeAnimatorController.clone();console.assert(this.runtimeAnimatorController!==e),this.runtimeAnimatorController=e,console.assert(this.runtimeAnimatorController===e),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.SetSpeed(this.speed),this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.Reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}};v([y()],Pe.prototype,"applyRootMotion",2),v([y()],Pe.prototype,"hasRootMotion",2),v([y()],Pe.prototype,"keepAnimatorControllerStateOnDisable",2),v([y()],Pe.prototype,"runtimeAnimatorController",1);import*as Vr from"three";import{AnimationClip as My}from"three";var zl=P("debuganimation"),Bt=class extends M{playAutomatically=!0;randomStartTime=!0;minMaxSpeed;minMaxOffsetNormalized;loop=!0;clampWhenFinished=!1;_tempAnimationClipBeforeGameObjectExisted=null;get clip(){return this.animations?.length?this.animations[0]:null}set clip(e){if(!this.__didAwake){zl&&console.log("Assign clip during serialization",e),this._tempAnimationClipBeforeGameObjectExisted=e;return}!e||(zl&&console.log("Assign clip",e,Boolean(this.gameObject)),this.gameObject.animations||(this.gameObject.animations=[]),!this.animations.includes(e)&&(this.animations.length>0?this.animations.splice(0,0,e):this.animations.push(e)))}set clips(e){this.animations=e}set animations(e){zl&&console.log("assign animations",e),this.gameObject.animations=e}get animations(){return this.gameObject.animations}get currentAction(){return this._currentActions[0]}get currentActions(){return this._currentActions}mixer=void 0;get actions(){return this._actions}set actions(e){this._actions=e}_actions=[];_currentActions=[];_handles=[];awake(){zl&&console.log(this),this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.playAutomatically&&this.init()}onEnable(){if(this.playAutomatically&&this.animations?.length>0&&this.currentActions.length<=0){let e=Math.floor(Math.random()*this.actions.length);this.play(e)}}start(){this.randomStartTime&&this.currentAction&&(this.currentAction.time=Math.random()*this.currentAction.getClip().duration)}update(){if(!!this.mixer){this.mixer.update(this.context.time.deltaTime);for(let e of this._handles)e._update();this._handles?.length>0&&oe.markDirty(this.gameObject)}}getAction(e){return this.actions?.find(t=>t.getClip().name===e)}get isPlaying(){for(let e=0;e<this._currentActions.length;e++)if(this._currentActions[e].isRunning())return!0;return!1}play(e,t){if(this.init(),!this.mixer)return;e===void 0&&(e=0);let i=e;if(typeof e=="number"){if(e>=this.animations.length)return;i=this.animations[e]}else typeof e=="string"&&(i=this.animations.find(r=>r.name===e));if(!i){console.error("Could not find clip",e);return}t||(t={}),t.minMaxOffsetNormalized||(t.minMaxOffsetNormalized=this.minMaxOffsetNormalized),t.minMaxSpeed||(t.minMaxSpeed=this.minMaxSpeed),t.loop||(t.loop=this.loop),t.clampWhenFinished||(t.clampWhenFinished=this.clampWhenFinished);for(let r of this.actions)if(r.getClip()===i)return this.internalOnPlay(r,t);let n=this.mixer.clipAction(i);return this.actions.push(n),this.internalOnPlay(n,t)}internalOnPlay(e,t){var i=this.currentAction;if(i===e&&i.isRunning()&&i.time<i.getClip().duration){let a=this.tryFindHandle(e);if(a)return a.getPromise()}let n=t?.exclusive??!0;t?.fadeDuration?(n&&i?.fadeOut(t.fadeDuration),e.fadeIn(t.fadeDuration)):n&&i?.stop(),e.reset(),e.enabled=!0,e.time=0,e.timeScale=1;let r=e.getClip();t?.minMaxOffsetNormalized&&(e.time=H.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*r.duration),t?.minMaxSpeed&&(e.timeScale=H.lerp(t.minMaxSpeed.x,t.minMaxSpeed.y,Math.random())),t?.clampWhenFinished&&(e.clampWhenFinished=!0),t?.startTime!==void 0&&(e.time=t.startTime),t?.loop!==void 0?e.loop=t.loop?Vr.LoopRepeat:Vr.LoopOnce:e.loop=Vr.LoopOnce,e.play();let s=new pd(e,this.mixer,t,a=>{this._handles.splice(this._handles.indexOf(s),1)});return this._handles.push(s),s.getPromise()}tryFindHandle(e){for(let t of this._handles)if(t.action===e)return t}_didInit=!1;init(){this._didInit||(this._didInit=!0,this.gameObject&&(this.actions=[],this.mixer=new Vr.AnimationMixer(this.gameObject)))}};v([y()],Bt.prototype,"playAutomatically",2),v([y()],Bt.prototype,"randomStartTime",2),v([y()],Bt.prototype,"loop",2),v([y()],Bt.prototype,"clampWhenFinished",2),v([y(My)],Bt.prototype,"clips",1);var pd=class{mixer;action;promise=null;resolve=null;reject=null;_options;_resolveCallback=null;_rejectCallback=null;_loopCallback;_finishedCallback;_resolvedOrRejectedCallback;constructor(e,t,i,n){this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=n,this._options=i}getPromise(){return this.promise?this.promise:(this.promise=new Promise((e,t)=>{this._resolveCallback=e,this._rejectCallback=t,this.resolve=this.onResolve.bind(this),this.reject=this.onReject.bind(this)}),this._loopCallback=this.onLoop.bind(this),this._finishedCallback=this.onFinished.bind(this),this.mixer.addEventListener("loop",this._loopCallback),this.mixer.addEventListener("finished",this._finishedCallback),this.promise)}_update(){!this._options||this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._resolveCallback?.call(this,this.action)}onReject(e){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._rejectCallback?.call(this,e)}onLoop(e){}onFinished(e){e.action===this.action&&this.onResolve()}dispose(){this._loopCallback&&this.mixer.removeEventListener("loop",this._loopCallback),this._finishedCallback&&this.mixer.removeEventListener("finished",this._finishedCallback),this._loopCallback=void 0,this._finishedCallback=void 0}};import{GLTFLoader as Ng}from"three/examples/jsm/loaders/GLTFLoader.js";import*as X from"three";import{RawShaderMaterial as Ay}from"three";var wn=P("debugshaders"),Vo="NEEDLE_techniques_webgl";var fd=class{objectToWorldMatrix=new X.Matrix4;worldToObjectMatrix=new X.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),ea(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),ea(this.worldToObjectMatrix,this.worldToObject)}};var ce=class extends Ay{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){let e=super.clone();return fm(e),e}constructor(e,...t){super(...t),this.identifier=e,wn&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName]&&this.waitForLighting(),(this.depthTextureUniform||this.opaqueTextureUniform)&&G.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();let e=G.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&G.Current.pre_render_callbacks.splice(e,1)}async waitForLighting(){let e=G.Current;if(!e){console.error("Missing context");return}let t=await e.rendererData.getSceneLightingData(this.identifier);if(!t||!t.array){console.warn("Missing lighting data for custom shader, getSceneLightingData did not return anything");return}wn&&console.log(t);let i=t.array,n=t.texture;this.uniforms.unity_SpecCube0={value:n},Qu(this.uniforms,i);let r=Math.sqrt(Math.PI*.5);this.uniforms.unity_SpecCube0_HDR={value:new X.Vector4(r,r,r,r)},wn&&console.log("Set environment lighting",this.uniforms)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";_rendererData=new fd;get depthTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&G.Current.setRequireColor(!0),this.depthTextureUniform&&G.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,r,s){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,r)}onUpdateUniforms(e,t){let i=G.Current;e&&(ce.viewProjection&&this.uniforms[this._viewProjectionName]&&(ce.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),ea(ce.viewProjection,ce._viewProjectionValues)),ce.viewMatrix&&this.uniforms[this._viewMatrixName]&&(ce.viewMatrix.copy(e.matrixWorldInverse),ea(ce.viewMatrix,ce._viewMatrixValues)),this.uniforms[ce._worldSpaceCameraPosName]&&ce._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters?this.uniforms._TimeParameters.value=i.rendererData.timeVec4:this.uniforms._Time&&(this.uniforms._Time.value=i.rendererData.timeVec4);let n=i.mainLight;if(n){let a=B(n.gameObject,ce._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},ce._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:ce._mainLightColor};let c=n.intensity;ce._lightData.z=c,this.uniforms.unity_LightData={value:ce._lightData}}if(e&&(ce.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=ce._viewProjectionValues),ce.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=ce._viewMatrixValues),this.uniforms[ce._worldSpaceCameraPosName]&&(this.uniforms[ce._worldSpaceCameraPosName]={value:ce._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){let a=this.uniforms._ProjectionParams.value;a.x=1,a.y=i.mainCameraComponent.nearClipPlane,a.z=i.mainCameraComponent.farClipPlane,a.w=1/a.z,this.uniforms._ProjectionParams.value=a}if(this.uniforms._ZBufferParams){let a=this.uniforms._ZBufferParams.value,c=i.mainCameraComponent;a.x=1-c.farClipPlane/c.nearClipPlane,a.y=c.farClipPlane/c.nearClipPlane,a.z=a.x/c.farClipPlane,a.w=a.y/c.farClipPlane,this.uniforms._ZBufferParams.value=a}if(this.uniforms._ScreenParams){let a=this.uniforms._ScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScreenParams.value=a}}let r=this.depthTextureUniform;r&&(r.value=i.depthTexture);let s=this.opaqueTextureUniform;if(s&&(s.value=i.opaqueColorTexture),t){let a=this._rendererData;a.updateFrom(t),this.uniforms[this._worldToObjectName].value=a.worldToObject,this.uniforms[this._objToWorldName].value=a.objectToWorld}this.uniformsNeedUpdate=!0}},Ut=ce;I(Ut,"viewProjection",new X.Matrix4),I(Ut,"_viewProjectionValues",[]),I(Ut,"viewMatrix",new X.Matrix4),I(Ut,"_viewMatrixValues",[]),I(Ut,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),I(Ut,"_worldSpaceCameraPos",new X.Vector3),I(Ut,"_mainLightColor",new X.Vector4),I(Ut,"_mainLightPosition",new X.Vector3),I(Ut,"_lightData",new X.Vector4);var Wl=class{get name(){return Vo}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){let t=this.parser.json.materials[e];if(!t)return wn&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Vo])return wn&&console.log("material "+e+" does not use NEEDLE_techniques_webgl"),null;let i=t.extensions[Vo].technique;if(i<0)return null;let n=this.parser.json.extensions[Vo];if(!n)return null;wn&&console.log(n);let r=n.techniques[i];return r?new Promise(async(s,a)=>{let c=await Yf(n,r.program),u=c?.fragmentShader,l=c?.vertexShader;if(!u||!l)return a();wn&&console.log("loadMaterial",t,c);let d={},h=r.uniforms;l.includes("_Time")&&(d._Time={value:new X.Vector4(0,0,0,0)});for(let m in h){let f=m;switch(f){case"_TimeParameters":let p=new X.Vector4;d[f]={value:p};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":d[f]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":d[f]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":d[f]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":d[f]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":d[f]={value:null};break}}let g=!1;if(t.extensions&&t.extensions[Vo]){let m=t.extensions[Vo];if(m.technique===i){wn&&console.log(t.name,"Material Properties",m);for(let f in m.values){let p=m.values[f];if(typeof p=="string"){if(p.startsWith("/textures/")){let b=p.substring(10),w=Number.parseInt(b);if(w>=0){let C=await this.parser.getDependency("texture",w);C&&(C.encoding=X.LinearEncoding,C.needsUpdate=!0),d[f]={value:C};continue}}switch(f){case"alphaMode":p==="BLEND"&&(g=!0);continue}}if(Array.isArray(p)&&p.length===4){d[f]={value:new X.Vector4(p[0],p[1],p[2],p[3])};continue}d[f]={value:p}}}}let E=new Ut(this.identifier,{name:t.name??"",uniforms:d,vertexShader:l,fragmentShader:u,lights:!1});switch(d._Cull?.value){case 0:E.side=X.DoubleSide;break;case 1:E.side=X.BackSide;break;case 2:E.side=X.FrontSide;break;default:E.side=X.FrontSide;break}switch(d._ZTest?.value){case 3:E.depthTest=!0,E.depthFunc=X.EqualDepth;break;case 6:E.depthTest=!0,E.depthFunc=X.NotEqualDepth;break;case 2:E.depthTest=!0,E.depthFunc=X.LessDepth;break;case 4:E.depthTest=!0,E.depthFunc=X.LessEqualDepth;break;case 5:E.depthTest=!0,E.depthFunc=X.GreaterDepth;break;case 7:E.depthTest=!0,E.depthFunc=X.GreaterEqualDepth;break;case 8:E.depthTest=!1,E.depthFunc=X.AlwaysDepth;break}E.transparent=g,g&&(E.depthWrite=!1),Qu(d),E.onUpdateUniforms();for(let m in h){let f=m,p=h[m].type;if(d[f]?.value===void 0)switch(p){case 35678:d[f]={value:Qf},console.warn("Missing/unassigned texture, fallback to white: "+f);break;default:console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+f,h[m]);break}}wn&&console.log(E.uuid,d),fm(E),s(E)}):null}};function fm(o){if(o.uniforms)for(let e in o.uniforms)Object.getOwnPropertyDescriptor(o,e)||Object.defineProperty(o,e,{get:()=>o.uniforms[e].value,set:t=>{o.uniforms[e].value=t,o.needsUpdate=!0}})}var er=pe,Nl="$___Export_Components",Dy="NEEDLE_components",md=class{[Ar]},gd=class{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}},zo=class{get name(){return Dy}parser;nodeToObjectMap={};exportContext;objectToNodeMap={};context;writer;registerExport(e){e.register(t=>{if("serializeUserData"in t){let i=t.serializeUserData.bind(t);this.writer=t,t.serializeUserData=(n,r)=>{try{this.serializeUserData(n,r),i(n,r)}finally{this.afterSerializeUserData(n,r)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){let i=e.userData?.components;!i||i.length<=0||(delete e.userData.components,e[Nl]=i)}afterSerializeUserData(e,t){if(e.type==="Scene"&&er&&console.log("DONE",JSON.stringify(t)),e[Nl]===void 0)return;let i=e[Nl];delete e[Nl],i!==null&&(e.userData.components=i)}writeNode(e,t){let i=this.writer.json.nodes.length;console.log(e.name,i,e.uuid);let n=new gd(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){er&&console.log("AFTER",e);for(let t in this.exportContext){let i=this.exportContext[t],n=i.node,r=i.nodeDef,s=i.nodeIndex,a=n.userData?.components;if(!a||a.length<=0)continue;let c=new md;r.extensions=r.extensions||{},r.extensions[this.name]=c,this.context.object=n,this.context.nodeId=s,this.context.objectToNode=this.objectToNodeMap;let u=[];for(let l of a){this.context.target=l;let d=Ke().writeBuiltinComponentData(l,this.context);d!==null&&u.push(d)}u.length>0&&(c[Ar]=u,er&&console.log("DID WRITE",n,"nodeIndex",s,u))}}beforeRoot(){return er&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){let t=e.parser,i=t?.extensions;if(!i)return;let n=i[this.name];er&&console.log("After root",e,this.parser,i);let r=[];if(n===!0){let s=t.json.nodes;for(let a=0;a<s.length;a++){let c=await t.getDependency("node",a);this.nodeToObjectMap[a]=c}for(let a=0;a<s.length;a++){let c=s[a],u=a,l=c.extensions;if(!l)continue;let d=l[this.name];if(!d)continue;er&&console.log("NODE",c);let h=this.nodeToObjectMap[u];if(!h){console.error("Could not find object for node index: "+u,c,t);continue}Mo(h),r.push(this.createComponents(h,d))}}await Promise.all(r)}async createComponents(e,t){if(!t)return;let i=t[Ar];if(i){let n=new Array;er&&console.log(e.name,i);for(let r in i){let s=i[r];er&&console.log("Serialized data",JSON.parse(JSON.stringify(s))),s&&this.parser&&n.push(Eo(this.parser,s)),e.userData=e.userData||{},e.userData[Ar]=e.userData[Ar]||[],e.userData[Ar].push(s)}await Promise.all(n)}}};import{EXRLoader as Ly}from"three/examples/jsm/loaders/EXRLoader";var bd=P("debugexr"),Xl=class{parser;name;constructor(e){this.parser=e,this.name="EXT_texture_exr",bd&&console.log(e)}loadTexture(e){let t=this.name,i=this.parser,r=i.json.textures[e];if(bd&&console.log("EXT_texture_exr.loadTexture",e,r),!r.extensions||!r.extensions[t])return null;let s=r.extensions[t],a=new Ly(i.options.manager);return bd&&console.log("EXT_texture_exr.loadTexture",s,a),i.loadTextureImage(e,s.source,a)}};window.addEventListener("unhandledrejection",o=>{});var mm="NEEDLE_gameobject_data",Ql=class{get name(){return mm}parser;constructor(e){this.parser=e}afterRoot(e){let t=[];for(let i=0;i<this.parser.json.nodes.length;i++){let n=this.parser.json.nodes[i];if(n&&n.extensions){let r=n.extensions[mm];if(r){let s=this.findAndApplyExtensionData(i,r);t.push(s)}}}return Promise.all(t).then(()=>{})}async findAndApplyExtensionData(e,t){let i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(t.layers),e.userData.tag=t.tag,e.userData.hideFlags=t.hideFlags,e.userData.static=t.static,e.visible=t.activeSelf,e.guid=t.guid}};import{AmbientLight as jy,Color as gm,HemisphereLight as Hy}from"three";var bm="NEEDLE_lighting_settings",Wo=P("debugenvlight"),ql=class{get name(){return bm}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}afterRoot(e){let t=this.parser.json.extensions;if(t){let i=t[bm];if(i){Wo&&console.log(i);let n=R.addNewComponent(e.scene,vd,!1);n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new gm().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(r=>new gm().fromArray(r))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource,this.context&&this.context.rendererData.registerSceneLightSettings(n)}}return null}},vd=class extends M{ambientMode=0;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=0;_hasReflection=!1;_ambientLightObj;_lightProbeObj;awake(){if(this.sourceId){let e=this.environmentReflectionSource===0?1:2,t=this.context.lightmaps.tryGet(this.sourceId,e,0);this._hasReflection=t!=null,t&&this.context.rendererData.registerReflection(this.sourceId,t)}Wo&&window.addEventListener("keydown",e=>{switch(e.key){case"l":this.enabled=!this.enabled;break}})}onEnable(){let e=this.context.mainCameraComponent?.sourceId===this.sourceId;if(Wo&&console.log("Enable scene lighting",this.sourceId,e,this,this.context.mainCameraComponent?.sourceId),e||Wo&&console.warn("This is no active?!",this.context.mainCameraComponent?.sourceId),this.ambientMode==3)this.ambientLight&&!this._ambientLightObj&&(this._ambientLightObj=new jy(this.ambientLight,Math.PI*this.ambientIntensity)),this._ambientLightObj&&this.gameObject.add(this._ambientLightObj),this._lightProbeObj&&this._lightProbeObj.removeFromParent();else if(this.ambientMode===1){if(this.ambientTrilight){let t=this.ambientTrilight[0],i=this.ambientTrilight[this.ambientTrilight.length-1],n=new Hy(i,t,this.ambientIntensity);this.gameObject.add(n)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._lightProbeObj?this.enabled&&this.destroyed&&this._lightProbeObj&&this.scene.add(this._lightProbeObj):this.sourceId&&this.context.rendererData.getSceneLightingData(this.sourceId).then(t=>{Wo&&console.log(t),t&&(this._lightProbeObj=t.lightProbe,this.enabled&&!this.destroyed&&this._lightProbeObj&&this.scene.add(this._lightProbeObj))});this.sourceId&&this.context.rendererData.enableReflection(this.sourceId)}onDisable(){Wo&&console.log("disable",this.sourceId,this),this._lightProbeObj&&this._lightProbeObj.removeFromParent(),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this.sourceId&&this.context.rendererData.disableReflection()}};import{NeverStencilFunc as Fy,LessStencilFunc as By,EqualStencilFunc as Uy,LessEqualStencilFunc as Gy,GreaterStencilFunc as Vy,NotEqualStencilFunc as zy,GreaterEqualStencilFunc as Wy,AlwaysStencilFunc as Ny,ZeroStencilOp as Xy,KeepStencilOp as Qy,ReplaceStencilOp as qy,IncrementStencilOp as Yy,DecrementStencilOp as Ky,IncrementWrapStencilOp as Jy,DecrementWrapStencilOp as Zy,InvertStencilOp as $y}from"three";var yd=P("debugstencil");function e_(o,e){return(o&1<<e.layer)!=0}var zr=class{static applyStencil(e){if(!e)return;let t=e.sourceId;if(yd&&console.log(t,zr.stencils),!t)return;let i=zr.stencils[t];if(!!i)for(let n=i.length-1;n>=0;n--){let r=i[n];if(e_(r.layer,e)){yd&&console.log(r);let s=e.sharedMaterial?.clone();s&&(e.sharedMaterial=s,e.gameObject.renderOrder=r.event*1e3+r.index*50,s.stencilWrite=!0,s.stencilWriteMask=255,s.stencilFuncMask=255,s.stencilRef=r.value,s.stencilFunc=r.compareFunc,s.stencilZPass=r.passOp,s.stencilFail=r.failOp,s.stencilZFail=r.zFailOp);break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){let t=this.parser.json.extensions;if(t){let i=t[i_];if(i){yd&&console.log(i);let n=i.stencil;if(n&&Array.isArray(n))for(let r of n){let s={...r};s.compareFunc=t_(s.compareFunc),s.passOp=_d(s.passOp),s.failOp=_d(s.failOp),s.zFailOp=_d(s.zFailOp),zr.stencils[this.source]||(zr.stencils[this.source]=[]),zr.stencils[this.source].push(s)}}}return null}},Wr=zr;I(Wr,"stencils",{});function _d(o){switch(o){case 0:return Qy;case 1:return Xy;case 2:return qy;case 3:return Yy;case 4:return Ky;case 6:return Jy;case 7:return Zy;case 5:return $y}return 0}function t_(o){switch(o){case 1:return Fy;case 2:return By;case 3:return Uy;case 4:return Gy;case 5:return Vy;case 6:return zy;case 7:return Wy;case 8:return Ny}return 0}var i_="NEEDLE_render_objects";import{TextureLoader as n_}from"three";import{GLTFLoader as r_}from"three/examples/jsm/loaders/GLTFLoader";var xd="NEEDLE_progressive",ze=P("debugprogressive"),Ed=new Map,wd=!1;ze&&window.addEventListener("keyup",o=>{o.key==="p"&&(Ed.forEach((e,t)=>{Object.entries(e).forEach(([i,n])=>{wd?t[i]=n.lod0:t[i]=n.original,t.needsUpdate=!0})}),wd=!wd)});var sa=class{static assignTextureLOD(e,t,i,n=0){if(!!i)for(let r of Object.keys(i)){let s=i[r];s?.isTexture===!0&&(ze&&console.log(`-----------
|
|
214
214
|
`,"FIND",i.name,r,s?.name,s?.userData,s,i),sa.getOrLoadTexture(e,t,i,r,s,n).then(a=>{if(a?.isTexture===!0&&(ze&&console.log("Assign LOD",i.name,r,a.name,a.guid,i,"Prev:",s,"Now:",a,`
|
|
215
|
-
--------------`),i[r]=a,a.needsUpdate=!0,i.needsUpdate=!0,ze)){let c=Ed.get(i);c||(c={},Ed.set(i,c));let u=c[r];u||(u=c[r]={original:s,lod0:a}),u.lod0=a}}))}}get name(){return xd}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}_loading=[];afterRoot(e){return ze&&console.log("AFTER",this.sourceId,e),this.parser.json.textures?.forEach((t,i)=>{if(t?.extensions){let n=t?.extensions[xd];if(n){let r=this.parser.getDependency("texture",i);this._loading.splice(this._loading.indexOf(i),1),r.then(s=>{ze&&console.log("register texture",s.name,s.uuid,n),s.userData.deferred=n,sa.cache.set(s.uuid,n)})}}}),null}static async getOrLoadTexture(e,t,i,n,r,s){let a=r.uuid,c=sa.cache.get(a);if(c){ze&&console.log(a,c.uri,c.guid);let u=Ii(t,c.uri);if(u.endsWith(".glb")||u.endsWith(".gltf")){if(!c.guid)return console.warn("missing pointer for glb/gltf texture",c),null;let l=u+"_"+c.guid;if(this.resolved[l])return ze&&console.log("Texture has already been loaded: "+l,i.name,n,r.name),this.resolved[l];let d=this.onProgressiveLoadStart(e,t,u,i,n);try{if(this.currentlyLoading[l]!==void 0)return ze&&console.log("Already loading:",i.name+"."+n,l),await this.currentlyLoading[l];let h=new Promise(async(E,_)=>{let x=new r_;xn(x,e),ze&&console.log("Load "+u,i.name,n,c.guid),ze&&await _o(Math.random()*1e3);let m=await x.loadAsync(u),f=m.parser;ze&&console.log("Loading finished "+u,i.name,n,c.guid);let p=-1,b=!1;for(let C of m.parser.json.textures)if(p++,C?.extensions){let T=C?.extensions[xd];if(T?.guid&&T.guid===c.guid){b=!0;break}}if(!b)return E(null);let w=await f.getDependency("texture",p);w.encoding=r.encoding,w&&(w.guid=c.guid),this.resolved[l]=w,ze&&console.log(i.name,n,'change "'+r.name+'" \u2192 "'+w.name+'"',u,p,w,i,l),E(w)});return this.currentlyLoading[l]=h,await h}finally{delete this.currentlyLoading[l],this.onProgressiveLoadEnd(d)}}else{let l=this.onProgressiveLoadStart(e,t,u,i,n);try{ze&&console.log("Load texture from uri: "+u);let h=await new n_().loadAsync(u);return h?(h.guid=c.guid,h.flipY=!1,h.needsUpdate=!0,h.encoding=r.encoding,ze&&console.log(c,h)):ze&&console.warn("failed loading",u),h}finally{this.onProgressiveLoadEnd(l)}}}else ze&&console.warn("unknown uuid",r.name,r.uuid,r);return null}static beginListenStart(e,t){this._progressiveEventListeners.has(e)||this._progressiveEventListeners.set(e,new Yl),this._progressiveEventListeners.get(e).start.push(t)}static stopListenStart(e,t){if(!this._progressiveEventListeners.has(e))return;let i=this._progressiveEventListeners.get(e).start,n=i.indexOf(t);n>=0&&i.splice(n,1)}static beginListenEnd(e,t){this._progressiveEventListeners.has(e)||this._progressiveEventListeners.set(e,new Yl),this._progressiveEventListeners.get(e).end.push(t)}static stopListenEnd(e,t){if(!this._progressiveEventListeners.has(e))return;let i=this._progressiveEventListeners.get(e).end,n=i.indexOf(t);n>=0&&i.splice(n,1)}static onProgressiveLoadStart(e,t,i,n,r){this._currentProgressiveLoadingInfo.has(e)||this._currentProgressiveLoadingInfo.set(e,[]);let s=new Cd(e,t,i,n,r),a=this._currentProgressiveLoadingInfo.get(e),c=this._progressiveEventListeners.get(e);return c&&c.onStart(s),a.push(s),s}static onProgressiveLoadEnd(e){if(!e)return;let t=e.context;if(!this._currentProgressiveLoadingInfo.has(t))return;let i=this._currentProgressiveLoadingInfo.get(t),n=i.indexOf(e);if(n<0)return;i.splice(n,1);let r=this._progressiveEventListeners.get(t);r&&r.onEnd(e)}},mi=sa;I(mi,"cache",new Map),I(mi,"resolved",{}),I(mi,"currentlyLoading",{}),I(mi,"_progressiveEventListeners",new Map),I(mi,"_currentProgressiveLoadingInfo",new Map);var Cd=class{context;source;uri;material;slot;constructor(e,t,i,n,r){this.context=e,this.source=t,this.uri=i,this.material=n,this.slot=r}},Yl=class{start=[];end=[];onStart(e){for(let t of this.start)t(e)}onEnd(e){for(let t of this.end)t(e)}};function Rd(o){let e=new zo;return o.register(t=>(e.parser=t,e)),e}var Td=class{resolvePath(e){return e.includes("/extensions/builtin_components/")?e.replace("/extensions/builtin_components/","/userData/components/"):e.includes("extensions/builtin_components/")?e.replace("extensions/builtin_components/","/userData/components/"):e}};function Sd(o,e,t){o.register(n=>new Ql(n)),o.register(n=>new Va(n)),o.register(n=>new kl(n,e.lightmaps,t)),o.register(n=>new ql(n,t,e)),o.register(n=>new Wl(n,t)),o.register(n=>new Wr(n,t)),o.register(n=>new mi(n,t,e)),o.register(n=>new Xl(n));let i=o.setAnimationPointerResolver;typeof i=="function"&&i.bind(o)(new Td)}var Yh={};hp(Yh,{AlignmentConstraint:()=>tr,Animation:()=>Bt,AnimationCurve:()=>gi,AnimationExtension:()=>ir,AnimationTrackHandler:()=>nr,Animator:()=>Pe,AnimatorController:()=>fi,AttachedObject:()=>bt,AudioListener:()=>bi,AudioSource:()=>se,AudioTrackHandler:()=>rr,AvatarBlink_Simple:()=>Qi,AvatarEyeLook_Rotation:()=>qi,AvatarLoader:()=>or,AvatarMarker:()=>le,AvatarModel:()=>Kr,Avatar_Brain_LookAt:()=>Sn,Avatar_MouthShapes:()=>ur,Avatar_MustacheShake:()=>ns,Avatar_POI:()=>ye,AxesHelper:()=>Mn,BaseUIComponent:()=>We,BasicIKConstraint:()=>rs,BoxCollider:()=>pr,BoxGizmo:()=>_i,BoxHelperComponent:()=>Ne,Button:()=>qt,CallInfo:()=>vi,Camera:()=>Z,Canvas:()=>Xe,CanvasGroup:()=>Ln,CapsuleCollider:()=>Xt,CharacterController:()=>Yi,CharacterControllerInput:()=>Ti,Collider:()=>Ot,ColorAdjustments:()=>gr,ColorBySpeedModule:()=>Ri,ColorOverLifetimeModule:()=>jn,ControlTrackHandler:()=>Rn,Deletable:()=>ds,DeleteBox:()=>ro,DeviceFlag:()=>oo,DragControls:()=>Ji,DropListener:()=>br,Duplicatable:()=>Zi,EmissionModule:()=>_t,EventList:()=>de,EventListEvent:()=>Qr,EventSystem:()=>Je,EventTrigger:()=>so,FieldWithDefault:()=>ps,FixedJoint:()=>ms,FlyControls:()=>gs,GltfExport:()=>$t,GltfExportBox:()=>bs,Gradient:()=>Si,Graphic:()=>yt,GraphicRaycaster:()=>vs,GridHelper:()=>Un,GridLayoutGroup:()=>xs,GroundProjectedEnv:()=>tn,HingeJoint:()=>vr,HorizontalLayoutGroup:()=>_s,Image:()=>An,InheritVelocityModule:()=>Jt,InputField:()=>kt,Interactable:()=>Vt,Keyboard:()=>ws,LODGroup:()=>yr,LODModel:()=>nn,LayoutGroup:()=>Gn,Light:()=>qe,LimitVelocityOverLifetimeModule:()=>ue,LogStats:()=>Cs,LookAtConstraint:()=>_n,MainModule:()=>_e,MaskableGraphic:()=>In,MeshCollider:()=>Zr,MeshRenderer:()=>ao,MinMaxCurve:()=>U,MinMaxGradient:()=>Me,NestedGltf:()=>ho,Networking:()=>Pi,NoiseModule:()=>K,ObjectRaycaster:()=>co,OffsetConstraint:()=>rn,OrbitControls:()=>Ve,ParticleBurst:()=>Hn,ParticleSubEmitter:()=>_r,ParticleSystem:()=>ve,ParticleSystemRenderer:()=>on,PlayableDirector:()=>Cn,PlayerColor:()=>xt,PointerEventData:()=>xi,RGBAColor:()=>Q,RawImage:()=>to,Raycaster:()=>lo,Rect:()=>eo,RectTransform:()=>vt,ReflectionProbe:()=>Zt,RegisteredAnimationInfo:()=>Nr,RemoteSkybox:()=>Oi,Renderer:()=>ae,RendererLightmap:()=>Bn,Rigidbody:()=>J,RotationBySpeedModule:()=>Qe,RotationOverLifetimeModule:()=>Ze,ScreenCapture:()=>Er,ShadowCatcher:()=>Cr,ShapeModule:()=>ne,SignalAsset:()=>qr,SignalReceiver:()=>En,SignalReceiverEvent:()=>Yr,SignalTrackHandler:()=>Tn,Size:()=>ss,SizeBySpeedModule:()=>ke,SizeOverLifetimeModule:()=>Kt,SkinnedMeshRenderer:()=>fs,SmoothFollow:()=>Mt,SpatialHtml:()=>Ps,SpatialTrigger:()=>Vn,SpatialTriggerReceiver:()=>It,SpectatorCamera:()=>Os,SphereCollider:()=>hr,Sprite:()=>ei,SpriteRenderer:()=>sn,SpriteSheet:()=>an,SubEmitterSystem:()=>xr,SyncedCamera:()=>Rr,SyncedRoom:()=>ki,SyncedTransform:()=>Pt,TeleportTarget:()=>Jr,TestRunner:()=>Ms,TestSimulateUserData:()=>Is,Text:()=>Ie,TextureSheetAnimationModule:()=>xe,ToneMapping:()=>mr,TrailModule:()=>te,TransformData:()=>Xr,TransformGizmo:()=>fo,UIRaycastUtils:()=>Ei,UIRootComponent:()=>kn,USDZExporter:()=>Sr,UsageMarker:()=>zt,VRUserState:()=>Nt,VelocityOverLifetimeModule:()=>He,VerticalLayoutGroup:()=>ys,VideoPlayer:()=>Te,Voip:()=>rt,Volume:()=>no,VolumeComponent:()=>Ki,VolumeParameter:()=>cs,VolumeProfile:()=>fr,WebAR:()=>cr,WebARSessionRoot:()=>mt,WebXR:()=>V,WebXRAvatar:()=>Gt,WebXRController:()=>$,WebXRSync:()=>On,XRFlag:()=>Ee,XRGrabModel:()=>mo,XRGrabRendering:()=>As,XRRig:()=>lr,XRState:()=>St,__Ignore:()=>Oa});import{Vector3 as o_}from"three";var tr=class extends M{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new o_}update(){if(!this.from||!this.to)return;let e=B(this.from).clone(),t=B(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),ie(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(B(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}};v([y(R)],tr.prototype,"from",2),v([y(R)],tr.prototype,"to",2);var Vi=class{time;value;inTangent;inWeight;outTangent;outWeight;weightedMode};v([y()],Vi.prototype,"time",2),v([y()],Vi.prototype,"value",2),v([y()],Vi.prototype,"inTangent",2),v([y()],Vi.prototype,"inWeight",2),v([y()],Vi.prototype,"outTangent",2),v([y()],Vi.prototype,"outWeight",2),v([y()],Vi.prototype,"weightedMode",2);var gi=class{keys;get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;if(this.keys[0].time>=e)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){let i=this.keys[t];if(i.time<=e)if(t+1<this.keys.length){let r=this.keys[t+1];if(r.time<e)continue;let s=H.remap(e,i.time,r.time,0,1);return H.lerp(i.value,r.value,s)}else return i.value}return this.keys[this.keys.length-1].value}};v([y(Vi)],gi.prototype,"keys",2);import{Matrix4 as s_,Vector3 as vm,Quaternion as a_}from"three";import{buildMatrix as l_}from"three/examples/jsm/exporters/USDZExporter";var No=P("debugusdzanimation"),Nr=class{get start(){return this.ext.getStartTime01(this.root,this.clip)}get duration(){return this.clip.duration}ext;root;clip;constructor(e,t,i){this.ext=e,this.root=t,this.clip=i}},Xr=class{clip;pos;rot;scale;get frameRate(){return 60}ext;root;target;constructor(e,t,i,n){this.ext=e,this.root=t,this.target=i,this.clip=n}addTrack(e){e.name.endsWith("position")&&(this.pos=e),e.name.endsWith("quaternion")&&(this.rot=e),e.name.endsWith("scale")&&(this.scale=e)}getFrames(){return Math.max(this.pos?.times?.length??0,this.rot?.times?.length??0,this.scale?.times?.length??0)}getDuration(){let e=this.pos?.times??this.rot?.times??this.scale?.times;return e?e[e.length-1]:0}getStartTime(e){let t=0;for(let i=0;i<e.length;i++){let n=e[i];if(n===this)return t;t+=n.getDuration()}return t}},ir=class{get extensionName(){return"animation"}dict=new Map;rootTargetMap=new Map;getStartTime01(e,t){let i=this.rootTargetMap.get(e);if(!i)return 1/0;let n=-1;for(let r of i){let s=this.dict.get(r),a=0;if(s?.length){for(let c of s){if(c.clip===t)break;a+=c.getDuration()}n=Math.max(n,a)}else console.warn("No animation found on root",e,t,s)}return n}registerAnimation(e,t){if(!t||!e)return null;this.rootTargetMap.has(e)||this.rootTargetMap.set(e,[]);for(let n of t.tracks){let r=n.name.split(".")[2],s=e.getObjectByName(r);if(!s){console.warn("no object found for track",n.name,"using "+e.name+" instead");continue}this.dict.has(s)||this.dict.set(s,[]);let a=this.dict.get(s);if(!a)continue;let c=a.find(l=>l.clip===t);c||(c=new Xr(this,e,s,t),a.push(c)),c.addTrack(n);let u=this.rootTargetMap.get(e);u?.includes(s)||u?.push(s)}return new Nr(this,e,t)}onAfterHierarchy(e){No&&console.log(this.dict)}serializers=[];onAfterBuildDocument(e){for(let t of this.serializers){let i=t.model?.parent,n=i?.isDynamic===!0;No&&console.log(n,t.model?.parent),n&&t.registerCallback(i)}}onExportObject(e,t,i){R.foreachComponent(e,r=>{let s=r;typeof s.createAnimation=="function"&&s.createAnimation(this,t,i)},!1);let n=new Pd(e,this.dict);this.serializers.push(n),n.registerCallback(t)}},Pd=class{object;dict;model;callback;constructor(e,t){this.object=e,this.dict=t}registerCallback(e){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),No&&console.log("REPARENT",e),this.model=e,this.model.addEventListener("serialize",this.callback)}onSerialize(e,t){No&&console.log("SERIALIZE",this.model.name,this.object.type);let i=this.object,n=this.dict.get(i);if(!n)return;let r=new s_,s=new vm,a=new a_,c=new vm(1,1,1);e.appendLine("matrix4d xformOp:transform.timeSamples = {"),e.indent++;for(let u of n){let l=u.pos?.times;if((!l||u.rot&&u.rot.times?.length>l?.length)&&(l=u.rot?.times),(!l||u.scale&&u.scale.times?.length>l?.length)&&(l=u.scale?.times),!l){console.error("got an animated object but no time values??",i,u);continue}let d=u.getStartTime(n);No&&e.appendLine(u.clip.name+": start="+d.toFixed(3)+", length="+u.getDuration().toFixed(3)+", frames="+u.getFrames());let h=u.pos?.createInterpolant(),g=u.rot?.createInterpolant(),E=u.scale?.createInterpolant();h||s.set(i.position.x,i.position.y,i.position.z),g||a.set(i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w),E||c.set(i.scale.x,i.scale.y,i.scale.z);for(let _=0;_<l.length;_++){let x=l[_];if(h){let f=h.evaluate(x);s.set(f[0],f[1],f[2])}if(g){let f=g.evaluate(x);a.set(f[0],f[1],f[2],f[3])}if(E){let f=E.evaluate(x);f.set(f[0],f[1],f[2])}r.compose(s,a,c);let m=`${(d+x)*u.frameRate}: ${l_(r)},`;No&&(m="#"+_+" "+m),e.appendLine(m)}}e.indent--,e.appendLine("}")}};import*as wm from"three";import*as ym from"three";import*as aa from"three";import{PositionalAudioHelper as c_}from"three/examples/jsm/helpers/PositionalAudioHelper.js";var pt=P("debugaudio");var De=class extends M{static get userInteractionRegistered(){return De._didCallBeginWaitForUserInteraction||(De._didCallBeginWaitForUserInteraction=!0,De._beginWaitForUserInteraction()),De._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),De._didCallBeginWaitForUserInteraction||(De._didCallBeginWaitForUserInteraction=!0,De._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);let i=(()=>{if(i!=null&&!De._userInteractionRegistered){De._userInteractionRegistered=!0,console.log("registered interaction, can play audio now"),document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i);for(let n of this.callbacks)n();this.callbacks.length=0}}).bind(this);document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)}clip="";playOnAwake=!1;get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}_spatialBlend=0;_minDistance=1;_maxDistance=100;get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&(pt&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}_volume=1;rollOffMode=0;_loop=!1;sound=null;helper=null;wasPlaying=!1;audioLoader=null;shouldPlay=!1;_lastClipStartedLoading=null;get Sound(){if(!this.sound&&De._userInteractionRegistered){let e=R.getComponent(this.context.mainCamera,bi)??R.findObjectOfType(bi,this.context);e?.listener&&(this.sound=new aa.PositionalAudio(e.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}_focusCallback;awake(){this.audioLoader=new aa.AudioLoader,this.playOnAwake&&(this.shouldPlay=!0),window.addEventListener("visibilitychange",e=>{switch(document.visibilityState){case"hidden":this.wasPlaying=this.isPlaying,this.pause();break;case"visible":this.wasPlaying&&this.play();break}}),this._focusCallback=()=>{this.enabled&&this.playOnAwake&&!this.isPlaying&&De._userInteractionRegistered&&this.play()},this.context.application.addEventListener("application-visible",this._focusCallback)}onDestroy(){this.context.application.removeEventListener("application-visible",this._focusCallback)}onEnable(){De._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():De._beginWaitForUserInteraction(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.loadAndPlay(this.clip)})}onDisable(){this.stop()}lerp=(e,t,i)=>e*(1-i)+t*i;onLoaded(e){pt&&console.log("audio buffer loaded"),De.registerWaitForAllowAudio(()=>{pt&&console.log("finished loading",e);let t=this.Sound;if(!t){console.warn("Failed getting sound",this.name);return}t.isPlaying&&t.stop(),t.setBuffer(e),t.loop=this._loop,t.setVolume(this.volume),t.autoplay=this.shouldPlay,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),pt&&console.log(this.name,this.shouldPlay,De.userInteractionRegistered,this),this.shouldPlay&&De._userInteractionRegistered&&this.play()})}applySpatialDistanceSettings(){let e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;let t=this.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(pt&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:break}this.spatialBlend>0?pt&&!this.helper&&(this.helper=new c_(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&(pt&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new aa.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){pt&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,pt&&console.log("load audio",this.clip),this.audioLoader.load(this.clip,this.onLoaded.bind(this),()=>{},console.error)}}play(e=void 0){if(!this.audioLoader||!this.sound||e&&e!==this.clip){this.loadAndPlay(e);return}this.shouldPlay=!0,this._hasEnded=!1,pt&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying&&this.sound.play()}pause(){pt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause())}stop(){pt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,pt&&console.log(this._lastContextTime),this.sound.stop())}_lastContextTime=0;get isPlaying(){return this.sound?.isPlaying??!1}set isPlaying(e){}get time(){return this.sound?.source?this.sound.source?.context.currentTime-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;let t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}_hasEnded=!0;_needUpdateSpatialDistanceSettings=!1;update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,pt&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},se=De;I(se,"_didCallBeginWaitForUserInteraction",!1),I(se,"callbacks",[]),I(se,"_userInteractionRegistered",!1),v([y()],se.prototype,"clip",2),v([y()],se.prototype,"playOnAwake",2),v([y()],se.prototype,"loop",1),v([y()],se.prototype,"spatialBlend",1),v([y()],se.prototype,"minDistance",1),v([y()],se.prototype,"maxDistance",1),v([y()],se.prototype,"volume",1),v([y()],se.prototype,"rollOffMode",2);var bi=class extends M{get listener(){return this._listener==null&&(this._listener=new ym.AudioListener),this._listener}_listener=null;awake(){se.registerWaitForAllowAudio(()=>{let e=this.listener;if(e==null||e.parent)return;let t=R.getComponentInParent(this.gameObject,Z);t?t.cam.add(e):this.gameObject.add(e)})}};var vi=class{method;enabled;constructor(e,t){this.method=e,this.enabled=t!==void 0?t:!0}invoke(...e){if(this.enabled!==!1){if(!this.method){console.warn("No function. Please check you assigned a method to invoke on export",this);return}this.method(...e)}}},u_=o=>/^[A-Z]*$/.test(o),Qr=class extends Event{args},de=class{target;key;setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let i="",n=!1;for(let r of this.key)n&&u_(r)&&(i+="-"),n=!0,i+=r.toLowerCase();this.key=i}}_isInvoking=!1;methods=[];constructor(e){this.methods=e??[]}invoke(...e){if(this._isInvoking){console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this);return}this._isInvoking=!0;try{for(let t of this.methods)t.invoke(...e);if(typeof this.target=="object"&&typeof this.key=="string"){let t=this.target.dispatchEvent;if(typeof t=="function"){let i=new Qr(this.key);i.args=e,t.call(this.target,i)}}}finally{this._isInvoking=!1}}addEventListener(e){return this.methods.push(new vi(e,!0)),e}removeEventListener(e){if(!!e)for(let t=this.methods.length-1;t>=0;t--)this.methods[t].method===e&&(this.methods[t].enabled=!1,this.methods.splice(t,1))}removeAllEventListeners(){this.methods.length=0}};var qr=class{guid},Yr=class{signal;reaction;$serializedTypes={signal:qr,reaction:de}},En=class extends M{events;start(){console.log(this)}invoke(e){if(!this.events||!Array.isArray(this.events))return;let t=typeof e=="object"?e.guid:e;for(let i of this.events)if(i.signal.guid===t)try{if(i.reaction){if(!i.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",i,this);continue}}else{console.warn("Missing reaction for signal",i,this);continue}i.reaction.invoke()}catch(n){console.error(n)}}};v([y(Yr)],En.prototype,"events",2);var xm=P("debugtimeline");var Kl=class extends M{static registerCreateTrack(e,t){this.createTrackFunctions[e]=t}playableAsset;playOnAwake;extrapolationMode=1;get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(e){this._time=e}get duration(){return this._duration}set duration(e){this._duration=e}get weight(){return this._weight}set weight(e){this._weight=e}_visibilityChangeEvt;_clonedPlayableAsset=!1;awake(){xm&&console.log(this,this.playableAsset?.tracks),this.rebuildGraph(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,this.playableAsset?.tracks,Array.isArray(this.playableAsset?.tracks),this)}onEnable(){for(let e of this._audioTracks)e.onEnable?.();for(let e of this._customTracks)e.onEnable?.();this.playOnAwake&&this.play(),this._visibilityChangeEvt||(this._visibilityChangeEvt=()=>{switch(document.visibilityState){case"hidden":this.setAudioTracksAllowPlaying(!1);break;case"visible":this.setAudioTracksAllowPlaying(!0);break}}),window.addEventListener("visibilitychange",this._visibilityChangeEvt)}onDisable(){this.stop();for(let e of this._audioTracks)e.onDisable?.();for(let e of this._customTracks)e.onDisable?.();this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){for(let e of this._audioTracks)e.onDestroy?.()}rebuildGraph(){!this.isValid()||(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}play(){!this.isValid()||(this._isPaused=!1,!this._isPlaying&&(this._isPlaying=!0,this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate())))}pause(){this._isPaused=!0}stop(){this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.evaluate()),this._isPlaying=!1,this._isPaused=!1,this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null}evaluate(){if(!this.isValid())return;let e=this._time;switch(this.extrapolationMode){case 0:e=Math.min(e,this._duration);break;case 1:e%=this._duration;break;case 2:if(e>this._duration){this.stop();return}break}this.internalEvaluate(e)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(let e of this._allTracks)for(let t of e)yield t}get audioTracks(){return this._audioTracks}_guidsMap;resolveGuids(e){this._guidsMap=e}_isPlaying=!1;_internalUpdateRoutine;_isPaused=!1;_time=0;_duration=0;_weight=1;_animationTracks=[];_audioTracks=[];_signalTracks=[];_controlTracks=[];_customTracks=[];_allTracks=[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks];*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime,this.evaluate()),yield}internalEvaluate(e){for(let t of this.playableAsset.tracks)if(!t.muted)switch(t.type){case"ActivationTrack":for(let i=0;i<t.outputs.length;i++){let n=t.outputs[i];if(typeof n=="object"){let r=!1;for(let a of t.clips)a.start<=e&&e<=a.end&&(r=!0);let s=n;s.visible!==void 0&&(s.visible=r)}}break}for(let t of this._animationTracks)t.evaluate(e);for(let t of this._audioTracks)t.evaluate(e);for(let t of this._signalTracks)t.evaluate(e);for(let t of this._controlTracks)t.evaluate(e);for(let t of this._customTracks)t.evaluate(e)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Us(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;let e=this.findRoot(this.gameObject);for(let t of this.playableAsset.tracks)for(let i=t.outputs.length-1;i>=0;i--){let n=t.outputs[i];if(typeof n=="string"){this._guidsMap&&this._guidsMap[n]&&(n=this._guidsMap[n]);let r=R.findByGuid(n,e);r===null||typeof r!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(xm&&console.log("Resolved binding",n,"to",r),t.outputs[i]=r,r instanceof Pe)}else if(n===null){if(t.outputs.splice(i,1),Kl.createTrackFunctions[t.type])continue;t.type!=="AudioTrack"&&t.type!=="ControlTrack"&&t.type!=="MarkerTrack"&&console.warn("Missing binding",n,t.name,t.type,this.name,this.playableAsset.name)}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(let e of this.playableAsset.tracks)if(e.muted!==!0)for(let t of e.clips)t.end>this._duration&&(this._duration=t.end)}}setupAndCreateTrackHandlers(){if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let e=[];for(let t of this.playableAsset.tracks){let i=t.type,n=Kl.createTrackFunctions[i];if(n!=null){let r=n(this,t);if(typeof r.evaluate=="function"){r.director=this,r.track=t,this._customTracks.push(r);continue}}if(t.type==="AnimationTrack"){if(t.clips.length<=0)continue;for(let r=t.outputs.length-1;r>=0;r--){let s=t.outputs[r];typeof s.enabled=="boolean"&&(s.enabled=!1);let a=s?.gameObject?.animations;if(a){let c=new nr;c.trackOffset=t.trackOffset,c.director=this,c.track=t;for(let u=0;u<t.clips.length;u++){let l=t.clips[u],d=l.asset;if(!d){console.error("MISSING anim model?","clip#"+u,l,t,this.playableAsset,this.name);continue}let h=d.clip,g=h;if((typeof g=="string"||typeof g=="number")&&(g=a.find(_=>_.name===h)),!g){console.warn("Could not find animationClip for model",l,t.name,this.name,this.playableAsset?.name);continue}c.mixer||(c.mixer=new wm.AnimationMixer(s.gameObject)),c.clips.push(g),c.mixer.uncacheAction(g),c.createHooks(l.asset,g);let E=c.mixer.clipAction(g);c.actions.push(E),c.models.push(l)}this._animationTracks.push(c)}}}else if(t.type==="AudioTrack"){if(t.clips.length<=0)continue;e.push(t)}else if(t.type==="MarkerTrack"){let r=new Tn;r.director=this,r.track=t;for(let s of t.markers)switch(s.type){case"SignalEmitter":r.models.push(s),r.didTrigger.push(!1);break}if(r!==null&&r.models.length>0){let s=R.getComponent(this.gameObject,En);s&&(r.receivers.push(s),this._signalTracks.push(r))}}else if(t.type==="SignalTrack"){let r=new Tn;r.director=this,r.track=t;for(let s of t.markers)r.models.push(s),r.didTrigger.push(!1);for(let s of t.outputs)r.receivers.push(s);this._signalTracks.push(r)}else if(t.type==="ControlTrack"){let r=new Rn;r.director=this,r.track=t;for(let s of t.clips)r.models.push(s);r.resolveSourceObjects(this.context),this._controlTracks.push(r)}}se.registerWaitForAllowAudio(()=>{let t=R.findObjectOfType(bi,this.context);if(!!t)for(let i of e){let n=new rr;n.director=this,n.track=i,n.listener=t.listener;for(let r=0;r<i.clips.length;r++){let s=i.clips[r];n.addModel(s)}this._audioTracks.push(n)}})}setAudioTracksAllowPlaying(e){for(let t of this._audioTracks)t.onAllowAudioChanged(e)}},Cn=Kl;I(Cn,"createTrackFunctions",{});import*as ee from"three";import{Quaternion as h_,Vector3 as p_}from"three";var Xo=P("debugtimeline"),Qo=class{director;track;get muted(){return this.track.muted}set muted(e){e!==this.track.muted&&(this.track.muted=e,this.onMuteChanged?.call(this))}*forEachClip(e=!1){if(!!this.track?.clips)if(e)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(let t of this.track.clips)yield t}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,i,n=!0){if(t<0||t>=i.length)return 0;let r=i[t];if(n||e>=r.start&&e<=r.end){let s=1,a=!1;if(r.easeInDuration>0){let c=Math.min((e-r.start)/r.easeInDuration,1);s*=c}if(r.easeOutDuration>0&&!a){let c=Math.min((r.end-e)/r.easeOutDuration,1);s*=c}return s}return 0}},Od=class{clip;rootPositionOffset;rootQuaternionOffset;get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}rootStartPosition;rootEndPosition;rootStartQuaternion;rootEndQuaternion;constructor(e){let t=e.getClip();this.clip=t;let i=e.getRoot(),n=i.name+".position",r=i.name+".quaternion";Xo&&console.log(t.name,t.tracks,n);for(let s of t.tracks)if(!(s.times.length<=0)){if(s.name.endsWith(n))this.rootStartPosition=new ee.Vector3().fromArray(s.values,0),this.rootEndPosition=new ee.Vector3().fromArray(s.values,s.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),Xo&&console.log(this.rootPositionOffset);else if(s.name.endsWith(r)&&(this.rootStartQuaternion=new ee.Quaternion().fromArray(s.values,0),this.rootEndQuaternion=new ee.Quaternion().fromArray(s.values,s.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),Xo)){let a=new ee.Euler().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",a)}}}},nr=class extends Qo{models=[];trackOffset;target;mixer;clips=[];actions=[];_actionOffsets=[];_didBind=!1;createHooks(e,t){if(t.tracks?.length<=0){console.warn("No tracks in AnimationClip",t);return}let i=t.tracks[0].name.split("."),n=i[i.length-2],r=n+".position",s=n+".quaternion",a=!1,c=!1;for(let u of t.tracks)u.name.endsWith(r)?(a=!0,this.createPositionInterpolant(t,e,u)):u.name.endsWith(s)&&(c=!0,this.createRotationInterpolant(t,e,u));if(!a||!c){let u=this.mixer?.getRoot(),l=t.tracks[0],d=l.name.lastIndexOf("."),h=l.name.substring(0,d),g=h.substring(h.lastIndexOf(".")+1),E=u.getObjectByName(g);if(E)if(a){if(!c){let _=t.tracks[0].name.substring(0,d)+".quaternion";Xo&&console.warn("Create quaternion track",g,E);let x=E.quaternion,m=new ee.QuaternionKeyframeTrack(_,[0,t.duration],[x.x,x.y,x.z,x.w,x.x,x.y,x.z,x.w]);t.tracks.push(m),this.createRotationInterpolant(t,e,m)}}else{let _=h+".position";Xo&&console.warn("Create position track",g,E);let x=E.position,m=new ee.VectorKeyframeTrack(_,[0,t.duration],[x.x,x.y,x.z,x.x,x.y,x.z]);t.tracks.push(m),this.createPositionInterpolant(t,e,m)}}}bind(){if(!this._didBind){this._didBind=!0,Xo&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(let e of this.actions){let t=new Od(e);this._actionOffsets.push(t)}for(let e of this.models){let t=e.asset,i=t.position,n=t.rotation;i.x!==void 0&&(i.isVector3||(t.position=new p_(i.x,i.y,i.z)),n.isQuaternion||(t.rotation=new h_(n.x,n.y,n.z,n.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){let e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new ee.Vector3(e.x,e.y,e.z)));let t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new ee.Quaternion(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new ee.Vector3;_totalOffsetRotation=new ee.Quaternion;_totalOffsetPosition2=new ee.Vector3;_totalOffsetRotation2=new ee.Quaternion;_summedPos=new ee.Vector3;_tempPos=new ee.Vector3;_summedRot=new ee.Quaternion;_tempRot=new ee.Quaternion;evaluate(e){if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let t=0,i=0,n=!1;for(let r=0;r<this.clips.length;r++){let s=this.models[r],a=this.actions[r],c=s.asset;a.weight=0;let u=e>=s.start&&e<=s.end,l=s.postExtrapolationMode,d=u;if(!d&&!n&&s.end<e&&s.postExtrapolationMode!==0){let h=r<this.clips.length-1?this.models[r+1]:null;(!h||h.start>e)&&(d=!0,n=!0)}if(d){let h=1;h*=this.evaluateWeight(e,r,this.models,d);let g=this.getClipTime(e,s),E=0,_=c.duration;if(u){if(c.loop)for(E+=Math.floor(g/(_+1e-6));g>_;)g-=_}else if(!u)switch(l){case 2:g%=_;break;case 3:let f=Math.floor(g/_)%2!==0;g%=_,f&&(g=_-g);break}a.time=g,a.timeScale=0;let x=h*this.director.weight;if(a.weight=x,a.clampWhenFinished=!0,a.isRunning()||a.play(),this._useclipOffsets){let m=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,f=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-h),t+=1;let p=this._summedPos.set(0,0,0),b=this._tempPos.set(0,0,0),w=this._summedRot.identity(),C=this._tempRot.identity(),T=c.rotation,S=new ee.Quaternion;S.slerp(T,h);let A=this._actionOffsets[r];if(A.hasOffsets)for(let D=0;D<E;D++)A.rootPositionOffset?b.copy(A.rootPositionOffset):b.set(0,0,0),b.applyQuaternion(w).applyQuaternion(S),A.rootQuaternionOffset&&(C.copy(A.rootQuaternionOffset),w.multiply(C)),p.add(b);f.multiply(S),f.multiply(w),p.add(c.position),m.add(p)}}}this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,i),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,i)),this.mixer.update(e)}createRotationInterpolant(e,t,i){let n=i.createInterpolant.bind(i),r=new ee.Quaternion;this.ensureTrackOffsets();let s=this.trackOffset?.rotation;i.createInterpolant=()=>{let a=n(),c=a.evaluate.bind(a);return a.evaluate=u=>{let l=c(u);return r.set(l[0],l[1],l[2],l[3]),r.premultiply(this._totalOffsetRotation),s&&r.premultiply(s),l[0]=r.x,l[1]=r.y,l[2]=r.z,l[3]=r.w,l},a}}createPositionInterpolant(e,t,i){let n=i.createInterpolant.bind(i),r=new ee.Vector3;this.ensureTrackOffsets();let s=this.trackOffset?.rotation,a=this.trackOffset?.position,c;i.createInterpolant=()=>{let u=n(),l=u.evaluate.bind(u);return u.evaluate=d=>{let h=l(d);return r.set(h[0],h[1],h[2]),t.removeStartOffset&&(c===void 0?(c=null,c=this._actionOffsets.find(g=>g.clip===e)?.rootStartPosition?.clone()):c?.isVector3&&r.sub(c)),r.applyQuaternion(this._totalOffsetRotation),r.add(this._totalOffsetPosition),s&&r.applyQuaternion(s),a&&(r.x-=a.x,r.y+=a.y,r.z+=a.z),h[0]=r.x,h[1]=r.y,h[2]=r.z,h},u}}},rr=class extends Qo{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;getAudioFilePath(e){let t=this.director.sourceId;return Ii(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){let i=this.models[t];this.audio[t].setVolume(e?i.asset.volume:0)}}addModel(e){let t=this.getAudioFilePath(e.asset.clip),i=new ee.Audio(this.listener);i.setVolume(e.asset.volume);let n=new ee.AudioLoader;console.log(t,this.director.sourceId),n.load(t,r=>{i.setBuffer(r),i.loop=e.asset.loop,this.audio.push(i),this.models.push(e)})}onDisable(){for(let e of this.audio)e.isPlaying&&e.stop()}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){let t=this.audio[e];t?.isPlaying&&t.stop()}}evaluate(e){if(!this.track.muted){for(let t=0;t<this.models.length;t++){let i=this.models[t],n=this.audio[t];if(e>=i.start&&e<=i.end){if(this.director.isPaused&&(n.isPlaying&&n.stop(),this.lastTime===e))continue;n.isPlaying||(n.offset=i.clipIn+(e-i.start)*i.timeScale,n.play());let r=i.asset.volume;if(i.easeInDuration>0){let s=Math.min((e-i.start)/i.easeInDuration,1);r*=s}if(i.easeOutDuration>0){let s=Math.min((i.end-e)/i.easeOutDuration,1);r*=s}n.setVolume(r*this.director.weight)}else n.isPlaying&&n.stop()}this.lastTime=e}}},Tn=class extends Qo{models=[];didTrigger=[];receivers=[];evaluate(e){if(!(this.receivers.length<=0)&&!this.track.muted)for(let t=0;t<this.models.length;t++){let i=this.models[t],n=this.didTrigger[t],r=i.time-e;if(i.retroActive?r<0:r<0&&Math.abs(r)<.1){if(!n){this.didTrigger[t]=!0;for(let a of this.receivers)!a||a.invoke(i.asset)}}else i.emitOnce||(this.didTrigger[t]=!1)}}},la=class extends Qo{models=[];timelines=[];resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){let n=this.models[t].asset;if(typeof n.sourceObject=="string"){let r=n.sourceObject;la.resolved[r]?n.sourceObject=la.resolved[r]:(n.sourceObject=R.findByGuid(r,e.scene),la.resolved[r]=n.sourceObject)}if(n.sourceObject){let r=R.getComponent(n.sourceObject,Cn);this.timelines.push(r),r&&n.updateDirector&&(r.playOnAwake=!1)}else{this.models.splice(t,1);continue}}}_previousActiveModel=null;evaluate(e){this._previousActiveModel=null;for(let t=0;t<this.models.length;t++){let i=this.models[t],n=i.asset;if(e>=i.start&&e<=i.end){this._previousActiveModel=i;let r=this.getClipTime(e,i);if(n.controlActivation){let s=n.sourceObject;s.visible=!0}if(n.updateDirector){let s=this.timelines[t];s&&(s.isPlaying&&s.pause(),s.time=r,s.evaluate())}}else{let r=this._previousActiveModel?.asset;if(n.controlActivation){let s=n.sourceObject;r?.sourceObject!==s&&(s.visible=!1)}}}}},Rn=la;I(Rn,"resolved",{});import{BoxHelper as F_,BufferGeometry as B_,Color as Dm,Euler as U_,Layers as G_,Line as V_,Mesh as z_,MeshBasicMaterial as W_,Quaternion as sc,Ray as N_,SphereGeometry as X_,Vector2 as Q_,Vector3 as Ci}from"three";import{OculusHandModel as q_}from"three/examples/jsm/webxr/OculusHandModel.js";import{OculusHandPointerModel as Y_}from"three/examples/jsm/webxr/OculusHandPointerModel.js";import{XRControllerModelFactory as K_}from"three/examples/jsm/webxr/XRControllerModelFactory.js";import{GLTFLoader as J_}from"three/examples/jsm/loaders/GLTFLoader.js";import*as Tm from"three";import{Quaternion as m_,Vector3 as Zl}from"three";import{GLTFLoader as f_}from"three/examples/jsm/loaders/GLTFLoader";import*as Jl from"three";var ca=P("debugavatar"),Kr=class{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(r=>r.layers.set(2))}},or=class{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){let r=new Ue;i=R.instantiate(Wn(t,e.scene),r)}}else i=t;if(!i)return null;let n=this.findAvatar(i);return n.isValid?(ca&&console.log("[Custom Avatar] valid config",t,ca?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,ca?n:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(ca&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){let n=await fetch("./"+t),r=null;if(n.ok){let a=await n.blob();a&&(r=await a.arrayBuffer())}return!r&&(r=await _l(t,t,0,"no url here go away",!0),!r)?null:(await Ke().parseSync(e,r,null,0))?.scene??null}let i=new f_;return xn(i,e),new Promise((n,r)=>{let s=this.avatarRegistryUrl+"/"+t;i.load(s,async a=>{await Ke().createBuiltinComponents(e,s,a,null,void 0),n(a.scene)},a=>{ca&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),n(null)})})}cacheModel(e,t){}findAvatar(e){let t=e,i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,["head"]),r=this.findAvatarPart(i,["left","hand"]),s=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;let c=new Jl.Vector3;new Jl.Box3().setFromObject(n).getSize(c);let u=Math.max(c.x,c.y,c.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+u+" meters! Should be < 0.3m"),u>.3&&n.scale.multiplyScalar(1/u*.3)}return new Kr(t,n,r,s)}findAvatarPart(e,t){let i=e.name.toLowerCase(),n=!0;for(let r of t){if(!n)break;i.indexOf(r)===-1&&(n=!1)}if(n)return e;if(e.children)for(let r of e.children){let s=this.findAvatarPart(r,t);if(s)return s}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}};var qo=P("debugflags");var kd=class{Mask=17;Has(e){return(this.Mask&e)!==0}Set(e){qo&&console.warn("Set XR flag state to",e),this.Mask=e,Ee.Apply()}Enable(e){this.Mask|=e,Ee.Apply()}Disable(e){this.Mask&=~e,Ee.Apply()}Toggle(e){this.Mask^=e,Ee.Apply()}EnableAll(){this.Mask=-1,Ee.Apply()}DisableAll(){this.Mask=0,Ee.Apply()}},St=kd;I(St,"Global",new kd);var zi=class extends M{static Apply(){for(let e of this.registry)e.UpdateVisible(St.Global)}awake(){zi.registry.push(this)}onEnable(){zi.firstApply||(zi.firstApply=!0,zi.Apply())}onDestroy(){let e=zi.registry.indexOf(this);e>=0&&zi.registry.splice(e,1)}visibleIn;get isOn(){return this.gameObject.visible}UpdateVisible(e=null){let t,i=e;i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),qo&&console.log(i),zi.buffer.Mask=i,e=zi.buffer);let n=e;if(n?(qo&&console.warn(this.name,"use passed in mask",n.Mask,this.visibleIn),t=n.Has(this.visibleIn)):(qo&&console.log(this.name,"use global mask"),St.Global.Has(this.visibleIn)),t!==void 0)if(t)qo&&console.log(this.name,"is visible",this.gameObject.uuid),R.setActive(this.gameObject,!0);else{if(qo&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},Ee=zi;I(Ee,"registry",[]),I(Ee,"firstApply"),I(Ee,"buffer",new St);import{Object3D as Md}from"three";var sr=P("debugavatar"),yi=class extends M{static getAvatar(e){return e>=0&&e<yi.instances.length?yi.instances[e]:null}static onAvatarMarkerCreated(e){return yi._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return yi._onAvatarMarkerDestroyed.push(e),e}connectionId;avatar;awake(){yi.instances.push(this),sr&&console.log(this);for(let e of yi._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){yi.instances.splice(yi.instances.indexOf(this),1);for(let e of yi._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}setVisible(e){this.avatar&&("setVisible"in this.avatar?this.avatar.setVisible(e):R.setActive(this.avatar,e))}},le=yi;I(le,"instances",[]),I(le,"_onNewAvatarMarkerAdded",[]),I(le,"_onAvatarMarkerDestroyed",[]);var ua=class{_isVisible=!0;setVisible(e){this._isVisible=e,this.updateVisibility()}get isWebXRAvatar(){return!0}guid;root=null;head=null;handLeft=null;handRight=null;lastUpdate=-1;isLocalAvatar=!1;flags=null;headScale=new Zl(1,1,1);handLeftScale=new Zl(1,1,1);handRightScale=new Zl(1,1,1);webxr;lastAvatarId=null;hasAvatarOverride=!1;context;avatarMarker=null;constructor(e,t,i){this.context=e,this.guid=t,this.webxr=i,this.setupCustomAvatar(this.webxr.defaultAvatar)}updateFlags(){if(!this.flags)return;let e=this.isLocalAvatar?8:16;this.context.isInVR?e|=4:this.context.isInAR?e|=2:e|=1;for(let t of this.flags)t.gameObject.visible=!0,t.UpdateVisible(e)}async setAvatarOverride(e){return this.hasAvatarOverride=e!==null,this.hasAvatarOverride&&this.lastAvatarId!==e&&(this.lastAvatarId=e,e!=null&&e.length>0)?await this.setupCustomAvatar(e):null}_headTarget=new Md;_handLeftTarget=new Md;_handRightTarget=new Md;_canInterpolate=!1;tryUpdate(e,t){if(e.guid===this.guid&&(this.lastAvatarId!==e.avatarId&&e.avatarId&&e.avatarId.length>0&&(this.lastAvatarId=e.avatarId,this.setupCustomAvatar(e.avatarId)),this.lastUpdate=e.time,this.head)){let i=this.webxr.IsInAR?"handheld":"headset",n=this.head;this.context.players.setPlayerView(e.guid,n,i),oe.markDirty(this.head),this._canInterpolate=!0;let r=this.isLocalAvatar?this.head:this._headTarget;if(r.position.set(e.position.x,e.position.y,e.position.z),r.quaternion.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),r.scale.set(e.scale,e.scale,e.scale),r.scale.multiply(this.headScale),this.handLeft){let s=this.isLocalAvatar?this.handLeft:this._handLeftTarget;s.position.set(e.posLeftHand.x,e.posLeftHand.y,e.posLeftHand.z),s.quaternion.set(e.rotLeftHand._x,e.rotLeftHand._y,e.rotLeftHand._z,e.rotLeftHand._w),s.quaternion.multiply(ua.invertRotation),s.scale.set(e.scale,e.scale,e.scale),s.scale.multiply(this.handLeftScale),oe.markDirty(this.handLeft)}if(this.handRight){let s=this.isLocalAvatar?this.handRight:this._handRightTarget;s.position.set(e.posRightHand.x,e.posRightHand.y,e.posRightHand.z),s.quaternion.set(e.rotRightHand._x,e.rotRightHand._y,e.rotRightHand._z,e.rotRightHand._w),s.quaternion.multiply(ua.invertRotation),s.scale.set(e.scale,e.scale,e.scale),s.scale.multiply(this.handRightScale),oe.markDirty(this.handRight)}}}update(){if(this.isLocalAvatar||!this._canInterpolate)return;let e=this.context.time.deltaTime/.1;this.head&&(this.head.position.lerp(this._headTarget.position,e),this.head.quaternion.slerp(this._headTarget.quaternion,e),this.head.scale.lerp(this._headTarget.scale,e)),this.handLeft&&this._handLeftTarget&&(this.handLeft.position.lerp(this._handLeftTarget.position,e),this.handLeft.quaternion.slerp(this._handLeftTarget.quaternion,e),this.handLeft.scale.lerp(this._handLeftTarget.scale,e)),this.handRight&&this._handRightTarget&&(this.handRight.position.lerp(this._handRightTarget.position,e),this.handRight.quaternion.slerp(this._handRightTarget.quaternion,e),this.handRight.scale.lerp(this._handRightTarget.scale,e))}destroy(){sr&&console.log("Destroy avatar",this.guid),this.root?.removeFromParent(),this.avatarMarker?.destroy(),this.lastAvatarId=null,this.head&&ye.Remove(this.context,this.head)}updateVisibility(){let e=this.root;e&&R.setActive(e,this._isVisible)}async setupCustomAvatar(e){if(sr&&console.log("LOAD",e,this),!e||typeof e=="string"&&e.length<=0)return!1;this.head&&ye.Remove(this.context,this.head);let t=e;if(t?.loadAssetAsync!==void 0){await t.loadAssetAsync();let n=t.asset;R.setActive(n,!1),e=R.instantiate(n),R.setActive(e,!0)}sr&&console.log(e);let i=await ua.loader.getOrCreateNewAvatarInstance(this.context,e);if(sr&&console.log(i,i?.isValid,this.lastAvatarId,e),i?.isValid){if(this.root=i.root,this.root.position.set(0,0,0),this.root.quaternion.set(0,0,0,1),this.root.scale.set(1,1,1),this.avatarMarker=R.addNewComponent(this.root,le),this.avatarMarker.connectionId=this.guid,this.avatarMarker.avatar=this,this.head&&this.head!==i.head&&this.head?.removeFromParent(),this.head=i.head,this.headScale.copy(this.head.scale),this.head&&!this.isLocalAvatar&&ye.Add(this.context,this.head,this.avatarMarker),i.leftHand&&this.handLeft?.removeFromParent(),this.handLeft=i.leftHand??this.handLeft,this.handLeft?this.handLeftScale.copy(this.handLeft.scale):this.handLeftScale.set(1,1,1),i.rigthHand&&this.handRight?.removeFromParent(),this.handRight=i.rigthHand??this.handRight,this.handRight?this.handRightScale.copy(this.handRight.scale):this.handRightScale.set(1,1,1),this.context.scene.add(this.root),this.flags==null&&(this.flags=[]),this.flags.length=0,this.flags.push(...R.getComponentsInChildren(this.root,Ee)),this.flags.length<=0&&this.head){let n=R.addNewComponent(this.head,Ee);n.visibleIn=20,this.flags.push(n),sr&&console.log("Added flag to head: "+n.visibleIn,this.head.name)}return sr&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return sr&&console.warn("build avatar failed"),!1}},Gt=ua;I(Gt,"loader",new or),I(Gt,"invertRotation",new m_().setFromAxisAngle(new Zl(0,1,0),Math.PI));var ye=class{static Add(e,t,i=null){if(!!t){for(let n of this.Pois)if(n.obj===t)return;this.Pois.push({obj:t,avatar:i}),this.LastChangeTime=e.time.time}}static Remove(e,t){if(!!t){for(let i of this.Pois)if(i.obj===t){this.Pois.splice(this.Pois.indexOf(i),1),this.LastChangeTime=e?.time.time??G.Current?.time.time;return}}}};I(ye,"Pois",[]),I(ye,"LastChangeTime",0);var Id=class{guid;position=new Tm.Vector3},Sn=class extends M{set controlledTarget(e){this.target=e;let t=O.get("MoveRandom");if(t&&this.target){let i=R.getComponent(this.target,t);i&&i.destroy()}}target=null;avatar=null;_model=null;_targetModel=new Id;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=R.getComponentInParent(this.gameObject,le),this.avatar){let e=R.getComponentInParent(this.gameObject,le);this._model=new Kn(this.context.connection,this.guid),e?.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{this.target&&e&&e.guid===this.avatar?.guid&&ie(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(ye.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=ye.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){let t=B(this._currentTargetObject);ie(this.target,t),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(t))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;let t=ye.Pois;if(t.length>0){let i=t[Math.floor(Math.random()*t.length)];if(i&&i.obj){if(i.avatar&&i.avatar===this.avatar)return;this._currentTargetObject=i.obj}}}}};var Vt=class extends M{canGrab=!0;onPointerClick(e){}},zt=class extends M{isUsed=!0;usedBy=null};import*as Yo from"three";import{Matrix4 as g_,Vector3 as Rm}from"three";var Ad=class{get isDirty(){return this.positionChanged||this.rotationChanged}positionChanged=!1;rotationChanged=!1;position;quaternion;_positionKeys=["x","y","z"];_quaternionKeys=["_x","_y","_z","_w"];reset(e=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,e){if(this.position)for(let t of this._positionKeys)delete this.position[t];if(this.quaternion)for(let t of this._quaternionKeys)delete this.quaternion[t]}}syncValues(){for(let e of this._positionKeys)this.position[e]=this.obj.position[e];for(let e of this._quaternionKeys)this.quaternion[e]=this.obj.quaternion[e]}mute=!1;applyValues(){if(this.positionChanged&&this.position)for(let e of this._positionKeys){let t=this.position[e];t!==void 0&&(this.obj.position[e]=t)}if(this.rotationChanged&&this.quaternion)for(let e of this._quaternionKeys){let t=this.quaternion[e];t!==void 0&&(this.obj.quaternion[e]=t)}}context;obj;_positionWatch;_rotationWatch;constructor(e,t){this.context=t,this.obj=e}start(e,t){this.reset(),e&&(this._positionWatch||(this._positionWatch=new dn(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((r,s)=>{if(this.context.physics.isUpdating||this.mute)return;let a=this.position[s];Math.abs(a-r)<1e-5||(this.position[s]=r,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new dn(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((r,s)=>{if(this.context.physics.isUpdating||this.mute)return;let a=this.quaternion[s];Math.abs(a-r)<1e-5||(this.quaternion[s]=r,this.rotationChanged=!0)}));let i=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),n=new g_;this.obj.matrixWorld.multiplyMatrices=(r,s)=>(n.equals(r)||(this.positionChanged=!0,this.rotationChanged=!0,n.copy(r)),i(r,s))}stop(){this._positionWatch?.revoke(),this._rotationWatch?.revoke()}},$l=class extends M{mass=1;useGravity=!0;constraints=0;isKinematic=!1;drag=0;angularDrag=1;detectCollisions=!0;sleepThreshold=.01;collisionDetectionMode=0;get lockPositionX(){return(this.constraints&2)!==0}get lockPositionY(){return(this.constraints&4)!==0}get lockPositionZ(){return(this.constraints&8)!==0}get lockRotationX(){return(this.constraints&16)!==0}get lockRotationY(){return(this.constraints&32)!==0}get lockRotationZ(){return(this.constraints&64)!==0}set lockPositionX(e){e?this.constraints|=2:this.constraints&=-3}set lockPositionY(e){e?this.constraints|=4:this.constraints&=-5}set lockPositionZ(e){e?this.constraints|=8:this.constraints&=-9}set lockRotationX(e){e?this.constraints|=16:this.constraints&=-17}set lockRotationY(e){e?this.constraints|=32:this.constraints&=-33}set lockRotationZ(e){e?this.constraints|=64:this.constraints&=-65}set gravityScale(e){this._gravityScale=e}get gravityScale(){return this._gravityScale}_gravityScale=1;_propertiesChanged=!1;_currentVelocity=new Yo.Vector3;_smoothedVelocity=new Yo.Vector3;_smoothedVelocityGetter=new Yo.Vector3;_lastPosition=new Yo.Vector3;_watch;awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new Ad(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),2)}onDisable(){this._watch?.stop(),this.context.physics.removeBody(this)}onDestroy(){this.context.physics.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,this.context.physics.updateProperties(this)),this._watch?.isDirty?(this._watch.mute=!0,this._watch.applyValues(),this.context.physics.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):this._watch?.syncValues(),this.captureVelocity(),yield}get body(){return this.context.physics.internal_getRigidbody(this)}teleport(e,t=!0){this._watch?.reset(!0),t?this.gameObject.position.set(e.x,e.y,e.z):this.setWorldPosition(e.x,e.y,e.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(){this.body?.resetForces(!0)}resetTorques(){this.body?.resetTorques(!0)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){this.body?.wakeUp()}applyForce(e,t){this.body?.addForce(e,!0)}applyImpulse(e){this.body?.applyImpulse(e,!0)}setForce(e,t,i){this.body?.resetForces(!0),this.body?.addForce({x:e,y:t,z:i},!0)}getVelocity(){let e=this.body?.linvel();return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(e,t,i){if(e instanceof Rm){let n=e;this.body?.setLinvel(n,!0);return}t===void 0||i===void 0||this.body?.setLinvel({x:e,y:t,z:i},!0)}setAngularVelocity(e,t,i){if(e instanceof Rm){let n=e;this.body?.setAngvel(n,!0);return}t===void 0||i===void 0||this.body?.setAngvel({x:e,y:t,z:i},!0)}getAngularVelocity(){let e=this.body?.angvel();return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setTorque(e,t,i){this.setAngularVelocity(e,t,i)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(e=null){}captureVelocity(){if(this.body){let e=B(this.gameObject);$l.tempPosition.copy(e);let t=e.sub(this._lastPosition);this._lastPosition.copy($l.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}}},J=$l;I(J,"tempPosition",new Yo.Vector3),v([ui(),y()],J.prototype,"mass",2),v([ui(),y()],J.prototype,"useGravity",2),v([ui(),y()],J.prototype,"constraints",2),v([ui(),y()],J.prototype,"isKinematic",2),v([ui(),y()],J.prototype,"drag",2),v([ui(),y()],J.prototype,"angularDrag",2),v([ui(),y()],J.prototype,"detectCollisions",2),v([ui(),y()],J.prototype,"sleepThreshold",2),v([ui(),y()],J.prototype,"collisionDetectionMode",2);import*as Pn from"three";var Ce=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(e,t,i,n){return e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var Ko=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Ce).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Ce).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Ce).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,n,r,s,a,c,u,l){return e.prep(4,36),e.prep(4,12),e.writeFloat32(l),e.writeFloat32(u),e.writeFloat32(c),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(s),e.writeFloat32(r),e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var Wt=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new Wt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+4),(t||new Wt).__init(e.readInt32(e.position())+e.position(),e)}guid(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){let e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){let t=this.bb.__offset(this.bb_pos,8);return t?(e||new Ko).__init(this.bb_pos+t,this.bb):null}dontSave(){let e=this.bb.__offset(this.bb_pos,10);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startSyncedTransformModel(e){e.startObject(4)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addFast(e,t){e.addFieldInt8(1,+t,0)}static addTransform(e,t){e.addFieldStruct(2,t,0)}static addDontSave(e,t){e.addFieldInt8(3,+t,0)}static endSyncedTransformModel(e){return e.endObject()}static finishSyncedTransformModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedTransformModelBuffer(e,t){e.finish(t,void 0,!0)}};var ar=P("debugsync"),Jo="STRS";Ho(Jo,Wt.getRootAsSyncedTransformModel);var Wi=new Ct;function Dd(o,e,t=!0){Wi.clear();let i=Wi.createString(o);Wt.startSyncedTransformModel(Wi),Wt.addGuid(Wi,i),Wt.addFast(Wi,t);let n=e.worldPosition,r=e.worldEuler,s=e.gameObject.scale;Wt.addTransform(Wi,Ko.createTransform(Wi,n.x,n.y,n.z,r.x,r.y,r.z,s.x,s.y,s.z));let a=Wt.endSyncedTransformModel(Wi);return Wi.finish(a,Jo),Wi.asUint8Array()}var Pt=class extends M{overridePhysics=!0;interpolatePosition=!0;interpolateRotation=!0;fastMode=!1;syncDestroy=!1;_model=null;_needsUpdate=!0;rb=null;_wasKinematic=!1;_receivedDataBefore=!1;_targetPosition;_targetRotation;_receivedFastUpdate=!1;_shouldRequestOwnership=!1;requestOwnership(){ar&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){return this._model?.hasOwnership??void 0}isOwned(){return this._model?.isOwned}joinedRoomCallback=null;receivedDataCallback=null;awake(){ar&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new Pn.Vector3,this._targetRotation=new Pn.Quaternion,this.lastWorldPos=new Pn.Vector3,this.lastWorldRotation=new Pn.Quaternion,this.rb=R.getComponentInChildren(this.gameObject,J),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Kn(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen("joined-room",this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinrary(Jo,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Kp(this.guid,this.context.connection),this._model=null,this.context.connection.stopListening("joined-room",this.joinedRoomCallback),this.context.connection.stopListenBinary(Jo,this.receivedDataCallback)}tryGetLastState(){let e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new Pn.Euler;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){ar&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();let t=e.transform();if(t){oe.markDirty(this.gameObject,!0);let i=t.position();i&&(this.interpolatePosition&&this._targetPosition?.set(i.x(),i.y(),i.z()),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(i.x(),i.y(),i.z()));let n=t.rotation();n&&(this.tempEuler.set(n.x(),n.y(),n.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&Fp(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}receivedUpdate=!1;lastWorldPos;lastWorldRotation;onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){ar&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());let e=this.worldPosition,t=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){let r=e.distanceTo(this.lastWorldPos),s=t.angleTo(this.lastWorldRotation),a=this._model.hasOwnership||this.fastMode?1e-4:.001;(r>a||s>a)&&(this._model.hasOwnership?this._needsUpdate=!0:(ar&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,e.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,t.copy(this.lastWorldRotation),oe.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){let s=this._receivedFastUpdate||this.fastMode?.5:.3,a=!1;if(this.interpolatePosition&&this._targetPosition){let c=this.worldPosition;c.lerp(this._targetPosition,s),this.worldPosition=c,a=!0}if(this.interpolateRotation&&this._targetRotation){let c=this.worldQuaternion;c.slerp(this._targetRotation,s),this.worldQuaternion=c,a=!0}a&&oe.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(e),this.lastWorldRotation.copy(t),!this._model)return;if(!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership){this.rb&&(this.rb.isKinematic=this._model.isOwned??!1,this.rb.setVelocity(0,0,0));return}this.rb&&(this._wasKinematic!==void 0&&(ar&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new Pn.Vector3(0,0,0))>1e3&&(ar&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0)));let i=10,n=this.rb||this.fastMode;if(this._needsUpdate&&(i<=0||i>0&&this.context.time.frameCount%i===0||n)){ar&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this.overridePhysics&&this.rb,this._needsUpdate=!1;let r=Dd(this.guid,this,!!n);this.context.connection.sendBinary(r)}}};import*as oc from"three-mesh-ui";import{Euler as C_,EventDispatcher as T_,Group as R_,Matrix4 as S_,Mesh as P_,MeshBasicMaterial as O_,Object3D as Mm,Quaternion as rc,RingGeometry as k_,Vector3 as Im}from"three";var ec=class{static createButton(e,t={}){let i=document.createElement("button"),n=!1;function r(){if(t.domOverlay===void 0){var u=document.createElement("div");u.style.display="none",document.body.appendChild(u);var l=document.createElementNS("http://www.w3.org/2000/svg","svg");l.setAttribute("width",38),l.setAttribute("height",38),l.style.position="absolute",l.style.right="20px",l.style.top="20px",l.addEventListener("click",function(){h.end()}),u.appendChild(l);var d=document.createElementNS("http://www.w3.org/2000/svg","path");d.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),d.setAttribute("stroke","#fff"),d.setAttribute("stroke-width",2),l.appendChild(d),t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("dom-overlay"),t.domOverlay={root:u},n=!0}t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("local-floor"),t.optionalFeatures.push("hand-tracking"),t.optionalFeatures.push("layers");let h=null,g=null;async function E(x){if(/WebXRViewer\//i.test(navigator.userAgent))if(t.domOverlay?.root){let f=t.domOverlay.root;g=f.parentElement,g&&(console.log("Reparent DOM Overlay to body",f,f.style.display),f.style.display="",f.style.visibility="",document.body.appendChild(f))}else console.warn("WebXRViewer: No DOM Overlay found");x.addEventListener("end",_),await e.xr.setSession(x),i.textContent="STOP AR",n&&(t.domOverlay.root.style.display=""),h=x}function _(){h.removeEventListener("end",_),i.textContent="START AR",g&&g.appendChild(t.domOverlay.root),n&&(t.domOverlay.root.style.display="none"),h=null}i.style.display="",i.style.cursor="pointer",i.style.left="calc(50% - 50px)",i.style.width="100px",i.textContent="START AR",i.onmouseenter=function(){i.style.opacity="1.0"},i.onmouseleave=function(){i.style.opacity="0.5"},i.onclick=function(){h===null?navigator.xr.requestSession("immersive-ar",t).then(E):h.end()}}function s(){i.disabled=!0,i.style.display="",i.style.cursor="auto",i.style.left="calc(50% - 75px)",i.style.width="150px",i.onmouseenter=null,i.onmouseleave=null,i.onclick=null}function a(){s(),i.textContent="AR NOT SUPPORTED"}function c(u){u.style.position="absolute",u.style.bottom="20px",u.style.padding="12px 6px",u.style.border="1px solid #fff",u.style.borderRadius="4px",u.style.background="rgba(0,0,0,0.1)",u.style.color="#fff",u.style.font="normal 13px sans-serif",u.style.textAlign="center",u.style.opacity="0.5",u.style.outline="none",u.style.zIndex="999"}if("xr"in navigator)return i.id="ARButton",i.style.display="none",c(i),navigator.xr.isSessionSupported("immersive-ar").then(function(u){u?r():a()}).catch(a),i;{let u=document.createElement("a");return window.isSecureContext===!1?(u.href=document.location.href.replace(/^http:/,"https:"),u.innerHTML="WEBXR NEEDS HTTPS"):(u.href="https://immersiveweb.dev/",u.innerHTML="WEBXR NOT AVAILABLE"),u.style.left="calc(50% - 90px)",u.style.width="180px",u.style.textDecoration="none",c(u),u}}};var tc=class{static createButton(e,t){t&&console.error('THREE.VRButton: The "options" parameter has been removed. Please set the reference space type via renderer.xr.setReferenceSpaceType() instead.');let i=document.createElement("button");function n(){let c=null;async function u(d){d.addEventListener("end",l),await e.xr.setSession(d),i.textContent="EXIT VR",c=d}function l(){c.removeEventListener("end",l),i.textContent="ENTER VR",c=null}i.style.display="",i.style.cursor="pointer",i.style.left="calc(50% - 50px)",i.style.width="100px",i.textContent="ENTER VR",i.onmouseenter=function(){i.style.opacity="1.0"},i.onmouseleave=function(){i.style.opacity="0.5"},i.onclick=function(){if(c===null){let d={optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};navigator.xr.requestSession("immersive-vr",d).then(u)}else c.end()}}function r(){i.disabled=!0,i.style.display="",i.style.cursor="auto",i.style.left="calc(50% - 75px)",i.style.width="150px",i.onmouseenter=null,i.onmouseleave=null,i.onclick=null}function s(){r(),i.textContent="VR NOT SUPPORTED"}function a(c){c.style.position="absolute",c.style.bottom="20px",c.style.padding="12px 6px",c.style.border="1px solid #fff",c.style.borderRadius="4px",c.style.background="rgba(0,0,0,0.1)",c.style.color="#fff",c.style.font="normal 13px sans-serif",c.style.textAlign="center",c.style.opacity="0.5",c.style.outline="none",c.style.zIndex="999"}if("xr"in navigator)return i.id="VRButton",i.style.display="none",a(i),navigator.xr.isSessionSupported("immersive-vr").then(function(c){c?n():s(),tc.xrSessionIsGranted&&(console.log("XR session is granted - will enter immersive web now"),i.click())}),i;{let c=document.createElement("a");return window.isSecureContext===!1?(c.href=document.location.href.replace(/^http:/,"https:"),c.innerHTML="WEBXR NEEDS HTTPS"):(c.href="https://immersiveweb.dev/",c.innerHTML="WEBXR NOT AVAILABLE"),c.style.left="calc(50% - 90px)",c.style.width="180px",c.style.textDecoration="none",a(c),c}}static registerSessionGrantedListener(){if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent))return;navigator.xr.addEventListener("sessiongranted",()=>{tc.xrSessionIsGranted=!0})}}},$o=tc;I($o,"xrSessionIsGranted",!1);$o.registerSessionGrantedListener();import*as ic from"three";var Sm=ja(fl(),1);import{AudioAnalyser as b_}from"three";var es="noVoip",ft=P("debugvoip"),v_=P("voip");var Ld=class{id;constructor(e){this.id=e}};var jd=class{peer;voip;userId;peerId;call=null;callErrorListener=null;stream=null;constructor(e,t,i,n){this.voip=e,this.peer=t,this.userId=i,this.peerId=n}close(){ft&&console.log("close voip call"),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.open&&this.call.close(),this.stream?.getTracks().forEach(function(e){e.stop()})}updateMute(e){if(!this.stream)return;let t=this.stream?.getAudioTracks();for(let i of t)i.enabled=!e}async startVoipCall(){if(!await rt.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}ft&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),ft&&console.log(this.stream),this.call=this.peer.call(this.peerId,this.stream,{metadata:{userId:this.userId}}),this.call.on("error",t=>{console.error(t)}),this.call.on("stream",t=>{ft&&console.log("received stream from remote again",t)}),this.peer.on("close",this.onCallClose.bind(this)),this.callErrorListener=t=>{t.message.includes(this.peerId)?(console.log("Could not connect to "+this.peerId),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.close(),this.stream?.getTracks().forEach(function(i){i.stop()}),this.stream=null):console.error(t)},this.peer.on("error",this.callErrorListener)}onCallClose(e){ft&&console.log("call closed",e)}},Hd=class{get currentStream(){return this.stream}get currentAudio(){return this.audio}get currentAnalyzer(){return this.analyzer}voip;call;audio=null;stream=null;obj;analyzer=null;waitingForStart=!1;closed=!1;audioElement=null;constructor(e,t,i){this.voip=e,this.obj=t,this.call=i}openAudioStream(e){let t=e.getAudioTracks();for(let i of t)if(i.kind==="audio"&&i.readyState==="live"){this.open(i);return}console.warn("failed finding valid audio stream to begin call")}open(e){console.assert(e.kind==="audio","invalid track kind, expected audio but received "+e.kind),!this.waitingForStart&&(this.waitingForStart=!0,se.userInteractionRegistered||ft&&console.log("Incoming call, waiting for user interaction before opening audio"),se.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){ft&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);let t=new ic.AudioListener;this.audio=new ic.Audio(t),this.audio.setVolume(this.voip.muteInput?0:1),this.audio.setMediaStreamSource(this.stream);let i=document.createElement("audio");this.audioElement=i,i.style.display="none",document.body.appendChild(i),i.srcObject=this.stream,i.sinkId!==void 0&&navigator.mediaDevices.enumerateDevices().then(n=>{if(!!i){console.log(n);for(let r of n)if(r.label==="Speakerphone"){i.sinkId=r.deviceId;break}}}),ft&&console.log("call is setup, you should hear something now"),this.analyzer=new b_(this.audio,32)}}))}close(){this.closed=!0,this.call?.open&&this.call.close(),this.audio?.disconnect(),this.stream?.getTracks().forEach(e=>{e.stop()}),this.stream=null,this.audioElement&&this.audioElement.remove()}},rt=class extends M{requireParam=!1;set muteInput(e){if(e===this._inputMuted||(this._inputMuted=e,!this.currentIncomingCalls))return;let t=this._inputMuted?0:1;for(let i in this.currentIncomingCalls)this.currentIncomingCalls[i]?.currentAudio?.setVolume(t)}get muteInput(){return this._inputMuted}set muteOutput(e){if(e!==this._outputMuted&&(this._outputMuted=e,!!this.connections))for(let t in this.connections)this.connections[t]?.updateMute(e)}get muteOutput(){return this._outputMuted}getFrequency(e){if(e===null){for(let i in this.currentIncomingCalls){let n=this.currentIncomingCalls[i];if(n&&n.currentAnalyzer)return n.currentAnalyzer.getAverageFrequency()}return null}let t=this.currentIncomingCalls[e];return t&&t.currentAnalyzer?t.currentAnalyzer.getAverageFrequency():null}peer=null;model=null;connections={};currentIncomingCalls={};_inputMuted=!1;_outputMuted=!1;awake(){if(P(es)){console.log("VOIP is disabled by url parameter: "+es);return}if(this.requireParam&&!v_){console.debug("VOIP must be enabled explicitly by url parameter");return}if(wo()&&Fa()){console.log("VOIP is currently not supported on Safari iOS");return}this.peer=new Sm.default,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,this.context.connection.beginListen("joined-room",e=>{navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}),this.context.connection.beginListen("peer-update-id",e=>{if(e.id!==this.context.connection.connectionId){let t=this.connections[e.id];if(t&&t.close(),this.peer&&this.context.connection.connectionId){let i=new jd(this,this.peer,this.context.connection.connectionId,e.peerId);this.connections[e.id]=i,i.startVoipCall()}}}),this.context.connection.beginListen("user-left-room",e=>{let{userId:t}=e,i=this.connections[t];this.connections[t]=null,i&&i.close();let n=this.currentIncomingCalls[t];ft&&console.log("UserLeftRoom",e,t,n),n&&(n.close(),this.currentIncomingCalls[t]=null)}),this.peer.on("open",this.onOpenPeerConnection.bind(this))}onEnable(){}onDisable(){console.log("TODO: close all");for(let e in this.currentIncomingCalls)try{this.currentIncomingCalls[e]?.close(),this.connections[e]?.close()}catch(t){console.error(t)}}async onOpenPeerConnection(e){ft&&console.log("Peer connection established and received id"),this.model=new Ld(e),this.context.connection.send("peer-update-id",this.model,1),this.peer&&(this.peer.on("call",this.onReceiveCall.bind(this)),this.peer.on("connection",function(t){ft&&console.log("CONNECTION",t),t.on("data",function(i){ft&&console.log("Received",i)})}))}async onReceiveCall(e){let{metadata:t}=e;console.assert(t.userId);let{userId:i}=t,{peer:n}=e,r=this.currentIncomingCalls[i];if(r&&r.close(),ft&&console.log("received call"),await rt.HasMicrophonePermissions()){let s=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(s)}else e.answer(null);this.currentIncomingCalls[i]=new Hd(this,this.gameObject,e),e.on("stream",s=>{ft&&console.log("receive caller stream, will setup audio now"),this.currentIncomingCalls[i]?.openAudioStream(s)}),e.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}};import{Matrix4 as da}from"three";var mt=class extends M{webAR=null;get rig(){return this.webAR?.webxr.Rig}invertForward=!1;get arScale(){return this._arScale}set arScale(e){e!==this._arScale&&(this._arScale=e,this.setScale(e))}_initalMatrix=new da;_selectStartFn=this.onSelectStart.bind(this);_selectEndFn=this.onSelectEnd.bind(this);start(){let e=R.findObjectOfType(V);e&&(e.Rig.updateMatrix(),this._initalMatrix.copy(e.Rig.matrix))}_arScale=5;_rig=null;_startPose=null;_placementPose=null;_isTouching=!1;_rigStartPose=null;onBegin(e){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose=this.gameObject.matrix.clone(),this._rigStartPose=this.rig?.matrix.clone(),e.addEventListener("selectstart",this._selectStartFn),e.addEventListener("selectend",this._selectEndFn),this.gameObject.visible=!1,this.rig&&(this.rig.matrixAutoUpdate=!0,this._initalMatrix.decompose(this.rig.position,this.rig.quaternion,this.rig.scale))}onUpdate(e,t,i){return i&&!this._placementPose&&this._isTouching?(this.webAR&&this.webAR.setReticleActive(!1),this.placeAt(e,new da().fromArray(i.transform.matrix).invert()),!0):!1}placeAt(e,t){this._placementPose||(this._placementPose=new da),this._placementPose.copy(t);let i=this.gameObject.matrixWorld.clone().invert();if(this._placementPose.premultiply(i),e){if(this.invertForward){let n=new da().makeRotationY(Math.PI);this._placementPose.premultiply(n)}this._rig=e,this.setScale(this.arScale)}else this._rig=null;this.gameObject.visible=!0}onEnd(e,t){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose&&this.gameObject.matrix.copy(this._startPose),e&&(e.matrixAutoUpdate=!0,this._rigStartPose&&this._rigStartPose.decompose(e.position,e.quaternion,e.scale)),oe.markDirty(this.gameObject,!0),setTimeout(()=>{this.gameObject.matrixAutoUpdate=!0,this.gameObject.visible=!0},100)}onSelectStart(){this._isTouching=!0}onSelectEnd(){this._isTouching=!1}setScale(e){let t=this._rig;!t||!this._placementPose||(this._rigStartPose||(this._rigStartPose=t.matrix.clone()),t.matrixAutoUpdate=!1,t.matrix.multiplyMatrices(new da().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld(),console.log("Place",t.position))}};v([y()],mt.prototype,"invertForward",2),v([y()],mt.prototype,"arScale",1);import{Object3D as __}from"three";import*as Pm from"three";import{Color as y_}from"three";var _i=class extends M{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!Di||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new Pm.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=cl(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),3)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}};v([y()],_i.prototype,"objectBounds",2),v([y(y_)],_i.prototype,"color",2),v([y()],_i.prototype,"isGizmo",2);var x_=P("debugrig"),lr=class extends M{awake(){if(x_){let e=new __;e.position.y+=.5,this.gameObject.add(e);let t=e.addNewComponent(_i);t&&(t.isGizmo=!1)}}};import{Quaternion as ha,Vector3 as nc,Vector4 as w_}from"three";var Ni=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}w(){return this.bb.readFloat32(this.bb_pos+12)}static sizeOf(){return 16}static createVec4(e,t,i,n,r){return e.prep(4,16),e.writeFloat32(r),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var Oe=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsVrUserStateBuffer(e,t){return(t||new Oe).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+4),(t||new Oe).__init(e.readInt32(e.position())+e.position(),e)}guid(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}time(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}avatarId(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__string(this.bb_pos+t,e):null}position(e){let t=this.bb.__offset(this.bb_pos,10);return t?(e||new Ce).__init(this.bb_pos+t,this.bb):null}rotation(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new Ni).__init(this.bb_pos+t,this.bb):null}scale(){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.readFloat32(this.bb_pos+e):0}posLeftHand(e){let t=this.bb.__offset(this.bb_pos,16);return t?(e||new Ce).__init(this.bb_pos+t,this.bb):null}posRightHand(e){let t=this.bb.__offset(this.bb_pos,18);return t?(e||new Ce).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){let t=this.bb.__offset(this.bb_pos,20);return t?(e||new Ni).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){let t=this.bb.__offset(this.bb_pos,22);return t?(e||new Ni).__init(this.bb_pos+t,this.bb):null}static startVrUserStateBuffer(e){e.startObject(10)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addTime(e,t){e.addFieldInt64(1,t,e.createLong(0,0))}static addAvatarId(e,t){e.addFieldOffset(2,t,0)}static addPosition(e,t){e.addFieldStruct(3,t,0)}static addRotation(e,t){e.addFieldStruct(4,t,0)}static addScale(e,t){e.addFieldFloat32(5,t,0)}static addPosLeftHand(e,t){e.addFieldStruct(6,t,0)}static addPosRightHand(e,t){e.addFieldStruct(7,t,0)}static addRotLeftHand(e,t){e.addFieldStruct(8,t,0)}static addRotRightHand(e,t){e.addFieldStruct(9,t,0)}static endVrUserStateBuffer(e){return e.endObject()}static finishVrUserStateBufferBuffer(e,t){e.finish(t)}static finishSizePrefixedVrUserStateBufferBuffer(e,t){e.finish(t,void 0,!0)}};var Om=P("debugxr"),pa=P("debugavatar");var Bd="VRUS";Ho(Bd,Oe.getRootAsVrUserStateBuffer);function Fd(){return new Date().getTime()}function E_(o){let e=o&4294967295,t=o/Math.pow(2,32)&1048575;return Ye.create(e,t)}var fa=class{guid;time;avatarId;position=new nc;rotation=new w_;scale=1;posLeftHand=new nc;posRightHand=new nc;rotLeftHand=new ha;rotRightHand=new ha;constructor(e){this.guid=e}update(e,t,i,n,r){this.time=Fd(),this.avatarId=r,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let s=fa.quat0,a=fa.quat1;s.set(i.x,i.y,i.z,i.w),s=s.multiplyQuaternions(s,fa.invertRotation),e&&(e.getWorldQuaternion(a),s.multiplyQuaternions(a,s)),this.rotation.set(s.x,s.y,s.z,s.w),this.scale=e.scale.x;let c=n.LeftController?.controllerGrip;c&&(c.getWorldPosition(this.posLeftHand),c.getWorldQuaternion(this.rotLeftHand));let u=n.RightController?.controllerGrip;if(u&&(u.getWorldPosition(this.posRightHand),u.getWorldQuaternion(this.rotRightHand)),n.LeftController?.hand?.visible){let l=n.LeftController.wrist;l&&(l.getWorldPosition(this.posLeftHand),l.getWorldQuaternion(this.rotLeftHand))}if(n.RightController?.hand?.visible){let l=n.RightController.wrist;l&&(l.getWorldPosition(this.posRightHand),l.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(e,t){e.clear();let i=e.createString(this.guid),n=e.createString(this.avatarId);Oe.startVrUserStateBuffer(e),Oe.addGuid(e,i),Oe.addTime(e,E_(this.time)),Oe.addAvatarId(e,n),Oe.addPosition(e,Ce.createVec3(e,this.position.x,this.position.y,this.position.z)),Oe.addRotation(e,Ni.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),Oe.addScale(e,this.scale),Oe.addPosLeftHand(e,Ce.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),Oe.addPosRightHand(e,Ce.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),Oe.addRotLeftHand(e,Ni.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),Oe.addRotRightHand(e,Ni.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));let r=Oe.endVrUserStateBuffer(e);e.finish(r,Bd);let s=e.asUint8Array();t.sendBinary(s)}setFromBuffer(e,t){if(!e)return;this.guid=e,this.time=t.time().toFloat64();let i=t.avatarId();i&&(this.avatarId=i);let n=t.position();n&&this.position.set(n.x(),n.y(),n.z());let r=t.rotation();r&&this.rotation.set(r.x(),r.y(),r.z(),r.w());let s=t.posLeftHand();s&&this.posLeftHand.set(s.x(),s.y(),s.z());let a=t.posRightHand();a&&this.posRightHand.set(a.x(),a.y(),a.z());let c=t.rotLeftHand();c&&this.rotLeftHand.set(c.x(),c.y(),c.z(),c.w());let u=t.rotRightHand();u&&this.rotRightHand.set(u.x(),u.y(),u.z(),u.w()),this.scale=t.scale()}},Nt=fa;I(Nt,"invertRotation",new ha().setFromAxisAngle(new nc(0,1,0),Math.PI)),I(Nt,"quat0",new ha),I(Nt,"quat1",new ha);var On=class extends M{webXR=null;debugAvatarUser=null;voip=null;async awake(){if(this.webXR||(this.webXR=R.getComponent(this.gameObject,V)),this.webXR||(this.webXR=R.findObjectOfType(V,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=R.findObjectOfType(V,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=R.findObjectOfType(rt,this.context)),pa){let e="debug-avatar-"+pa,t=new Gt(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof pa=="string"&&pa.length>0)if(await t.setAvatarOverride(pa)){let i=new Nt(e);i.position.y+=1;let n=.5;i.posLeftHand.y+=n,i.posLeftHand.x+=n,i.posRightHand.y+=n,i.posRightHand.x-=n,t.tryUpdate(i,0)}else t.destroy()}}onEnable(){if(!this.webXR&&(this.webXR=R.getComponent(this.gameObject,V),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),V.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),V.addEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),V.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.eventSub_ConnectionEvent=this.onConnected.bind(this),this.context.connection.beginListen("joined-room",this.eventSub_ConnectionEvent),this.context.connection.beginListen("webxr-user-joined",e=>{console.log("webxr user joined evt")}),this.context.connection.beginListen("webxr-user-left",e=>{let t=e.id!==null&&e.id!==void 0;!t||(console.log("webxr user left evt"),t&&(this.avatars[e.id]?.destroy(),this.avatars[e.id]=void 0))}),this.context.connection.beginListenBinrary(Bd,e=>{let t=e.guid();if(!t)return;let i=e.time().toFloat64(),n=this.tempState;n.setFromBuffer(t,e),this.onTryGetAvatar(t,i)?.tryUpdate(n,i)}),this.context.connection.beginListen("vr-session-update",e=>{let t=e.guid,i=e.time;this.onTryGetAvatar(t,i)?.tryUpdate(e,i)})}tempState=new Nt("");onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;let i=new Date().getTime()-t;if(i>5e3)return Om&&console.log("old data",i,e),null;let n=this.avatars[e];if(n===void 0)try{console.log("create new avatar");let r=new Gt(this.context,e,this.webXR);n=r,this.avatars[e]=r}catch(r){this.avatars[e]=null,console.error(r)}return n}onDisable(){this.eventSub_ConnectionEvent&&this.context.connection.stopListening("joined-room",this.eventSub_ConnectionEvent),V.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),V.removeEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),V.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}update(){let e=Fd();this.debugAvatarUser&&(this.debugAvatarUser.lastUpdate=e),this.detectPotentiallyDisconnectedAvatarsAndRemove();for(let t in this.avatars){let i=this.avatars[t];!i||i.update()}}_removeAvatarsList=[];detectPotentiallyDisconnectedAvatarsAndRemove(){let e=Fd();for(let t in this.avatars){let i=this.avatars[t];if(!i){this._removeAvatarsList.push(t);continue}e-i.lastUpdate>1e4&&(console.log("avatar timed out (didnt receive any updates in a while) - destroying it now"),i.destroy(),this.avatars[t]=void 0)}for(let t of this._removeAvatarsList)delete this.avatars[t];this._removeAvatarsList.length=0}buildLocalAvatar(){if(this.localAvatar)return;let e=this.context.connection?.connectionId??this.k_LocalAvatarNoNetworkingGuid;this.localAvatar=new Gt(this.context,e,this.webXR),this.localAvatar.isLocalAvatar=!0,this.localAvatar.setAvatarOverride(this.getAvatarId()),this.avatars[this.localAvatar.guid]=this.localAvatar}eventSub_ConnectionEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;eventSub_WebXRUpdateEvent=null;avatars={};localAvatar=null;k_LocalAvatarNoNetworkingGuid="local";onConnected(){Om&&console.log("Hey you are connected as "+this.context.connection.connectionId),this.localAvatar?.guid===this.k_LocalAvatarNoNetworkingGuid&&(this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0),this.localAvatar=null,this.xrState=null,this.ownership?.freeOwnership(),this.ownership=null)}onXRSessionStart(e){if(console.log("XR session started"),this.context.connection.send("webxr-user-joined",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null),this.xrState=null,this.ownership?.freeOwnership(),this.ownership=null,this.avatars)for(let t in this.avatars)this.avatars[t]?.updateFlags()}onXRSessionEnded(e){console.log("XR session ended"),this.context.connection.send("webxr-user-left",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null)}ownership=null;xrState=null;builder=new Ct(1024);onXRSessionUpdate(e){this.xrState??=new Nt(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership??=new Kn(this.context.connection,this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership.guid=this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid,this.buildLocalAvatar();let{frame:t,xr:i,rig:n}=e,r=t.getViewerPose(i.getReferenceSpace());if(!r)return;let s=r?.transform,a=s.position,c=s.orientation;this.xrState.update(n,a,c,this.webXR,this.getAvatarId()),this.localAvatar&&(this.context.connection.connectionId&&(this.localAvatar.guid=this.context.connection.connectionId),this.localAvatar.tryUpdate(this.xrState,0)),!(this.ownership&&!this.ownership.hasOwnership&&this.context.connection.isConnected&&(this.context.time.frameCount%120===0&&this.ownership.requestOwnership(),!this.ownership.hasOwnership))&&(!this.context.connection.isConnected||!this.context.connection.connectionId||this.xrState.sendAsBuffer(this.builder,this.context.connection))}getAvatarId(){return P("avatar")??null}};async function M_(){return Ha()?!0:"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function I_(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}var Ud=!1,Gd=!1;M_().then(o=>Ud=o);I_().then(o=>Gd=o);var Le=class extends M{enableVR=!0;enableAR=!0;defaultAvatar;handModelPath="";createVRButton=!0;createARButton=!0;static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(Ud||Gd)}static get IsARSupported(){return Ud}static get IsVRSupported(){return Gd}static addEventListener(e,t){return this.events.addEventListener(e,t),t}static removeEventListener(e,t){return this.events.removeEventListener(e,t),t}static createVRButton(e,t){Le.XRSupported?e.__internalAwake():console.warn("WebXR is not supported on this device");let i=$o.createButton(e.context.renderer);return i.classList.add("webxr-ar-button"),i.classList.add("webxr-button"),this.resetButtonStyles(i),(t?.registerClick??!0)&&i.addEventListener("click",e.onClickedVRButton.bind(e)),i}static createARButton(e,t){e.__internalAwake();let i=e.webAR?.getAROverlayContainer(),n={};i?(n.domOverlay={root:i},n.optionalFeatures=["hit-test","dom-overlay"]):console.warn("No dom overlay root found, HTML overlays on top of screen-based AR will not work."),n.optionalFeatures.push("plane-detection"),n.optionalFeatures.push("anchors");let r=ec.createButton(e.context.renderer,n);return r.classList.add("webxr-ar-button"),r.classList.add("webxr-button"),Le.resetButtonStyles(r),(t?.registerClick??!0)&&r.addEventListener("click",e.onClickedARButton.bind(e)),r}static resetButtonStyles(e){!e||(e.style.position="",e.style.bottom="",e.style.left="")}endSession(){let e=this.context.renderer.xr.getSession();e&&e.end()}get Rig(){return this.rig||this.ensureRig(),this.rig}controllers=[];get Controllers(){return this.controllers}get LeftController(){return this.controllers.length>0&&this.controllers[0].input?.handedness==="left"?this.controllers[0]:this.controllers.length>1&&this.controllers[1].input?.handedness==="left"?this.controllers[1]:null}get RightController(){return this.controllers.length>0&&this.controllers[0].input?.handedness==="right"?this.controllers[0]:this.controllers.length>1&&this.controllers[1].input?.handedness==="right"?this.controllers[1]:null}get ARButton(){return this._arButton}get VRButton(){return this._vrButton}get IsInVR(){return this._isInVR}get IsInAR(){return this._isInAR}rig;isInit=!1;_requestedAR=!1;_requestedVR=!1;_isInAR=!1;_isInVR=!1;_arButton;_vrButton;webAR=null;awake(){if(this.defaultAvatar&&typeof this.defaultAvatar=="string"&&(this.defaultAvatar=it.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!R.findObjectOfType(On,this.context)){let e=R.addNewComponent(this.gameObject,On,!1);e.webXR=this}this.webAR=new cr(this)}onEnable(){if(this.isInit||!this.enableAR&&!this.enableVR)return;this.isInit=!0,this.context.renderer.xr.enabled=!0;let e=Le.XRSupported,t,i,n=document.createElement("div");n.classList.add("webxr-buttons"),this.context.domElement.append(n),this.enableAR&&this.createARButton&&(t=Le.createARButton(this),this._arButton=t,n.appendChild(t)),this.createVRButton&&this.enableVR&&(i=Le.createVRButton(this),this._vrButton=i,n.appendChild(i)),setTimeout(()=>{Le.resetButtonStyles(i),Le.resetButtonStyles(t)},1e3)}_transformOrientation=new rc;get TransformOrientation(){return this._transformOrientation}_currentHeadPose=null;get HeadPose(){return this._currentHeadPose}onBeforeRender(e){if(!e)return;let t=this.context.renderer.xr.getSession();if(t){let i=e.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(!i)return;this._currentHeadPose=i;let n=i?.transform;n&&this._transformOrientation.set(n.orientation.x,n.orientation.y,n.orientation.z,n.orientation.w),Le._isInXr===!1&&t&&this.onEnterXR(t,e);for(let r of this.controllers)r.onUpdate(t);this._isInAR&&this.webAR?.onUpdate(t,e)}Le.events.dispatchEvent({type:"xrUpdate",frame:e,xr:this.context.renderer.xr,rig:this.rig})}onClickedARButton(){this._isInAR||(this._requestedAR=!0,this._requestedVR=!1,this.captureStateBeforeXR())}onClickedVRButton(){if(!this._isInVR){if(this._requestedVR){this.onExitXR(null);return}this._requestedAR=!1,this._requestedVR=!0,this.captureStateBeforeXR(),this.ensureRig();for(let e=0;e<2;e++)$.Create(this,e,this.gameObject,0);Le.events.dispatchEvent({type:"requestVRSession"})}}captureStateBeforeXR(){this.context.mainCamera&&(this._originalCameraPosition.copy(B(this.context.mainCamera)),this._originalCameraRotation.copy(me(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent),this.Rig&&(this._originalXRRigParent=this.Rig.parent,this._originalXRRigPosition.copy(this.Rig.position),this._originalXRRigRotation.copy(this.Rig.quaternion))}ensureRig(){if(!this.rig){let e=R.findObjectOfType(lr,this.context);e?this.rig=e.gameObject:(this.rig=new R_,this.rig.rotateY(Math.PI),this.rig.name="XRRig",this.context.scene.add(this.rig))}}_originalCameraParent=null;_originalCameraPosition=new Im;_originalCameraRotation=new rc;_originalXRRigParent=null;_originalXRRigPosition=new Im;_originalXRRigRotation=new rc;onEnterXR(e,t){console.log("[XR] session begin",e),Le._isInXr=!0,this.ensureRig();let i=this.context.renderer.xr.getReferenceSpace();if(i&&this.rig){let a=t.getViewerPose(i)?.transform.orientation;if(a){let c=new rc(a.x,a.y,a.z,a.w),u=new C_().setFromQuaternion(c);this.rig.rotateY(u.y)}}let n=this.context.renderer.xr;if(this.context.mainCamera){let s=n.getCamera(this.context.mainCamera);for(let a of s.cameras)a.layers.enableAll();this.rig.add(this.context.mainCamera),this._requestedAR&&this.context.scene.add(this.rig)}let r=this._requestedAR?2:4;switch(St.Global.Set(r),r){case 2:this.context.xrSessionMode="immersive-ar",this._isInAR=!0,this.webAR?.onBegin(e);break;case 4:this.context.xrSessionMode="immersive-vr",this._isInVR=!0,this.onEnterVR(e);break}e.addEventListener("end",()=>{console.log("[XR] session end"),Le._isInXr=!1,this.onExitXR(e)}),this.onEnterXR_HandleMirrorWindow(e),Le.events.dispatchEvent({type:"xrStarted",session:e})}onExitXR(e){let t=this._isInAR;this._isInAR&&e&&this.webAR?.onEnd(e),this._isInAR=!1,this._isInVR=!1,this._requestedAR=!1,this._requestedVR=!1,this.context.xrSessionMode=void 0,this.xrMirrorWindow&&(this.xrMirrorWindow.close(),this.xrMirrorWindow=null),this.destroyControllers(),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),ie(this.context.mainCamera,this._originalCameraPosition),et(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),t&&(this._originalXRRigParent?.add(this.rig),this.rig.position.copy(this._originalXRRigPosition),this.rig.quaternion.copy(this._originalXRRigRotation)),St.Global.Set(17),Le.events.dispatchEvent({type:"xrStopped",session:e})}onEnterVR(e){}destroyControllers(){for(let e=this.controllers.length-1;e>=0;e-=1)this.controllers[e]?.destroy();this.controllers.length=0}xrMirrorWindow=null;onEnterXR_HandleMirrorWindow(e){!P("mirror")||setTimeout(()=>{if(!Le.IsInWebXR)return;let t=new URL(window.location.href);yo(t.searchParams,es,1),yo(t.searchParams,"isMirror",1);let i=t.toString();this.xrMirrorWindow=window.open(i,"webxr sync","popup=yes"),this.xrMirrorWindow&&(this.xrMirrorWindow.onload=()=>{this.xrMirrorWindow&&(this.xrMirrorWindow.onbeforeunload=()=>{Le.IsInWebXR&&e.end()})})},1e3)}},V=Le;I(V,"_isInXr",!1),I(V,"events",new T_),v([y()],V.prototype,"enableVR",2),v([y()],V.prototype,"enableAR",2),v([y(it)],V.prototype,"defaultAvatar",2),v([y()],V.prototype,"handModelPath",2),v([y()],V.prototype,"createVRButton",2),v([y()],V.prototype,"createARButton",2);var ts=class{get webxr(){return this._webxr}_webxr;reticle=null;reticleParent=null;hitTestSource=null;reticleActive=!0;previousBackground=null;previousEnvironment=null;sessionRoot=null;_previousParent=null;get context(){return this.webxr.context}constructor(e){this._webxr=e}arDomOverlay=null;arOverlayElement=null;noHitTestAvailable=!1;didPlaceARSessionRoot=!1;getAROverlayContainer(){this.arDomOverlay=this.webxr.context.domElement;let e=this.arDomOverlay;return e.getAROverlayContainer?this.arOverlayElement=e.getAROverlayContainer():this.arOverlayElement=this.arDomOverlay,this.arOverlayElement}setReticleActive(e){this.reticleActive=e}async onBegin(e){let t=this.webxr.context;this.reticleActive=!0,this.didPlaceARSessionRoot=!1,this.getAROverlayContainer();let i=navigator.userAgent?.includes("OculusBrowser")?0:1,n=i===1?4:2;for(let s=0;s<n;s++)$.Create(this.webxr,s,this.webxr.gameObject,i);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=R.findObjectOfType(mt,t)),this.previousBackground=t.scene.background,this.previousEnvironment=t.scene.environment,t.scene.background=null,e.requestReferenceSpace("viewer").then(s=>{e.requestHitTestSource?.call(e,{space:s})?.then(a=>{this.hitTestSource=a}).catch(a=>{this.noHitTestAvailable=!0,console.warn("WebXR: Hit test not supported",a)})}),!this.reticle&&this.sessionRoot&&(this.reticle=new P_(new k_(.07,.09,32).rotateX(-Math.PI/2),new O_),this.reticle.name="AR Placement reticle",this.reticle.matrixAutoUpdate=!1,this.reticle.visible=!1,this.reticleParent=new Mm,this.reticleParent.name="AR Reticle Parent",this.reticleParent.matrixAutoUpdate=!1,this.reticleParent.add(this.reticle),this.webxr.scene?(this.context.scene.add(this.reticleParent),this.context.scene.visible=!0):console.warn("Could not found WebXR Rig")),this._previousParent=this.webxr.gameObject,ts.tempWebXRObject||(ts.tempWebXRObject=new Mm),this.context.scene.add(ts.tempWebXRObject),R.addComponent(ts.tempWebXRObject,this.webxr),this.sessionRoot?(this.sessionRoot.webAR=this,this.sessionRoot?.onBegin(e)):console.warn("No WebARSessionRoot found in scene");let r=this.context.domElement;r?.onEnterAR?.call(r,e,this.arOverlayElement),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onEnd(e){this._previousParent&&(R.addComponent(this._previousParent,this.webxr),this._previousParent=null),this.hitTestSource=null;let t=this.webxr.context;t.scene.background=this.previousBackground,t.scene.environment=this.previousEnvironment,this.sessionRoot&&this.sessionRoot.onEnd(this.webxr.Rig,e);let i=this.context.domElement;i.onExitAR?.call(i,e),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onUpdate(e,t){if(this.noHitTestAvailable===!0){if(this.reticle&&(this.reticle.visible=!1),!this.didPlaceARSessionRoot){this.didPlaceARSessionRoot=!0;let n=this.webxr.Rig,r=A_.clone();this.sessionRoot?.placeAt(n,r)}return}if(!this.hitTestSource)return;let i=t.getHitTestResults(this.hitTestSource);if(i.length){let n=i[0],r=this.webxr.context.renderer.xr.getReferenceSpace();if(r){let s=n.getPose(r);if(this.sessionRoot){let a=this.sessionRoot.onUpdate(this.webxr.Rig,e,s);this.didPlaceARSessionRoot=a}if(this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&s)){let a=s.transform.matrix;this.reticle.matrix.fromArray(a),this.webxr.Rig&&this.reticle.matrix.premultiply(this.webxr.Rig.matrix)}}}else this.sessionRoot?.onUpdate(this.webxr.Rig,e,null),this.reticle&&(this.reticle.visible=!1)}},cr=ts;I(cr,"tempWebXRObject");var A_=new S_().identity().makeTranslation(0,0,0);var xi=class{used=!1;Use(){this.used=!0}StopPropagation(){this.event?.stopImmediatePropagation()}inputSource;object;isDown;isUp;isPressed;isClicked;event;constructor(e){this.event=e}};import{Object3D as L_}from"three";var j_=P("debugeventsystem"),Xi=class extends M{static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Xi.systems.length<=0&&Xi.systems.push(...R.findObjectsOfType(Xi,e)));for(let i of Xi.systems)if(i.context===e)return;let t=new L_;R.addNewComponent(t,Xi),e.scene.add(t)}static get systems(){let e=G.Current;return this._eventSystemMap.has(e)||this._eventSystemMap.set(e,[]),this._eventSystemMap.get(e)}static ensureUpdateMeshUI(e,t){wi.update(e,t)}static markUIDirty(e){wi.markDirty()}static get instance(){return this.systems[0]}orbitControl=null;orbitControlWasEnabled=!1;raycaster=[];constructor(){super(),Xi.systems.push(this)}onDestroy(){Xi.systems.splice(Xi.systems.indexOf(this),1)}start(){}register(e){e&&this.raycaster&&!this.raycaster.includes(e)&&this.raycaster?.push(e)}unregister(e){let t=this.raycaster?.indexOf(e);t!==void 0&&t!==-1&&this.raycaster?.splice(t,1)}_selectStartFn;_selectEndFn;_selectUpdateFn;onEnable(){let e=new Map;this._selectStartFn??=(i,n)=>{if(!n.grab)return;wi.resetLastSelected();let r=new xi;r.inputSource=i,r.isDown=i.selectionDown,r.isUp=i.selectionUp,r.isPressed=i.selectionPressed,r.isClicked=!1,e.set(i,n.grab),n.grab&&!this.handleEvents(n.grab,r)&&(n.grab=null)},this._selectEndFn??=(i,n)=>{if(!n.grab)return;let r=new xi;r.inputSource=i,r.isDown=i.selectionDown,r.isUp=i.selectionUp,r.isPressed=i.selectionPressed,r.isClicked=i.selectionClick,this.handleEvents(n.grab,r);let s=e.get(i);if(e.set(i,null),s)for(let a=0;a<this.raisedPointerDownEvents.length;a++){let c=this.raisedPointerDownEvents[a];this.raisedPointerDownObjects[a]===s&&c&&(c.onPointerUp?.call(c,r),this.raisedPointerDownEvents.splice(a,1),this.raisedPointerDownObjects.splice(a,1),a--)}};let t=new be;this._selectUpdateFn??=i=>{t.ray=i.getRay();let n=this.performRaycast(t);if(!n)return;let r=new xi;r.inputSource=i,this.handleIntersections(n,r)},$.addEventListener("select-start",this._selectStartFn),$.addEventListener("select-end",this._selectEndFn),$.addEventListener("update",this._selectUpdateFn),this.context.pre_update_callbacks.push(this.onBeforeUpdate.bind(this)),this.context.input.addEventListener("pointerdown",this.onPointerDown.bind(this))}onDisable(){$.removeEventListener("select-start",this._selectStartFn),$.removeEventListener("select-end",this._selectEndFn),$.removeEventListener("update",this._selectUpdateFn)}onPointerDown(){this.onBeforeUpdate()}lastPointerEvent=null;objectsHoveredThisFrame=[];objectsHoveredLastFrame=[];raisedPointerDownEvents=[];raisedPointerDownObjects=[];_didMove=!1;onBeforeUpdate(){if(this.objectsHoveredThisFrame.length=0,this.resetMeshUIStates(),V.IsInWebXR||this.context.input.isKeyPressed("Alt"))return;if(!this._didMove){let r=this.context.input.getPointerPositionRC(0);if(r&&r.x===0&&r.y===0)return;this._didMove=!0}let e=this.performRaycast(null),t=new xi(this.context.input.getPointerEvent(0));if(t.inputSource=this.context.input,t.isClicked=this.context.input.mouseClick,t.isDown=this.context.input.mouseDown,t.isUp=this.context.input.mouseUp,t.isPressed=this.context.input.mousePressed,this.lastPointerEvent=t,!e)return;let i=null,n=null;this.context.input.mouseDown&&this.currentActiveMeshUIComponents.length>0&&this.context.mainCameraComponent&&(i=R.getComponent(this.context.mainCameraComponent.gameObject,Ve)??null,i&&(n=i.enabled,i.enabled=!1)),this.handleIntersections(e,t),i&&(this.orbitControl=i,this.orbitControl?.enabled?(this.orbitControlWasEnabled=this.orbitControl.enabled,this.orbitControl.enabled=!1):this.orbitControl&&!this.context.input.mousePressed&&(this.orbitControl.enabled=this.orbitControlWasEnabled,this.orbitControl=null))}_tempComponentsArray=[];onBeforeRender(){if(this.lastPointerEvent)this.lastPointerEvent.used=!1;else return;if(this.lastPointerEvent.isUp){for(let t of this.raisedPointerDownEvents)t.onPointerUp&&t.onPointerUp(this.lastPointerEvent);this.raisedPointerDownEvents.length=0,this.raisedPointerDownObjects.length=0}for(let t of this.objectsHoveredLastFrame)if(this.objectsHoveredThisFrame.indexOf(t)<0){this._tempComponentsArray.length=0;let i=R.getComponentsInParent(t,M,this._tempComponentsArray);this.lastPointerEvent.object=t;for(let n=0;n<i.length;n++){let r=i[n];if(!r.gameObject||r.destroyed)continue;let s=r;s.onPointerExit&&s.onPointerExit(this.lastPointerEvent)}}let e=this.objectsHoveredLastFrame;this.objectsHoveredLastFrame=this.objectsHoveredThisFrame,this.objectsHoveredThisFrame=e}_sortedHits=[];performRaycast(e){if(!this.raycaster)return null;this._sortedHits.length=0;for(let t of this.raycaster){if(!t.activeAndEnabled)continue;let i=t.performRaycast(e);i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}handleIntersections(e,t){if(!e||e.length<=0)return!1;e=this.sortCandidates(e);for(let i of e){let{object:n}=i;if(this.handleEvents(n,t))return!0}return!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){let i=e[t],n=i.object;if(n.material&&n.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(let t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventsArray=[];out={};handleEvents(e,t){if(!this.testIsVisible(e))return t.isClicked&&j_&&console.log("not allowed",e),!1;let i=e;t.object=e,this.lastPointerEvent=t;let n=e.parent,r=!1,s=t.isClicked??!1,a=null;if(n&&n.isUI){let c=(t.isPressed||t.isClicked)??!1;if(n[gt]){let u=n[gt].gameObject;if(u){if(!Ei.isInteractable(u,this.out))return this.out.canvasGroup?.interactable??!1;a=this.out.canvasGroup??null;let d=this.handleMeshUIIntersection(e,c);e=u,r=!0}}if(!r&&this.handleMeshUiObjectWithoutShadowDom(n,c))return!0}if(this.objectsHoveredThisFrame.push(e),a===null||a.interactable){let c=this.objectsHoveredLastFrame.indexOf(e)>=0;this.handleEventsArray.length=0;let u=R.getComponentsInParent(e,M,this.handleEventsArray);for(let l=0;l<u.length;l++){if(t.used)return!0;if(u[l].destroyed)continue;let d=u[l];d.interactable!==!1&&(d.onPointerEnter&&(c||d.onPointerEnter(t)),t.isDown&&d.onPointerDown&&!this.raisedPointerDownEvents.includes(d)&&(d.onPointerDown(t),this.raisedPointerDownEvents.push(d),this.raisedPointerDownObjects.push(i)),t.isUp&&d.onPointerUp&&d.onPointerUp(t),t.isClicked&&d.onPointerClick&&d.onPointerClick(t))}}return!0}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){let i=wi.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&wi.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){let t=this.currentActiveMeshUIComponents[e];wi.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?R.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}},Je=Xi;I(Je,"_eventSystemMap",new Map),I(Je,"didSearchEventSystem",!1);var wi=class{static markDirty(){this.needsUpdate=!0}static update(e,t){for(let i of this.lastUpdateFrame)if(i.context===t){if(t.time.frameCount===i.frame)return;i.frame=t.time.frameCount,(this.needsUpdate||t.time.frameCount<30)&&(this.needsUpdate=!1,e.update());return}this.lastUpdateFrame=[{context:t,frame:t.time.frameCount}],e.update()}static updateState(e,t){let i=null;if(e&&(i=this.findBlockInParent(e),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;t?(this.lastSelected=i,i.states.pressed&&i.setState("pressed")):i.states.hovered&&i.setState("hovered"),this.needsUpdate=!0}return i}static resetLastSelected(){let e=this.lastSelected;!e||(this.lastSelected=null,this.resetState(e))}static resetState(e){if(!e)return;e.interactable===!1?e.states.disabled&&e.setState("disabled"):e===this.lastSelected&&e.states.selected?e.setState("selected"):e.setState("normal"),this.needsUpdate=!0}static findBlockInParent(e){return e?e.isBlock&&Object.keys(e.states).length>0?e:this.findBlockInParent(e.parent):null}};I(wi,"lastSelected",null),I(wi,"lastUpdateFrame",[]),I(wi,"needsUpdate",!1);import{AxesHelper as H_}from"three";var is="./include";oc.Block.prototype.interactable={get(){return this.interactive},set(o){this.interactable=o}};var gt=Symbol("shadowDomOwner"),We=class extends M{isRoot(){return this.Root?.gameObject===this.gameObject}markDirty(){Je.markUIDirty(this.context)}shadowComponent=null;_controlsChildLayout=!0;get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}_root=void 0;get Root(){return this._root===void 0&&(this._root=R.getComponentInParent(this.gameObject,kn)),this._root}_parentComponent=void 0;onEnable(){super.onEnable()}addShadowComponent(e,t){this.removeShadowComponent();let i=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=R.getComponentInParent(i,We),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have a UI element outside a Canvas?`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[gt]=this,e.traverse(r=>{r[gt]===void 0&&(r[gt]=this)});let n=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{let r=this._parentComponent.shadowComponent;r&&(r?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),Di&&e.add(new H_(.5)),this.onAfterAddedToScene(),n&&oc.update()}set(e){}traverseOwnedShadowComponents(e,t,i){if(!!e&&e[gt]===t){i(e);for(let n of e.children)this.traverseOwnedShadowComponents(n,t,i)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}},kn=class extends We{awake(){super.awake()}};var Ei=class{static getObject(e){let t=e[gt];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;let i=this.tryFindCanvasGroup(e);if(i?.isCanvasGroup===!0&&(t&&(t.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;let n=ai(e,r=>{if(r.isGraphic===!0)return r},!1);return t&&n?.isGraphic===!0&&(t.graphic=n),n?.raycastTarget!==!1}static tryFindCanvasGroup(e){if(!e)return null;let t=ai(e,i=>{let n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}};var ma=P("debugwebxrcontroller");var Jr=class extends M{},je=class extends M{static CreateRaycastLine(){let e=new V_(this.geometry),t=e.material;return t.color=this.raycastColor,e.layers.set(2),e.name="line",e.scale.z=1,e}static CreateRaycastHitPoint(){let e=new X_(.5,22,22),t=new W_({color:this.raycastColor}),i=new z_(e,t);return i.visible=!1,i.layers.set(2),i}static Create(e,t,i,n){let r=i?R.addNewComponent(i,je,!1):new je;r.webXR=e,r.index=t,r.type=n;let s=e.context;r.controller=s.renderer.xr.getController(t),r.controllerGrip=s.renderer.xr.getControllerGrip(t),r.controllerModel=this.Factory.createControllerModel(r.controller),r.controllerGrip.add(r.controllerModel),r.hand=s.renderer.xr.getHand(t);let a=new J_;xn(a,s),r.webXR.handModelPath&&r.webXR.handModelPath!==""?a.setPath(Ii(e.sourceId,r.webXR.handModelPath)):a.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/");let c=new q_(r.hand,a);return r.hand.add(c),r.hand.traverse(u=>u.layers.set(2)),r.handPointerModel=new Y_(r.hand,r.controller),r.controller.addEventListener("connected",u=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),r.setControllerLayers(r.hand,2),setTimeout(()=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),r.setControllerLayers(r.hand,2)},1e3)}),r.hand.addEventListener("connected",u=>{if(u.data.hand){e.Rig&&e.Rig.add(r.hand),r.type=0,r.handPointerModel.traverse(h=>h.layers.set(2)),r.handPointerModel.pointerObject?.traverse(h=>h.layers.set(2));let d=r.hand.joints;if(d)for(let h of Object.keys(d)){let g=d[h];g.parent||r.hand.add(g)}}}),r}static addEventListener(e,t){let i=this.eventSubs[e]??[];i.push(t),this.eventSubs[e]=i}static removeEventListener(e,t){if(!t)return;let i=this.eventSubs[e]??[],n=i.indexOf(t);n>=0&&i.splice(n,1),this.eventSubs[e]=i}webXR;index=-1;controllerModel;controller;controllerGrip;hand;handPointerModel;grabbed=null;input=null;type=0;showRaycastLine=!0;get isUsingHands(){let e=this.input?.hand;return e!=null}get wrist(){if(!this.hand)return null;let e=this.hand.joints;return e?e.wrist:null}_wristQuaternion=null;getWristQuaternion(){let e=this.wrist;return e?(this._wristQuaternion||(this._wristQuaternion=new sc),me(e).multiply(this._wristQuaternion.setFromEuler(new U_(-Math.PI/4,0,0)))):null}movementVector=new Ci;worldRot=new sc;joystick=new Q_;didRotate=!1;didTeleport=!1;didChangeScale=!1;lastHit=null;raycastLine=null;_raycastHitPoint=null;_connnectedCallback=null;_disconnectedCallback=null;_selectStartEvt=null;_selectEndEvt=null;get selectionDown(){return this._selectionPressed&&!this._selectionPressedLastFrame}get selectionUp(){return!this._selectionPressed&&this._selectionPressedLastFrame}get selectionPressed(){return this._selectionPressed}get selectionClick(){return this._selectionEndTime-this._selectionStartTime<.3}get raycastHitPoint(){return this._raycastHitPoint}_selectionPressed=!1;_selectionPressedLastFrame=!1;_selectionStartTime=0;_selectionEndTime=0;get useSmoothing(){return this._useSmoothing}_useSmoothing=!0;awake(){if(!this.controller){console.warn("Missing Controller!!!",this);return}this._connnectedCallback=this.onSourceConnected.bind(this),this._disconnectedCallback=this.onSourceDisconnected.bind(this),this._selectStartEvt=this.onSelectStart.bind(this),this._selectEndEvt=this.onSelectEnd.bind(this),this.type===1&&(this.controllerGrip.addEventListener("connected",this._connnectedCallback),this.controllerGrip.addEventListener("disconnected",this._disconnectedCallback),this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt))}onDestroy(){this.type===1&&(this.controllerGrip.removeEventListener("connected",this._connnectedCallback),this.controllerGrip.removeEventListener("disconnected",this._disconnectedCallback),this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.hand?.clear(),this.controllerGrip?.clear(),this.controller?.clear()}onEnable(){this.hand&&(this.hand.name="Hand"),this.controllerGrip&&(this.controllerGrip.name="ControllerGrip"),this.controller&&(this.controller.name="Controller"),this.raycastLine&&(this.raycastLine.name="RaycastLine;"),this.webXR.Controllers.indexOf(this)<0&&this.webXR.Controllers.push(this),this.raycastLine||(this.raycastLine=je.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=je.CreateRaycastHitPoint()),this.webXR.Rig?.add(this.hand),this.webXR.Rig?.add(this.controllerGrip),this.webXR.Rig?.add(this.controller),this.webXR.Rig?.add(this.raycastLine),this.raycastLine?.add(this._raycastHitPoint),this._raycastHitPoint.visible=!1,this.hand.add(this.handPointerModel),ma&&console.log("ADDED TO RIG",this.webXR.Rig)}onDisable(){this.hand?.removeFromParent(),this.controllerGrip?.removeFromParent(),this.controller?.removeFromParent(),this.raycastLine?.removeFromParent(),this._raycastHitPoint?.removeFromParent();let e=this.webXR.Controllers.indexOf(this);e>=0&&this.webXR.Controllers.splice(e,1)}_isConnected=!1;onSourceConnected(e){if(this._isConnected){console.warn("Received connected event for controller that is already connected",this.index,e);return}this._isConnected=!0,this.input=e.data,this.type===1&&(this.onSelectStart(),this.createPointerEvent("down"))}onSourceDisconnected(e){if(!this._isConnected){console.warn("Received discnnected event for controller that is not connected",e);return}this._isConnected=!1,this.type===1&&(this.onSelectEnd(),this.createPointerEvent("up")),this.input=null}createPointerEvent(e){switch(e){case"down":this.context.input.createPointerDown({clientX:0,clientY:0,button:this.index,pointerType:"touch"});break;case"move":break;case"up":this.context.input.createPointerUp({clientX:0,clientY:0,button:this.index,pointerType:"touch"});break}}rayRotation=new sc;update(){this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));let e=je.eventSubs["update"];if(e&&e.length>0)for(let n of e)n(this);let t=1;this.type===0?t=this.context.time.deltaTime/.1:this.isUsingHands&&this.handPointerModel.pinched&&(t=this.context.time.deltaTime/.3),this.rayRotation.slerp(me(this.controller),this.useSmoothing?t:1);let i=B(this.controller);if(this.isUsingHands&&this.handPointerModel.cursorObject&&(this.handPointerModel.cursorObject.visible=!1),this.raycastLine){let n=this.showRaycastLine&&this.type!==1;if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed&&n,ie(this.raycastLine,i);let r=this.hand.joints;if(r&&r.wrist&&this.grabbed&&this.grabbed.isCloseGrab){let a=this.getWristQuaternion();a&&this.rayRotation.copy(a)}et(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=n,et(this.raycastLine,this.rayRotation),ie(this.raycastLine,i)}this.lastHit=this.updateLastHit(),this.grabbed&&this.grabbed.update(),this._selectionPressedLastFrame=this._selectionPressed,this.selectStartCallback&&this.selectStartCallback()}_pinchStartTime=void 0;onUpdate(e){if(this.lastHit=null,!e||e.inputSources.length<=this.index){this.input=null;return}if(this.type===0&&(this.input=e.inputSources[this.index]),!this.input)return;let t=this.webXR.Rig;if(!t)return;this._didNotEndSelection&&!this.handPointerModel.pinched&&(this._didNotEndSelection=!1,this.onSelectEnd()),this.updateStick(this.input);let i=this.input?.gamepad?.buttons;switch(this.input.handedness){case"left":let n=3*je.MovementSpeedFactor,r=2,s=H.clamp01(this.joystick.length()*2),a=this.joystick.x>0?1:-1,c=Math.pow(this.joystick.x,r);c*=a,c*=s;let u=this.joystick.y>0?1:-1,l=Math.pow(this.joystick.y,r);l*=u,c*=s,t.getWorldQuaternion(this.worldRot),this.movementVector.set(c,0,l),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),this.movementVector.multiplyScalar(n*this.context.time.deltaTime),t.position.add(this.movementVector),this.isUsingHands&&this.runTeleport(t,i);break;case"right":let d=this.joystick.x,h=Math.abs(d);if(h<.4)this.didRotate=!1;else if(h>.5&&!this.didRotate){let g=d>0?-1:1;t.rotateY(H.toRadians(30*g)),this.didRotate=!0}this.runTeleport(t,i);break}}runTeleport(e,t){let i=-this.joystick.y;if(this.hand?.visible&&!this.grabbed){let a=this.handPointerModel.isPinched();a&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),a&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(i=this.handPointerModel.isPinched()?1:0),a||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;let n=i>.5&&this.webXR.IsInVR,r=this.webXR.Rig?this.webXR.Rig?.scale?.x<.999:!1,s=null;if(t&&this.input&&!this.input.hand)for(let a=0;a<t.length;a++){let c=t[a];if(a===4)if(c.pressed&&!this.didChangeScale&&this.webXR.IsInVR){this.didChangeScale=!0;let u=this.webXR.Rig;if(u)if(r){r=!1,u.scale.set(1,1,1),s=1,je.MovementSpeedFactor=1;let l=this.context.mainCamera;je.PreviousCameraFarDistance&&(l.far=je.PreviousCameraFarDistance)}else{r=!0,n=!0,s=.1,je.MovementSpeedFactor=s*2;let l=this.context.mainCamera;je.PreviousCameraFarDistance=l.far,l.far/=s}}else c.pressed||(this.didChangeScale=!1)}if(n){if(!this.didTeleport){let a=this.raycast();if(this.didTeleport=!0,a&&a.length>0){let c=a[0];if(r||this.isValidTeleportTarget(c.object)){let u=c.point;ie(e,u)}}}}else i<.1&&(this.didTeleport=!1);s!==null&&(e.scale.set(s,s,s),e.updateMatrixWorld())}isValidTeleportTarget(e){return R.getComponentInParent(e,Jr)!=null}updateStick(e){!e||!e.gamepad||e.gamepad.axes?.length<4||(this.joystick.x=e.gamepad.axes[2],this.joystick.y=e.gamepad.axes[3])}updateLastHit(){let e=this.raycast(),t=e?e[0]:null;this.lastHit=t;let i=1;if(this.webXR.Rig&&(i/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=i*(this.lastHit?.distance??9999);let n=this.raycastLine.material;t!=null?n.color=je.raycastColor:n.color=je.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;let n=H.clamp(this.lastHit.distance*.01*i,.015,.1);this._raycastHitPoint.scale.set(n,n,n)}this._raycastHitPoint.visible=this.lastHit!==null&&this.lastHit!==void 0}return t}onSelectStart(){!this.context.connection.allowEditing||(this.selectStartCallback=()=>this.onHandleSelectStart())}selectStartCallback=null;lastSelectStartObject=null;onHandleSelectStart(){this.selectStartCallback=null,this._selectionPressed=!0,this._selectionStartTime=this.context.time.time,this._selectionEndTime=1e3;let e=null,t=!1;if(this.isUsingHands?(e=this.overlap(),e.length<=0?(e=this.raycast(),t=!1):t=!0):e=this.raycast(),ma&&console.log("onHandleSelectStart","close grab? "+t,"intersections",e),e&&e.length>0)for(let i of e){let n=i.object;this.lastSelectStartObject=n;let r={selected:n,grab:n},s=je.eventSubs["select-start"];if(s&&s.length>0)for(let a of s)a(this,r);r.grab!==n&&ma&&console.log("Grabbed object changed","original",n,"new",r.grab),r.grab&&(this.grabbed=bt.TryTake(this,r.grab,i,t));break}else{let i=je.eventSubs["select-start"],n={selected:null,grab:null};if(i&&i.length>0)for(let r of i)r(this,n)}}_didNotEndSelection=!1;onSelectEnd(){if(this.isUsingHands&&this.handPointerModel.pinched){this._didNotEndSelection=!0;return}if(!this._selectionPressed)return;this.selectStartCallback=null,this._selectionPressed=!1,this._selectionEndTime=this.context.time.time;let e={grab:this.grabbed?.selected??this.lastSelectStartObject},t=je.eventSubs["select-end"];if(t&&t.length>0)for(let i of t)i(this,e);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(e){return!(!e||R.isActiveInHierarchy(e)===!1||Ei.isInteractable(e)===!1)}setControllerLayers(e,t){if(!!e&&(e.layers.set(t),e.children))for(let i of e.children)this.grabbed?.selected===i||this.grabbed?.selectedMesh===i||this.setControllerLayers(i,t)}getRay(){let e=new N_;return e.origin.copy(B(this.controller)),e.direction.set(0,0,-1).applyQuaternion(this.rayRotation),e}closeGrabBoundingBoxHelper;overlap(){let e=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(ma&&(!this.closeGrabBoundingBoxHelper&&e&&(this.closeGrabBoundingBoxHelper=new F_(e,16776960),this.scene.add(this.closeGrabBoundingBoxHelper)),this.closeGrabBoundingBoxHelper&&e&&this.closeGrabBoundingBoxHelper.setFromObject(e)),!e)return new Array;let t=B(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){let e=new be;e.layerMask=new G_,e.layerMask.set(0),e.layerMask.disable(2),e.ray=this.getRay();let t=this.context.physics.raycast(e);for(let i=0;i<t.length;i++){let n=t[i],r=n.object;if(!this.testIsVisible(r)){t.splice(i,1),i--;continue}n.object=Ei.getObject(r);break}return t}},$=je;I($,"Factory",new K_),I($,"raycastColor",new Dm(.9,.3,.3)),I($,"raycastNoHitColor",new Dm(.6,.6,.6)),I($,"geometry",new B_().setFromPoints([new Ci(0,0,0),new Ci(0,0,-1)])),I($,"handModels",{}),I($,"eventSubs",{}),I($,"PreviousCameraFarDistance"),I($,"MovementSpeedFactor",1);var ot=class{static AddEventListener(e,t){return ot.Events[e]||(ot.Events[e]=[]),ot.Events[e].push(t),t}static RemoveEventListener(e,t){if(!t||!ot.Events[e])return;let i=ot.Events[e].indexOf(t);i>=0&&ot.Events[e].splice(i,1)}static Register(e){this.Current.find(t=>t===e)||this.Current.push(e)}static Remove(e){let t=this.Current.indexOf(e);t>=0&&this.Current.splice(t,1)}static TryTake(e,t,i,n){let r=R.getComponentInParent(t,Vt);if(r)t=r.gameObject;else return ma&&console.warn("Prevented taking object that is not interactable",t),null;let s=t,a=R.getComponentInParent(t,Pt);a&&(a.requestOwnership(),s=a.gameObject);for(let u of this.Current)if(u.selected===s)return u.controller===e||(u.free(),u.Take(e,s,t,a,r,i,n)),u;let c=new ot;return c.Take(e,s,t,a,r,i,n),c}sync=null;selected=null;selectedParent=null;selectedMesh=null;controller=null;grabTime=0;grabUUID="";isCloseGrab=!1;originalMaterial=null;usageMarker=null;rigidbodies=null;didReparent=!1;grabDistance=0;interactable=null;positionSource=null;Take(e,t,i,n,r,s,a){if(console.assert(t!==null,"Expected object to be taken but was",t),e.isUsingHands?this.positionSource=a?e.wrist:e.controller:this.positionSource=e.controller,!this.positionSource)return console.warn("No position source"),this;let c={controller:e,take:t,hit:i,sync:n,interactable:r};ot.Events.WillTake?.forEach(g=>g(this,c));let u=i;u?.material&&(this.originalMaterial=u.material,Array.isArray(u.material)||(u.material=u.material.clone(),u.material&&u.material.emissive&&(u.material.emissive.b=.2))),this.selected=t,this.selectedParent||(this.selectedParent=t.parent),this.selectedMesh=u,this.controller=e,this.interactable=r,this.isCloseGrab=a,this.didReparent=!1,this.sync=n,this.grabTime=e.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=R.addNewComponent(this.selected,zt),this.rigidbodies=R.getComponentsInChildren(this.selected,J),B(this.positionSource,this.lastControllerWorldPos);let l=()=>a?this.lastControllerWorldPos.clone():s.point.clone();this.grabDistance=l().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(l());let d=e.isUsingHands&&a?this.controller.getWristQuaternion().clone():e.rayRotation.clone();me(this.selected,this.localQuaternionToGrab).premultiply(d.invert());let h=this.controller.webXR.Rig;return h&&this.rigPositionLastFrame.copy(B(h)),ye.Add(e.context,this.selected),ot.Register(this),this.sync&&(this.sync.fastMode=!0),ot.Events.DidTake?.forEach(g=>g(this,c)),this}free(){if(!this.selected)return;let e={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};ot.Events.WillFree?.forEach(n=>n(this,e)),ye.Remove(this.controller.context,this.selected),ot.Remove(this),this.sync&&(this.sync.fastMode=!1);let t=this.selectedMesh;t&&this.originalMaterial&&t.material&&(t.material=this.originalMaterial);let i=this.selected;if(this.didReparent&&i.parent){let n=this.selectedParent;n?n.attach(i):this.controller?.context.scene.attach(i)}if(this.usageMarker?.destroy(),this.controller&&(this.controller.grabbed=null),this.selected=null,this.selectedParent=null,this.selectedMesh=null,this.sync=null,this.rigidbodies)for(let n of this.rigidbodies)n.wakeUp(),n.setVelocity(n.smoothedVelocity);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,ot.Events.DidFree?.forEach(n=>n(this,e))}grabPoint=new Ci;localPositionOffsetToGrab=null;localPositionOffsetToGrab_worldSpace=new Ci;localQuaternionToGrab=new sc(0,0,0,1);targetDir=null;quaternionLerp=null;controllerDir=new Ci;controllerWorldPos=new Ci;lastControllerWorldPos=new Ci;controllerPosDelta=new Ci;totalChangeAlongDirection=0;rigPositionLastFrame=new Ci;controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),B(this.positionSource,this.controllerWorldPos),this.controllerPosDelta.copy(this.controllerWorldPos),this.controllerPosDelta.sub(this.lastControllerWorldPos),this.lastControllerWorldPos.copy(this.controllerWorldPos);let e=this.controller.webXR.Rig;if(e){let i=B(e),n=this.rigPositionLastFrame.sub(i);this.controllerPosDelta.add(n),this.rigPositionLastFrame.copy(i)}return this.controllerDir.dot(this.controllerPosDelta)}update(){if(this.rigidbodies)for(let e of this.rigidbodies)e.resetVelocities();if(this.sync&&this.controller&&this.controller.context.connection.isInRoom&&this.controller.context.time.time-this.grabTime>3&&this.sync.hasOwnership()===!1&&(console.log("no ownership, will leave",this.sync.guid),this.free()),!(this.interactable&&!this.interactable.canGrab)){if(!this.didReparent&&this.selected&&this.controller){let e=this.controller.webXR.Rig?.scale.x??1;this.totalChangeAlongDirection+=this.controllerMovementSinceLastFrame();let t=1;this.controller.type===0&&(t=Math.max(0,1+this.totalChangeAlongDirection*2/e),t=t*t*t),this.grabDistance/e<.8&&(t=1),this.targetDir||(this.targetDir=new Ci),this.targetDir.set(0,0,-this.grabDistance*t);let i=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),n=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=n.clone()),this.quaternionLerp.slerp(n,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),et(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(i),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(B(this.selected)),i.sub(this.localPositionOffsetToGrab_worldSpace)),ie(this.selected,i)}if(this.rigidbodies!=null)for(let e of this.rigidbodies)e.wakeUp();oe.markDirty(this.selected,!0)}}},bt=ot;I(bt,"Events",{}),I(bt,"Current",[]);import{Object3D as Lm}from"three";var Z_=P("debugmouth"),ur=class extends M{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){setTimeout(()=>{this.voip=R.findObjectOfType(rt,this.context),this.marker||(this.marker=R.getComponentInParent(this.gameObject,le))},3e3)}update(){if(!this.voip||this.context.time.frameCount%10!==0)return;let e=this.marker?.connectionId??null;if(!e){Z_&&(e=null);return}let t=this.voip.getFrequency(e)??0;this.updateLips(t)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;let t=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,t)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;let t=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,t)}}}setMouthShapeActive(e,t){if(!!e){e!=this.idle?this.idle.map(i=>i.visible=!1):this.talking.map(i=>i.visible=!1);for(let i=0;i<e.length;i++){let n=e[i];n&&(n.visible=i===t)}}}};v([y(Lm)],ur.prototype,"idle",2),v([y(Lm)],ur.prototype,"talking",2);var ns=class extends M{voip=null;marker=null;_startPosition=null;awake(){this.voip=R.findObjectOfType(rt,this.context),this.marker=R.getComponentInParent(this.gameObject,le)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;let e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());let i=t/100;this.gameObject.position.y=this._startPosition.y+i*.07}};import{Object3D as $_}from"three";var Qi=class extends M{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=R.getComponentInParent(this.gameObject,Ee)}update(){if(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)return;if(this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(let t of this.eyes)t&&(t.visible=this.eyesOpen)}}};v([y($_)],Qi.prototype,"eyes",2),v([y()],Qi.prototype,"lastBlinkTime",2),v([y()],Qi.prototype,"blinkLength",2),v([y()],Qi.prototype,"eyesOpen",2);import*as ac from"three";import{Object3D as zd}from"three";var Wd=class extends M{head=null;eyes=null;target=null;brain=null;awake(){this.brain||(this.brain=R.getComponentInParent(this.gameObject,Sn)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=R.addNewComponent(this.gameObject,Sn)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new ac.Vector3;currentTargetPoint=new ac.Vector3;update(){let e=this.target;if(e&&this.head){let t=this.eyes;if(t){let i=B(e);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);let n=B(this.head),r=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(r.length()<.1)return;let s=Wd.forward;if(s.set(0,0,1),s.applyQuaternion(me(this.head)),s.dot(r)>.45)for(let c=0;c<t.length;c++)t[c].lookAt(this.currentTargetPoint)}}}},qi=Wd;I(qi,"forward",new ac.Vector3(0,0,1)),v([y(zd)],qi.prototype,"head",2),v([y(zd)],qi.prototype,"eyes",2),v([y(zd)],qi.prototype,"target",2);import{AxesHelper as ex}from"three";var Mn=class extends M{length=1;depthTest=!0;isGizmo=!0;_axes=null;onEnable(){if(this.isGizmo&&!Di)return;this._axes||(this._axes=new ex(this.length)),this.gameObject.add(this._axes);let e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){!this._axes||this.gameObject.remove(this._axes)}};v([y()],Mn.prototype,"length",2),v([y()],Mn.prototype,"depthTest",2),v([y()],Mn.prototype,"isGizmo",2);import*as jm from"three";var rs=class extends M{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=B(this.to).clone(),t=B(this.from).clone(),i=e.distanceTo(t),n=e.clone();n.sub(t);let r=t.clone();r.add(e),r.multiplyScalar(.5);let s=B(this.hint).clone();s.sub(r);let a=new jm.Vector3;a.crossVectors(s,n),a.crossVectors(n,a),a.normalize();let c=i*.5,u=Math.max(this.desiredDistance,c),l=Math.sqrt(u*u-c*c),d=a.clone();d.multiplyScalar(l),d.add(r),ie(this.gameObject,d);let h=r.clone();h.sub(a),this.gameObject.lookAt(h)}};import{Mesh as tx,Vector3 as dr}from"three";var Ot=class extends M{get isCollider(){return!0}attachedRigidbody=null;isTrigger=!1;sharedMaterial;awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(J))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(J))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(J))}onDisable(){this.context.physics.removeBody(this)}};v([y(J)],Ot.prototype,"attachedRigidbody",2),v([y()],Ot.prototype,"isTrigger",2),v([y()],Ot.prototype,"sharedMaterial",2);var hr=class extends Ot{radius=.5;center=new dr(0,0,0);onEnable(){super.onEnable(),this.context.physics.addSphereCollider(this,this.center,this.radius)}};v([y()],hr.prototype,"radius",2),v([y(dr)],hr.prototype,"center",2);var pr=class extends Ot{size=new dr(1,1,1);center=new dr(0,0,0);onEnable(){super.onEnable(),this.context.physics.addBoxCollider(this,this.center,this.size)}};v([y(dr)],pr.prototype,"size",2),v([y(dr)],pr.prototype,"center",2);var Zr=class extends Ot{sharedMesh;convex=!1;onEnable(){super.onEnable(),this.sharedMesh?.isMesh||this.gameObject instanceof tx&&(this.sharedMesh=this.gameObject),this.sharedMesh?.isMesh&&this.context.physics.addMeshCollider(this,this.sharedMesh,this.convex,Ae(this.gameObject))}};v([y()],Zr.prototype,"convex",2);var Xt=class extends Ot{center=new dr(0,0,0);radius=.5;height=2;onEnable(){super.onEnable(),this.context.physics.addCapsuleCollider(this,this.center,this.height,this.radius)}};v([y(dr)],Xt.prototype,"center",2),v([y()],Xt.prototype,"radius",2),v([y()],Xt.prototype,"height",2);import*as $r from"three";var ix=P("gizmos"),nx=P("debugboxhelper"),Qt=class extends M{box=null;_lastMatrixUpdateFrame=-1;isInBox(e,t){if(!e)return;if(this.box||(this.box=new $r.Box3),e.type==="Mesh")Qt.testBox.setFromObject(e);else if(e.type==="Group"){if(Qt.testBox.makeEmpty(),e.children.length>0)for(let n=0;n<e.children.length;n++)e.children[n].type==="Mesh"&&Qt.testBox.expandByObject(e)}else{let n=B(e,Qt._position),r=Ae(e,Qt._size);t!==void 0&&r.multiplyScalar(t),Qt.testBox.setFromCenterAndSize(n,r)}this.updateBox();let i=this.box?.intersectsBox(Qt.testBox);return i&&nx&&Et.DrawBox3(Qt.testBox,16711680,5),i}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new $r.Box3),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){let t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;let i=t,n=B(this.gameObject,Qt._position,i),r=Ae(this.gameObject,Qt._size);this.box.setFromCenterAndSize(n,r)}return this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!ix&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=cl(e),this.gameObject.add(this._helper)}}},Ne=Qt;I(Ne,"testBox",new $r.Box3),I(Ne,"_position",new $r.Vector3),I(Ne,"_size",new $r.Vector3(.01,.01,.01));import{Color as lx,Texture as zm}from"three";import{LinearEncoding as sx,sRGBEncoding as ax}from"three";import*as Qd from"three-mesh-ui";import{Matrix4 as rx,Object3D as ox,Vector2 as Gm,Vector3 as Xd}from"three";import{FrontSide as Hm,DoubleSide as Fm}from"three";function Nd(o){let e=o[gt];return e||(o.parent?Nd(o.parent):null)}function os(o,e){if(!o)return;let t=o.material;t?.isMaterial===!0&&(t.depthTest=!e.renderOnTop,t.side=e.doubleSided??!0?Fm:Hm,t.depthWrite=e.depthWrite??!1,t.shadowSide=e.doubleSided?Fm:Hm,o.castShadow=e.castShadows?e.castShadows:!1,o.receiveShadow=e.receiveShadows?e.receiveShadows:!1);for(let i of o.children)os(i,e)}function lc(o,e,t){o[e]===void 0&&console.warn("Field",e,"is undefined on",o);let i=Proxy.revocable(o[e],{set(s,a,c,u){let l=s[a],d=Reflect.set(s,a,c,u);return t(c,l),d}}),n=i.revoke,r=o[e];return i.revoke=()=>{o[e]=r,n()},o[e]=i.proxy,i}var Bm=Symbol("Scheduled action");function Um(o,e,t=3){let i=o[Bm];i||(i=o[Bm]={});let n=e.name;i[t]||(i[t]={});let r=i[t];if(r[n])return;function*a(){e?.call(o),r[n]=null}let c=o.startCoroutine(a(),t);r[n]=c}var Vm=P("debugui"),ss=class{width;height},eo=class{x;y;width;height},vt=class extends We{offset=.01;get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}_anchoredPosition;get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new Xd),this._anchoredPosition}rect;sizeDelta;anchoredPosition3D;pivot;lastMatrix;rectBlock;_transformNeedsUpdate=!1;awake(){super.awake(),this.lastMatrix=new rx,this.rectBlock=new ox,this.rectBlock.position.z=.1,this.rectBlock.name=this.name,this._anchoredPosition||(this._anchoredPosition=new Xd),lc(this,"_anchoredPosition",()=>{this._transformNeedsUpdate=!0})}onEnable(){super.onEnable(),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0}onDisable(){super.onDisable(),this.removeShadowComponent()}applyTransform(){let e=this.shadowComponent;!e||(this._transformNeedsUpdate=!1,this.isRoot()?e.rotation.y=Math.PI:(e.position.copy(this.gameObject.position),e.position.x*=-1,e.position.z*=-1,e.position.z-=this.offset,e.quaternion.copy(this.gameObject.quaternion),e.rotation.x*=-1,e.rotation.z*=-1,e.scale.copy(this.gameObject.scale)),this.applyAnchoring(e.position),this.lastMatrix.copy(this.gameObject.matrix))}markDirty(){this._transformNeedsUpdate=!0}onBeforeRender(){(this._transformNeedsUpdate||this.lastMatrix.equals(this.gameObject.matrix)===!1)&&(Vm&&console.log("updating",this.name),this.applyTransform()),Je.ensureUpdateMeshUI(Qd,this.context)}applyAnchoring(e){if(this.pivot&&this.sizeDelta){let t=this.pivot.x*2-1,i=this.pivot.y*2-1;i-=this.anchoredPosition.y*.05;let n=this.sizeDelta.x*t,r=this.sizeDelta.y*i;e.x-=n*.5,e.y-=r*.5}}getBasicOptions(){let e={width:this.rect.width,height:this.rect.height,offset:this.offset,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}_createdBlocks=[];createNewBlock(e){e={...this.getBasicOptions(),...e},Vm&&console.log(this.name,e);let t=new Qd.Block(e);return this._createdBlocks.push(t),t}};v([y(eo)],vt.prototype,"rect",2),v([y(Gm)],vt.prototype,"sizeDelta",2),v([y(Xd)],vt.prototype,"anchoredPosition3D",2),v([y(Gm)],vt.prototype,"pivot",2);var ga=class extends We{get isGraphic(){return!0}get color(){return this._color||(this._color=new Q(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new Q(1,1,1,1)),this._color.copy(e))}onColorChanged(){let e=this.color;this.setOptions({backgroundColor:e,backgroundOpacity:e.alpha,borderOpacity:e.alpha})}get m_Color(){return this._color}raycastTarget=!0;uiObject=null;_color=null;_rect=null;get rectTransform(){return this._rect||(this._rect=R.getComponent(this.gameObject,vt)),this._rect}setState(e){this.makePanel(),this.uiObject&&this.uiObject.setState(e)}setupState(e){this.makePanel(),this.uiObject&&this.uiObject.setupState(e)}setOptions(e){this.makePanel(),this.uiObject&&(this.uiObject.set(e),(e.backgroundColor!==void 0||e.backgroundOpacity!==void 0)&&this.uiObject.updateBackgroundMaterial?.call(this.uiObject))}awake(){super.awake(),this.makePanel(),lc(this,"_color",()=>Um(this,this.onColorChanged))}onEnable(){super.onEnable(),this.uiObject&&(this.rectTransform.shadowComponent?.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}_currentlyCreatingPanel=!1;makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;let e={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:1};this.onBeforeCreate(e),this.onCreate(e),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}async setTexture(e){if(!!e&&(this.setOptions({backgroundOpacity:0}),e)){if(e.encoding===ax)if(ga.textureCache.has(e))e=ga.textureCache.get(e);else{let t=e.clone();t.encoding=sx,ga.textureCache.set(e,t),e=t}this.setOptions({backgroundTexture:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"})}}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}},yt=ga;I(yt,"textureCache",new Map),v([y(Q)],yt.prototype,"color",1),v([y()],yt.prototype,"raycastTarget",2);var In=class extends yt{onAfterCreated(){this.uiObject&&(this.uiObject.scale.y*=-1)}};var cc=class{texture;rect};v([y(zm)],cc.prototype,"texture",2);var An=class extends In{get sprite(){return this._sprite}set sprite(e){this._sprite!==e&&(this._sprite=e,this.onAfterCreated())}_sprite;isBuiltinSprite(){switch(this.sprite?.texture?.name){case"InputFieldBackground":case"UISprite":case"Background":return!0}return this.sprite?.texture?.image?.width===32&&this.sprite?.texture?.image?.height===32}onBeforeCreate(e){this.isBuiltinSprite()&&(e.borderRadius=5,e.borderColor=new lx(.4,.4,.4),e.borderOpacity=this.color.alpha,e.borderWidth=.3)}onAfterCreated(){!this.__didAwake||(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture))}};v([y(cc)],An.prototype,"sprite",1);var to=class extends In{get mainTexture(){return this._mainTexture}set mainTexture(e){this._mainTexture!==e&&(this._mainTexture=e,this.onAfterCreated())}_mainTexture;onAfterCreated(){!this.__didAwake||(super.onAfterCreated(),this.setTexture(this.mainTexture))}};v([y(zm)],to.prototype,"mainTexture",1);var as=P("debugbutton");var Dn=class{colorMultiplier;disabledColor;fadeDuration;highlightedColor;normalColor;pressedColor;selectedColor};v([y()],Dn.prototype,"colorMultiplier",2),v([y(Q)],Dn.prototype,"disabledColor",2),v([y()],Dn.prototype,"fadeDuration",2),v([y(Q)],Dn.prototype,"highlightedColor",2),v([y(Q)],Dn.prototype,"normalColor",2),v([y(Q)],Dn.prototype,"pressedColor",2),v([y(Q)],Dn.prototype,"selectedColor",2);var qt=class extends M{onClick;_isHovered=!1;onPointerEnter(e){as&&console.log("Button Enter",this.animationTriggers?.highlightedTrigger,this.animator),this._isHovered=!0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&this._image?.setState("hovered"),this.context.input.setCursorPointer()}onPointerExit(){as&&console.log("Button Exit",this.animationTriggers?.highlightedTrigger,this.animator),this._isHovered=!1,this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState("normal"),this.context.input.setCursorNormal()}onPointerDown(e){as&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&this._image?.setState("pressed")}onPointerUp(e){as&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState(this._isHovered?"hovered":"normal")}onPointerClick(e){as&&console.trace("Button Click",this.onClick),this.onClick?.invoke()}colors;transition;animationTriggers;animator;set interactable(e){this._interactable=e,this._image&&(this._image.setInteractable(e),e?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}_interactable=!0;set_interactable(e){this.interactable=e}awake(){super.awake(),as&&console.log(this),this.init()}start(){this._image?.setInteractable(this.interactable)}onEnable(){super.onEnable()}_requestedAnimatorTrigger;*setAnimatorTriggerAtEndOfFrame(e){this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&this.animator?.SetTrigger(e)}_isInit=!1;_image;init(){this._isInit||(this._isInit=!0,this._image=R.getComponent(this.gameObject,An),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){e.setInteractable(this.interactable);let t=this.getFinalColor(e.color,this.colors?.normalColor),i={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(i);let n=this.getFinalColor(e.color,this.colors?.highlightedColor),r={state:"hovered",attributes:{backgroundColor:n,backgroundOpacity:n.alpha}};e.setupState(r);let s=this.getFinalColor(e.color,this.colors?.pressedColor),a={state:"pressed",attributes:{backgroundColor:s,backgroundOpacity:s.alpha}};e.setupState(a);let c=this.getFinalColor(e.color,this.colors?.selectedColor),u={state:"selected",attributes:{backgroundColor:c,backgroundOpacity:c.alpha}};e.setupState(u);let l=this.getFinalColor(e.color,this.colors?.disabledColor),d={state:"disabled",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(d)}getFinalColor(e,t){return t?e.clone().multiply(t):e.clone()}};v([y(de)],qt.prototype,"onClick",2),v([y()],qt.prototype,"colors",2),v([y()],qt.prototype,"transition",2),v([y()],qt.prototype,"animationTriggers",2),v([y(Pe)],qt.prototype,"animator",2),v([y()],qt.prototype,"interactable",1);var qd=class extends kn{set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop}_renderOnTop=!1;set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}_depthWrite=!1;set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}_doubleSided=!0;set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}_castShadows=!0;set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}_receiveShadows=!0;get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}_renderMode=-1;_rootCanvas;set rootCanvas(e){this._rootCanvas instanceof qd||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}_scaleFactor=1;get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}awake(){this.shadowComponent=this.gameObject,super.awake()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this.onRenderSettingsChanged()}previousAspect=-1;onBeforeRender(){this.isScreenSpace&&this.context.mainCameraComponent&&this.context.mainCameraComponent.aspect!==this.previousAspect&&(this.previousAspect=this.context.mainCameraComponent.aspect,this.updateRenderMode())}_updateRenderSettingsRoutine;onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),3))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.updateRenderMode(),os(this.shadowComponent,this);for(let e of R.getComponentsInChildren(this.gameObject,We))os(e.shadowComponent,this)}}_activeRenderMode=-1;get isScreenSpace(){return this._activeRenderMode===1||this._activeRenderMode===0}updateRenderMode(){if(this.renderMode!==this._activeRenderMode)switch(this.renderMode){case 0:case 1:let e=this.context.mainCameraComponent;if(!e)return;let t=this.gameObject;e.gameObject?.add(t);let n=e.farClipPlane;t.position.x=0,t.position.y=0,t.position.z=-n;let r=Math.tan(H.toRadians(e.fieldOfView)*n)*(e.aspect*1.333333),s=r*(this.context.domHeight/this.context.domWidth);t.scale.x=-r,t.scale.y=s;break;case 2:break}}},Xe=qd;v([y()],Xe.prototype,"renderOnTop",1),v([y()],Xe.prototype,"depthWrite",1),v([y()],Xe.prototype,"doubleSided",1),v([y()],Xe.prototype,"castShadows",1),v([y()],Xe.prototype,"receiveShadows",1),v([y()],Xe.prototype,"renderMode",1),v([y(Xe)],Xe.prototype,"rootCanvas",1),v([y()],Xe.prototype,"scaleFactor",1);var Ln=class extends M{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}_alpha=1;interactable=!0;blocksRaycasts=!0;_isDirty=!1;markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),3))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){for(let e of R.getComponentsInChildren(this.gameObject,yt,this._buffer)){let t=e.color;t.alpha=this._alpha,e.color=t}}};v([y()],Ln.prototype,"alpha",1),v([y()],Ln.prototype,"interactable",2),v([y()],Ln.prototype,"blocksRaycasts",2);import{Quaternion as gx,Ray as bx,Vector3 as io}from"three";import*as Wm from"three";import{Color as ux,Object3D as dx,Texture as hx,WebGLRenderTarget as px}from"three";import{WebGLRenderTarget as cx}from"three";var ls=class extends cx{};var Kd=class extends Li{constructor(){super([ux,Q])}onDeserialize(e){if(e!=null)return e.a!==void 0?new Q(e.r,e.g,e.b,e.a):e.alpha!==void 0?new Q(e.r,e.g,e.b,e.alpha):new Wm.Color(e.r,e.g,e.b)}onSerialize(e){if(e!=null)return e.a!==void 0?{r:e.r,g:e.g,b:e.b,a:e.a}:{r:e.r,g:e.g,b:e.b}}},OL=new Kd,Jd=class extends Li{constructor(){super(dx)}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){let i=t.objectToNode[e.uuid];return pe&&console.log(i,e.name,e.uuid),{node:i}}}onDeserialize(e,t){if(e){if(e.node!==void 0&&t.nodeToObject){let i=t.nodeToObject[e.node];return pe&&console.log("Deserialized object reference?",e,i,t?.nodeToObject),i||console.warn("Did not find node: "+e.node,t.nodeToObject,t.object),i}else if(e.guid){if(!t.context){console.error("Missing context");return}let i,n=t.gltf?.scene;return n&&(i=R.findByGuid(e.guid,n)),i||(i=R.findByGuid(e.guid,t.context.scene)),i?pe&&console.log("Deserialized object reference?",e,i,t?.nodeToObject):((Ba()||pe)&&console.warn("Could not resolve object reference",t.path,e,t.target,t.context.scene),e.could_not_resolve=!0),i}}}},fx=new Jd,Zd=class extends Li{constructor(){super([Tt,M])}onSerialize(e,t){if(e?.guid)return{guid:e.guid}}onDeserialize(e,t){if(e?.guid){pe&&console.log(e.guid,t.root,t.object,t.target);let i=this.findObjectForGuid(e.guid,t.root);if(i||t.context&&(i=this.findObjectForGuid(e.guid,t.context?.scene),i))return i;(Ba()||pe)&&console.warn("Could not resolve component reference",t.path,e,t.target),e.could_not_resolve=!0;return}}findObjectForGuid(e,t){if(t.guid===e)return t;let i=R.foreachComponent(t,n=>{if(n.guid===e)return n},!1);if(i!==void 0)return i;for(let n=0;n<t.children.length;n++){let r=t.children[n],s=this.findObjectForGuid(e,r);if(s)return s}}},Yd=new Zd,$d=class extends Li{constructor(){super([de])}onSerialize(e,t){console.log("TODO: SERIALIZE EVENT")}onDeserialize(e,t){if(typeof e=="function")return new de([new vi(e,!0)]);if(e&&e.type==="EventList"){pe&&console.log("DESERIALIZE EVENT",e);let i=new Array;if(e.calls&&Array.isArray(e.calls))for(let s of e.calls){pe&&console.log(s);let a=Yd.findObjectForGuid(s.target,t.root);!a&&t.context?.scene&&(a=Yd.findObjectForGuid(s.target,t.context?.scene));let c=s.method?.length>0;if(a&&c){let h=()=>console.warn(`Could not find method ${s.method} on object ${a.name}`,a,typeof a[s.method]);if(typeof a[s.method]!="function"){let g=!1;s.method.startsWith("set_")&&s.method.length>4&&(s.method=s.method.substring(4),a[s.method]!==void 0&&(g=!0)),!g&&(Ba()||pe)&&h()}}let u,l=s.argument;s.argument!==void 0?(typeof l=="object"&&(l=fx.onDeserialize(s.argument,t),l||(l=Yd.onDeserialize(s.argument,t))),u=new vi(c?(...h)=>d(...h):void 0,s.enabled)):u=new vi(c?(...h)=>d(...h):void 0,s.enabled);let d=(...h)=>{let g=a[s.method];typeof g=="function"?l!==void 0?g?.call(a,l):g?.call(a,...h):a[s.method]=l};if(u.method||(u.__debuginfo=t.object?.name),!a||!u.method){let h=t.object?"Current object: "+t.object.name+", "+t.object.guid:null;a?console.warn('EventList method not found: "'+s.method+'" on',a):console.warn("EventList is missing target - will be ignored",s.target,h,e)}else i.push(u)}let n=new de(i);pe&&console.log(n);let r=t.target;return r!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,r),n}}},kL=new $d,eh=class extends Li{constructor(){super([ls,px])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof hx&&t.type===ls){let i=e,n=new ls(i.image.width,i.image.height);return n.texture=i,n}}};new eh;var Yi=class extends M{center=new io(0,0,0);radius=.5;height=2;_rigidbody=null;get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(J),this._rigidbody||(this._rigidbody=this.gameObject.addNewComponent(J)),this.rigidbody)}onEnable(){let e=this.rigidbody,t=this.gameObject.getComponent(Xt);t||(t=this.gameObject.addNewComponent(Xt)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height,this.gameObject.rotation.x=0,this.gameObject.rotation.z=0,e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}_activeGroundCollisions=new Set;onCollisionEnter(e){for(let t of e.contacts)if(t.normal.y>.1){this._activeGroundCollisions.add(e);break}}onCollisionExit(e){this._activeGroundCollisions.delete(e)}get isGrounded(){return this._activeGroundCollisions.size>0}};v([y(io)],Yi.prototype,"center",2),v([y()],Yi.prototype,"radius",2),v([y()],Yi.prototype,"height",2);var Ti=class extends M{controller;movementSpeed=2;rotationSpeed=2;jumpForce=1;animator;lookForward=!0;_currentSpeed=new io(0,0,0);_currentAngularSpeed=new io(0,0,0);_temp=new io(0,0,0);_jumpCount=0;_currentRotation;awake(){this._currentRotation=new gx}update(){this.controller?.isGrounded&&(this._jumpCount=0,this.animator?.SetBool("doubleJump",!1));let e=this.context.input.isKeyPressed("w"),t=this.context.input.isKeyPressed("s"),i=this.context.input.isKeyPressed("a"),n=this.context.input.isKeyPressed("d"),r=this.context.input.isKeyDown(" "),s=e?1:0+t?-1:0;this._currentSpeed.z+=s*this.movementSpeed*this.context.time.deltaTime,this.animator?.SetBool("running",s!=0),this.animator?.SetBool("jumping",this.controller?.isGrounded===!0&&r),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp);let a=i?1:0+n?-1:0;if(this._currentAngularSpeed.y+=H.toRadians(a*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){let c=this.context.mainCameraComponent.forward;c.y=0,c.normalize(),this._currentRotation.setFromUnitVectors(new io(0,0,1),c),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&&r&&this.jumpForce>0){let c=this.controller?.isGrounded;if(!this.controller?.isGrounded&&this._jumpCount===1&&(c=!0,this.animator?.SetBool("doubleJump",!0)),c){this._jumpCount+=1;let u=this.controller.rigidbody,l=this._jumpCount===2?2:1;u.applyImpulse(new io(0,1,0).multiplyScalar(this.jumpForce*l))}}if(this.controller){let c=this.controller?.rigidbody.getVelocity().y;if(c<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new bx),this._raycastOptions.ray.origin.copy(B(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);let u=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);let l=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(u),(l.length&&l[0].distance>2||c<-10)&&this.animator?.SetBool("falling",!0)}else this.animator?.SetBool("falling",!1)}}_raycastOptions=new be};v([y(Yi)],Ti.prototype,"controller",2),v([y()],Ti.prototype,"movementSpeed",2),v([y()],Ti.prototype,"rotationSpeed",2),v([y()],Ti.prototype,"jumpForce",2),v([y(Pe)],Ti.prototype,"animator",2);import{LinearToneMapping as th,ACESFilmicToneMapping as Nm,ReinhardToneMapping as vx}from"three";var uc=P("debugvolume"),Qm=(i=>(i[i.None=0]="None",i[i.Neutral=1]="Neutral",i[i.ACES=2]="ACES",i))(Qm||{}),cs=class{overrideState=!1;value=0},Ki=class{active=!1;parameters},mr=class extends Ki{mode;get isToneMapping(){return!0}},gr=class extends Ki{postExposure};function yx(o){return"mode"in o?mr:"postExposure"in o?gr:Ki}var Xm=Symbol("volumeprofile"),fr=class{components;apply(e){this.onUpdate(e,!1)}unapply(e){this.onUpdate(e,!0)}onUpdate(e,t){if(!this.components)return;let i=e.renderer,r=i[Xm]!==void 0;if(t){if(!r)return}else i[Xm]=this;for(let s of this.components)if(s instanceof mr){let a=s;if(!s.active||t){e.renderer.toneMapping=th;continue}uc&&console.log("VOLUME:",Qm[a.mode?.value??0]);let c=a.mode;switch((c?.overrideState?c?.value:0)??0){case 0:e.renderer.toneMapping=th;break;case 1:e.renderer.toneMapping=vx;break;case 2:e.renderer.toneMapping=Nm;break}}else if(s instanceof gr){let a=s;uc&&console.log(a.postExposure);let c=1;a.postExposure&&(c=Math.pow(2,a.postExposure.value)),e.renderer.toneMapping,Nm;let u=a.postExposure?.overrideState&&!t;e.renderer.toneMappingExposure=u?c:1,e.renderer.toneMapping||(e.renderer.toneMapping=th)}}};v([y([o=>yx(o),Ki])],fr.prototype,"components",2);var no=class extends M{sharedProfile;awake(){uc&&(console.log(this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",e=>{e.key==="p"&&(console.log("Toggle volume: "+this.name,!this.enabled),this.enabled=!this.enabled)}))}onEnable(){uc&&console.log("APPLY VOLUME",this),this.sharedProfile?.apply(this.context)}onDisable(){this.sharedProfile?.unapply(this.context)}};v([y(fr)],no.prototype,"sharedProfile",2);import{Matrix4 as qm,Quaternion as _x,Vector3 as $e,Vector2 as Ym,Euler as xx}from"three";import{createNoise4D as wx}from"simplex-noise";var Ex=P("debugparticles");var Si=class{alphaKeys;colorKeys;get duration(){return 1}evaluate(e,t){let i,n=0,r=null,s=0;for(let a=0;a<this.alphaKeys.length;a++){let c=this.alphaKeys[a];(c.time<e||!i)&&(i=c,n=a)}for(let a=0;a<this.colorKeys.length;a++){let c=this.colorKeys[a];(c.time<e||!r)&&(r=c,s=a)}if(r)if(s+1<this.colorKeys.length){let c=this.colorKeys[s+1],u=H.remap(e,r.time,c.time,0,1);t.r=H.lerp(r.color.r,c.color.r,u),t.g=H.lerp(r.color.g,c.color.g,u),t.b=H.lerp(r.color.b,c.color.b,u)}else t.r=r.color.r,t.g=r.color.g,t.b=r.color.b;if(i)if(n+1<this.alphaKeys.length){let c=this.alphaKeys[n+1],u=H.remap(e,i.time,c.time,0,1);t.alpha=H.lerp(i.alpha,c.alpha,u)}else t.alpha=i.alpha;return t}};v([y()],Si.prototype,"alphaKeys",2),v([y()],Si.prototype,"colorKeys",2);var Km=(w=>(w[w.Sphere=0]="Sphere",w[w.SphereShell=1]="SphereShell",w[w.Hemisphere=2]="Hemisphere",w[w.HemisphereShell=3]="HemisphereShell",w[w.Cone=4]="Cone",w[w.Box=5]="Box",w[w.Mesh=6]="Mesh",w[w.ConeShell=7]="ConeShell",w[w.ConeVolume=8]="ConeVolume",w[w.ConeVolumeShell=9]="ConeVolumeShell",w[w.Circle=10]="Circle",w[w.CircleEdge=11]="CircleEdge",w[w.SingleSidedEdge=12]="SingleSidedEdge",w[w.MeshRenderer=13]="MeshRenderer",w[w.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",w[w.BoxShell=15]="BoxShell",w[w.BoxEdge=16]="BoxEdge",w[w.Donut=17]="Donut",w[w.Rectangle=18]="Rectangle",w[w.Sprite=19]="Sprite",w[w.SpriteRenderer=20]="SpriteRenderer",w))(Km||{});var U=class{mode;constant;constantMin;constantMax;curve;curveMin;curveMax;curveMultiplier;evaluate(e,t){let i=t===void 0?Math.random():t;switch(this.mode){case 0:return this.constant;case 1:return e=H.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:let n=e*this.curveMin.duration,r=e*this.curveMax.duration;return H.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(r),i%1)*this.curveMultiplier;case 3:return H.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(e)*this.curveMultiplier;break}return 0}};v([y()],U.prototype,"mode",2),v([y()],U.prototype,"constant",2),v([y()],U.prototype,"constantMin",2),v([y()],U.prototype,"constantMax",2),v([y(gi)],U.prototype,"curve",2),v([y(gi)],U.prototype,"curveMin",2),v([y(gi)],U.prototype,"curveMax",2),v([y()],U.prototype,"curveMultiplier",2);var Yt=class{mode;color;colorMin;colorMax;gradient;gradientMin;gradientMax;evaluate(e,t){let i=t===void 0?Math.random():t;switch(this.mode){case 0:return this.color;case 1:return this.gradient.evaluate(e,Yt._temp),Yt._temp;case 2:return Yt._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:return this.gradientMin.evaluate(e,Yt._temp),this.gradientMax.evaluate(e,Yt._temp2),Yt._temp.lerp(Yt._temp2,i)}return Yt._temp.set(16711935),Yt._temp.alpha=1,Yt._temp}},Me=Yt;I(Me,"_temp",new Q(0,0,0,1)),I(Me,"_temp2",new Q(0,0,0,1)),v([y(Q)],Me.prototype,"color",2),v([y(Q)],Me.prototype,"colorMin",2),v([y(Q)],Me.prototype,"colorMax",2),v([y(Si)],Me.prototype,"gradient",2),v([y(Si)],Me.prototype,"gradientMin",2),v([y(Si)],Me.prototype,"gradientMax",2);var _e=class{cullingMode;duration;emitterVelocityMode;flipRotation;gravityModifier;gravityModifierMultiplier;loop;maxParticles;playOnAwake;prewarm;ringBufferLoopRange;ringBufferMode;scalingMode;simulationSpace;simulationSpeed;startColor;startDelay;startDelayMultiplier;startLifetime;startLifetimeMultiplier;startRotation;startRotationMultiplier;startRotation3D;startRotationX;startRotationXMultiplier;startRotationY;startRotationYMultiplier;startRotationZ;startRotationZMultiplier;startSize;startSize3D;startSizeMultiplier;startSizeX;startSizeXMultiplier;startSizeY;startSizeYMultiplier;startSizeZ;startSizeZMultiplier;startSpeed;startSpeedMultiplier;stopAction;useUnscaledTime};v([y(U)],_e.prototype,"gravityModifier",2),v([y(Me)],_e.prototype,"startColor",2),v([y(U)],_e.prototype,"startDelay",2),v([y(U)],_e.prototype,"startLifetime",2),v([y(U)],_e.prototype,"startRotation",2),v([y(U)],_e.prototype,"startRotationX",2),v([y(U)],_e.prototype,"startRotationY",2),v([y(U)],_e.prototype,"startRotationZ",2),v([y(U)],_e.prototype,"startSize",2),v([y(U)],_e.prototype,"startSizeX",2),v([y(U)],_e.prototype,"startSizeY",2),v([y(U)],_e.prototype,"startSizeZ",2),v([y(U)],_e.prototype,"startSpeed",2);var Hn=class{cycleCount;maxCount;minCount;probability;repeatInterval;time;count;_performed=0;reset(){this._performed=0}run(e){if(e<=this.time)return this.reset(),0;let t=0;if(this.cycleCount===0||this._performed<this.cycleCount){let i=this.time+this.repeatInterval*this._performed;if(e>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=H.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:let n=Math.random();t=H.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return t}},_t=class{enabled;get burstCount(){return this.bursts?.length??0}bursts;rateOverTime;rateOverTimeMultiplier;rateOverDistance;rateOverDistanceMultiplier;system;reset(){this.bursts?.forEach(e=>e.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){let i=this.bursts[t];i.time>=this.system.time&&i.reset(),e+=Math.round(i.run(this.system.time))}return e}};v([y()],_t.prototype,"enabled",2),v([y()],_t.prototype,"bursts",2),v([y(U)],_t.prototype,"rateOverTime",2),v([y()],_t.prototype,"rateOverTimeMultiplier",2),v([y(U)],_t.prototype,"rateOverDistance",2),v([y()],_t.prototype,"rateOverDistanceMultiplier",2);var jn=class{enabled;color};v([y(Me)],jn.prototype,"color",2);var Kt=class{enabled;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_time=0;_temp=new $e;evaluate(e,t,i){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,i)*this.xMultiplier,t.y=this.y.evaluate(e,i)*this.yMultiplier,t.z=this.z.evaluate(e,i)*this.zMultiplier;else{let n=this.size.evaluate(e,i)*this.sizeMultiplier;t.x=n}return t}};v([y(U)],Kt.prototype,"size",2),v([y(U)],Kt.prototype,"x",2),v([y(U)],Kt.prototype,"y",2),v([y(U)],Kt.prototype,"z",2);var us=class{get type(){return Km[this.shapeType]}initialize(e){this.getPosition(),e.position.copy(this._vector)}toJSON(){return this}clone(){return new us}shapeType=5;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcSpread;arcSpeedMultiplier;arcMode;boxThickness;position;rotation;_rotation=new xx;scale;radius;radiusThickness;sphericalDirectionAmount;randomDirectionAmount;randomPositionAmount;system;_space;_worldSpaceMatrix=new qm;_worldSpaceMatrixInverse=new qm;update(e,t,i,n){this.system=e,this._space=i,i===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}updateRotation(){let e=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return e&&(this._rotation.x=H.toRadians(this.rotation.x),this._rotation.y=-H.toRadians(this.rotation.y),this._rotation.z=-H.toRadians(this.rotation.z)),e}_vector=new $e(0,0,0);_temp=new $e(0,0,0);get vector(){return this._vector}getPosition(){this._vector.set(0,0,0);let e=this._temp.copy(this.position),t=this._space===1;t&&e.applyQuaternion(this.system.worldQuaternion);let i=this.radius;if(t&&(i*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(e);break;case 4:this.randomConePoint(this.position,this.angle,i,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,i,this.radiusThickness,this.arc,this._vector,this.scale);break;case 10:this._temp.copy(this.scale),this._temp.z=0,this.randomSpherePoint(this.position,i,this.radiusThickness,this.arc,this._vector,this._temp);break;default:this._vector.set(0,0,0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.updateRotation()&&this._vector.applyEuler(this._rotation),t&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos))}_dir=new $e;getDirection(e){if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:let t=e.x,i=e.y,n=e.z;this._dir.set(t,i,n),this._dir.sub(this.position);break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyMatrix4(this._worldSpaceMatrixInverse),this.updateRotation()&&this._dir.applyEuler(this._rotation),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),Ex&&(Et.DrawSphere(e,.01,8925952,.5,!0),Et.DrawDirection(e,this._dir,8925952,.5,!0)),this._dir}randomizePosition(e,t){if(t<=0)return;let i=us._tempVec;i.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),i.x*=t*this.scale.x,i.y*=t*this.scale.y,i.z*=t*this.scale.z,e.add(i)}randomizeDirection(e,t){if(t===0)return;let i=us._randomQuat,n=us._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),e.applyQuaternion(i)}spherizeDirection(e,t){if(t===0)return;let i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),r=Math.sin(n)*Math.cos(i),s=Math.sin(n)*Math.sin(i),a=Math.cos(n),c=new $e(r,s,a);e.lerp(c,t)}randomSpherePoint(e,t,i,n,r,s){let a=Math.random(),c=Math.random(),u=2*Math.PI*a*(n/360),l=Math.acos(2*c-1),d=H.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,h=e.x+s.x*(-d*Math.sin(l)*Math.cos(u)),g=e.y+s.y*(d*Math.sin(l)*Math.sin(u)),E=e.z+s.z*(d*Math.cos(l));r.x=h,r.y=g,r.z=E}_loopTime=0;_loopDirection=1;randomConePoint(e,t,i,n,r,s,a){let c=0,u=0;switch(s){case 0:c=Math.random(),u=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:c=.5,u=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let l=2*Math.PI*c*(r/360);switch(s){case 2:case 1:l+=Math.PI+.5,l+=this._loopTime*Math.PI*2,l%=H.toRadians(r);break}let d=Math.acos(2*u-1),h=H.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,g=e.x+-h*Math.sin(d)*Math.cos(l),E=e.y+h*Math.sin(d)*Math.sin(l),_=e.z;a.x=g*this.scale.x,a.y=E*this.scale.y,a.z=_*this.scale.z}},ne=us;I(ne,"_randomQuat",new _x),I(ne,"_tempVec",new $e),v([y()],ne.prototype,"shapeType",2),v([y()],ne.prototype,"enabled",2),v([y()],ne.prototype,"alignToDirection",2),v([y()],ne.prototype,"angle",2),v([y()],ne.prototype,"arc",2),v([y()],ne.prototype,"arcSpread",2),v([y()],ne.prototype,"arcSpeedMultiplier",2),v([y()],ne.prototype,"arcMode",2),v([y($e)],ne.prototype,"boxThickness",2),v([y($e)],ne.prototype,"position",2),v([y($e)],ne.prototype,"rotation",2),v([y($e)],ne.prototype,"scale",2),v([y()],ne.prototype,"radius",2),v([y()],ne.prototype,"radiusThickness",2),v([y()],ne.prototype,"sphericalDirectionAmount",2),v([y()],ne.prototype,"randomDirectionAmount",2),v([y()],ne.prototype,"randomPositionAmount",2);var K=class{damping;enabled;frequency;octaveCount;octaveMultiplier;octaveScale;positionAmount;quality;remap;remapEnabled;remapMultiplier;remapX;remapXMultiplier;remapY;remapYMultiplier;remapZ;remapZMultiplier;scrollSpeedMultiplier;separateAxes;strengthMultiplier;strengthX;strengthXMultiplier;strengthY;strengthYMultiplier;strengthZ;strengthZMultiplier;_noise;_time=0;update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}_temp=new $e;apply(e,t,i,n,r,s){if(!this.enabled)return;this._noise||(this._noise=wx(()=>0));let a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),c=this._noise(a.x,a.y,a.z,this._time),u=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),l=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(c,u,l).normalize();let d=r/s,h=this.positionAmount.evaluate(d);this.separateAxes?(this._temp.x*=h*this.strengthXMultiplier,this._temp.y*=h*this.strengthYMultiplier,this._temp.z*=h*this.strengthZMultiplier):(this.strengthX&&(h*=this.strengthX.evaluate(d)*1.5),this._temp.multiplyScalar(h)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}};v([y()],K.prototype,"damping",2),v([y()],K.prototype,"enabled",2),v([y()],K.prototype,"frequency",2),v([y()],K.prototype,"octaveCount",2),v([y()],K.prototype,"octaveMultiplier",2),v([y()],K.prototype,"octaveScale",2),v([y(U)],K.prototype,"positionAmount",2),v([y()],K.prototype,"quality",2),v([y(U)],K.prototype,"remap",2),v([y()],K.prototype,"remapEnabled",2),v([y()],K.prototype,"remapMultiplier",2),v([y(U)],K.prototype,"remapX",2),v([y()],K.prototype,"remapXMultiplier",2),v([y(U)],K.prototype,"remapY",2),v([y()],K.prototype,"remapYMultiplier",2),v([y(U)],K.prototype,"remapZ",2),v([y()],K.prototype,"remapZMultiplier",2),v([y()],K.prototype,"scrollSpeedMultiplier",2),v([y()],K.prototype,"separateAxes",2),v([y()],K.prototype,"strengthMultiplier",2),v([y(U)],K.prototype,"strengthX",2),v([y()],K.prototype,"strengthXMultiplier",2),v([y(U)],K.prototype,"strengthY",2),v([y()],K.prototype,"strengthYMultiplier",2),v([y(U)],K.prototype,"strengthZ",2),v([y()],K.prototype,"strengthZMultiplier",2);var te=class{enabled;attachRibbonToTransform=!1;colorOverLifetime;colorOverTrail;dieWithParticles=!0;inheritParticleColor=!0;lifetime;lifetimeMultiplier;minVertexDistance=.2;mode=0;ratio=1;ribbonCount=1;shadowBias=0;sizeAffectsLifetime=!1;sizeAffectsWidth=!1;splitSubEmitterRibbons=!1;textureMode=0;widthOverTrail;widthOverTrailMultiplier;worldSpace=!1;getWidth(e,t,i){let n=this.widthOverTrail.evaluate(i);return i===0&&(n=e),e*=n,e}getColor(e,t,i){let n=this.colorOverTrail.evaluate(i),r=this.colorOverLifetime.evaluate(t);e.x*=n.r*r.r,e.y*=n.g*r.g,e.z*=n.b*r.b,e.w*=n.alpha*r.alpha}};v([y()],te.prototype,"enabled",2),v([y()],te.prototype,"attachRibbonToTransform",2),v([y(Me)],te.prototype,"colorOverLifetime",2),v([y(Me)],te.prototype,"colorOverTrail",2),v([y()],te.prototype,"dieWithParticles",2),v([y()],te.prototype,"inheritParticleColor",2),v([y(U)],te.prototype,"lifetime",2),v([y()],te.prototype,"lifetimeMultiplier",2),v([y()],te.prototype,"minVertexDistance",2),v([y()],te.prototype,"mode",2),v([y()],te.prototype,"ratio",2),v([y()],te.prototype,"ribbonCount",2),v([y()],te.prototype,"shadowBias",2),v([y()],te.prototype,"sizeAffectsLifetime",2),v([y()],te.prototype,"sizeAffectsWidth",2),v([y()],te.prototype,"splitSubEmitterRibbons",2),v([y()],te.prototype,"textureMode",2),v([y(U)],te.prototype,"widthOverTrail",2),v([y()],te.prototype,"widthOverTrailMultiplier",2),v([y()],te.prototype,"worldSpace",2);var He=class{enabled;space=0;speedModifier;speedModifierMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_system;update(e){this._system=e}_temp=new $e;apply(e,t,i,n,r,s){if(!this.enabled)return;let a=r/s,c=this.speedModifier.evaluate(a)*this.speedModifierMultiplier,u=this.x.evaluate(a),l=this.y.evaluate(a),d=this.z.evaluate(a);this._temp.set(-u,l,d),this._system&&(this.space===1&&this._temp.applyQuaternion(this._system.worldQuaternionInverted),this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z,i.x*=c,i.y*=c,i.z*=c}};v([y()],He.prototype,"enabled",2),v([y()],He.prototype,"space",2),v([y(U)],He.prototype,"speedModifier",2),v([y()],He.prototype,"speedModifierMultiplier",2),v([y(U)],He.prototype,"x",2),v([y()],He.prototype,"xMultiplier",2),v([y(U)],He.prototype,"y",2),v([y()],He.prototype,"yMultiplier",2),v([y(U)],He.prototype,"z",2),v([y()],He.prototype,"zMultiplier",2);var xe=class{animation;enabled;cycleCount;frameOverTime;frameOverTimeMultiplier;numTilesX;numTilesY;startFrame;startFrameMultiplier;rowMode;rowIndex;spriteCount;timeMode;sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?this.frameOverTime.evaluate(Math.random()):0}evaluate(e){if(!this.sampleOnceAtStart())return this.getIndex(e)}getIndex(e){let t=this.numTilesX*this.numTilesY,i=this.frameOverTime.evaluate(e%1);return i*=this.frameOverTimeMultiplier,i*=t,i=i%t,i=Math.floor(i),i}};v([y()],xe.prototype,"animation",2),v([y()],xe.prototype,"enabled",2),v([y()],xe.prototype,"cycleCount",2),v([y(U)],xe.prototype,"frameOverTime",2),v([y()],xe.prototype,"frameOverTimeMultiplier",2),v([y()],xe.prototype,"numTilesX",2),v([y()],xe.prototype,"numTilesY",2),v([y(U)],xe.prototype,"startFrame",2),v([y()],xe.prototype,"startFrameMultiplier",2),v([y()],xe.prototype,"rowMode",2),v([y()],xe.prototype,"rowIndex",2),v([y()],xe.prototype,"spriteCount",2),v([y()],xe.prototype,"timeMode",2);var Ze=class{enabled;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}};v([y()],Ze.prototype,"enabled",2),v([y()],Ze.prototype,"separateAxes",2),v([y(U)],Ze.prototype,"x",2),v([y()],Ze.prototype,"xMultiplier",2),v([y(U)],Ze.prototype,"y",2),v([y()],Ze.prototype,"yMultiplier",2),v([y(U)],Ze.prototype,"z",2),v([y()],Ze.prototype,"zMultiplier",2);var Qe=class{enabled;range;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){let i=H.lerp(this.range.x,this.range.y,t);return this.z.evaluate(i)*-1}return 0}};v([y()],Qe.prototype,"enabled",2),v([y()],Qe.prototype,"range",2),v([y()],Qe.prototype,"separateAxes",2),v([y(U)],Qe.prototype,"x",2),v([y()],Qe.prototype,"xMultiplier",2),v([y(U)],Qe.prototype,"y",2),v([y()],Qe.prototype,"yMultiplier",2),v([y(U)],Qe.prototype,"z",2),v([y()],Qe.prototype,"zMultiplier",2);var ue=class{enabled;dampen;drag;dragMultiplier;limit;limitMultiplier;separateAxes;limitX;limitXMultiplier;limitY;limitYMultiplier;limitZ;limitZMultiplier;multiplyDragByParticleSize=!1;multiplyDragByParticleVelocity=!1;space;_temp=new $e;_temp2=new $e;apply(e,t,i,n,r,s,a){if(!!this.enabled){let c=this.limit.evaluate(r)*this.limitMultiplier;if(t.length()>c){this._temp.copy(t).normalize().multiplyScalar(c);let l=this.dampen*.5;t.x=H.lerp(t.x,this._temp.x,l),t.y=H.lerp(t.y,this._temp.y,l),t.z=H.lerp(t.z,this._temp.z,l),i.x=H.lerp(i.x,this._temp.x,l),i.y=H.lerp(i.y,this._temp.y,l),i.z=H.lerp(i.z,this._temp.z,l)}}}};v([y()],ue.prototype,"enabled",2),v([y()],ue.prototype,"dampen",2),v([y(U)],ue.prototype,"drag",2),v([y()],ue.prototype,"dragMultiplier",2),v([y(U)],ue.prototype,"limit",2),v([y()],ue.prototype,"limitMultiplier",2),v([y()],ue.prototype,"separateAxes",2),v([y(U)],ue.prototype,"limitX",2),v([y()],ue.prototype,"limitXMultiplier",2),v([y(U)],ue.prototype,"limitY",2),v([y()],ue.prototype,"limitYMultiplier",2),v([y(U)],ue.prototype,"limitZ",2),v([y()],ue.prototype,"limitZMultiplier",2),v([y()],ue.prototype,"multiplyDragByParticleSize",2),v([y()],ue.prototype,"multiplyDragByParticleVelocity",2),v([y()],ue.prototype,"space",2);var Jt=class{enabled;curve;curveMultiplier;mode;system;_lastWorldPosition;_velocity=new $e;_temp=new $e;update(e){!this.enabled||this.system.worldspace!==!1&&(this._lastWorldPosition?(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)):(this._velocity.set(0,0,0),this._lastWorldPosition=this.system.worldPos.clone()))}applyInitial(e){if(!!this.enabled&&this.system.worldspace!==!1&&this.mode===0){let t=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(t),e.add(this._temp)}}applyCurrent(e,t,i){if(!!this.enabled&&this.system.worldspace!==!1&&this.mode===1){let n=this.curve.evaluate(t,i);this._temp.copy(this._velocity).multiplyScalar(n),e.add(this._temp)}}};v([y()],Jt.prototype,"enabled",2),v([y(U)],Jt.prototype,"curve",2),v([y()],Jt.prototype,"curveMultiplier",2),v([y()],Jt.prototype,"mode",2);var ke=class{enabled;range;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t,i,n){let r=e.length(),s=H.remap(r,this.range.x,this.range.y,0,1),a=this.size.evaluate(s,i);return n*a}};v([y()],ke.prototype,"enabled",2),v([y(Ym)],ke.prototype,"range",2),v([y()],ke.prototype,"separateAxes",2),v([y(U)],ke.prototype,"size",2),v([y()],ke.prototype,"sizeMultiplier",2),v([y(U)],ke.prototype,"x",2),v([y()],ke.prototype,"xMultiplier",2),v([y(U)],ke.prototype,"y",2),v([y()],ke.prototype,"yMultiplier",2),v([y(U)],ke.prototype,"z",2),v([y()],ke.prototype,"zMultiplier",2);var Ri=class{enabled;range;color;evaluate(e,t,i){let n=e.length(),r=H.remap(n,this.range.x,this.range.y,0,1),s=this.color.evaluate(r,t);i.x*=s.r,i.y*=s.g,i.z*=s.b,i.w*=s.alpha}};v([y()],Ri.prototype,"enabled",2),v([y(Ym)],Ri.prototype,"range",2),v([y(Me)],Ri.prototype,"color",2);var ro=class extends Ne{},ds=class extends M{deleteBoxes=[];awake(){this.deleteBoxes=R.findObjectsOfType(ro,this.context)}update(){for(let e of this.deleteBoxes){let t=this.gameObject;e.isInBox(t)===!0&&(R.getComponentInParent(this.gameObject,zt)||So(this.gameObject,this.context.connection))}}};var oo=class extends M{visibleOn;onEnable(){this.apply()}apply(){this.test()||R.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:Cx()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}};v([y()],oo.prototype,"visibleOn",2);var dc;function Cx(){if(dc===!0||dc===!1)return dc;let o=!1;return function(e){(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4)))&&(o=!0)}(navigator.userAgent||navigator.vendor||window.opera),dc=o,o}import*as Y from"three";var ih=!1;var Fn=class extends Vt{static get HasAnySelected(){return this._active>0}transformSelf=!0;orbit=null;selectStartEventListener=[];selectEndEventListener=[];constructor(){super(),this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new Y.Vector2}addDragEventListener(e,t){switch(e){case"selectstart":this.selectStartEventListener.push(t);break;case"selectend":this.selectEndEventListener.push(t);break}}_dragHelper=null;start(){this.orbit=R.findObjectOfType(Ve,this.context)}_draggingRigidbodies=[];allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||V.IsInWebXR)return;let t=R.getComponentInParent(e.object,Fn);!t||t!==this||(Fn.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){!this.allowEdit(this.gameObject)||V.IsInWebXR||Fn.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}_waitingForDragStart=null;onPointerDown(e){!this.allowEdit(this.gameObject)||V.IsInWebXR||(Fn._active+=1,this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation(),this.orbit&&(this.orbit.enabled=!1))}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&(Fn._active>0&&(Fn._active-=1),!V.IsInWebXR&&(this.onDragEnd(e),e.StopPropagation(),this.orbit&&(this.orbit.enabled=!0)))}update(){if(!V.IsInWebXR){if(this._waitingForDragStart){if(!this._didDrag){let t=this.context.input.getPointerPositionDelta(0);if(t&&this._dragDelta.add(t),this._dragDelta.length()>2)this._didDrag=!0;else return}let e=this._waitingForDragStart;this._waitingForDragStart=null,this.onDragStart(e)}this._dragHelper&&this._dragHelper.hasSelected&&this.onUpdateDrag(),this._isDragging&&this._dragHelper?.hasSelected===!1&&this.onDragEnd(null)}}_isDragging=!1;_marker=null;_dragDelta;_didDrag=!1;onDragStart(e){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new hc(this.context.mainCamera);else return;if(!e||!e.object)return;let t=R.getComponentInParent(e.object,Fn);if(!t||t!==this)return;let i=e.object;this.transformSelf&&(i=this.gameObject);let n={selected:i,attached:i};for(let c of this.selectStartEventListener)c(this,n);if(!n.attached)return;n.attached,i=n.attached,this._isDragging=!0,this._dragHelper.setSelected(i,this.context),this.orbit&&(this.orbit.enabled=!1);let r=R.getComponentInChildren(i,Pt);ih&&console.log("DRAG START",r,i),r&&(r.fastMode=!0,r?.requestOwnership()),this._marker=R.addNewComponent(i,zt),this._draggingRigidbodies.length=0;let s=R.getComponentsInChildren(i,J);s&&this._draggingRigidbodies.push(...s);let a=Kc();R.invokeOnChildren(this._dragHelper.selected,a("onDragStart"))}onUpdateDrag(){if(!!this._dragHelper){this._dragHelper.onUpdate(this.context);for(let e of this._draggingRigidbodies)e.wakeUp(),e.resetVelocities()}}onDragEnd(e){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;for(let n of this._draggingRigidbodies)n.setVelocity(n.smoothedVelocity);this._draggingRigidbodies.length=0;let t=this._dragHelper.selected;if(ih&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context),this.orbit&&(this.orbit.enabled=!0),e?.object){let n=R.getComponentInChildren(e.object,Pt);n&&(n.fastMode=!1),this._marker&&this._marker.destroy()}for(let n of this.selectEndEventListener)n(this);let i=Kc();R.invokeOnChildren(t,i("onDragEnd"))}},Ji=Fn;I(Ji,"_active",0),I(Ji,"lastHovered");var nh=class{get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}_selected=null;_context=null;_camera;_cameraPlane=new Y.Plane;_hasGroundPlane=!1;_groundPlane=new Y.Plane;_groundOffset=new Y.Vector3;_groundOffsetFactor=0;_groundDistance=0;_groundPlanePoint=new Y.Vector3;_raycaster=new Y.Raycaster;_cameraPlaneOffset=new Y.Vector3;_intersection=new Y.Vector3;_worldPosition=new Y.Vector3;_inverseMatrix=new Y.Matrix4;_rbs=[];_groundLine;_groundMarker;constructor(e){this._camera=e;let t=new Y.Line(nh.geometry),i=t.material;i.color=new Y.Color(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;let n=new Y.SphereGeometry(.5,22,22),r=new Y.MeshBasicMaterial({color:i.color}),s=new Y.Mesh(n,r);s.visible=!1,s.layers.set(2),this._groundMarker=s}setSelected(e,t){if(this._selected&&t)for(let i of this._rbs)i.wakeUp(),i.setVelocity(0,0,0);if(this._selected&&ye.Remove(t,this._selected),this._selected=e,this._context=t,this._rbs.length=0,e?(t.scene.add(this._groundLine),t.scene.add(this._groundMarker)):(this._groundLine.removeFromParent(),this._groundMarker.removeFromParent()),this._selected){if(!t){console.error("DragHelper: no context");return}ye.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this.onUpdateScreenSpacePlane()}}_groundOffsetVector=new Y.Vector3(0,1,0);_requireUpdateGroundPlane=!0;_didDragOnGroundPlaneLastFrame=!1;onUpdate(e){if(!this._context)return;let t=" ",i="d",n="s",r=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(i),s=this._context.input.getTouchesPressedCount()>=2||r;if(s){let c=this._context.input.getPointerPositionDelta(0);c&&(this._groundOffsetVector.set(0,1,0),this._selected?.rotateOnWorldAxis(this._groundOffsetVector,c.x*this._context.time.deltaTime))}let a=this._context.input.getPointerPositionRC(0);if(!!a&&(this._raycaster.setFromCamera(a,this._camera),this._selected)){ih&&console.log("UPDATE DRAG",this._selected),this._groundOffsetVector.set(0,1,0);let c=B(this._camera).clone().sub(B(this._selected)).normalize(),u=Math.abs(c.dot(this._groundOffsetVector)),l=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(i),d=!s&&u>.2&&!l&&this._context.input.getPointerPressedCount()<=1,h=this._didDragOnGroundPlaneLastFrame!==d;if(this._didDragOnGroundPlaneLastFrame=d,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!d||h)&&this.onUpdateGroundPlane(),this._requireUpdateGroundPlane=!1,this._hasGroundPlane)if(this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection)){let g=this._intersection.y;if(this._groundPlanePoint.copy(this._intersection).sub(this._groundOffset),this._groundPlanePoint.y=g,d){this._groundOffsetVector.set(0,1,0);let E=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(E,this._groundPlanePoint,!1),this.onDidUpdate();return}}else this._groundPlanePoint.set(0,99999,0);h&&this.onUpdateScreenSpacePlane(),this._requireUpdateGroundPlane=!0,this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&(this.onUpdateWorldPosition(this._intersection.sub(this._cameraPlaneOffset),this._groundPlanePoint,!0),this.onDidUpdate())}}onUpdateWorldPosition(e,t,i){if(!!this._selected){if(i){let n=B(this._selected);n.y=e.y,e=n}if(ie(this._selected,e),ie(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=t!==null,t){let n=B(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(n,n,n),ie(this._groundMarker,t)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;let e=this._context.input.getPointerPositionRC(0);!e||(this._raycaster.setFromCamera(e,this._camera),this._cameraPlane.setFromNormalAndCoplanarPoint(this._camera.getWorldDirection(this._cameraPlane.normal),this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld)),this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&this._selected.parent&&(this._inverseMatrix.copy(this._selected.parent.matrixWorld).invert(),this._cameraPlaneOffset.copy(this._intersection).sub(this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld))))}onUpdateGroundPlane(){if(!this._selected||!this._context)return;let e=B(this._selected),t=new Y.Ray(new Y.Vector3(0,.1,0).add(e),new Y.Vector3(0,-1,0)),i=new be;i.ignore=[this._selected];let n=this._context.physics.raycastFromRay(t,i);for(let r=0;r<n.length;r++){let s=n[r];if(!s.face||this.contains(this._selected,s.object))continue;let a=new Y.Vector3(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(a,s.point);break}this._hasGroundPlane=!0,this._groundPlane.setFromNormalAndCoplanarPoint(t.direction.multiplyScalar(-1),t.origin),this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection),this._groundDistance=this._intersection.distanceTo(e),this._groundOffset.copy(this._intersection).sub(e)}onDidUpdate(){oe.markDirty(this._selected);for(let e of this._rbs)e.wakeUp(),e.resetForcesAndTorques(),e.setAngularVelocity(0,0,0)}contains(e,t){if(e===t)return!0;if(e.children){for(let i of e.children)if(this.contains(i,t))return!0}return!1}},hc=nh;I(hc,"geometry",new Y.BufferGeometry().setFromPoints([new Y.Vector3(0,0,0),new Y.Vector3(0,-1,0)]));var Pi=class extends M{url=null;urlParameterName=null;localhost=null;awake(){this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?Pi.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){let r=P(this.urlParameterName);r&&typeof r=="string"&&(e=r)}if(!e)return null;let i=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return i?.groups?i?.groups.socket_prefix?e:"wss://"+i?.groups.url:null}static GetUrl(e,t){let i=e,n=Pi.IsLocalNetwork()&&t;return n&&(i=t),e?.startsWith("/")&&(i=(n?i:window.location.origin)+e),i}static IsLocalNetwork(e=window.location.hostname){return ct(e)}};var br=class extends M{filesBackendUrl;localhost;_dragOver;_drop;onEnable(){this.filesBackendUrl=this.filesBackendUrl?Pi.GetUrl(this.filesBackendUrl,this.localhost):void 0,this._dragOver=this.onDrag.bind(this),this._drop=this.onDrop.bind(this),this.context.domElement.addEventListener("dragover",this._dragOver),this.context.domElement.addEventListener("drop",this._drop)}onDisable(){this.context.domElement.removeEventListener("dragover",this._dragOver),this.context.domElement.removeEventListener("drop",this._drop)}onDrag(e){e.preventDefault()}async addFiles(e){for(let t of e){if(!t)continue;console.log("Register file "+t.name+" to",this.filesBackendUrl,t);let i=await Uu(t,this.context,this.filesBackendUrl);this.dispatchEvent(new CustomEvent("file-dropped",{detail:t})),i&&this.addObject(void 0,i)}}async onDrop(e){if(console.log(e),!e.dataTransfer)return;e.preventDefault();let t=e.dataTransfer.items;if(!!t)for(let i in t){let n=t[i];if(n.kind==="file"){let r=n.getAsFile();if(!r)continue;console.log("Register file "+r.name+" to",this.filesBackendUrl,r);let s=await Uu(r,this.context,this.filesBackendUrl);this.dispatchEvent(new CustomEvent("file-dropped",{detail:r})),s&&this.addObject(e,s)}else n.kind==="string"&&n.type=="text/plain"&&n.getAsString(async r=>{console.log("dropped url",r);try{let s=new URL(r);if(!s)return;let a=await Gf(s,this.context);a&&this.addObject(e,a)}catch{console.log("dropped string is not a valid URL!",r)}})}}async addObject(e,t){console.log("Dropped",t);let i=t.scene;if(e!==void 0){let n=new be;n.setMask(16777215),n.screenPointFromOffset(e.offsetX,e.offsetY);let r=this.context.physics.raycast(n);if(r&&r.length>0)for(let s of r){i.position.copy(s.point);break}}this.gameObject.add(i),this.dispatchEvent(new CustomEvent("object-added",{detail:t}))}};v([y()],br.prototype,"filesBackendUrl",2),v([y()],br.prototype,"localhost",2);import{Vector3 as Tx,Quaternion as Rx,Object3D as Jm}from"three";var Zi=class extends Vt{parent=null;object=null;limitCount=10;limitInterval=60;_currentCount=0;_startPosition=null;_startQuaternion=null;awake(){if(this.object){if(this.object===this.gameObject){console.error("Can not duplicate self");return}this.object.visible=!1,this._startPosition=this.object.position?.clone()??new Tx(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new Rx(0,0,0,1)}let e=R.getComponentInParent(this.gameObject,Ji);e?e.addDragEventListener("selectstart",(t,i)=>{if(this._currentCount>=this.limitCount){i.attached=null;return}let n=this.handleDuplication(i.selected);n&&(console.assert(n!==i.selected,"Duplicated object is original"),i.attached=n)}):console.warn("Could no find drag controls in parent",this.name),$.addEventListener("select-start",(t,i)=>{if(this._currentCount>=this.limitCount){i.grab=null;return}let n=this.handleDuplication(i.selected);n&&(i.grab=n)}),this.cloneLimitIntervalFn()}cloneLimitIntervalFn(){this.destroyed||(this._currentCount>0&&(this._currentCount-=1),setTimeout(()=>{this.cloneLimitIntervalFn()},this.limitInterval/this.limitCount*1e3))}handleDuplication(e){if(this._currentCount>=this.limitCount||!this.object)return null;if(e===this.gameObject||this.handleMultiObject(e)){if(this.object===this.gameObject)return null;this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);let t=new Ue;this.parent||(this.parent=this.gameObject.parent),this.parent&&(t.parent=this.parent.guid??this.parent.userData?.guid,t.keepWorldPosition=!0),t.position=this.worldPosition,t.rotation=this.worldQuaternion,t.context=this.context,this._currentCount+=1;let i=R.instantiateSynced(this.object,t);return console.assert(i!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),i}return null}handleMultiObject(e){return this.gameObject.type==="Group"||this.gameObject.type==="Object3D"?this.isInChildren(this.gameObject,e):!1}isInChildren(e,t){if(!e)return!1;if(e===t)return!0;if(e.children){for(let i of e.children)if(this.isInChildren(i,t))return!0}return!1}};v([y(Jm)],Zi.prototype,"parent",2),v([y(Jm)],Zi.prototype,"object",2),v([y()],Zi.prototype,"limitCount",2),v([y()],Zi.prototype,"limitInterval",2);var ba=class{eventID;callback};v([y()],ba.prototype,"eventID",2),v([y(de)],ba.prototype,"callback",2);var so=class extends M{triggers;invoke(e){if(!!this.triggers)for(let t of this.triggers)t.eventID===e&&t.callback.invoke()}onPointerClick(e){this.invoke(4)}onPointerEnter(e){this.invoke(0)}onPointerExit(e){this.invoke(1)}onPointerDown(e){this.invoke(2)}onPointerUp(e){this.invoke(3)}};v([y(ba)],so.prototype,"triggers",2);import*as en from"three";import*as va from"three";var Bn=class{get lightmap(){return this.lightmapTexture}set lightmap(e){e!==this.lightmapTexture&&(this.lightmapTexture=e,this.setupLightmap())}lightmapIndex=-1;lightmapScaleOffset=new va.Vector4(1,1,0,0);context;gameObject;lightmapTexture=null;lightmapScaleOffsetUniform={value:new va.Vector4(1,1,0,0)};lightmapUniform={value:null};beforeRenderCallback;constructor(e,t){this.gameObject=e,this.context=t}init(e,t,i,n=!1){if(console.assert(this.gameObject!==void 0&&this.gameObject!==null,"Missing gameobject",this),this.lightmapIndex=e,this.lightmapIndex<0)return;this.lightmapScaleOffset=t,this.lightmapTexture=i,n&&this.setLightmapDebugMaterial(),this.setupLightmap()}bindOnBeforeRender(){this.beforeRenderCallback=this.onBeforeRenderThreeComplete.bind(this),this.context.addBeforeRenderListener(this.gameObject,this.beforeRenderCallback)}onBeforeRenderThreeComplete(e,t,i,n,r,s){this.onBeforeRenderThree(r)}setupLightmap(){if(this.gameObject.type==="Object3D")return;if(this.gameObject.type==="Group"){console.warn("Lightmap on multimaterial object is not supported yet... please ask kindly for implementation.");return}console.assert(this.gameObject.type==="Mesh","Lightmap only works on meshes",this);let e=this.gameObject;e.geometry.getAttribute("uv2")||e.geometry.setAttribute("uv2",e.geometry.getAttribute("uv"));let t=this.gameObject.material.clone();if(this.gameObject.material=t,this.gameObject.material.onBeforeCompile=(i,n)=>{i.uniforms.lightmap=this.lightmapUniform,i.uniforms.lightmapScaleOffset=this.lightmapScaleOffsetUniform},this.lightmapIndex>=0){let i=this.lightmapTexture,n=this.gameObject.material;n&&i&&(n.uniforms||(n.uniforms={}),n.lightMap=i,n.uniforms.lightmap={value:i})}}onBeforeRenderThree(e){let t=e.uniforms;t&&t.lightmap&&(this.lightmapScaleOffsetUniform.value=this.lightmapScaleOffset,this.lightmapUniform.value=this.lightmapTexture,t.lightmap=this.lightmapUniform,t.lightmapScaleOffset=this.lightmapScaleOffsetUniform)}setLightmapDebugMaterial(){this.gameObject.material=new va.ShaderMaterial({vertexShader:`
|
|
215
|
+
--------------`),i[r]=a,a.needsUpdate=!0,i.needsUpdate=!0,ze)){let c=Ed.get(i);c||(c={},Ed.set(i,c));let u=c[r];u||(u=c[r]={original:s,lod0:a}),u.lod0=a}}))}}get name(){return xd}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}_loading=[];afterRoot(e){return ze&&console.log("AFTER",this.sourceId,e),this.parser.json.textures?.forEach((t,i)=>{if(t?.extensions){let n=t?.extensions[xd];if(n){let r=this.parser.getDependency("texture",i);this._loading.splice(this._loading.indexOf(i),1),r.then(s=>{ze&&console.log("register texture",s.name,s.uuid,n),s.userData.deferred=n,sa.cache.set(s.uuid,n)})}}}),null}static async getOrLoadTexture(e,t,i,n,r,s){let a=r.uuid,c=sa.cache.get(a);if(c){ze&&console.log(a,c.uri,c.guid);let u=Ii(t,c.uri);if(u.endsWith(".glb")||u.endsWith(".gltf")){if(!c.guid)return console.warn("missing pointer for glb/gltf texture",c),null;let l=u+"_"+c.guid;if(this.resolved[l])return ze&&console.log("Texture has already been loaded: "+l,i.name,n,r.name),this.resolved[l];let d=this.onProgressiveLoadStart(e,t,u,i,n);try{if(this.currentlyLoading[l]!==void 0)return ze&&console.log("Already loading:",i.name+"."+n,l),await this.currentlyLoading[l];let h=new Promise(async(E,_)=>{let x=new r_;xn(x,e),ze&&console.log("Load "+u,i.name,n,c.guid),ze&&await _o(Math.random()*1e3);let m=await x.loadAsync(u),f=m.parser;ze&&console.log("Loading finished "+u,i.name,n,c.guid);let p=-1,b=!1;for(let C of m.parser.json.textures)if(p++,C?.extensions){let T=C?.extensions[xd];if(T?.guid&&T.guid===c.guid){b=!0;break}}if(!b)return E(null);let w=await f.getDependency("texture",p);w.encoding=r.encoding,w&&(w.guid=c.guid),this.resolved[l]=w,ze&&console.log(i.name,n,'change "'+r.name+'" \u2192 "'+w.name+'"',u,p,w,i,l),E(w)});return this.currentlyLoading[l]=h,await h}finally{delete this.currentlyLoading[l],this.onProgressiveLoadEnd(d)}}else{let l=this.onProgressiveLoadStart(e,t,u,i,n);try{ze&&console.log("Load texture from uri: "+u);let h=await new n_().loadAsync(u);return h?(h.guid=c.guid,h.flipY=!1,h.needsUpdate=!0,h.encoding=r.encoding,ze&&console.log(c,h)):ze&&console.warn("failed loading",u),h}finally{this.onProgressiveLoadEnd(l)}}}else ze&&console.warn("unknown uuid",r.name,r.uuid,r);return null}static beginListenStart(e,t){this._progressiveEventListeners.has(e)||this._progressiveEventListeners.set(e,new Yl),this._progressiveEventListeners.get(e).start.push(t)}static stopListenStart(e,t){if(!this._progressiveEventListeners.has(e))return;let i=this._progressiveEventListeners.get(e).start,n=i.indexOf(t);n>=0&&i.splice(n,1)}static beginListenEnd(e,t){this._progressiveEventListeners.has(e)||this._progressiveEventListeners.set(e,new Yl),this._progressiveEventListeners.get(e).end.push(t)}static stopListenEnd(e,t){if(!this._progressiveEventListeners.has(e))return;let i=this._progressiveEventListeners.get(e).end,n=i.indexOf(t);n>=0&&i.splice(n,1)}static onProgressiveLoadStart(e,t,i,n,r){this._currentProgressiveLoadingInfo.has(e)||this._currentProgressiveLoadingInfo.set(e,[]);let s=new Cd(e,t,i,n,r),a=this._currentProgressiveLoadingInfo.get(e),c=this._progressiveEventListeners.get(e);return c&&c.onStart(s),a.push(s),s}static onProgressiveLoadEnd(e){if(!e)return;let t=e.context;if(!this._currentProgressiveLoadingInfo.has(t))return;let i=this._currentProgressiveLoadingInfo.get(t),n=i.indexOf(e);if(n<0)return;i.splice(n,1);let r=this._progressiveEventListeners.get(t);r&&r.onEnd(e)}},mi=sa;I(mi,"cache",new Map),I(mi,"resolved",{}),I(mi,"currentlyLoading",{}),I(mi,"_progressiveEventListeners",new Map),I(mi,"_currentProgressiveLoadingInfo",new Map);var Cd=class{context;source;uri;material;slot;constructor(e,t,i,n,r){this.context=e,this.source=t,this.uri=i,this.material=n,this.slot=r}},Yl=class{start=[];end=[];onStart(e){for(let t of this.start)t(e)}onEnd(e){for(let t of this.end)t(e)}};function Rd(o){let e=new zo;return o.register(t=>(e.parser=t,e)),e}var Td=class{resolvePath(e){return e.includes("/extensions/builtin_components/")?e.replace("/extensions/builtin_components/","/userData/components/"):e.includes("extensions/builtin_components/")?e.replace("extensions/builtin_components/","/userData/components/"):e}};function Sd(o,e,t){o.register(n=>new Ql(n)),o.register(n=>new Va(n)),o.register(n=>new kl(n,e.lightmaps,t)),o.register(n=>new ql(n,t,e)),o.register(n=>new Wl(n,t)),o.register(n=>new Wr(n,t)),o.register(n=>new mi(n,t,e)),o.register(n=>new Xl(n));let i=o.setAnimationPointerResolver;typeof i=="function"&&i.bind(o)(new Td)}var Yh={};hp(Yh,{AlignmentConstraint:()=>tr,Animation:()=>Bt,AnimationCurve:()=>gi,AnimationExtension:()=>ir,AnimationTrackHandler:()=>nr,Animator:()=>Pe,AnimatorController:()=>fi,AttachedObject:()=>bt,AudioListener:()=>bi,AudioSource:()=>se,AudioTrackHandler:()=>rr,AvatarBlink_Simple:()=>Qi,AvatarEyeLook_Rotation:()=>qi,AvatarLoader:()=>or,AvatarMarker:()=>le,AvatarModel:()=>Kr,Avatar_Brain_LookAt:()=>Sn,Avatar_MouthShapes:()=>ur,Avatar_MustacheShake:()=>ns,Avatar_POI:()=>ye,AxesHelper:()=>Mn,BaseUIComponent:()=>We,BasicIKConstraint:()=>rs,BoxCollider:()=>pr,BoxGizmo:()=>_i,BoxHelperComponent:()=>Ne,Button:()=>qt,CallInfo:()=>vi,Camera:()=>Z,Canvas:()=>Xe,CanvasGroup:()=>Ln,CapsuleCollider:()=>Xt,CharacterController:()=>Yi,CharacterControllerInput:()=>Ti,Collider:()=>Ot,ColorAdjustments:()=>gr,ColorBySpeedModule:()=>Ri,ColorOverLifetimeModule:()=>jn,ControlTrackHandler:()=>Rn,Deletable:()=>ds,DeleteBox:()=>ro,DeviceFlag:()=>oo,DragControls:()=>Ji,DropListener:()=>br,Duplicatable:()=>Zi,EmissionModule:()=>_t,EventList:()=>de,EventListEvent:()=>Qr,EventSystem:()=>Je,EventTrigger:()=>so,FieldWithDefault:()=>ps,FixedJoint:()=>ms,FlyControls:()=>gs,GltfExport:()=>$t,GltfExportBox:()=>bs,Gradient:()=>Si,Graphic:()=>yt,GraphicRaycaster:()=>vs,GridHelper:()=>Un,GridLayoutGroup:()=>xs,GroundProjectedEnv:()=>tn,HingeJoint:()=>vr,HorizontalLayoutGroup:()=>_s,Image:()=>An,InheritVelocityModule:()=>Jt,InputField:()=>kt,Interactable:()=>Vt,Keyboard:()=>ws,LODGroup:()=>yr,LODModel:()=>nn,LayoutGroup:()=>Gn,Light:()=>qe,LimitVelocityOverLifetimeModule:()=>ue,LogStats:()=>Cs,LookAtConstraint:()=>_n,MainModule:()=>_e,MaskableGraphic:()=>In,MeshCollider:()=>Zr,MeshRenderer:()=>ao,MinMaxCurve:()=>U,MinMaxGradient:()=>Me,NestedGltf:()=>ho,Networking:()=>Pi,NoiseModule:()=>K,ObjectRaycaster:()=>co,OffsetConstraint:()=>rn,OrbitControls:()=>Ve,ParticleBurst:()=>Hn,ParticleSubEmitter:()=>_r,ParticleSystem:()=>ve,ParticleSystemRenderer:()=>on,PlayableDirector:()=>Cn,PlayerColor:()=>xt,PointerEventData:()=>xi,RGBAColor:()=>Q,RawImage:()=>to,Raycaster:()=>lo,Rect:()=>eo,RectTransform:()=>vt,ReflectionProbe:()=>Zt,RegisteredAnimationInfo:()=>Nr,RemoteSkybox:()=>Oi,Renderer:()=>ae,RendererLightmap:()=>Bn,Rigidbody:()=>J,RotationBySpeedModule:()=>Qe,RotationOverLifetimeModule:()=>Ze,ScreenCapture:()=>Er,ShadowCatcher:()=>Cr,ShapeModule:()=>ne,SignalAsset:()=>qr,SignalReceiver:()=>En,SignalReceiverEvent:()=>Yr,SignalTrackHandler:()=>Tn,Size:()=>ss,SizeBySpeedModule:()=>ke,SizeOverLifetimeModule:()=>Kt,SkinnedMeshRenderer:()=>fs,SmoothFollow:()=>Mt,SpatialHtml:()=>Ps,SpatialTrigger:()=>Vn,SpatialTriggerReceiver:()=>It,SpectatorCamera:()=>Os,SphereCollider:()=>hr,Sprite:()=>ei,SpriteRenderer:()=>sn,SpriteSheet:()=>an,SubEmitterSystem:()=>xr,SyncedCamera:()=>Rr,SyncedRoom:()=>ki,SyncedTransform:()=>Pt,TeleportTarget:()=>Jr,TestRunner:()=>Ms,TestSimulateUserData:()=>Is,Text:()=>Ie,TextureSheetAnimationModule:()=>xe,ToneMapping:()=>mr,TrailModule:()=>te,TransformData:()=>Xr,TransformGizmo:()=>fo,UIRaycastUtils:()=>Ei,UIRootComponent:()=>kn,USDZExporter:()=>Sr,UsageMarker:()=>zt,VRUserState:()=>Nt,VelocityOverLifetimeModule:()=>He,VerticalLayoutGroup:()=>ys,VideoPlayer:()=>Te,Voip:()=>rt,Volume:()=>no,VolumeComponent:()=>Ki,VolumeParameter:()=>cs,VolumeProfile:()=>fr,WebAR:()=>cr,WebARSessionRoot:()=>mt,WebXR:()=>V,WebXRAvatar:()=>Gt,WebXRController:()=>$,WebXRSync:()=>On,XRFlag:()=>Ee,XRGrabModel:()=>mo,XRGrabRendering:()=>As,XRRig:()=>lr,XRState:()=>St,__Ignore:()=>Oa});import{Vector3 as o_}from"three";var tr=class extends M{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new o_}update(){if(!this.from||!this.to)return;let e=B(this.from).clone(),t=B(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),ie(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(B(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}};v([y(R)],tr.prototype,"from",2),v([y(R)],tr.prototype,"to",2);var Vi=class{time;value;inTangent;inWeight;outTangent;outWeight;weightedMode};v([y()],Vi.prototype,"time",2),v([y()],Vi.prototype,"value",2),v([y()],Vi.prototype,"inTangent",2),v([y()],Vi.prototype,"inWeight",2),v([y()],Vi.prototype,"outTangent",2),v([y()],Vi.prototype,"outWeight",2),v([y()],Vi.prototype,"weightedMode",2);var gi=class{keys;get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;if(this.keys[0].time>=e)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){let i=this.keys[t];if(i.time<=e)if(t+1<this.keys.length){let r=this.keys[t+1];if(r.time<e)continue;let s=H.remap(e,i.time,r.time,0,1);return H.lerp(i.value,r.value,s)}else return i.value}return this.keys[this.keys.length-1].value}};v([y(Vi)],gi.prototype,"keys",2);import{Matrix4 as s_,Vector3 as vm,Quaternion as a_}from"three";import{buildMatrix as l_}from"three/examples/jsm/exporters/USDZExporter";var No=P("debugusdzanimation"),Nr=class{get start(){return this.ext.getStartTime01(this.root,this.clip)}get duration(){return this.clip.duration}ext;root;clip;constructor(e,t,i){this.ext=e,this.root=t,this.clip=i}},Xr=class{clip;pos;rot;scale;get frameRate(){return 60}ext;root;target;constructor(e,t,i,n){this.ext=e,this.root=t,this.target=i,this.clip=n}addTrack(e){e.name.endsWith("position")&&(this.pos=e),e.name.endsWith("quaternion")&&(this.rot=e),e.name.endsWith("scale")&&(this.scale=e)}getFrames(){return Math.max(this.pos?.times?.length??0,this.rot?.times?.length??0,this.scale?.times?.length??0)}getDuration(){let e=this.pos?.times??this.rot?.times??this.scale?.times;return e?e[e.length-1]:0}getStartTime(e){let t=0;for(let i=0;i<e.length;i++){let n=e[i];if(n===this)return t;t+=n.getDuration()}return t}},ir=class{get extensionName(){return"animation"}dict=new Map;rootTargetMap=new Map;getStartTime01(e,t){let i=this.rootTargetMap.get(e);if(!i)return 1/0;let n=-1;for(let r of i){let s=this.dict.get(r),a=0;if(s?.length){for(let c of s){if(c.clip===t)break;a+=c.getDuration()}n=Math.max(n,a)}else console.warn("No animation found on root",e,t,s)}return n}registerAnimation(e,t){if(!t||!e)return null;this.rootTargetMap.has(e)||this.rootTargetMap.set(e,[]);for(let n of t.tracks){let r=n.name.split(".")[2],s=e.getObjectByName(r);if(!s){console.warn("no object found for track",n.name,"using "+e.name+" instead");continue}this.dict.has(s)||this.dict.set(s,[]);let a=this.dict.get(s);if(!a)continue;let c=a.find(l=>l.clip===t);c||(c=new Xr(this,e,s,t),a.push(c)),c.addTrack(n);let u=this.rootTargetMap.get(e);u?.includes(s)||u?.push(s)}return new Nr(this,e,t)}onAfterHierarchy(e){No&&console.log(this.dict)}serializers=[];onAfterBuildDocument(e){for(let t of this.serializers){let i=t.model?.parent,n=i?.isDynamic===!0;No&&console.log(n,t.model?.parent),n&&t.registerCallback(i)}}onExportObject(e,t,i){R.foreachComponent(e,r=>{let s=r;typeof s.createAnimation=="function"&&s.createAnimation(this,t,i)},!1);let n=new Pd(e,this.dict);this.serializers.push(n),n.registerCallback(t)}},Pd=class{object;dict;model;callback;constructor(e,t){this.object=e,this.dict=t}registerCallback(e){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),No&&console.log("REPARENT",e),this.model=e,this.model.addEventListener("serialize",this.callback)}onSerialize(e,t){No&&console.log("SERIALIZE",this.model.name,this.object.type);let i=this.object,n=this.dict.get(i);if(!n)return;let r=new s_,s=new vm,a=new a_,c=new vm(1,1,1);e.appendLine("matrix4d xformOp:transform.timeSamples = {"),e.indent++;for(let u of n){let l=u.pos?.times;if((!l||u.rot&&u.rot.times?.length>l?.length)&&(l=u.rot?.times),(!l||u.scale&&u.scale.times?.length>l?.length)&&(l=u.scale?.times),!l){console.error("got an animated object but no time values??",i,u);continue}let d=u.getStartTime(n);No&&e.appendLine(u.clip.name+": start="+d.toFixed(3)+", length="+u.getDuration().toFixed(3)+", frames="+u.getFrames());let h=u.pos?.createInterpolant(),g=u.rot?.createInterpolant(),E=u.scale?.createInterpolant();h||s.set(i.position.x,i.position.y,i.position.z),g||a.set(i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w),E||c.set(i.scale.x,i.scale.y,i.scale.z);for(let _=0;_<l.length;_++){let x=l[_];if(h){let f=h.evaluate(x);s.set(f[0],f[1],f[2])}if(g){let f=g.evaluate(x);a.set(f[0],f[1],f[2],f[3])}if(E){let f=E.evaluate(x);f.set(f[0],f[1],f[2])}r.compose(s,a,c);let m=`${(d+x)*u.frameRate}: ${l_(r)},`;No&&(m="#"+_+" "+m),e.appendLine(m)}}e.indent--,e.appendLine("}")}};import*as wm from"three";import*as ym from"three";import*as aa from"three";import{PositionalAudioHelper as c_}from"three/examples/jsm/helpers/PositionalAudioHelper.js";var pt=P("debugaudio");var De=class extends M{static get userInteractionRegistered(){return De._didCallBeginWaitForUserInteraction||(De._didCallBeginWaitForUserInteraction=!0,De._beginWaitForUserInteraction()),De._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),De._didCallBeginWaitForUserInteraction||(De._didCallBeginWaitForUserInteraction=!0,De._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);let i=(()=>{if(i!=null&&!De._userInteractionRegistered){De._userInteractionRegistered=!0,console.log("registered interaction, can play audio now"),document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i);for(let n of this.callbacks)n();this.callbacks.length=0}}).bind(this);document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)}clip="";playOnAwake=!1;get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}_spatialBlend=0;_minDistance=1;_maxDistance=100;get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&(pt&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}_volume=1;rollOffMode=0;_loop=!1;sound=null;helper=null;wasPlaying=!1;audioLoader=null;shouldPlay=!1;_lastClipStartedLoading=null;get Sound(){if(!this.sound&&De._userInteractionRegistered){let e=R.getComponent(this.context.mainCamera,bi)??R.findObjectOfType(bi,this.context);e?.listener&&(this.sound=new aa.PositionalAudio(e.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}_focusCallback;awake(){this.audioLoader=new aa.AudioLoader,this.playOnAwake&&(this.shouldPlay=!0),window.addEventListener("visibilitychange",e=>{switch(document.visibilityState){case"hidden":this.wasPlaying=this.isPlaying,this.pause();break;case"visible":this.wasPlaying&&this.play();break}}),this._focusCallback=()=>{this.enabled&&this.playOnAwake&&!this.isPlaying&&De._userInteractionRegistered&&this.play()},this.context.application.addEventListener("application-visible",this._focusCallback)}onDestroy(){this.context.application.removeEventListener("application-visible",this._focusCallback)}onEnable(){De._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():De._beginWaitForUserInteraction(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.loadAndPlay(this.clip)})}onDisable(){this.stop()}lerp=(e,t,i)=>e*(1-i)+t*i;onLoaded(e){pt&&console.log("audio buffer loaded"),De.registerWaitForAllowAudio(()=>{pt&&console.log("finished loading",e);let t=this.Sound;if(!t){console.warn("Failed getting sound",this.name);return}t.isPlaying&&t.stop(),t.setBuffer(e),t.loop=this._loop,t.setVolume(this.volume),t.autoplay=this.shouldPlay,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),pt&&console.log(this.name,this.shouldPlay,De.userInteractionRegistered,this),this.shouldPlay&&De._userInteractionRegistered&&this.play()})}applySpatialDistanceSettings(){let e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;let t=this.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(pt&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:break}this.spatialBlend>0?pt&&!this.helper&&(this.helper=new c_(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&(pt&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new aa.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){pt&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,pt&&console.log("load audio",this.clip),this.audioLoader.load(this.clip,this.onLoaded.bind(this),()=>{},console.error)}}play(e=void 0){if(!this.audioLoader||!this.sound||e&&e!==this.clip){this.loadAndPlay(e);return}this.shouldPlay=!0,this._hasEnded=!1,pt&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying&&this.sound.play()}pause(){pt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause())}stop(){pt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,pt&&console.log(this._lastContextTime),this.sound.stop())}_lastContextTime=0;get isPlaying(){return this.sound?.isPlaying??!1}set isPlaying(e){}get time(){return this.sound?.source?this.sound.source?.context.currentTime-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;let t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}_hasEnded=!0;_needUpdateSpatialDistanceSettings=!1;update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,pt&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},se=De;I(se,"_didCallBeginWaitForUserInteraction",!1),I(se,"callbacks",[]),I(se,"_userInteractionRegistered",!1),v([y()],se.prototype,"clip",2),v([y()],se.prototype,"playOnAwake",2),v([y()],se.prototype,"loop",1),v([y()],se.prototype,"spatialBlend",1),v([y()],se.prototype,"minDistance",1),v([y()],se.prototype,"maxDistance",1),v([y()],se.prototype,"volume",1),v([y()],se.prototype,"rollOffMode",2);var bi=class extends M{get listener(){return this._listener==null&&(this._listener=new ym.AudioListener),this._listener}_listener=null;awake(){se.registerWaitForAllowAudio(()=>{let e=this.listener;if(e==null||e.parent)return;let t=R.getComponentInParent(this.gameObject,Z);t?t.cam.add(e):this.gameObject.add(e)})}};var vi=class{method;enabled;constructor(e,t){this.method=e,this.enabled=t!==void 0?t:!0}invoke(...e){if(this.enabled!==!1){if(!this.method){console.warn("No function. Please check you assigned a method to invoke on export",this);return}this.method(...e)}}},u_=o=>/^[A-Z]*$/.test(o),Qr=class extends Event{args},de=class{target;key;setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let i="",n=!1;for(let r of this.key)n&&u_(r)&&(i+="-"),n=!0,i+=r.toLowerCase();this.key=i}}_isInvoking=!1;methods=[];constructor(e){this.methods=e??[]}invoke(...e){if(this._isInvoking){console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this);return}this._isInvoking=!0;try{for(let t of this.methods)t.invoke(...e);if(typeof this.target=="object"&&typeof this.key=="string"){let t=this.target.dispatchEvent;if(typeof t=="function"){let i=new Qr(this.key);i.args=e,t.call(this.target,i)}}}finally{this._isInvoking=!1}}addEventListener(e){return this.methods.push(new vi(e,!0)),e}removeEventListener(e){if(!!e)for(let t=this.methods.length-1;t>=0;t--)this.methods[t].method===e&&(this.methods[t].enabled=!1,this.methods.splice(t,1))}removeAllEventListeners(){this.methods.length=0}};var qr=class{guid},Yr=class{signal;reaction;$serializedTypes={signal:qr,reaction:de}},En=class extends M{events;start(){console.log(this)}invoke(e){if(!this.events||!Array.isArray(this.events))return;let t=typeof e=="object"?e.guid:e;for(let i of this.events)if(i.signal.guid===t)try{if(i.reaction){if(!i.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",i,this);continue}}else{console.warn("Missing reaction for signal",i,this);continue}i.reaction.invoke()}catch(n){console.error(n)}}};v([y(Yr)],En.prototype,"events",2);var xm=P("debugtimeline");var Kl=class extends M{static registerCreateTrack(e,t){this.createTrackFunctions[e]=t}playableAsset;playOnAwake;extrapolationMode=1;get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(e){this._time=e}get duration(){return this._duration}set duration(e){this._duration=e}get weight(){return this._weight}set weight(e){this._weight=e}_visibilityChangeEvt;_clonedPlayableAsset=!1;awake(){xm&&console.log(this,this.playableAsset?.tracks),this.rebuildGraph(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,this.playableAsset?.tracks,Array.isArray(this.playableAsset?.tracks),this)}onEnable(){for(let e of this._audioTracks)e.onEnable?.();for(let e of this._customTracks)e.onEnable?.();this.playOnAwake&&this.play(),this._visibilityChangeEvt||(this._visibilityChangeEvt=()=>{switch(document.visibilityState){case"hidden":this.setAudioTracksAllowPlaying(!1);break;case"visible":this.setAudioTracksAllowPlaying(!0);break}}),window.addEventListener("visibilitychange",this._visibilityChangeEvt)}onDisable(){this.stop();for(let e of this._audioTracks)e.onDisable?.();for(let e of this._customTracks)e.onDisable?.();this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){for(let e of this._audioTracks)e.onDestroy?.()}rebuildGraph(){!this.isValid()||(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}play(){!this.isValid()||(this._isPaused=!1,!this._isPlaying&&(this._isPlaying=!0,this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate())))}pause(){this._isPaused=!0}stop(){this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.evaluate()),this._isPlaying=!1,this._isPaused=!1,this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null}evaluate(){if(!this.isValid())return;let e=this._time;switch(this.extrapolationMode){case 0:e=Math.min(e,this._duration);break;case 1:e%=this._duration;break;case 2:if(e>this._duration){this.stop();return}break}this.internalEvaluate(e)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(let e of this._allTracks)for(let t of e)yield t}get audioTracks(){return this._audioTracks}_guidsMap;resolveGuids(e){this._guidsMap=e}_isPlaying=!1;_internalUpdateRoutine;_isPaused=!1;_time=0;_duration=0;_weight=1;_animationTracks=[];_audioTracks=[];_signalTracks=[];_controlTracks=[];_customTracks=[];_allTracks=[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks];*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime,this.evaluate()),yield}internalEvaluate(e){for(let t of this.playableAsset.tracks)if(!t.muted)switch(t.type){case"ActivationTrack":for(let i=0;i<t.outputs.length;i++){let n=t.outputs[i];if(typeof n=="object"){let r=!1;for(let a of t.clips)a.start<=e&&e<=a.end&&(r=!0);let s=n;s.visible!==void 0&&(s.visible=r)}}break}for(let t of this._animationTracks)t.evaluate(e);for(let t of this._audioTracks)t.evaluate(e);for(let t of this._signalTracks)t.evaluate(e);for(let t of this._controlTracks)t.evaluate(e);for(let t of this._customTracks)t.evaluate(e)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Us(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;let e=this.findRoot(this.gameObject);for(let t of this.playableAsset.tracks)for(let i=t.outputs.length-1;i>=0;i--){let n=t.outputs[i];if(typeof n=="string"){this._guidsMap&&this._guidsMap[n]&&(n=this._guidsMap[n]);let r=R.findByGuid(n,e);r===null||typeof r!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(xm&&console.log("Resolved binding",n,"to",r),t.outputs[i]=r,r instanceof Pe)}else if(n===null){if(t.outputs.splice(i,1),Kl.createTrackFunctions[t.type])continue;t.type!=="AudioTrack"&&t.type!=="ControlTrack"&&t.type!=="MarkerTrack"&&console.warn("Missing binding",n,t.name,t.type,this.name,this.playableAsset.name)}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(let e of this.playableAsset.tracks)if(e.muted!==!0)for(let t of e.clips)t.end>this._duration&&(this._duration=t.end)}}setupAndCreateTrackHandlers(){if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let e=[];for(let t of this.playableAsset.tracks){let i=t.type,n=Kl.createTrackFunctions[i];if(n!=null){let r=n(this,t);if(typeof r.evaluate=="function"){r.director=this,r.track=t,this._customTracks.push(r);continue}}if(t.type==="AnimationTrack"){if(t.clips.length<=0)continue;for(let r=t.outputs.length-1;r>=0;r--){let s=t.outputs[r];typeof s.enabled=="boolean"&&(s.enabled=!1);let a=s?.gameObject?.animations;if(a){let c=new nr;c.trackOffset=t.trackOffset,c.director=this,c.track=t;for(let u=0;u<t.clips.length;u++){let l=t.clips[u],d=l.asset;if(!d){console.error("MISSING anim model?","clip#"+u,l,t,this.playableAsset,this.name);continue}let h=d.clip,g=h;if((typeof g=="string"||typeof g=="number")&&(g=a.find(_=>_.name===h)),!g){console.warn("Could not find animationClip for model",l,t.name,this.name,this.playableAsset?.name);continue}c.mixer||(c.mixer=new wm.AnimationMixer(s.gameObject)),c.clips.push(g),c.mixer.uncacheAction(g),c.createHooks(l.asset,g);let E=c.mixer.clipAction(g);c.actions.push(E),c.models.push(l)}this._animationTracks.push(c)}}}else if(t.type==="AudioTrack"){if(t.clips.length<=0)continue;e.push(t)}else if(t.type==="MarkerTrack"){let r=new Tn;r.director=this,r.track=t;for(let s of t.markers)switch(s.type){case"SignalEmitter":r.models.push(s),r.didTrigger.push(!1);break}if(r!==null&&r.models.length>0){let s=R.getComponent(this.gameObject,En);s&&(r.receivers.push(s),this._signalTracks.push(r))}}else if(t.type==="SignalTrack"){let r=new Tn;r.director=this,r.track=t;for(let s of t.markers)r.models.push(s),r.didTrigger.push(!1);for(let s of t.outputs)r.receivers.push(s);this._signalTracks.push(r)}else if(t.type==="ControlTrack"){let r=new Rn;r.director=this,r.track=t;for(let s of t.clips)r.models.push(s);r.resolveSourceObjects(this.context),this._controlTracks.push(r)}}se.registerWaitForAllowAudio(()=>{let t=R.findObjectOfType(bi,this.context);if(!!t)for(let i of e){let n=new rr;n.director=this,n.track=i,n.listener=t.listener;for(let r=0;r<i.clips.length;r++){let s=i.clips[r];n.addModel(s)}this._audioTracks.push(n)}})}setAudioTracksAllowPlaying(e){for(let t of this._audioTracks)t.onAllowAudioChanged(e)}},Cn=Kl;I(Cn,"createTrackFunctions",{});import*as ee from"three";import{Quaternion as h_,Vector3 as p_}from"three";var Xo=P("debugtimeline"),Qo=class{director;track;get muted(){return this.track.muted}set muted(e){e!==this.track.muted&&(this.track.muted=e,this.onMuteChanged?.call(this))}*forEachClip(e=!1){if(!!this.track?.clips)if(e)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(let t of this.track.clips)yield t}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,i,n=!0){if(t<0||t>=i.length)return 0;let r=i[t];if(n||e>=r.start&&e<=r.end){let s=1,a=!1;if(r.easeInDuration>0){let c=Math.min((e-r.start)/r.easeInDuration,1);s*=c}if(r.easeOutDuration>0&&!a){let c=Math.min((r.end-e)/r.easeOutDuration,1);s*=c}return s}return 0}},Od=class{clip;rootPositionOffset;rootQuaternionOffset;get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}rootStartPosition;rootEndPosition;rootStartQuaternion;rootEndQuaternion;constructor(e){let t=e.getClip();this.clip=t;let i=e.getRoot(),n=i.name+".position",r=i.name+".quaternion";Xo&&console.log(t.name,t.tracks,n);for(let s of t.tracks)if(!(s.times.length<=0)){if(s.name.endsWith(n))this.rootStartPosition=new ee.Vector3().fromArray(s.values,0),this.rootEndPosition=new ee.Vector3().fromArray(s.values,s.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),Xo&&console.log(this.rootPositionOffset);else if(s.name.endsWith(r)&&(this.rootStartQuaternion=new ee.Quaternion().fromArray(s.values,0),this.rootEndQuaternion=new ee.Quaternion().fromArray(s.values,s.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),Xo)){let a=new ee.Euler().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",a)}}}},nr=class extends Qo{models=[];trackOffset;target;mixer;clips=[];actions=[];_actionOffsets=[];_didBind=!1;createHooks(e,t){if(t.tracks?.length<=0){console.warn("No tracks in AnimationClip",t);return}let i=t.tracks[0].name.split("."),n=i[i.length-2],r=n+".position",s=n+".quaternion",a=!1,c=!1;for(let u of t.tracks)u.name.endsWith(r)?(a=!0,this.createPositionInterpolant(t,e,u)):u.name.endsWith(s)&&(c=!0,this.createRotationInterpolant(t,e,u));if(!a||!c){let u=this.mixer?.getRoot(),l=t.tracks[0],d=l.name.lastIndexOf("."),h=l.name.substring(0,d),g=h.substring(h.lastIndexOf(".")+1),E=u.getObjectByName(g);if(E)if(a){if(!c){let _=t.tracks[0].name.substring(0,d)+".quaternion";Xo&&console.warn("Create quaternion track",g,E);let x=E.quaternion,m=new ee.QuaternionKeyframeTrack(_,[0,t.duration],[x.x,x.y,x.z,x.w,x.x,x.y,x.z,x.w]);t.tracks.push(m),this.createRotationInterpolant(t,e,m)}}else{let _=h+".position";Xo&&console.warn("Create position track",g,E);let x=E.position,m=new ee.VectorKeyframeTrack(_,[0,t.duration],[x.x,x.y,x.z,x.x,x.y,x.z]);t.tracks.push(m),this.createPositionInterpolant(t,e,m)}}}bind(){if(!this._didBind){this._didBind=!0,Xo&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(let e of this.actions){let t=new Od(e);this._actionOffsets.push(t)}for(let e of this.models){let t=e.asset,i=t.position,n=t.rotation;i.x!==void 0&&(i.isVector3||(t.position=new p_(i.x,i.y,i.z)),n.isQuaternion||(t.rotation=new h_(n.x,n.y,n.z,n.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){let e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new ee.Vector3(e.x,e.y,e.z)));let t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new ee.Quaternion(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new ee.Vector3;_totalOffsetRotation=new ee.Quaternion;_totalOffsetPosition2=new ee.Vector3;_totalOffsetRotation2=new ee.Quaternion;_summedPos=new ee.Vector3;_tempPos=new ee.Vector3;_summedRot=new ee.Quaternion;_tempRot=new ee.Quaternion;evaluate(e){if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let t=0,i=0,n=!1;for(let r=0;r<this.clips.length;r++){let s=this.models[r],a=this.actions[r],c=s.asset;a.weight=0;let u=e>=s.start&&e<=s.end,l=s.postExtrapolationMode,d=u;if(!d&&!n&&s.end<e&&s.postExtrapolationMode!==0){let h=r<this.clips.length-1?this.models[r+1]:null;(!h||h.start>e)&&(d=!0,n=!0)}if(d){let h=1;h*=this.evaluateWeight(e,r,this.models,d);let g=this.getClipTime(e,s),E=0,_=c.duration;if(u){if(c.loop)for(E+=Math.floor(g/(_+1e-6));g>_;)g-=_}else if(!u)switch(l){case 2:g%=_;break;case 3:let f=Math.floor(g/_)%2!==0;g%=_,f&&(g=_-g);break}a.time=g,a.timeScale=0;let x=h*this.director.weight;if(a.weight=x,a.clampWhenFinished=!0,a.isRunning()||a.play(),this._useclipOffsets){let m=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,f=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-h),t+=1;let p=this._summedPos.set(0,0,0),b=this._tempPos.set(0,0,0),w=this._summedRot.identity(),C=this._tempRot.identity(),T=c.rotation,S=new ee.Quaternion;S.slerp(T,h);let A=this._actionOffsets[r];if(A.hasOffsets)for(let D=0;D<E;D++)A.rootPositionOffset?b.copy(A.rootPositionOffset):b.set(0,0,0),b.applyQuaternion(w).applyQuaternion(S),A.rootQuaternionOffset&&(C.copy(A.rootQuaternionOffset),w.multiply(C)),p.add(b);f.multiply(S),f.multiply(w),p.add(c.position),m.add(p)}}}this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,i),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,i)),this.mixer.update(e)}createRotationInterpolant(e,t,i){let n=i.createInterpolant.bind(i),r=new ee.Quaternion;this.ensureTrackOffsets();let s=this.trackOffset?.rotation;i.createInterpolant=()=>{let a=n(),c=a.evaluate.bind(a);return a.evaluate=u=>{let l=c(u);return r.set(l[0],l[1],l[2],l[3]),r.premultiply(this._totalOffsetRotation),s&&r.premultiply(s),l[0]=r.x,l[1]=r.y,l[2]=r.z,l[3]=r.w,l},a}}createPositionInterpolant(e,t,i){let n=i.createInterpolant.bind(i),r=new ee.Vector3;this.ensureTrackOffsets();let s=this.trackOffset?.rotation,a=this.trackOffset?.position,c;i.createInterpolant=()=>{let u=n(),l=u.evaluate.bind(u);return u.evaluate=d=>{let h=l(d);return r.set(h[0],h[1],h[2]),t.removeStartOffset&&(c===void 0?(c=null,c=this._actionOffsets.find(g=>g.clip===e)?.rootStartPosition?.clone()):c?.isVector3&&r.sub(c)),r.applyQuaternion(this._totalOffsetRotation),r.add(this._totalOffsetPosition),s&&r.applyQuaternion(s),a&&(r.x-=a.x,r.y+=a.y,r.z+=a.z),h[0]=r.x,h[1]=r.y,h[2]=r.z,h},u}}},rr=class extends Qo{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;getAudioFilePath(e){let t=this.director.sourceId;return Ii(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){let i=this.models[t];this.audio[t].setVolume(e?i.asset.volume:0)}}addModel(e){let t=this.getAudioFilePath(e.asset.clip),i=new ee.Audio(this.listener);i.setVolume(e.asset.volume);let n=new ee.AudioLoader;console.log(t,this.director.sourceId),n.load(t,r=>{i.setBuffer(r),i.loop=e.asset.loop,this.audio.push(i),this.models.push(e)})}onDisable(){for(let e of this.audio)e.isPlaying&&e.stop()}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){let t=this.audio[e];t?.isPlaying&&t.stop()}}evaluate(e){if(!this.track.muted){for(let t=0;t<this.models.length;t++){let i=this.models[t],n=this.audio[t];if(e>=i.start&&e<=i.end){if(this.director.isPaused&&(n.isPlaying&&n.stop(),this.lastTime===e))continue;n.isPlaying||(n.offset=i.clipIn+(e-i.start)*i.timeScale,n.play());let r=i.asset.volume;if(i.easeInDuration>0){let s=Math.min((e-i.start)/i.easeInDuration,1);r*=s}if(i.easeOutDuration>0){let s=Math.min((i.end-e)/i.easeOutDuration,1);r*=s}n.setVolume(r*this.director.weight)}else n.isPlaying&&n.stop()}this.lastTime=e}}},Tn=class extends Qo{models=[];didTrigger=[];receivers=[];evaluate(e){if(!(this.receivers.length<=0)&&!this.track.muted)for(let t=0;t<this.models.length;t++){let i=this.models[t],n=this.didTrigger[t],r=i.time-e;if(i.retroActive?r<0:r<0&&Math.abs(r)<.1){if(!n){this.didTrigger[t]=!0;for(let a of this.receivers)!a||a.invoke(i.asset)}}else i.emitOnce||(this.didTrigger[t]=!1)}}},la=class extends Qo{models=[];timelines=[];resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){let n=this.models[t].asset;if(typeof n.sourceObject=="string"){let r=n.sourceObject;la.resolved[r]?n.sourceObject=la.resolved[r]:(n.sourceObject=R.findByGuid(r,e.scene),la.resolved[r]=n.sourceObject)}if(n.sourceObject){let r=R.getComponent(n.sourceObject,Cn);this.timelines.push(r),r&&n.updateDirector&&(r.playOnAwake=!1)}else{this.models.splice(t,1);continue}}}_previousActiveModel=null;evaluate(e){this._previousActiveModel=null;for(let t=0;t<this.models.length;t++){let i=this.models[t],n=i.asset;if(e>=i.start&&e<=i.end){this._previousActiveModel=i;let r=this.getClipTime(e,i);if(n.controlActivation){let s=n.sourceObject;s.visible=!0}if(n.updateDirector){let s=this.timelines[t];s&&(s.isPlaying&&s.pause(),s.time=r,s.evaluate())}}else{let r=this._previousActiveModel?.asset;if(n.controlActivation){let s=n.sourceObject;r?.sourceObject!==s&&(s.visible=!1)}}}}},Rn=la;I(Rn,"resolved",{});import{BoxHelper as F_,BufferGeometry as B_,Color as Dm,Euler as U_,Layers as G_,Line as V_,Mesh as z_,MeshBasicMaterial as W_,Quaternion as sc,Ray as N_,SphereGeometry as X_,Vector2 as Q_,Vector3 as Ci}from"three";import{OculusHandModel as q_}from"three/examples/jsm/webxr/OculusHandModel.js";import{OculusHandPointerModel as Y_}from"three/examples/jsm/webxr/OculusHandPointerModel.js";import{XRControllerModelFactory as K_}from"three/examples/jsm/webxr/XRControllerModelFactory.js";import{GLTFLoader as J_}from"three/examples/jsm/loaders/GLTFLoader.js";import*as Tm from"three";import{Quaternion as m_,Vector3 as Zl}from"three";import{GLTFLoader as f_}from"three/examples/jsm/loaders/GLTFLoader";import*as Jl from"three";var ca=P("debugavatar"),Kr=class{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(r=>r.layers.set(2))}},or=class{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){let r=new Ue;i=R.instantiate(Wn(t,e.scene),r)}}else i=t;if(!i)return null;let n=this.findAvatar(i);return n.isValid?(ca&&console.log("[Custom Avatar] valid config",t,ca?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,ca?n:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(ca&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){let n=await fetch("./"+t),r=null;if(n.ok){let a=await n.blob();a&&(r=await a.arrayBuffer())}return!r&&(r=await _l(t,t,0,"no url here go away",!0),!r)?null:(await Ke().parseSync(e,r,null,0))?.scene??null}let i=new f_;return xn(i,e),new Promise((n,r)=>{let s=this.avatarRegistryUrl+"/"+t;i.load(s,async a=>{await Ke().createBuiltinComponents(e,s,a,null,void 0),n(a.scene)},a=>{ca&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),n(null)})})}cacheModel(e,t){}findAvatar(e){let t=e,i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,["head"]),r=this.findAvatarPart(i,["left","hand"]),s=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;let c=new Jl.Vector3;new Jl.Box3().setFromObject(n).getSize(c);let u=Math.max(c.x,c.y,c.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+u+" meters! Should be < 0.3m"),u>.3&&n.scale.multiplyScalar(1/u*.3)}return new Kr(t,n,r,s)}findAvatarPart(e,t){let i=e.name.toLowerCase(),n=!0;for(let r of t){if(!n)break;i.indexOf(r)===-1&&(n=!1)}if(n)return e;if(e.children)for(let r of e.children){let s=this.findAvatarPart(r,t);if(s)return s}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}};var qo=P("debugflags");var kd=class{Mask=17;Has(e){return(this.Mask&e)!==0}Set(e){qo&&console.warn("Set XR flag state to",e),this.Mask=e,Ee.Apply()}Enable(e){this.Mask|=e,Ee.Apply()}Disable(e){this.Mask&=~e,Ee.Apply()}Toggle(e){this.Mask^=e,Ee.Apply()}EnableAll(){this.Mask=-1,Ee.Apply()}DisableAll(){this.Mask=0,Ee.Apply()}},St=kd;I(St,"Global",new kd);var zi=class extends M{static Apply(){for(let e of this.registry)e.UpdateVisible(St.Global)}awake(){zi.registry.push(this)}onEnable(){zi.firstApply||(zi.firstApply=!0,zi.Apply())}onDestroy(){let e=zi.registry.indexOf(this);e>=0&&zi.registry.splice(e,1)}visibleIn;get isOn(){return this.gameObject.visible}UpdateVisible(e=null){let t,i=e;i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),qo&&console.log(i),zi.buffer.Mask=i,e=zi.buffer);let n=e;if(n?(qo&&console.warn(this.name,"use passed in mask",n.Mask,this.visibleIn),t=n.Has(this.visibleIn)):(qo&&console.log(this.name,"use global mask"),St.Global.Has(this.visibleIn)),t!==void 0)if(t)qo&&console.log(this.name,"is visible",this.gameObject.uuid),R.setActive(this.gameObject,!0);else{if(qo&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},Ee=zi;I(Ee,"registry",[]),I(Ee,"firstApply"),I(Ee,"buffer",new St);import{Object3D as Md}from"three";var sr=P("debugavatar"),yi=class extends M{static getAvatar(e){return e>=0&&e<yi.instances.length?yi.instances[e]:null}static onAvatarMarkerCreated(e){return yi._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return yi._onAvatarMarkerDestroyed.push(e),e}connectionId;avatar;awake(){yi.instances.push(this),sr&&console.log(this);for(let e of yi._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){yi.instances.splice(yi.instances.indexOf(this),1);for(let e of yi._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}setVisible(e){this.avatar&&("setVisible"in this.avatar?this.avatar.setVisible(e):R.setActive(this.avatar,e))}},le=yi;I(le,"instances",[]),I(le,"_onNewAvatarMarkerAdded",[]),I(le,"_onAvatarMarkerDestroyed",[]);var ua=class{_isVisible=!0;setVisible(e){this._isVisible=e,this.updateVisibility()}get isWebXRAvatar(){return!0}guid;root=null;head=null;handLeft=null;handRight=null;lastUpdate=-1;isLocalAvatar=!1;flags=null;headScale=new Zl(1,1,1);handLeftScale=new Zl(1,1,1);handRightScale=new Zl(1,1,1);webxr;lastAvatarId=null;hasAvatarOverride=!1;context;avatarMarker=null;constructor(e,t,i){this.context=e,this.guid=t,this.webxr=i,this.setupCustomAvatar(this.webxr.defaultAvatar)}updateFlags(){if(!this.flags)return;let e=this.isLocalAvatar?8:16;this.context.isInVR?e|=4:this.context.isInAR?e|=2:e|=1;for(let t of this.flags)t.gameObject.visible=!0,t.UpdateVisible(e)}async setAvatarOverride(e){return this.hasAvatarOverride=e!==null,this.hasAvatarOverride&&this.lastAvatarId!==e&&(this.lastAvatarId=e,e!=null&&e.length>0)?await this.setupCustomAvatar(e):null}_headTarget=new Md;_handLeftTarget=new Md;_handRightTarget=new Md;_canInterpolate=!1;tryUpdate(e,t){if(e.guid===this.guid&&(this.lastAvatarId!==e.avatarId&&e.avatarId&&e.avatarId.length>0&&(this.lastAvatarId=e.avatarId,this.setupCustomAvatar(e.avatarId)),this.lastUpdate=e.time,this.head)){let i=this.webxr.IsInAR?"handheld":"headset",n=this.head;this.context.players.setPlayerView(e.guid,n,i),oe.markDirty(this.head),this._canInterpolate=!0;let r=this.isLocalAvatar?this.head:this._headTarget;if(r.position.set(e.position.x,e.position.y,e.position.z),r.quaternion.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),r.scale.set(e.scale,e.scale,e.scale),r.scale.multiply(this.headScale),this.handLeft){let s=this.isLocalAvatar?this.handLeft:this._handLeftTarget;s.position.set(e.posLeftHand.x,e.posLeftHand.y,e.posLeftHand.z),s.quaternion.set(e.rotLeftHand._x,e.rotLeftHand._y,e.rotLeftHand._z,e.rotLeftHand._w),s.quaternion.multiply(ua.invertRotation),s.scale.set(e.scale,e.scale,e.scale),s.scale.multiply(this.handLeftScale),oe.markDirty(this.handLeft)}if(this.handRight){let s=this.isLocalAvatar?this.handRight:this._handRightTarget;s.position.set(e.posRightHand.x,e.posRightHand.y,e.posRightHand.z),s.quaternion.set(e.rotRightHand._x,e.rotRightHand._y,e.rotRightHand._z,e.rotRightHand._w),s.quaternion.multiply(ua.invertRotation),s.scale.set(e.scale,e.scale,e.scale),s.scale.multiply(this.handRightScale),oe.markDirty(this.handRight)}}}update(){if(this.isLocalAvatar||!this._canInterpolate)return;let e=this.context.time.deltaTime/.1;this.head&&(this.head.position.lerp(this._headTarget.position,e),this.head.quaternion.slerp(this._headTarget.quaternion,e),this.head.scale.lerp(this._headTarget.scale,e)),this.handLeft&&this._handLeftTarget&&(this.handLeft.position.lerp(this._handLeftTarget.position,e),this.handLeft.quaternion.slerp(this._handLeftTarget.quaternion,e),this.handLeft.scale.lerp(this._handLeftTarget.scale,e)),this.handRight&&this._handRightTarget&&(this.handRight.position.lerp(this._handRightTarget.position,e),this.handRight.quaternion.slerp(this._handRightTarget.quaternion,e),this.handRight.scale.lerp(this._handRightTarget.scale,e))}destroy(){sr&&console.log("Destroy avatar",this.guid),this.root?.removeFromParent(),this.avatarMarker?.destroy(),this.lastAvatarId=null,this.head&&ye.Remove(this.context,this.head)}updateVisibility(){let e=this.root;e&&R.setActive(e,this._isVisible)}async setupCustomAvatar(e){if(sr&&console.log("LOAD",e,this),!e||typeof e=="string"&&e.length<=0)return!1;this.head&&ye.Remove(this.context,this.head);let t=e;if(t?.loadAssetAsync!==void 0){await t.loadAssetAsync();let n=t.asset;R.setActive(n,!1),e=R.instantiate(n),R.setActive(e,!0)}sr&&console.log(e);let i=await ua.loader.getOrCreateNewAvatarInstance(this.context,e);if(sr&&console.log(i,i?.isValid,this.lastAvatarId,e),i?.isValid){if(this.root=i.root,this.root.position.set(0,0,0),this.root.quaternion.set(0,0,0,1),this.root.scale.set(1,1,1),this.avatarMarker=R.addNewComponent(this.root,le),this.avatarMarker.connectionId=this.guid,this.avatarMarker.avatar=this,this.head&&this.head!==i.head&&this.head?.removeFromParent(),this.head=i.head,this.headScale.copy(this.head.scale),this.head&&!this.isLocalAvatar&&ye.Add(this.context,this.head,this.avatarMarker),i.leftHand&&this.handLeft?.removeFromParent(),this.handLeft=i.leftHand??this.handLeft,this.handLeft?this.handLeftScale.copy(this.handLeft.scale):this.handLeftScale.set(1,1,1),i.rigthHand&&this.handRight?.removeFromParent(),this.handRight=i.rigthHand??this.handRight,this.handRight?this.handRightScale.copy(this.handRight.scale):this.handRightScale.set(1,1,1),this.context.scene.add(this.root),this.flags==null&&(this.flags=[]),this.flags.length=0,this.flags.push(...R.getComponentsInChildren(this.root,Ee)),this.flags.length<=0&&this.head){let n=R.addNewComponent(this.head,Ee);n.visibleIn=20,this.flags.push(n),sr&&console.log("Added flag to head: "+n.visibleIn,this.head.name)}return sr&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return sr&&console.warn("build avatar failed"),!1}},Gt=ua;I(Gt,"loader",new or),I(Gt,"invertRotation",new m_().setFromAxisAngle(new Zl(0,1,0),Math.PI));var ye=class{static Add(e,t,i=null){if(!!t){for(let n of this.Pois)if(n.obj===t)return;this.Pois.push({obj:t,avatar:i}),this.LastChangeTime=e.time.time}}static Remove(e,t){if(!!t){for(let i of this.Pois)if(i.obj===t){this.Pois.splice(this.Pois.indexOf(i),1),this.LastChangeTime=e?.time.time??G.Current?.time.time;return}}}};I(ye,"Pois",[]),I(ye,"LastChangeTime",0);var Id=class{guid;position=new Tm.Vector3},Sn=class extends M{set controlledTarget(e){this.target=e;let t=O.get("MoveRandom");if(t&&this.target){let i=R.getComponent(this.target,t);i&&i.destroy()}}target=null;avatar=null;_model=null;_targetModel=new Id;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=R.getComponentInParent(this.gameObject,le),this.avatar){let e=R.getComponentInParent(this.gameObject,le);this._model=new Kn(this.context.connection,this.guid),e?.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{this.target&&e&&e.guid===this.avatar?.guid&&ie(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(ye.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=ye.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){let t=B(this._currentTargetObject);ie(this.target,t),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(t))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;let t=ye.Pois;if(t.length>0){let i=t[Math.floor(Math.random()*t.length)];if(i&&i.obj){if(i.avatar&&i.avatar===this.avatar)return;this._currentTargetObject=i.obj}}}}};var Vt=class extends M{canGrab=!0;onPointerClick(e){}},zt=class extends M{isUsed=!0;usedBy=null};import*as Yo from"three";import{Matrix4 as g_,Vector3 as Rm}from"three";var Ad=class{get isDirty(){return this.positionChanged||this.rotationChanged}positionChanged=!1;rotationChanged=!1;position;quaternion;_positionKeys=["x","y","z"];_quaternionKeys=["_x","_y","_z","_w"];reset(e=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,e){if(this.position)for(let t of this._positionKeys)delete this.position[t];if(this.quaternion)for(let t of this._quaternionKeys)delete this.quaternion[t]}}syncValues(){for(let e of this._positionKeys)this.position[e]=this.obj.position[e];for(let e of this._quaternionKeys)this.quaternion[e]=this.obj.quaternion[e]}mute=!1;applyValues(){if(this.positionChanged&&this.position)for(let e of this._positionKeys){let t=this.position[e];t!==void 0&&(this.obj.position[e]=t)}if(this.rotationChanged&&this.quaternion)for(let e of this._quaternionKeys){let t=this.quaternion[e];t!==void 0&&(this.obj.quaternion[e]=t)}}context;obj;_positionWatch;_rotationWatch;constructor(e,t){this.context=t,this.obj=e}start(e,t){this.reset(),e&&(this._positionWatch||(this._positionWatch=new dn(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((r,s)=>{if(this.context.physics.isUpdating||this.mute)return;let a=this.position[s];Math.abs(a-r)<1e-5||(this.position[s]=r,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new dn(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((r,s)=>{if(this.context.physics.isUpdating||this.mute)return;let a=this.quaternion[s];Math.abs(a-r)<1e-5||(this.quaternion[s]=r,this.rotationChanged=!0)}));let i=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),n=new g_;this.obj.matrixWorld.multiplyMatrices=(r,s)=>(n.equals(r)||(this.positionChanged=!0,this.rotationChanged=!0,n.copy(r)),i(r,s))}stop(){this._positionWatch?.revoke(),this._rotationWatch?.revoke()}},$l=class extends M{mass=1;useGravity=!0;constraints=0;isKinematic=!1;drag=0;angularDrag=1;detectCollisions=!0;sleepThreshold=.01;collisionDetectionMode=0;get lockPositionX(){return(this.constraints&2)!==0}get lockPositionY(){return(this.constraints&4)!==0}get lockPositionZ(){return(this.constraints&8)!==0}get lockRotationX(){return(this.constraints&16)!==0}get lockRotationY(){return(this.constraints&32)!==0}get lockRotationZ(){return(this.constraints&64)!==0}set lockPositionX(e){e?this.constraints|=2:this.constraints&=-3}set lockPositionY(e){e?this.constraints|=4:this.constraints&=-5}set lockPositionZ(e){e?this.constraints|=8:this.constraints&=-9}set lockRotationX(e){e?this.constraints|=16:this.constraints&=-17}set lockRotationY(e){e?this.constraints|=32:this.constraints&=-33}set lockRotationZ(e){e?this.constraints|=64:this.constraints&=-65}set gravityScale(e){this._gravityScale=e}get gravityScale(){return this._gravityScale}_gravityScale=1;_propertiesChanged=!1;_currentVelocity=new Yo.Vector3;_smoothedVelocity=new Yo.Vector3;_smoothedVelocityGetter=new Yo.Vector3;_lastPosition=new Yo.Vector3;_watch;awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new Ad(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),2)}onDisable(){this._watch?.stop(),this.context.physics.removeBody(this)}onDestroy(){this.context.physics.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,this.context.physics.updateProperties(this)),this._watch?.isDirty?(this._watch.mute=!0,this._watch.applyValues(),this.context.physics.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):this._watch?.syncValues(),this.captureVelocity(),yield}get body(){return this.context.physics.internal_getRigidbody(this)}teleport(e,t=!0){this._watch?.reset(!0),t?this.gameObject.position.set(e.x,e.y,e.z):this.setWorldPosition(e.x,e.y,e.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(){this.body?.resetForces(!0)}resetTorques(){this.body?.resetTorques(!0)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){this.body?.wakeUp()}applyForce(e,t){this.body?.addForce(e,!0)}applyImpulse(e){this.body?.applyImpulse(e,!0)}setForce(e,t,i){this.body?.resetForces(!0),this.body?.addForce({x:e,y:t,z:i},!0)}getVelocity(){let e=this.body?.linvel();return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(e,t,i){if(e instanceof Rm){let n=e;this.body?.setLinvel(n,!0);return}t===void 0||i===void 0||this.body?.setLinvel({x:e,y:t,z:i},!0)}setAngularVelocity(e,t,i){if(e instanceof Rm){let n=e;this.body?.setAngvel(n,!0);return}t===void 0||i===void 0||this.body?.setAngvel({x:e,y:t,z:i},!0)}getAngularVelocity(){let e=this.body?.angvel();return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setTorque(e,t,i){this.setAngularVelocity(e,t,i)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(e=null){}captureVelocity(){if(this.body){let e=B(this.gameObject);$l.tempPosition.copy(e);let t=e.sub(this._lastPosition);this._lastPosition.copy($l.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}}},J=$l;I(J,"tempPosition",new Yo.Vector3),v([ui(),y()],J.prototype,"mass",2),v([ui(),y()],J.prototype,"useGravity",2),v([ui(),y()],J.prototype,"constraints",2),v([ui(),y()],J.prototype,"isKinematic",2),v([ui(),y()],J.prototype,"drag",2),v([ui(),y()],J.prototype,"angularDrag",2),v([ui(),y()],J.prototype,"detectCollisions",2),v([ui(),y()],J.prototype,"sleepThreshold",2),v([ui(),y()],J.prototype,"collisionDetectionMode",2);import*as Pn from"three";var Ce=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(e,t,i,n){return e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var Ko=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Ce).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Ce).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Ce).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,n,r,s,a,c,u,l){return e.prep(4,36),e.prep(4,12),e.writeFloat32(l),e.writeFloat32(u),e.writeFloat32(c),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(s),e.writeFloat32(r),e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var Wt=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new Wt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+4),(t||new Wt).__init(e.readInt32(e.position())+e.position(),e)}guid(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){let e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){let t=this.bb.__offset(this.bb_pos,8);return t?(e||new Ko).__init(this.bb_pos+t,this.bb):null}dontSave(){let e=this.bb.__offset(this.bb_pos,10);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startSyncedTransformModel(e){e.startObject(4)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addFast(e,t){e.addFieldInt8(1,+t,0)}static addTransform(e,t){e.addFieldStruct(2,t,0)}static addDontSave(e,t){e.addFieldInt8(3,+t,0)}static endSyncedTransformModel(e){return e.endObject()}static finishSyncedTransformModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedTransformModelBuffer(e,t){e.finish(t,void 0,!0)}};var ar=P("debugsync"),Jo="STRS";Ho(Jo,Wt.getRootAsSyncedTransformModel);var Wi=new Ct;function Dd(o,e,t=!0){Wi.clear();let i=Wi.createString(o);Wt.startSyncedTransformModel(Wi),Wt.addGuid(Wi,i),Wt.addFast(Wi,t);let n=e.worldPosition,r=e.worldEuler,s=e.gameObject.scale;Wt.addTransform(Wi,Ko.createTransform(Wi,n.x,n.y,n.z,r.x,r.y,r.z,s.x,s.y,s.z));let a=Wt.endSyncedTransformModel(Wi);return Wi.finish(a,Jo),Wi.asUint8Array()}var Pt=class extends M{overridePhysics=!0;interpolatePosition=!0;interpolateRotation=!0;fastMode=!1;syncDestroy=!1;_model=null;_needsUpdate=!0;rb=null;_wasKinematic=!1;_receivedDataBefore=!1;_targetPosition;_targetRotation;_receivedFastUpdate=!1;_shouldRequestOwnership=!1;requestOwnership(){ar&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){return this._model?.hasOwnership??void 0}isOwned(){return this._model?.isOwned}joinedRoomCallback=null;receivedDataCallback=null;awake(){ar&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new Pn.Vector3,this._targetRotation=new Pn.Quaternion,this.lastWorldPos=new Pn.Vector3,this.lastWorldRotation=new Pn.Quaternion,this.rb=R.getComponentInChildren(this.gameObject,J),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Kn(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen("joined-room",this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinrary(Jo,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Kp(this.guid,this.context.connection),this._model=null,this.context.connection.stopListening("joined-room",this.joinedRoomCallback),this.context.connection.stopListenBinary(Jo,this.receivedDataCallback)}tryGetLastState(){let e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new Pn.Euler;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){ar&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();let t=e.transform();if(t){oe.markDirty(this.gameObject,!0);let i=t.position();i&&(this.interpolatePosition&&this._targetPosition?.set(i.x(),i.y(),i.z()),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(i.x(),i.y(),i.z()));let n=t.rotation();n&&(this.tempEuler.set(n.x(),n.y(),n.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&Fp(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}receivedUpdate=!1;lastWorldPos;lastWorldRotation;onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){ar&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());let e=this.worldPosition,t=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){let r=e.distanceTo(this.lastWorldPos),s=t.angleTo(this.lastWorldRotation),a=this._model.hasOwnership||this.fastMode?1e-4:.001;(r>a||s>a)&&(this._model.hasOwnership?this._needsUpdate=!0:(ar&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,e.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,t.copy(this.lastWorldRotation),oe.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){let s=this._receivedFastUpdate||this.fastMode?.5:.3,a=!1;if(this.interpolatePosition&&this._targetPosition){let c=this.worldPosition;c.lerp(this._targetPosition,s),this.worldPosition=c,a=!0}if(this.interpolateRotation&&this._targetRotation){let c=this.worldQuaternion;c.slerp(this._targetRotation,s),this.worldQuaternion=c,a=!0}a&&oe.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(e),this.lastWorldRotation.copy(t),!this._model)return;if(!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership){this.rb&&(this.rb.isKinematic=this._model.isOwned??!1,this.rb.setVelocity(0,0,0));return}this.rb&&(this._wasKinematic!==void 0&&(ar&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new Pn.Vector3(0,0,0))>1e3&&(ar&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0)));let i=10,n=this.rb||this.fastMode;if(this._needsUpdate&&(i<=0||i>0&&this.context.time.frameCount%i===0||n)){ar&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this.overridePhysics&&this.rb,this._needsUpdate=!1;let r=Dd(this.guid,this,!!n);this.context.connection.sendBinary(r)}}};import*as oc from"three-mesh-ui";import{Euler as C_,EventDispatcher as T_,Group as R_,Matrix4 as S_,Mesh as P_,MeshBasicMaterial as O_,Object3D as Mm,Quaternion as rc,RingGeometry as k_,Vector3 as Im}from"three";var ec=class{static createButton(e,t={}){let i=document.createElement("button"),n=!1;function r(){if(t.domOverlay===void 0){var u=document.createElement("div");u.style.display="none",document.body.appendChild(u);var l=document.createElementNS("http://www.w3.org/2000/svg","svg");l.setAttribute("width",38),l.setAttribute("height",38),l.style.position="absolute",l.style.right="20px",l.style.top="20px",l.addEventListener("click",function(){h.end()}),u.appendChild(l);var d=document.createElementNS("http://www.w3.org/2000/svg","path");d.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),d.setAttribute("stroke","#fff"),d.setAttribute("stroke-width",2),l.appendChild(d),t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("dom-overlay"),t.domOverlay={root:u},n=!0}t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("local-floor"),t.optionalFeatures.push("hand-tracking"),t.optionalFeatures.push("layers");let h=null,g=null;async function E(x){if(/WebXRViewer\//i.test(navigator.userAgent))if(t.domOverlay?.root){let f=t.domOverlay.root;g=f.parentElement,g&&(console.log("Reparent DOM Overlay to body",f,f.style.display),f.style.display="",f.style.visibility="",document.body.appendChild(f))}else console.warn("WebXRViewer: No DOM Overlay found");x.addEventListener("end",_),await e.xr.setSession(x),i.textContent="STOP AR",n&&(t.domOverlay.root.style.display=""),h=x}function _(){h.removeEventListener("end",_),i.textContent="START AR",g&&g.appendChild(t.domOverlay.root),n&&(t.domOverlay.root.style.display="none"),h=null}i.style.display="",i.style.cursor="pointer",i.style.left="calc(50% - 50px)",i.style.width="100px",i.textContent="START AR",i.onmouseenter=function(){i.style.opacity="1.0"},i.onmouseleave=function(){i.style.opacity="0.5"},i.onclick=function(){h===null?navigator.xr.requestSession("immersive-ar",t).then(E):h.end()}}function s(){i.disabled=!0,i.style.display="",i.style.cursor="auto",i.style.left="calc(50% - 75px)",i.style.width="150px",i.onmouseenter=null,i.onmouseleave=null,i.onclick=null}function a(){s(),i.textContent="AR NOT SUPPORTED"}function c(u){u.style.position="absolute",u.style.bottom="20px",u.style.padding="12px 6px",u.style.border="1px solid #fff",u.style.borderRadius="4px",u.style.background="rgba(0,0,0,0.1)",u.style.color="#fff",u.style.font="normal 13px sans-serif",u.style.textAlign="center",u.style.opacity="0.5",u.style.outline="none",u.style.zIndex="999"}if("xr"in navigator)return i.id="ARButton",i.style.display="none",c(i),navigator.xr.isSessionSupported("immersive-ar").then(function(u){u?r():a()}).catch(a),i;{let u=document.createElement("a");return window.isSecureContext===!1?(u.href=document.location.href.replace(/^http:/,"https:"),u.innerHTML="WEBXR NEEDS HTTPS"):(u.href="https://immersiveweb.dev/",u.innerHTML="WEBXR NOT AVAILABLE"),u.style.left="calc(50% - 90px)",u.style.width="180px",u.style.textDecoration="none",c(u),u}}};var tc=class{static createButton(e,t){t&&console.error('THREE.VRButton: The "options" parameter has been removed. Please set the reference space type via renderer.xr.setReferenceSpaceType() instead.');let i=document.createElement("button");function n(){let c=null;async function u(d){d.addEventListener("end",l),await e.xr.setSession(d),i.textContent="EXIT VR",c=d}function l(){c.removeEventListener("end",l),i.textContent="ENTER VR",c=null}i.style.display="",i.style.cursor="pointer",i.style.left="calc(50% - 50px)",i.style.width="100px",i.textContent="ENTER VR",i.onmouseenter=function(){i.style.opacity="1.0"},i.onmouseleave=function(){i.style.opacity="0.5"},i.onclick=function(){if(c===null){let d={optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};navigator.xr.requestSession("immersive-vr",d).then(u)}else c.end()}}function r(){i.disabled=!0,i.style.display="",i.style.cursor="auto",i.style.left="calc(50% - 75px)",i.style.width="150px",i.onmouseenter=null,i.onmouseleave=null,i.onclick=null}function s(){r(),i.textContent="VR NOT SUPPORTED"}function a(c){c.style.position="absolute",c.style.bottom="20px",c.style.padding="12px 6px",c.style.border="1px solid #fff",c.style.borderRadius="4px",c.style.background="rgba(0,0,0,0.1)",c.style.color="#fff",c.style.font="normal 13px sans-serif",c.style.textAlign="center",c.style.opacity="0.5",c.style.outline="none",c.style.zIndex="999"}if("xr"in navigator)return i.id="VRButton",i.style.display="none",a(i),navigator.xr.isSessionSupported("immersive-vr").then(function(c){c?n():s(),tc.xrSessionIsGranted&&(console.log("XR session is granted - will enter immersive web now"),i.click())}),i;{let c=document.createElement("a");return window.isSecureContext===!1?(c.href=document.location.href.replace(/^http:/,"https:"),c.innerHTML="WEBXR NEEDS HTTPS"):(c.href="https://immersiveweb.dev/",c.innerHTML="WEBXR NOT AVAILABLE"),c.style.left="calc(50% - 90px)",c.style.width="180px",c.style.textDecoration="none",a(c),c}}static registerSessionGrantedListener(){if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent))return;navigator.xr.addEventListener("sessiongranted",()=>{tc.xrSessionIsGranted=!0})}}},$o=tc;I($o,"xrSessionIsGranted",!1);$o.registerSessionGrantedListener();import*as ic from"three";var Sm=ja(fl(),1);import{AudioAnalyser as b_}from"three";var es="noVoip",ft=P("debugvoip"),v_=P("voip");var Ld=class{id;constructor(e){this.id=e}};var jd=class{peer;voip;userId;peerId;call=null;callErrorListener=null;stream=null;constructor(e,t,i,n){this.voip=e,this.peer=t,this.userId=i,this.peerId=n}close(){ft&&console.log("close voip call"),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.open&&this.call.close(),this.stream?.getTracks().forEach(function(e){e.stop()})}updateMute(e){if(!this.stream)return;let t=this.stream?.getAudioTracks();for(let i of t)i.enabled=!e}async startVoipCall(){if(!await rt.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}ft&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),ft&&console.log(this.stream),this.call=this.peer.call(this.peerId,this.stream,{metadata:{userId:this.userId}}),this.call.on("error",t=>{console.error(t)}),this.call.on("stream",t=>{ft&&console.log("received stream from remote again",t)}),this.peer.on("close",this.onCallClose.bind(this)),this.callErrorListener=t=>{t.message.includes(this.peerId)?(console.log("Could not connect to "+this.peerId),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.close(),this.stream?.getTracks().forEach(function(i){i.stop()}),this.stream=null):console.error(t)},this.peer.on("error",this.callErrorListener)}onCallClose(e){ft&&console.log("call closed",e)}},Hd=class{get currentStream(){return this.stream}get currentAudio(){return this.audio}get currentAnalyzer(){return this.analyzer}voip;call;audio=null;stream=null;obj;analyzer=null;waitingForStart=!1;closed=!1;audioElement=null;constructor(e,t,i){this.voip=e,this.obj=t,this.call=i}openAudioStream(e){let t=e.getAudioTracks();for(let i of t)if(i.kind==="audio"&&i.readyState==="live"){this.open(i);return}console.warn("failed finding valid audio stream to begin call")}open(e){console.assert(e.kind==="audio","invalid track kind, expected audio but received "+e.kind),!this.waitingForStart&&(this.waitingForStart=!0,se.userInteractionRegistered||ft&&console.log("Incoming call, waiting for user interaction before opening audio"),se.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){ft&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);let t=new ic.AudioListener;this.audio=new ic.Audio(t),this.audio.setVolume(this.voip.muteInput?0:1),this.audio.setMediaStreamSource(this.stream);let i=document.createElement("audio");this.audioElement=i,i.style.display="none",document.body.appendChild(i),i.srcObject=this.stream,i.sinkId!==void 0&&navigator.mediaDevices.enumerateDevices().then(n=>{if(!!i){console.log(n);for(let r of n)if(r.label==="Speakerphone"){i.sinkId=r.deviceId;break}}}),ft&&console.log("call is setup, you should hear something now"),this.analyzer=new b_(this.audio,32)}}))}close(){this.closed=!0,this.call?.open&&this.call.close(),this.audio?.disconnect(),this.stream?.getTracks().forEach(e=>{e.stop()}),this.stream=null,this.audioElement&&this.audioElement.remove()}},rt=class extends M{requireParam=!1;set muteInput(e){if(e===this._inputMuted||(this._inputMuted=e,!this.currentIncomingCalls))return;let t=this._inputMuted?0:1;for(let i in this.currentIncomingCalls)this.currentIncomingCalls[i]?.currentAudio?.setVolume(t)}get muteInput(){return this._inputMuted}set muteOutput(e){if(e!==this._outputMuted&&(this._outputMuted=e,!!this.connections))for(let t in this.connections)this.connections[t]?.updateMute(e)}get muteOutput(){return this._outputMuted}getFrequency(e){if(e===null){for(let i in this.currentIncomingCalls){let n=this.currentIncomingCalls[i];if(n&&n.currentAnalyzer)return n.currentAnalyzer.getAverageFrequency()}return null}let t=this.currentIncomingCalls[e];return t&&t.currentAnalyzer?t.currentAnalyzer.getAverageFrequency():null}peer=null;model=null;connections={};currentIncomingCalls={};_inputMuted=!1;_outputMuted=!1;awake(){if(P(es)){console.log("VOIP is disabled by url parameter: "+es);return}if(this.requireParam&&!v_){console.debug("VOIP must be enabled explicitly by url parameter");return}if(wo()&&Fa()){console.log("VOIP is currently not supported on Safari iOS");return}this.peer=new Sm.default,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,this.context.connection.beginListen("joined-room",e=>{navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}),this.context.connection.beginListen("peer-update-id",e=>{if(e.id!==this.context.connection.connectionId){let t=this.connections[e.id];if(t&&t.close(),this.peer&&this.context.connection.connectionId){let i=new jd(this,this.peer,this.context.connection.connectionId,e.peerId);this.connections[e.id]=i,i.startVoipCall()}}}),this.context.connection.beginListen("user-left-room",e=>{let{userId:t}=e,i=this.connections[t];this.connections[t]=null,i&&i.close();let n=this.currentIncomingCalls[t];ft&&console.log("UserLeftRoom",e,t,n),n&&(n.close(),this.currentIncomingCalls[t]=null)}),this.peer.on("open",this.onOpenPeerConnection.bind(this))}onEnable(){}onDisable(){console.log("TODO: close all");for(let e in this.currentIncomingCalls)try{this.currentIncomingCalls[e]?.close(),this.connections[e]?.close()}catch(t){console.error(t)}}async onOpenPeerConnection(e){ft&&console.log("Peer connection established and received id"),this.model=new Ld(e),this.context.connection.send("peer-update-id",this.model,1),this.peer&&(this.peer.on("call",this.onReceiveCall.bind(this)),this.peer.on("connection",function(t){ft&&console.log("CONNECTION",t),t.on("data",function(i){ft&&console.log("Received",i)})}))}async onReceiveCall(e){let{metadata:t}=e;console.assert(t.userId);let{userId:i}=t,{peer:n}=e,r=this.currentIncomingCalls[i];if(r&&r.close(),ft&&console.log("received call"),await rt.HasMicrophonePermissions()){let s=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(s)}else e.answer(null);this.currentIncomingCalls[i]=new Hd(this,this.gameObject,e),e.on("stream",s=>{ft&&console.log("receive caller stream, will setup audio now"),this.currentIncomingCalls[i]?.openAudioStream(s)}),e.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}};import{Matrix4 as da}from"three";var mt=class extends M{webAR=null;get rig(){return this.webAR?.webxr.Rig}invertForward=!1;get arScale(){return this._arScale}set arScale(e){e!==this._arScale&&(this._arScale=e,this.setScale(e))}_initalMatrix=new da;_selectStartFn=this.onSelectStart.bind(this);_selectEndFn=this.onSelectEnd.bind(this);start(){let e=R.findObjectOfType(V);e&&(e.Rig.updateMatrix(),this._initalMatrix.copy(e.Rig.matrix))}_arScale=5;_rig=null;_startPose=null;_placementPose=null;_isTouching=!1;_rigStartPose=null;onBegin(e){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose=this.gameObject.matrix.clone(),this._rigStartPose=this.rig?.matrix.clone(),e.addEventListener("selectstart",this._selectStartFn),e.addEventListener("selectend",this._selectEndFn),this.gameObject.visible=!1,this.rig&&(this.rig.matrixAutoUpdate=!0,this._initalMatrix.decompose(this.rig.position,this.rig.quaternion,this.rig.scale))}onUpdate(e,t,i){return i&&!this._placementPose&&this._isTouching?(this.webAR&&this.webAR.setReticleActive(!1),this.placeAt(e,new da().fromArray(i.transform.matrix).invert()),!0):!1}placeAt(e,t){this._placementPose||(this._placementPose=new da),this._placementPose.copy(t);let i=this.gameObject.matrixWorld.clone().invert();if(this._placementPose.premultiply(i),e){if(this.invertForward){let n=new da().makeRotationY(Math.PI);this._placementPose.premultiply(n)}this._rig=e,this.setScale(this.arScale)}else this._rig=null;this.gameObject.visible=!0}onEnd(e,t){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose&&this.gameObject.matrix.copy(this._startPose),e&&(e.matrixAutoUpdate=!0,this._rigStartPose&&this._rigStartPose.decompose(e.position,e.quaternion,e.scale)),oe.markDirty(this.gameObject,!0),setTimeout(()=>{this.gameObject.matrixAutoUpdate=!0,this.gameObject.visible=!0},100)}onSelectStart(){this._isTouching=!0}onSelectEnd(){this._isTouching=!1}setScale(e){let t=this._rig;!t||!this._placementPose||(this._rigStartPose||(this._rigStartPose=t.matrix.clone()),t.matrixAutoUpdate=!1,t.matrix.multiplyMatrices(new da().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld(),console.log("Place",t.position))}};v([y()],mt.prototype,"invertForward",2),v([y()],mt.prototype,"arScale",1);import{Object3D as __}from"three";import*as Pm from"three";import{Color as y_}from"three";var _i=class extends M{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!Di||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new Pm.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=cl(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),3)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}};v([y()],_i.prototype,"objectBounds",2),v([y(y_)],_i.prototype,"color",2),v([y()],_i.prototype,"isGizmo",2);var x_=P("debugrig"),lr=class extends M{awake(){if(x_){let e=new __;e.position.y+=.5,this.gameObject.add(e);let t=e.addNewComponent(_i);t&&(t.isGizmo=!1)}}};import{Quaternion as ha,Vector3 as nc,Vector4 as w_}from"three";var Ni=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}w(){return this.bb.readFloat32(this.bb_pos+12)}static sizeOf(){return 16}static createVec4(e,t,i,n,r){return e.prep(4,16),e.writeFloat32(r),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var Oe=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsVrUserStateBuffer(e,t){return(t||new Oe).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+4),(t||new Oe).__init(e.readInt32(e.position())+e.position(),e)}guid(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}time(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}avatarId(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__string(this.bb_pos+t,e):null}position(e){let t=this.bb.__offset(this.bb_pos,10);return t?(e||new Ce).__init(this.bb_pos+t,this.bb):null}rotation(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new Ni).__init(this.bb_pos+t,this.bb):null}scale(){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.readFloat32(this.bb_pos+e):0}posLeftHand(e){let t=this.bb.__offset(this.bb_pos,16);return t?(e||new Ce).__init(this.bb_pos+t,this.bb):null}posRightHand(e){let t=this.bb.__offset(this.bb_pos,18);return t?(e||new Ce).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){let t=this.bb.__offset(this.bb_pos,20);return t?(e||new Ni).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){let t=this.bb.__offset(this.bb_pos,22);return t?(e||new Ni).__init(this.bb_pos+t,this.bb):null}static startVrUserStateBuffer(e){e.startObject(10)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addTime(e,t){e.addFieldInt64(1,t,e.createLong(0,0))}static addAvatarId(e,t){e.addFieldOffset(2,t,0)}static addPosition(e,t){e.addFieldStruct(3,t,0)}static addRotation(e,t){e.addFieldStruct(4,t,0)}static addScale(e,t){e.addFieldFloat32(5,t,0)}static addPosLeftHand(e,t){e.addFieldStruct(6,t,0)}static addPosRightHand(e,t){e.addFieldStruct(7,t,0)}static addRotLeftHand(e,t){e.addFieldStruct(8,t,0)}static addRotRightHand(e,t){e.addFieldStruct(9,t,0)}static endVrUserStateBuffer(e){return e.endObject()}static finishVrUserStateBufferBuffer(e,t){e.finish(t)}static finishSizePrefixedVrUserStateBufferBuffer(e,t){e.finish(t,void 0,!0)}};var Om=P("debugxr"),pa=P("debugavatar");var Bd="VRUS";Ho(Bd,Oe.getRootAsVrUserStateBuffer);function Fd(){return new Date().getTime()}function E_(o){let e=o&4294967295,t=o/Math.pow(2,32)&1048575;return Ye.create(e,t)}var fa=class{guid;time;avatarId;position=new nc;rotation=new w_;scale=1;posLeftHand=new nc;posRightHand=new nc;rotLeftHand=new ha;rotRightHand=new ha;constructor(e){this.guid=e}update(e,t,i,n,r){this.time=Fd(),this.avatarId=r,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let s=fa.quat0,a=fa.quat1;s.set(i.x,i.y,i.z,i.w),s=s.multiplyQuaternions(s,fa.invertRotation),e&&(e.getWorldQuaternion(a),s.multiplyQuaternions(a,s)),this.rotation.set(s.x,s.y,s.z,s.w),this.scale=e.scale.x;let c=n.LeftController?.controllerGrip;c&&(c.getWorldPosition(this.posLeftHand),c.getWorldQuaternion(this.rotLeftHand));let u=n.RightController?.controllerGrip;if(u&&(u.getWorldPosition(this.posRightHand),u.getWorldQuaternion(this.rotRightHand)),n.LeftController?.hand?.visible){let l=n.LeftController.wrist;l&&(l.getWorldPosition(this.posLeftHand),l.getWorldQuaternion(this.rotLeftHand))}if(n.RightController?.hand?.visible){let l=n.RightController.wrist;l&&(l.getWorldPosition(this.posRightHand),l.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(e,t){e.clear();let i=e.createString(this.guid),n=e.createString(this.avatarId);Oe.startVrUserStateBuffer(e),Oe.addGuid(e,i),Oe.addTime(e,E_(this.time)),Oe.addAvatarId(e,n),Oe.addPosition(e,Ce.createVec3(e,this.position.x,this.position.y,this.position.z)),Oe.addRotation(e,Ni.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),Oe.addScale(e,this.scale),Oe.addPosLeftHand(e,Ce.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),Oe.addPosRightHand(e,Ce.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),Oe.addRotLeftHand(e,Ni.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),Oe.addRotRightHand(e,Ni.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));let r=Oe.endVrUserStateBuffer(e);e.finish(r,Bd);let s=e.asUint8Array();t.sendBinary(s)}setFromBuffer(e,t){if(!e)return;this.guid=e,this.time=t.time().toFloat64();let i=t.avatarId();i&&(this.avatarId=i);let n=t.position();n&&this.position.set(n.x(),n.y(),n.z());let r=t.rotation();r&&this.rotation.set(r.x(),r.y(),r.z(),r.w());let s=t.posLeftHand();s&&this.posLeftHand.set(s.x(),s.y(),s.z());let a=t.posRightHand();a&&this.posRightHand.set(a.x(),a.y(),a.z());let c=t.rotLeftHand();c&&this.rotLeftHand.set(c.x(),c.y(),c.z(),c.w());let u=t.rotRightHand();u&&this.rotRightHand.set(u.x(),u.y(),u.z(),u.w()),this.scale=t.scale()}},Nt=fa;I(Nt,"invertRotation",new ha().setFromAxisAngle(new nc(0,1,0),Math.PI)),I(Nt,"quat0",new ha),I(Nt,"quat1",new ha);var On=class extends M{webXR=null;debugAvatarUser=null;voip=null;async awake(){if(this.webXR||(this.webXR=R.getComponent(this.gameObject,V)),this.webXR||(this.webXR=R.findObjectOfType(V,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=R.findObjectOfType(V,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=R.findObjectOfType(rt,this.context)),pa){let e="debug-avatar-"+pa,t=new Gt(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof pa=="string"&&pa.length>0)if(await t.setAvatarOverride(pa)){let i=new Nt(e);i.position.y+=1;let n=.5;i.posLeftHand.y+=n,i.posLeftHand.x+=n,i.posRightHand.y+=n,i.posRightHand.x-=n,t.tryUpdate(i,0)}else t.destroy()}}onEnable(){if(!this.webXR&&(this.webXR=R.getComponent(this.gameObject,V),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),V.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),V.addEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),V.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.eventSub_ConnectionEvent=this.onConnected.bind(this),this.context.connection.beginListen("joined-room",this.eventSub_ConnectionEvent),this.context.connection.beginListen("webxr-user-joined",e=>{console.log("webxr user joined evt")}),this.context.connection.beginListen("webxr-user-left",e=>{let t=e.id!==null&&e.id!==void 0;!t||(console.log("webxr user left evt"),t&&(this.avatars[e.id]?.destroy(),this.avatars[e.id]=void 0))}),this.context.connection.beginListenBinrary(Bd,e=>{let t=e.guid();if(!t)return;let i=e.time().toFloat64(),n=this.tempState;n.setFromBuffer(t,e),this.onTryGetAvatar(t,i)?.tryUpdate(n,i)}),this.context.connection.beginListen("vr-session-update",e=>{let t=e.guid,i=e.time;this.onTryGetAvatar(t,i)?.tryUpdate(e,i)})}tempState=new Nt("");onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;let i=new Date().getTime()-t;if(i>5e3)return Om&&console.log("old data",i,e),null;let n=this.avatars[e];if(n===void 0)try{console.log("create new avatar");let r=new Gt(this.context,e,this.webXR);n=r,this.avatars[e]=r}catch(r){this.avatars[e]=null,console.error(r)}return n}onDisable(){this.eventSub_ConnectionEvent&&this.context.connection.stopListening("joined-room",this.eventSub_ConnectionEvent),V.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),V.removeEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),V.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}update(){let e=Fd();this.debugAvatarUser&&(this.debugAvatarUser.lastUpdate=e),this.detectPotentiallyDisconnectedAvatarsAndRemove();for(let t in this.avatars){let i=this.avatars[t];!i||i.update()}}_removeAvatarsList=[];detectPotentiallyDisconnectedAvatarsAndRemove(){let e=Fd();for(let t in this.avatars){let i=this.avatars[t];if(!i){this._removeAvatarsList.push(t);continue}e-i.lastUpdate>1e4&&(console.log("avatar timed out (didnt receive any updates in a while) - destroying it now"),i.destroy(),this.avatars[t]=void 0)}for(let t of this._removeAvatarsList)delete this.avatars[t];this._removeAvatarsList.length=0}buildLocalAvatar(){if(this.localAvatar)return;let e=this.context.connection?.connectionId??this.k_LocalAvatarNoNetworkingGuid;this.localAvatar=new Gt(this.context,e,this.webXR),this.localAvatar.isLocalAvatar=!0,this.localAvatar.setAvatarOverride(this.getAvatarId()),this.avatars[this.localAvatar.guid]=this.localAvatar}eventSub_ConnectionEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;eventSub_WebXRUpdateEvent=null;avatars={};localAvatar=null;k_LocalAvatarNoNetworkingGuid="local";onConnected(){Om&&console.log("Hey you are connected as "+this.context.connection.connectionId),this.localAvatar?.guid===this.k_LocalAvatarNoNetworkingGuid&&(this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0),this.localAvatar=null,this.xrState=null,this.ownership?.freeOwnership(),this.ownership=null)}onXRSessionStart(e){if(console.log("XR session started"),this.context.connection.send("webxr-user-joined",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null),this.xrState=null,this.ownership?.freeOwnership(),this.ownership=null,this.avatars)for(let t in this.avatars)this.avatars[t]?.updateFlags()}onXRSessionEnded(e){console.log("XR session ended"),this.context.connection.send("webxr-user-left",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null)}ownership=null;xrState=null;builder=new Ct(1024);onXRSessionUpdate(e){this.xrState??=new Nt(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership??=new Kn(this.context.connection,this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership.guid=this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid,this.buildLocalAvatar();let{frame:t,xr:i,rig:n}=e,r=t.getViewerPose(i.getReferenceSpace());if(!r)return;let s=r?.transform,a=s.position,c=s.orientation;this.xrState.update(n,a,c,this.webXR,this.getAvatarId()),this.localAvatar&&(this.context.connection.connectionId&&(this.localAvatar.guid=this.context.connection.connectionId),this.localAvatar.tryUpdate(this.xrState,0)),!(this.ownership&&!this.ownership.hasOwnership&&this.context.connection.isConnected&&(this.context.time.frameCount%120===0&&this.ownership.requestOwnership(),!this.ownership.hasOwnership))&&(!this.context.connection.isConnected||!this.context.connection.connectionId||this.xrState.sendAsBuffer(this.builder,this.context.connection))}getAvatarId(){return P("avatar")??null}};async function M_(){return Ha()?!0:"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function I_(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}var Ud=!1,Gd=!1;M_().then(o=>Ud=o);I_().then(o=>Gd=o);var Le=class extends M{enableVR=!0;enableAR=!0;defaultAvatar;handModelPath="";createVRButton=!0;createARButton=!0;static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(Ud||Gd)}static get IsARSupported(){return Ud}static get IsVRSupported(){return Gd}static addEventListener(e,t){return this.events.addEventListener(e,t),t}static removeEventListener(e,t){return this.events.removeEventListener(e,t),t}static createVRButton(e,t){Le.XRSupported?e.__internalAwake():console.warn("WebXR is not supported on this device");let i=$o.createButton(e.context.renderer);return i.classList.add("webxr-ar-button"),i.classList.add("webxr-button"),this.resetButtonStyles(i),(t?.registerClick??!0)&&i.addEventListener("click",e.onClickedVRButton.bind(e)),i}static createARButton(e,t){e.__internalAwake();let i=e.webAR?.getAROverlayContainer(),n={};i?(n.domOverlay={root:i},n.optionalFeatures=["hit-test","dom-overlay"]):console.warn("No dom overlay root found, HTML overlays on top of screen-based AR will not work."),n.optionalFeatures.push("plane-detection"),n.optionalFeatures.push("anchors");let r=ec.createButton(e.context.renderer,n);return r.classList.add("webxr-ar-button"),r.classList.add("webxr-button"),Le.resetButtonStyles(r),(t?.registerClick??!0)&&r.addEventListener("click",e.onClickedARButton.bind(e)),r}static resetButtonStyles(e){!e||(e.style.position="",e.style.bottom="",e.style.left="")}endSession(){let e=this.context.renderer.xr.getSession();e&&e.end()}get Rig(){return this.rig||this.ensureRig(),this.rig}controllers=[];get Controllers(){return this.controllers}get LeftController(){return this.controllers.length>0&&this.controllers[0].input?.handedness==="left"?this.controllers[0]:this.controllers.length>1&&this.controllers[1].input?.handedness==="left"?this.controllers[1]:null}get RightController(){return this.controllers.length>0&&this.controllers[0].input?.handedness==="right"?this.controllers[0]:this.controllers.length>1&&this.controllers[1].input?.handedness==="right"?this.controllers[1]:null}get ARButton(){return this._arButton}get VRButton(){return this._vrButton}get IsInVR(){return this._isInVR}get IsInAR(){return this._isInAR}rig;isInit=!1;_requestedAR=!1;_requestedVR=!1;_isInAR=!1;_isInVR=!1;_arButton;_vrButton;webAR=null;awake(){if(this.defaultAvatar&&typeof this.defaultAvatar=="string"&&(this.defaultAvatar=it.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!R.findObjectOfType(On,this.context)){let e=R.addNewComponent(this.gameObject,On,!1);e.webXR=this}this.webAR=new cr(this)}onEnable(){if(this.isInit||!this.enableAR&&!this.enableVR)return;this.isInit=!0,this.context.renderer.xr.enabled=!0;let e=Le.XRSupported,t,i,n=document.createElement("div");n.classList.add("webxr-buttons"),this.context.domElement.append(n),this.enableAR&&this.createARButton&&(t=Le.createARButton(this),this._arButton=t,n.appendChild(t)),this.createVRButton&&this.enableVR&&(i=Le.createVRButton(this),this._vrButton=i,n.appendChild(i)),setTimeout(()=>{Le.resetButtonStyles(i),Le.resetButtonStyles(t)},1e3)}_transformOrientation=new rc;get TransformOrientation(){return this._transformOrientation}_currentHeadPose=null;get HeadPose(){return this._currentHeadPose}onBeforeRender(e){if(!e)return;let t=this.context.renderer.xr.getSession();if(t){let i=e.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(!i)return;this._currentHeadPose=i;let n=i?.transform;n&&this._transformOrientation.set(n.orientation.x,n.orientation.y,n.orientation.z,n.orientation.w),Le._isInXr===!1&&t&&this.onEnterXR(t,e);for(let r of this.controllers)r.onUpdate(t);this._isInAR&&this.webAR?.onUpdate(t,e)}Le.events.dispatchEvent({type:"xrUpdate",frame:e,xr:this.context.renderer.xr,rig:this.rig})}onClickedARButton(){this._isInAR||(this._requestedAR=!0,this._requestedVR=!1,this.captureStateBeforeXR())}onClickedVRButton(){if(!this._isInVR){if(this._requestedVR){this.onExitXR(null);return}this._requestedAR=!1,this._requestedVR=!0,this.captureStateBeforeXR(),this.ensureRig();for(let e=0;e<2;e++)$.Create(this,e,this.gameObject,0);Le.events.dispatchEvent({type:"requestVRSession"})}}captureStateBeforeXR(){this.context.mainCamera&&(this._originalCameraPosition.copy(B(this.context.mainCamera)),this._originalCameraRotation.copy(me(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent),this.Rig&&(this._originalXRRigParent=this.Rig.parent,this._originalXRRigPosition.copy(this.Rig.position),this._originalXRRigRotation.copy(this.Rig.quaternion))}ensureRig(){if(!this.rig){let e=R.findObjectOfType(lr,this.context);e?this.rig=e.gameObject:(this.rig=new R_,this.rig.rotateY(Math.PI),this.rig.name="XRRig",this.context.scene.add(this.rig))}}_originalCameraParent=null;_originalCameraPosition=new Im;_originalCameraRotation=new rc;_originalXRRigParent=null;_originalXRRigPosition=new Im;_originalXRRigRotation=new rc;onEnterXR(e,t){console.log("[XR] session begin",e),Le._isInXr=!0,this.ensureRig();let i=this.context.renderer.xr.getReferenceSpace();if(i&&this.rig){let a=t.getViewerPose(i)?.transform.orientation;if(a){let c=new rc(a.x,a.y,a.z,a.w),u=new C_().setFromQuaternion(c);this.rig.rotateY(u.y)}}let n=this.context.renderer.xr;if(this.context.mainCamera){let s=n.getCamera(this.context.mainCamera);for(let a of s.cameras)a.layers.enableAll();this.rig.add(this.context.mainCamera),this._requestedAR&&this.context.scene.add(this.rig)}let r=this._requestedAR?2:4;switch(St.Global.Set(r),r){case 2:this.context.xrSessionMode="immersive-ar",this._isInAR=!0,this.webAR?.onBegin(e);break;case 4:this.context.xrSessionMode="immersive-vr",this._isInVR=!0,this.onEnterVR(e);break}e.addEventListener("end",()=>{console.log("[XR] session end"),Le._isInXr=!1,this.onExitXR(e)}),this.onEnterXR_HandleMirrorWindow(e),Le.events.dispatchEvent({type:"xrStarted",session:e})}onExitXR(e){let t=this._isInAR;this._isInAR&&e&&this.webAR?.onEnd(e),this._isInAR=!1,this._isInVR=!1,this._requestedAR=!1,this._requestedVR=!1,this.context.xrSessionMode=void 0,this.xrMirrorWindow&&(this.xrMirrorWindow.close(),this.xrMirrorWindow=null),this.destroyControllers(),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),ie(this.context.mainCamera,this._originalCameraPosition),et(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),t&&(this._originalXRRigParent?.add(this.rig),this.rig.position.copy(this._originalXRRigPosition),this.rig.quaternion.copy(this._originalXRRigRotation)),St.Global.Set(17),Le.events.dispatchEvent({type:"xrStopped",session:e})}onEnterVR(e){}destroyControllers(){for(let e=this.controllers.length-1;e>=0;e-=1)this.controllers[e]?.destroy();this.controllers.length=0}xrMirrorWindow=null;onEnterXR_HandleMirrorWindow(e){!P("mirror")||setTimeout(()=>{if(!Le.IsInWebXR)return;let t=new URL(window.location.href);yo(t.searchParams,es,1),yo(t.searchParams,"isMirror",1);let i=t.toString();this.xrMirrorWindow=window.open(i,"webxr sync","popup=yes"),this.xrMirrorWindow&&(this.xrMirrorWindow.onload=()=>{this.xrMirrorWindow&&(this.xrMirrorWindow.onbeforeunload=()=>{Le.IsInWebXR&&e.end()})})},1e3)}},V=Le;I(V,"_isInXr",!1),I(V,"events",new T_),v([y()],V.prototype,"enableVR",2),v([y()],V.prototype,"enableAR",2),v([y(it)],V.prototype,"defaultAvatar",2),v([y()],V.prototype,"handModelPath",2),v([y()],V.prototype,"createVRButton",2),v([y()],V.prototype,"createARButton",2);var ts=class{get webxr(){return this._webxr}_webxr;reticle=null;reticleParent=null;hitTestSource=null;reticleActive=!0;previousBackground=null;previousEnvironment=null;sessionRoot=null;_previousParent=null;get context(){return this.webxr.context}constructor(e){this._webxr=e}arDomOverlay=null;arOverlayElement=null;noHitTestAvailable=!1;didPlaceARSessionRoot=!1;getAROverlayContainer(){this.arDomOverlay=this.webxr.context.domElement;let e=this.arDomOverlay;return e.getAROverlayContainer?this.arOverlayElement=e.getAROverlayContainer():this.arOverlayElement=this.arDomOverlay,this.arOverlayElement}setReticleActive(e){this.reticleActive=e}async onBegin(e){let t=this.webxr.context;this.reticleActive=!0,this.didPlaceARSessionRoot=!1,this.getAROverlayContainer();let i=navigator.userAgent?.includes("OculusBrowser")?0:1,n=i===1?4:2;for(let s=0;s<n;s++)$.Create(this.webxr,s,this.webxr.gameObject,i);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=R.findObjectOfType(mt,t)),this.previousBackground=t.scene.background,this.previousEnvironment=t.scene.environment,t.scene.background=null,e.requestReferenceSpace("viewer").then(s=>{e.requestHitTestSource?.call(e,{space:s})?.then(a=>{this.hitTestSource=a}).catch(a=>{this.noHitTestAvailable=!0,console.warn("WebXR: Hit test not supported",a)})}),!this.reticle&&this.sessionRoot&&(this.reticle=new P_(new k_(.07,.09,32).rotateX(-Math.PI/2),new O_),this.reticle.name="AR Placement reticle",this.reticle.matrixAutoUpdate=!1,this.reticle.visible=!1,this.reticleParent=new Mm,this.reticleParent.name="AR Reticle Parent",this.reticleParent.matrixAutoUpdate=!1,this.reticleParent.add(this.reticle),this.webxr.scene?(this.context.scene.add(this.reticleParent),this.context.scene.visible=!0):console.warn("Could not found WebXR Rig")),this._previousParent=this.webxr.gameObject,ts.tempWebXRObject||(ts.tempWebXRObject=new Mm),this.context.scene.add(ts.tempWebXRObject),R.addComponent(ts.tempWebXRObject,this.webxr),this.sessionRoot?(this.sessionRoot.webAR=this,this.sessionRoot?.onBegin(e)):console.warn("No WebARSessionRoot found in scene");let r=this.context.domElement;r?.onEnterAR?.call(r,e,this.arOverlayElement),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onEnd(e){this._previousParent&&(R.addComponent(this._previousParent,this.webxr),this._previousParent=null),this.hitTestSource=null;let t=this.webxr.context;t.scene.background=this.previousBackground,t.scene.environment=this.previousEnvironment,this.sessionRoot&&this.sessionRoot.onEnd(this.webxr.Rig,e);let i=this.context.domElement;i.onExitAR?.call(i,e),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onUpdate(e,t){if(this.noHitTestAvailable===!0){if(this.reticle&&(this.reticle.visible=!1),!this.didPlaceARSessionRoot){this.didPlaceARSessionRoot=!0;let n=this.webxr.Rig,r=A_.clone();this.sessionRoot?.placeAt(n,r)}return}if(!this.hitTestSource)return;let i=t.getHitTestResults(this.hitTestSource);if(i.length){let n=i[0],r=this.webxr.context.renderer.xr.getReferenceSpace();if(r){let s=n.getPose(r);if(this.sessionRoot){let a=this.sessionRoot.onUpdate(this.webxr.Rig,e,s);this.didPlaceARSessionRoot=a}if(this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&s)){let a=s.transform.matrix;this.reticle.matrix.fromArray(a),this.webxr.Rig&&this.reticle.matrix.premultiply(this.webxr.Rig.matrix)}}}else this.sessionRoot?.onUpdate(this.webxr.Rig,e,null),this.reticle&&(this.reticle.visible=!1)}},cr=ts;I(cr,"tempWebXRObject");var A_=new S_().identity().makeTranslation(0,0,0);var xi=class{used=!1;Use(){this.used=!0}StopPropagation(){this.event?.stopImmediatePropagation()}inputSource;object;isDown;isUp;isPressed;isClicked;event;constructor(e){this.event=e}};import{Object3D as L_}from"three";var j_=P("debugeventsystem"),Xi=class extends M{static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Xi.systems.length<=0&&Xi.systems.push(...R.findObjectsOfType(Xi,e)));for(let i of Xi.systems)if(i.context===e)return;let t=new L_;R.addNewComponent(t,Xi),e.scene.add(t)}static get systems(){let e=G.Current;return this._eventSystemMap.has(e)||this._eventSystemMap.set(e,[]),this._eventSystemMap.get(e)}static ensureUpdateMeshUI(e,t){wi.update(e,t)}static markUIDirty(e){wi.markDirty()}static get instance(){return this.systems[0]}orbitControl=null;orbitControlWasEnabled=!1;raycaster=[];constructor(){super(),Xi.systems.push(this)}onDestroy(){Xi.systems.splice(Xi.systems.indexOf(this),1)}start(){}register(e){e&&this.raycaster&&!this.raycaster.includes(e)&&this.raycaster?.push(e)}unregister(e){let t=this.raycaster?.indexOf(e);t!==void 0&&t!==-1&&this.raycaster?.splice(t,1)}_selectStartFn;_selectEndFn;_selectUpdateFn;onEnable(){let e=new Map;this._selectStartFn??=(i,n)=>{if(!n.grab)return;wi.resetLastSelected();let r=new xi;r.inputSource=i,r.isDown=i.selectionDown,r.isUp=i.selectionUp,r.isPressed=i.selectionPressed,r.isClicked=!1,e.set(i,n.grab),n.grab&&!this.handleEvents(n.grab,r)&&(n.grab=null)},this._selectEndFn??=(i,n)=>{if(!n.grab)return;let r=new xi;r.inputSource=i,r.isDown=i.selectionDown,r.isUp=i.selectionUp,r.isPressed=i.selectionPressed,r.isClicked=i.selectionClick,this.handleEvents(n.grab,r);let s=e.get(i);if(e.set(i,null),s)for(let a=0;a<this.raisedPointerDownEvents.length;a++){let c=this.raisedPointerDownEvents[a];this.raisedPointerDownObjects[a]===s&&c&&(c.onPointerUp?.call(c,r),this.raisedPointerDownEvents.splice(a,1),this.raisedPointerDownObjects.splice(a,1),a--)}};let t=new be;this._selectUpdateFn??=i=>{t.ray=i.getRay();let n=this.performRaycast(t);if(!n)return;let r=new xi;r.inputSource=i,this.handleIntersections(n,r)},$.addEventListener("select-start",this._selectStartFn),$.addEventListener("select-end",this._selectEndFn),$.addEventListener("update",this._selectUpdateFn),this.context.pre_update_callbacks.push(this.onBeforeUpdate.bind(this)),this.context.input.addEventListener("pointerdown",this.onPointerDown.bind(this))}onDisable(){$.removeEventListener("select-start",this._selectStartFn),$.removeEventListener("select-end",this._selectEndFn),$.removeEventListener("update",this._selectUpdateFn)}onPointerDown(){this.onBeforeUpdate()}lastPointerEvent=null;objectsHoveredThisFrame=[];objectsHoveredLastFrame=[];raisedPointerDownEvents=[];raisedPointerDownObjects=[];_didMove=!1;onBeforeUpdate(){if(this.objectsHoveredThisFrame.length=0,this.resetMeshUIStates(),V.IsInWebXR||this.context.input.isKeyPressed("Alt"))return;if(!this._didMove){let r=this.context.input.getPointerPositionRC(0);if(r&&r.x===0&&r.y===0)return;this._didMove=!0}let e=this.performRaycast(null),t=new xi(this.context.input.getPointerEvent(0));if(t.inputSource=this.context.input,t.isClicked=this.context.input.mouseClick,t.isDown=this.context.input.mouseDown,t.isUp=this.context.input.mouseUp,t.isPressed=this.context.input.mousePressed,this.lastPointerEvent=t,!e)return;let i=null,n=null;this.context.input.mouseDown&&this.currentActiveMeshUIComponents.length>0&&this.context.mainCameraComponent&&(i=R.getComponent(this.context.mainCameraComponent.gameObject,Ve)??null,i&&(n=i.enabled,i.enabled=!1)),this.handleIntersections(e,t),i&&(this.orbitControl=i,this.orbitControl?.enabled?(this.orbitControlWasEnabled=this.orbitControl.enabled,this.orbitControl.enabled=!1):this.orbitControl&&!this.context.input.mousePressed&&(this.orbitControl.enabled=this.orbitControlWasEnabled,this.orbitControl=null))}_tempComponentsArray=[];onBeforeRender(){if(this.lastPointerEvent)this.lastPointerEvent.used=!1;else return;if(this.lastPointerEvent.isUp){for(let t of this.raisedPointerDownEvents)t.onPointerUp&&t.onPointerUp(this.lastPointerEvent);this.raisedPointerDownEvents.length=0,this.raisedPointerDownObjects.length=0}for(let t of this.objectsHoveredLastFrame)if(this.objectsHoveredThisFrame.indexOf(t)<0){this._tempComponentsArray.length=0;let i=R.getComponentsInParent(t,M,this._tempComponentsArray);this.lastPointerEvent.object=t;for(let n=0;n<i.length;n++){let r=i[n];if(!r.gameObject||r.destroyed)continue;let s=r;s.onPointerExit&&s.onPointerExit(this.lastPointerEvent)}}let e=this.objectsHoveredLastFrame;this.objectsHoveredLastFrame=this.objectsHoveredThisFrame,this.objectsHoveredThisFrame=e}_sortedHits=[];performRaycast(e){if(!this.raycaster)return null;this._sortedHits.length=0;for(let t of this.raycaster){if(!t.activeAndEnabled)continue;let i=t.performRaycast(e);i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}handleIntersections(e,t){if(!e||e.length<=0)return!1;e=this.sortCandidates(e);for(let i of e){let{object:n}=i;if(this.handleEvents(n,t))return!0}return!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){let i=e[t],n=i.object;if(n.material&&n.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(let t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventsArray=[];out={};handleEvents(e,t){if(!this.testIsVisible(e))return t.isClicked&&j_&&console.log("not allowed",e),!1;let i=e;t.object=e,this.lastPointerEvent=t;let n=e.parent,r=!1,s=t.isClicked??!1,a=null;if(n&&n.isUI){let c=(t.isPressed||t.isClicked)??!1;if(n[gt]){let u=n[gt].gameObject;if(u){if(!Ei.isInteractable(u,this.out))return this.out.canvasGroup?.interactable??!1;a=this.out.canvasGroup??null;let d=this.handleMeshUIIntersection(e,c);e=u,r=!0}}if(!r&&this.handleMeshUiObjectWithoutShadowDom(n,c))return!0}if(this.objectsHoveredThisFrame.push(e),a===null||a.interactable){let c=this.objectsHoveredLastFrame.indexOf(e)>=0;this.handleEventsArray.length=0;let u=R.getComponentsInParent(e,M,this.handleEventsArray);for(let l=0;l<u.length;l++){if(t.used)return!0;if(u[l].destroyed)continue;let d=u[l];d.interactable!==!1&&(d.onPointerEnter&&(c||d.onPointerEnter(t)),t.isDown&&d.onPointerDown&&!this.raisedPointerDownEvents.includes(d)&&(d.onPointerDown(t),this.raisedPointerDownEvents.push(d),this.raisedPointerDownObjects.push(i)),t.isUp&&d.onPointerUp&&d.onPointerUp(t),t.isClicked&&d.onPointerClick&&d.onPointerClick(t))}}return!0}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){let i=wi.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&wi.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){let t=this.currentActiveMeshUIComponents[e];wi.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?R.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}},Je=Xi;I(Je,"_eventSystemMap",new Map),I(Je,"didSearchEventSystem",!1);var wi=class{static markDirty(){this.needsUpdate=!0}static update(e,t){for(let i of this.lastUpdateFrame)if(i.context===t){if(t.time.frameCount===i.frame)return;i.frame=t.time.frameCount,(this.needsUpdate||t.time.frameCount<30)&&(this.needsUpdate=!1,e.update());return}this.lastUpdateFrame=[{context:t,frame:t.time.frameCount}],e.update()}static updateState(e,t){let i=null;if(e&&(i=this.findBlockInParent(e),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;t?(this.lastSelected=i,i.states.pressed&&i.setState("pressed")):i.states.hovered&&i.setState("hovered"),this.needsUpdate=!0}return i}static resetLastSelected(){let e=this.lastSelected;!e||(this.lastSelected=null,this.resetState(e))}static resetState(e){if(!e)return;e.interactable===!1?e.states.disabled&&e.setState("disabled"):e===this.lastSelected&&e.states.selected?e.setState("selected"):e.setState("normal"),this.needsUpdate=!0}static findBlockInParent(e){return e?e.isBlock&&Object.keys(e.states).length>0?e:this.findBlockInParent(e.parent):null}};I(wi,"lastSelected",null),I(wi,"lastUpdateFrame",[]),I(wi,"needsUpdate",!1);import{AxesHelper as H_}from"three";var is="./include";oc.Block.prototype.interactable={get(){return this.interactive},set(o){this.interactable=o}};var gt=Symbol("shadowDomOwner"),We=class extends M{isRoot(){return this.Root?.gameObject===this.gameObject}markDirty(){Je.markUIDirty(this.context)}shadowComponent=null;_controlsChildLayout=!0;get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}_root=void 0;get Root(){return this._root===void 0&&(this._root=R.getComponentInParent(this.gameObject,kn)),this._root}_parentComponent=void 0;onEnable(){super.onEnable()}addShadowComponent(e,t){this.removeShadowComponent();let i=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=R.getComponentInParent(i,We),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have a UI element outside a Canvas?`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[gt]=this,e.traverse(r=>{r[gt]===void 0&&(r[gt]=this)});let n=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{let r=this._parentComponent.shadowComponent;r&&(r?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),Di&&e.add(new H_(.5)),this.onAfterAddedToScene(),n&&oc.update()}set(e){}traverseOwnedShadowComponents(e,t,i){if(!!e&&e[gt]===t){i(e);for(let n of e.children)this.traverseOwnedShadowComponents(n,t,i)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}},kn=class extends We{awake(){super.awake()}};var Ei=class{static getObject(e){let t=e[gt];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;let i=this.tryFindCanvasGroup(e);if(i?.isCanvasGroup===!0&&(t&&(t.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;let n=ai(e,r=>{if(r.isGraphic===!0)return r},!1);return t&&n?.isGraphic===!0&&(t.graphic=n),n?.raycastTarget!==!1}static tryFindCanvasGroup(e){if(!e)return null;let t=ai(e,i=>{let n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}};var ma=P("debugwebxrcontroller");var Jr=class extends M{},je=class extends M{static CreateRaycastLine(){let e=new V_(this.geometry),t=e.material;return t.color=this.raycastColor,e.layers.set(2),e.name="line",e.scale.z=1,e}static CreateRaycastHitPoint(){let e=new X_(.5,22,22),t=new W_({color:this.raycastColor}),i=new z_(e,t);return i.visible=!1,i.layers.set(2),i}static Create(e,t,i,n){let r=i?R.addNewComponent(i,je,!1):new je;r.webXR=e,r.index=t,r.type=n;let s=e.context;r.controller=s.renderer.xr.getController(t),r.controllerGrip=s.renderer.xr.getControllerGrip(t),r.controllerModel=this.Factory.createControllerModel(r.controller),r.controllerGrip.add(r.controllerModel),r.hand=s.renderer.xr.getHand(t);let a=new J_;xn(a,s),r.webXR.handModelPath&&r.webXR.handModelPath!==""?a.setPath(Ii(e.sourceId,r.webXR.handModelPath)):a.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/");let c=new q_(r.hand,a);return r.hand.add(c),r.hand.traverse(u=>u.layers.set(2)),r.handPointerModel=new Y_(r.hand,r.controller),r.controller.addEventListener("connected",u=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),r.setControllerLayers(r.hand,2),setTimeout(()=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),r.setControllerLayers(r.hand,2)},1e3)}),r.hand.addEventListener("connected",u=>{if(u.data.hand){e.Rig&&e.Rig.add(r.hand),r.type=0,r.handPointerModel.traverse(h=>h.layers.set(2)),r.handPointerModel.pointerObject?.traverse(h=>h.layers.set(2));let d=r.hand.joints;if(d)for(let h of Object.keys(d)){let g=d[h];g.parent||r.hand.add(g)}}}),r}static addEventListener(e,t){let i=this.eventSubs[e]??[];i.push(t),this.eventSubs[e]=i}static removeEventListener(e,t){if(!t)return;let i=this.eventSubs[e]??[],n=i.indexOf(t);n>=0&&i.splice(n,1),this.eventSubs[e]=i}webXR;index=-1;controllerModel;controller;controllerGrip;hand;handPointerModel;grabbed=null;input=null;type=0;showRaycastLine=!0;get isUsingHands(){let e=this.input?.hand;return e!=null}get wrist(){if(!this.hand)return null;let e=this.hand.joints;return e?e.wrist:null}_wristQuaternion=null;getWristQuaternion(){let e=this.wrist;return e?(this._wristQuaternion||(this._wristQuaternion=new sc),me(e).multiply(this._wristQuaternion.setFromEuler(new U_(-Math.PI/4,0,0)))):null}movementVector=new Ci;worldRot=new sc;joystick=new Q_;didRotate=!1;didTeleport=!1;didChangeScale=!1;lastHit=null;raycastLine=null;_raycastHitPoint=null;_connnectedCallback=null;_disconnectedCallback=null;_selectStartEvt=null;_selectEndEvt=null;get selectionDown(){return this._selectionPressed&&!this._selectionPressedLastFrame}get selectionUp(){return!this._selectionPressed&&this._selectionPressedLastFrame}get selectionPressed(){return this._selectionPressed}get selectionClick(){return this._selectionEndTime-this._selectionStartTime<.3}get raycastHitPoint(){return this._raycastHitPoint}_selectionPressed=!1;_selectionPressedLastFrame=!1;_selectionStartTime=0;_selectionEndTime=0;get useSmoothing(){return this._useSmoothing}_useSmoothing=!0;awake(){if(!this.controller){console.warn("Missing Controller!!!",this);return}this._connnectedCallback=this.onSourceConnected.bind(this),this._disconnectedCallback=this.onSourceDisconnected.bind(this),this._selectStartEvt=this.onSelectStart.bind(this),this._selectEndEvt=this.onSelectEnd.bind(this),this.type===1&&(this.controllerGrip.addEventListener("connected",this._connnectedCallback),this.controllerGrip.addEventListener("disconnected",this._disconnectedCallback),this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt))}onDestroy(){this.type===1&&(this.controllerGrip.removeEventListener("connected",this._connnectedCallback),this.controllerGrip.removeEventListener("disconnected",this._disconnectedCallback),this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.hand?.clear(),this.controllerGrip?.clear(),this.controller?.clear()}onEnable(){this.hand&&(this.hand.name="Hand"),this.controllerGrip&&(this.controllerGrip.name="ControllerGrip"),this.controller&&(this.controller.name="Controller"),this.raycastLine&&(this.raycastLine.name="RaycastLine;"),this.webXR.Controllers.indexOf(this)<0&&this.webXR.Controllers.push(this),this.raycastLine||(this.raycastLine=je.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=je.CreateRaycastHitPoint()),this.webXR.Rig?.add(this.hand),this.webXR.Rig?.add(this.controllerGrip),this.webXR.Rig?.add(this.controller),this.webXR.Rig?.add(this.raycastLine),this.raycastLine?.add(this._raycastHitPoint),this._raycastHitPoint.visible=!1,this.hand.add(this.handPointerModel),ma&&console.log("ADDED TO RIG",this.webXR.Rig)}onDisable(){this.hand?.removeFromParent(),this.controllerGrip?.removeFromParent(),this.controller?.removeFromParent(),this.raycastLine?.removeFromParent(),this._raycastHitPoint?.removeFromParent();let e=this.webXR.Controllers.indexOf(this);e>=0&&this.webXR.Controllers.splice(e,1)}_isConnected=!1;onSourceConnected(e){if(this._isConnected){console.warn("Received connected event for controller that is already connected",this.index,e);return}this._isConnected=!0,this.input=e.data,this.type===1&&(this.onSelectStart(),this.createPointerEvent("down"))}onSourceDisconnected(e){if(!this._isConnected){console.warn("Received discnnected event for controller that is not connected",e);return}this._isConnected=!1,this.type===1&&(this.onSelectEnd(),this.createPointerEvent("up")),this.input=null}createPointerEvent(e){switch(e){case"down":this.context.input.createPointerDown({clientX:0,clientY:0,button:this.index,pointerType:"touch"});break;case"move":break;case"up":this.context.input.createPointerUp({clientX:0,clientY:0,button:this.index,pointerType:"touch"});break}}rayRotation=new sc;update(){this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));let e=je.eventSubs["update"];if(e&&e.length>0)for(let n of e)n(this);let t=1;this.type===0?t=this.context.time.deltaTime/.1:this.isUsingHands&&this.handPointerModel.pinched&&(t=this.context.time.deltaTime/.3),this.rayRotation.slerp(me(this.controller),this.useSmoothing?t:1);let i=B(this.controller);if(this.isUsingHands&&this.handPointerModel.cursorObject&&(this.handPointerModel.cursorObject.visible=!1),this.raycastLine){let n=this.showRaycastLine&&this.type!==1;if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed&&n,ie(this.raycastLine,i);let r=this.hand.joints;if(r&&r.wrist&&this.grabbed&&this.grabbed.isCloseGrab){let a=this.getWristQuaternion();a&&this.rayRotation.copy(a)}et(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=n,et(this.raycastLine,this.rayRotation),ie(this.raycastLine,i)}this.lastHit=this.updateLastHit(),this.grabbed&&this.grabbed.update(),this._selectionPressedLastFrame=this._selectionPressed,this.selectStartCallback&&this.selectStartCallback()}_pinchStartTime=void 0;onUpdate(e){if(this.lastHit=null,!e||e.inputSources.length<=this.index){this.input=null;return}if(this.type===0&&(this.input=e.inputSources[this.index]),!this.input)return;let t=this.webXR.Rig;if(!t)return;this._didNotEndSelection&&!this.handPointerModel.pinched&&(this._didNotEndSelection=!1,this.onSelectEnd()),this.updateStick(this.input);let i=this.input?.gamepad?.buttons;switch(this.input.handedness){case"left":let n=3*je.MovementSpeedFactor,r=2,s=H.clamp01(this.joystick.length()*2),a=this.joystick.x>0?1:-1,c=Math.pow(this.joystick.x,r);c*=a,c*=s;let u=this.joystick.y>0?1:-1,l=Math.pow(this.joystick.y,r);l*=u,c*=s,t.getWorldQuaternion(this.worldRot),this.movementVector.set(c,0,l),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),this.movementVector.multiplyScalar(n*this.context.time.deltaTime),t.position.add(this.movementVector),this.isUsingHands&&this.runTeleport(t,i);break;case"right":let d=this.joystick.x,h=Math.abs(d);if(h<.4)this.didRotate=!1;else if(h>.5&&!this.didRotate){let g=d>0?-1:1;t.rotateY(H.toRadians(30*g)),this.didRotate=!0}this.runTeleport(t,i);break}}runTeleport(e,t){let i=-this.joystick.y;if(this.hand?.visible&&!this.grabbed){let a=this.handPointerModel.isPinched();a&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),a&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(i=this.handPointerModel.isPinched()?1:0),a||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;let n=i>.5&&this.webXR.IsInVR,r=this.webXR.Rig?this.webXR.Rig?.scale?.x<.999:!1,s=null;if(t&&this.input&&!this.input.hand)for(let a=0;a<t.length;a++){let c=t[a];if(a===4)if(c.pressed&&!this.didChangeScale&&this.webXR.IsInVR){this.didChangeScale=!0;let u=this.webXR.Rig;if(u)if(r){r=!1,u.scale.set(1,1,1),s=1,je.MovementSpeedFactor=1;let l=this.context.mainCamera;je.PreviousCameraFarDistance&&(l.far=je.PreviousCameraFarDistance)}else{r=!0,n=!0,s=.1,je.MovementSpeedFactor=s*2;let l=this.context.mainCamera;je.PreviousCameraFarDistance=l.far,l.far/=s}}else c.pressed||(this.didChangeScale=!1)}if(n){if(!this.didTeleport){let a=this.raycast();if(this.didTeleport=!0,a&&a.length>0){let c=a[0];if(r||this.isValidTeleportTarget(c.object)){let u=c.point;ie(e,u)}}}}else i<.1&&(this.didTeleport=!1);s!==null&&(e.scale.set(s,s,s),e.updateMatrixWorld())}isValidTeleportTarget(e){return R.getComponentInParent(e,Jr)!=null}updateStick(e){!e||!e.gamepad||e.gamepad.axes?.length<4||(this.joystick.x=e.gamepad.axes[2],this.joystick.y=e.gamepad.axes[3])}updateLastHit(){let e=this.raycast(),t=e?e[0]:null;this.lastHit=t;let i=1;if(this.webXR.Rig&&(i/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=i*(this.lastHit?.distance??9999);let n=this.raycastLine.material;t!=null?n.color=je.raycastColor:n.color=je.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;let n=H.clamp(this.lastHit.distance*.01*i,.015,.1);this._raycastHitPoint.scale.set(n,n,n)}this._raycastHitPoint.visible=this.lastHit!==null&&this.lastHit!==void 0}return t}onSelectStart(){!this.context.connection.allowEditing||(this.selectStartCallback=()=>this.onHandleSelectStart())}selectStartCallback=null;lastSelectStartObject=null;onHandleSelectStart(){this.selectStartCallback=null,this._selectionPressed=!0,this._selectionStartTime=this.context.time.time,this._selectionEndTime=1e3;let e=null,t=!1;if(this.isUsingHands?(e=this.overlap(),e.length<=0?(e=this.raycast(),t=!1):t=!0):e=this.raycast(),ma&&console.log("onHandleSelectStart","close grab? "+t,"intersections",e),e&&e.length>0)for(let i of e){let n=i.object;this.lastSelectStartObject=n;let r={selected:n,grab:n},s=je.eventSubs["select-start"];if(s&&s.length>0)for(let a of s)a(this,r);r.grab!==n&&ma&&console.log("Grabbed object changed","original",n,"new",r.grab),r.grab&&(this.grabbed=bt.TryTake(this,r.grab,i,t));break}else{let i=je.eventSubs["select-start"],n={selected:null,grab:null};if(i&&i.length>0)for(let r of i)r(this,n)}}_didNotEndSelection=!1;onSelectEnd(){if(this.isUsingHands&&this.handPointerModel.pinched){this._didNotEndSelection=!0;return}if(!this._selectionPressed)return;this.selectStartCallback=null,this._selectionPressed=!1,this._selectionEndTime=this.context.time.time;let e={grab:this.grabbed?.selected??this.lastSelectStartObject},t=je.eventSubs["select-end"];if(t&&t.length>0)for(let i of t)i(this,e);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(e){return!(!e||R.isActiveInHierarchy(e)===!1||Ei.isInteractable(e)===!1)}setControllerLayers(e,t){if(!!e&&(e.layers.set(t),e.children))for(let i of e.children)this.grabbed?.selected===i||this.grabbed?.selectedMesh===i||this.setControllerLayers(i,t)}getRay(){let e=new N_;return e.origin.copy(B(this.controller)),e.direction.set(0,0,-1).applyQuaternion(this.rayRotation),e}closeGrabBoundingBoxHelper;overlap(){let e=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(ma&&(!this.closeGrabBoundingBoxHelper&&e&&(this.closeGrabBoundingBoxHelper=new F_(e,16776960),this.scene.add(this.closeGrabBoundingBoxHelper)),this.closeGrabBoundingBoxHelper&&e&&this.closeGrabBoundingBoxHelper.setFromObject(e)),!e)return new Array;let t=B(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){let e=new be;e.layerMask=new G_,e.layerMask.set(0),e.layerMask.disable(2),e.ray=this.getRay();let t=this.context.physics.raycast(e);for(let i=0;i<t.length;i++){let n=t[i],r=n.object;if(!this.testIsVisible(r)){t.splice(i,1),i--;continue}n.object=Ei.getObject(r);break}return t}},$=je;I($,"Factory",new K_),I($,"raycastColor",new Dm(.9,.3,.3)),I($,"raycastNoHitColor",new Dm(.6,.6,.6)),I($,"geometry",new B_().setFromPoints([new Ci(0,0,0),new Ci(0,0,-1)])),I($,"handModels",{}),I($,"eventSubs",{}),I($,"PreviousCameraFarDistance"),I($,"MovementSpeedFactor",1);var ot=class{static AddEventListener(e,t){return ot.Events[e]||(ot.Events[e]=[]),ot.Events[e].push(t),t}static RemoveEventListener(e,t){if(!t||!ot.Events[e])return;let i=ot.Events[e].indexOf(t);i>=0&&ot.Events[e].splice(i,1)}static Register(e){this.Current.find(t=>t===e)||this.Current.push(e)}static Remove(e){let t=this.Current.indexOf(e);t>=0&&this.Current.splice(t,1)}static TryTake(e,t,i,n){let r=R.getComponentInParent(t,Vt);if(r)t=r.gameObject;else return ma&&console.warn("Prevented taking object that is not interactable",t),null;let s=t,a=R.getComponentInParent(t,Pt);a&&(a.requestOwnership(),s=a.gameObject);for(let u of this.Current)if(u.selected===s)return u.controller===e||(u.free(),u.Take(e,s,t,a,r,i,n)),u;let c=new ot;return c.Take(e,s,t,a,r,i,n),c}sync=null;selected=null;selectedParent=null;selectedMesh=null;controller=null;grabTime=0;grabUUID="";isCloseGrab=!1;originalMaterial=null;usageMarker=null;rigidbodies=null;didReparent=!1;grabDistance=0;interactable=null;positionSource=null;Take(e,t,i,n,r,s,a){if(console.assert(t!==null,"Expected object to be taken but was",t),e.isUsingHands?this.positionSource=a?e.wrist:e.controller:this.positionSource=e.controller,!this.positionSource)return console.warn("No position source"),this;let c={controller:e,take:t,hit:i,sync:n,interactable:r};ot.Events.WillTake?.forEach(g=>g(this,c));let u=i;u?.material&&(this.originalMaterial=u.material,Array.isArray(u.material)||(u.material=u.material.clone(),u.material&&u.material.emissive&&(u.material.emissive.b=.2))),this.selected=t,this.selectedParent||(this.selectedParent=t.parent),this.selectedMesh=u,this.controller=e,this.interactable=r,this.isCloseGrab=a,this.didReparent=!1,this.sync=n,this.grabTime=e.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=R.addNewComponent(this.selected,zt),this.rigidbodies=R.getComponentsInChildren(this.selected,J),B(this.positionSource,this.lastControllerWorldPos);let l=()=>a?this.lastControllerWorldPos.clone():s.point.clone();this.grabDistance=l().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(l());let d=e.isUsingHands&&a?this.controller.getWristQuaternion().clone():e.rayRotation.clone();me(this.selected,this.localQuaternionToGrab).premultiply(d.invert());let h=this.controller.webXR.Rig;return h&&this.rigPositionLastFrame.copy(B(h)),ye.Add(e.context,this.selected),ot.Register(this),this.sync&&(this.sync.fastMode=!0),ot.Events.DidTake?.forEach(g=>g(this,c)),this}free(){if(!this.selected)return;let e={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};ot.Events.WillFree?.forEach(n=>n(this,e)),ye.Remove(this.controller.context,this.selected),ot.Remove(this),this.sync&&(this.sync.fastMode=!1);let t=this.selectedMesh;t&&this.originalMaterial&&t.material&&(t.material=this.originalMaterial);let i=this.selected;if(this.didReparent&&i.parent){let n=this.selectedParent;n?n.attach(i):this.controller?.context.scene.attach(i)}if(this.usageMarker?.destroy(),this.controller&&(this.controller.grabbed=null),this.selected=null,this.selectedParent=null,this.selectedMesh=null,this.sync=null,this.rigidbodies)for(let n of this.rigidbodies)n.wakeUp(),n.setVelocity(n.smoothedVelocity);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,ot.Events.DidFree?.forEach(n=>n(this,e))}grabPoint=new Ci;localPositionOffsetToGrab=null;localPositionOffsetToGrab_worldSpace=new Ci;localQuaternionToGrab=new sc(0,0,0,1);targetDir=null;quaternionLerp=null;controllerDir=new Ci;controllerWorldPos=new Ci;lastControllerWorldPos=new Ci;controllerPosDelta=new Ci;totalChangeAlongDirection=0;rigPositionLastFrame=new Ci;controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),B(this.positionSource,this.controllerWorldPos),this.controllerPosDelta.copy(this.controllerWorldPos),this.controllerPosDelta.sub(this.lastControllerWorldPos),this.lastControllerWorldPos.copy(this.controllerWorldPos);let e=this.controller.webXR.Rig;if(e){let i=B(e),n=this.rigPositionLastFrame.sub(i);this.controllerPosDelta.add(n),this.rigPositionLastFrame.copy(i)}return this.controllerDir.dot(this.controllerPosDelta)}update(){if(this.rigidbodies)for(let e of this.rigidbodies)e.resetVelocities();if(this.sync&&this.controller&&this.controller.context.connection.isInRoom&&this.controller.context.time.time-this.grabTime>3&&this.sync.hasOwnership()===!1&&(console.log("no ownership, will leave",this.sync.guid),this.free()),!(this.interactable&&!this.interactable.canGrab)){if(!this.didReparent&&this.selected&&this.controller){let e=this.controller.webXR.Rig?.scale.x??1;this.totalChangeAlongDirection+=this.controllerMovementSinceLastFrame();let t=1;this.controller.type===0&&(t=Math.max(0,1+this.totalChangeAlongDirection*2/e),t=t*t*t),this.grabDistance/e<.8&&(t=1),this.targetDir||(this.targetDir=new Ci),this.targetDir.set(0,0,-this.grabDistance*t);let i=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),n=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=n.clone()),this.quaternionLerp.slerp(n,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),et(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(i),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(B(this.selected)),i.sub(this.localPositionOffsetToGrab_worldSpace)),ie(this.selected,i)}if(this.rigidbodies!=null)for(let e of this.rigidbodies)e.wakeUp();oe.markDirty(this.selected,!0)}}},bt=ot;I(bt,"Events",{}),I(bt,"Current",[]);import{Object3D as Lm}from"three";var Z_=P("debugmouth"),ur=class extends M{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){setTimeout(()=>{this.voip=R.findObjectOfType(rt,this.context),this.marker||(this.marker=R.getComponentInParent(this.gameObject,le))},3e3)}update(){if(!this.voip||this.context.time.frameCount%10!==0)return;let e=this.marker?.connectionId??null;if(!e){Z_&&(e=null);return}let t=this.voip.getFrequency(e)??0;this.updateLips(t)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;let t=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,t)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;let t=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,t)}}}setMouthShapeActive(e,t){if(!!e){e!=this.idle?this.idle.map(i=>i.visible=!1):this.talking.map(i=>i.visible=!1);for(let i=0;i<e.length;i++){let n=e[i];n&&(n.visible=i===t)}}}};v([y(Lm)],ur.prototype,"idle",2),v([y(Lm)],ur.prototype,"talking",2);var ns=class extends M{voip=null;marker=null;_startPosition=null;awake(){this.voip=R.findObjectOfType(rt,this.context),this.marker=R.getComponentInParent(this.gameObject,le)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;let e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());let i=t/100;this.gameObject.position.y=this._startPosition.y+i*.07}};import{Object3D as $_}from"three";var Qi=class extends M{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=R.getComponentInParent(this.gameObject,Ee)}update(){if(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)return;if(this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(let t of this.eyes)t&&(t.visible=this.eyesOpen)}}};v([y($_)],Qi.prototype,"eyes",2),v([y()],Qi.prototype,"lastBlinkTime",2),v([y()],Qi.prototype,"blinkLength",2),v([y()],Qi.prototype,"eyesOpen",2);import*as ac from"three";import{Object3D as zd}from"three";var Wd=class extends M{head=null;eyes=null;target=null;brain=null;awake(){this.brain||(this.brain=R.getComponentInParent(this.gameObject,Sn)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=R.addNewComponent(this.gameObject,Sn)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new ac.Vector3;currentTargetPoint=new ac.Vector3;update(){let e=this.target;if(e&&this.head){let t=this.eyes;if(t){let i=B(e);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);let n=B(this.head),r=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(r.length()<.1)return;let s=Wd.forward;if(s.set(0,0,1),s.applyQuaternion(me(this.head)),s.dot(r)>.45)for(let c=0;c<t.length;c++)t[c].lookAt(this.currentTargetPoint)}}}},qi=Wd;I(qi,"forward",new ac.Vector3(0,0,1)),v([y(zd)],qi.prototype,"head",2),v([y(zd)],qi.prototype,"eyes",2),v([y(zd)],qi.prototype,"target",2);import{AxesHelper as ex}from"three";var Mn=class extends M{length=1;depthTest=!0;isGizmo=!0;_axes=null;onEnable(){if(this.isGizmo&&!Di)return;this._axes||(this._axes=new ex(this.length)),this.gameObject.add(this._axes);let e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){!this._axes||this.gameObject.remove(this._axes)}};v([y()],Mn.prototype,"length",2),v([y()],Mn.prototype,"depthTest",2),v([y()],Mn.prototype,"isGizmo",2);import*as jm from"three";var rs=class extends M{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=B(this.to).clone(),t=B(this.from).clone(),i=e.distanceTo(t),n=e.clone();n.sub(t);let r=t.clone();r.add(e),r.multiplyScalar(.5);let s=B(this.hint).clone();s.sub(r);let a=new jm.Vector3;a.crossVectors(s,n),a.crossVectors(n,a),a.normalize();let c=i*.5,u=Math.max(this.desiredDistance,c),l=Math.sqrt(u*u-c*c),d=a.clone();d.multiplyScalar(l),d.add(r),ie(this.gameObject,d);let h=r.clone();h.sub(a),this.gameObject.lookAt(h)}};import{Mesh as tx,Vector3 as dr}from"three";var Ot=class extends M{get isCollider(){return!0}attachedRigidbody=null;isTrigger=!1;sharedMaterial;awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(J))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(J))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(J))}onDisable(){this.context.physics.removeBody(this)}};v([y(J)],Ot.prototype,"attachedRigidbody",2),v([y()],Ot.prototype,"isTrigger",2),v([y()],Ot.prototype,"sharedMaterial",2);var hr=class extends Ot{radius=.5;center=new dr(0,0,0);onEnable(){super.onEnable(),this.context.physics.addSphereCollider(this,this.center,this.radius)}};v([y()],hr.prototype,"radius",2),v([y(dr)],hr.prototype,"center",2);var pr=class extends Ot{size=new dr(1,1,1);center=new dr(0,0,0);onEnable(){super.onEnable(),this.context.physics.addBoxCollider(this,this.center,this.size)}};v([y(dr)],pr.prototype,"size",2),v([y(dr)],pr.prototype,"center",2);var Zr=class extends Ot{sharedMesh;convex=!1;onEnable(){super.onEnable(),this.sharedMesh?.isMesh||this.gameObject instanceof tx&&(this.sharedMesh=this.gameObject),this.sharedMesh?.isMesh&&this.context.physics.addMeshCollider(this,this.sharedMesh,this.convex,Ae(this.gameObject))}};v([y()],Zr.prototype,"convex",2);var Xt=class extends Ot{center=new dr(0,0,0);radius=.5;height=2;onEnable(){super.onEnable(),this.context.physics.addCapsuleCollider(this,this.center,this.height,this.radius)}};v([y(dr)],Xt.prototype,"center",2),v([y()],Xt.prototype,"radius",2),v([y()],Xt.prototype,"height",2);import*as $r from"three";var ix=P("gizmos"),nx=P("debugboxhelper"),Qt=class extends M{box=null;_lastMatrixUpdateFrame=-1;isInBox(e,t){if(!e)return;if(this.box||(this.box=new $r.Box3),e.type==="Mesh")Qt.testBox.setFromObject(e);else if(e.type==="Group"){if(Qt.testBox.makeEmpty(),e.children.length>0)for(let n=0;n<e.children.length;n++)e.children[n].type==="Mesh"&&Qt.testBox.expandByObject(e)}else{let n=B(e,Qt._position),r=Ae(e,Qt._size);t!==void 0&&r.multiplyScalar(t),Qt.testBox.setFromCenterAndSize(n,r)}this.updateBox();let i=this.box?.intersectsBox(Qt.testBox);return i&&nx&&Et.DrawBox3(Qt.testBox,16711680,5),i}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new $r.Box3),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){let t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;let i=t,n=B(this.gameObject,Qt._position,i),r=Ae(this.gameObject,Qt._size);this.box.setFromCenterAndSize(n,r)}return this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!ix&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=cl(e),this.gameObject.add(this._helper)}}},Ne=Qt;I(Ne,"testBox",new $r.Box3),I(Ne,"_position",new $r.Vector3),I(Ne,"_size",new $r.Vector3(.01,.01,.01));import{Color as lx,Texture as zm}from"three";import{LinearEncoding as sx,sRGBEncoding as ax}from"three";import*as Qd from"three-mesh-ui";import{Matrix4 as rx,Object3D as ox,Vector2 as Gm,Vector3 as Xd}from"three";import{FrontSide as Hm,DoubleSide as Fm}from"three";function Nd(o){let e=o[gt];return e||(o.parent?Nd(o.parent):null)}function os(o,e){if(!o)return;let t=o.material;t?.isMaterial===!0&&(t.depthTest=!e.renderOnTop,t.side=e.doubleSided??!0?Fm:Hm,t.depthWrite=e.depthWrite??!1,t.shadowSide=e.doubleSided?Fm:Hm,o.castShadow=e.castShadows?e.castShadows:!1,o.receiveShadow=e.receiveShadows?e.receiveShadows:!1);for(let i of o.children)os(i,e)}function lc(o,e,t){o[e]===void 0&&console.warn("Field",e,"is undefined on",o);let i=Proxy.revocable(o[e],{set(s,a,c,u){let l=s[a],d=Reflect.set(s,a,c,u);return t(c,l),d}}),n=i.revoke,r=o[e];return i.revoke=()=>{o[e]=r,n()},o[e]=i.proxy,i}var Bm=Symbol("Scheduled action");function Um(o,e,t=3){let i=o[Bm];i||(i=o[Bm]={});let n=e.name;i[t]||(i[t]={});let r=i[t];if(r[n])return;function*a(){e?.call(o),r[n]=null}let c=o.startCoroutine(a(),t);r[n]=c}var Vm=P("debugui"),ss=class{width;height},eo=class{x;y;width;height},vt=class extends We{offset=.01;get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}_anchoredPosition;get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new Xd),this._anchoredPosition}rect;sizeDelta;anchoredPosition3D;pivot;lastMatrix;rectBlock;_transformNeedsUpdate=!1;awake(){super.awake(),this.lastMatrix=new rx,this.rectBlock=new ox,this.rectBlock.position.z=.1,this.rectBlock.name=this.name,this._anchoredPosition||(this._anchoredPosition=new Xd),lc(this,"_anchoredPosition",()=>{this._transformNeedsUpdate=!0})}onEnable(){super.onEnable(),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0}onDisable(){super.onDisable(),this.removeShadowComponent()}applyTransform(){let e=this.shadowComponent;!e||(this._transformNeedsUpdate=!1,this.isRoot()?e.rotation.y=Math.PI:(e.position.copy(this.gameObject.position),e.position.x*=-1,e.position.z*=-1,e.position.z-=this.offset,e.quaternion.copy(this.gameObject.quaternion),e.rotation.x*=-1,e.rotation.z*=-1,e.scale.copy(this.gameObject.scale)),this.applyAnchoring(e.position),this.lastMatrix.copy(this.gameObject.matrix))}markDirty(){this._transformNeedsUpdate=!0}onBeforeRender(){(this._transformNeedsUpdate||this.lastMatrix.equals(this.gameObject.matrix)===!1)&&(Vm&&console.log("updating",this.name),this.applyTransform()),Je.ensureUpdateMeshUI(Qd,this.context)}applyAnchoring(e){if(this.pivot&&this.sizeDelta){let t=this.pivot.x*2-1,i=this.pivot.y*2-1;i-=this.anchoredPosition.y*.05;let n=this.sizeDelta.x*t,r=this.sizeDelta.y*i;e.x-=n*.5,e.y-=r*.5}}getBasicOptions(){let e={width:this.rect.width,height:this.rect.height,offset:this.offset,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}_createdBlocks=[];createNewBlock(e){e={...this.getBasicOptions(),...e},Vm&&console.log(this.name,e);let t=new Qd.Block(e);return this._createdBlocks.push(t),t}};v([y(eo)],vt.prototype,"rect",2),v([y(Gm)],vt.prototype,"sizeDelta",2),v([y(Xd)],vt.prototype,"anchoredPosition3D",2),v([y(Gm)],vt.prototype,"pivot",2);var ga=class extends We{get isGraphic(){return!0}get color(){return this._color||(this._color=new Q(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new Q(1,1,1,1)),this._color.copy(e))}onColorChanged(){let e=this.color;this.setOptions({backgroundColor:e,backgroundOpacity:e.alpha,borderOpacity:e.alpha})}get m_Color(){return this._color}raycastTarget=!0;uiObject=null;_color=null;_rect=null;get rectTransform(){return this._rect||(this._rect=R.getComponent(this.gameObject,vt)),this._rect}setState(e){this.makePanel(),this.uiObject&&this.uiObject.setState(e)}setupState(e){this.makePanel(),this.uiObject&&this.uiObject.setupState(e)}setOptions(e){this.makePanel(),this.uiObject&&(this.uiObject.set(e),(e.backgroundColor!==void 0||e.backgroundOpacity!==void 0)&&this.uiObject.updateBackgroundMaterial?.call(this.uiObject))}awake(){super.awake(),this.makePanel(),lc(this,"_color",()=>Um(this,this.onColorChanged))}onEnable(){super.onEnable(),this.uiObject&&(this.rectTransform.shadowComponent?.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}_currentlyCreatingPanel=!1;makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;let e={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:1};this.onBeforeCreate(e),this.onCreate(e),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}async setTexture(e){if(!!e&&(this.setOptions({backgroundOpacity:0}),e)){if(e.encoding===ax)if(ga.textureCache.has(e))e=ga.textureCache.get(e);else{let t=e.clone();t.encoding=sx,ga.textureCache.set(e,t),e=t}this.setOptions({backgroundTexture:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"})}}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}},yt=ga;I(yt,"textureCache",new Map),v([y(Q)],yt.prototype,"color",1),v([y()],yt.prototype,"raycastTarget",2);var In=class extends yt{_flippedObject=!1;onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}};var cc=class{texture;rect};v([y(zm)],cc.prototype,"texture",2);var An=class extends In{get sprite(){return this._sprite}set sprite(e){this._sprite!==e&&(this._sprite=e,this.onAfterCreated())}_sprite;isBuiltinSprite(){switch(this.sprite?.texture?.name){case"InputFieldBackground":case"UISprite":case"Background":return!0}return this.sprite?.texture?.image?.width===32&&this.sprite?.texture?.image?.height===32}onBeforeCreate(e){this.isBuiltinSprite()&&(e.borderRadius=5,e.borderColor=new lx(.4,.4,.4),e.borderOpacity=this.color.alpha,e.borderWidth=.3)}onAfterCreated(){!this.__didAwake||(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture))}};v([y(cc)],An.prototype,"sprite",1);var to=class extends In{get mainTexture(){return this._mainTexture}set mainTexture(e){this._mainTexture!==e&&(this._mainTexture=e,this.onAfterCreated())}_mainTexture;onAfterCreated(){!this.__didAwake||(super.onAfterCreated(),this.setTexture(this.mainTexture))}};v([y(zm)],to.prototype,"mainTexture",1);var as=P("debugbutton");var Dn=class{colorMultiplier;disabledColor;fadeDuration;highlightedColor;normalColor;pressedColor;selectedColor};v([y()],Dn.prototype,"colorMultiplier",2),v([y(Q)],Dn.prototype,"disabledColor",2),v([y()],Dn.prototype,"fadeDuration",2),v([y(Q)],Dn.prototype,"highlightedColor",2),v([y(Q)],Dn.prototype,"normalColor",2),v([y(Q)],Dn.prototype,"pressedColor",2),v([y(Q)],Dn.prototype,"selectedColor",2);var qt=class extends M{onClick;_isHovered=!1;onPointerEnter(e){as&&console.log("Button Enter",this.animationTriggers?.highlightedTrigger,this.animator),this._isHovered=!0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&this._image?.setState("hovered"),this.context.input.setCursorPointer()}onPointerExit(){as&&console.log("Button Exit",this.animationTriggers?.highlightedTrigger,this.animator),this._isHovered=!1,this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState("normal"),this.context.input.setCursorNormal()}onPointerDown(e){as&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&this._image?.setState("pressed")}onPointerUp(e){as&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState(this._isHovered?"hovered":"normal")}onPointerClick(e){as&&console.trace("Button Click",this.onClick),this.onClick?.invoke()}colors;transition;animationTriggers;animator;set interactable(e){this._interactable=e,this._image&&(this._image.setInteractable(e),e?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}_interactable=!0;set_interactable(e){this.interactable=e}awake(){super.awake(),as&&console.log(this),this.init()}start(){this._image?.setInteractable(this.interactable)}onEnable(){super.onEnable()}_requestedAnimatorTrigger;*setAnimatorTriggerAtEndOfFrame(e){this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&this.animator?.SetTrigger(e)}_isInit=!1;_image;init(){this._isInit||(this._isInit=!0,this._image=R.getComponent(this.gameObject,An),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){e.setInteractable(this.interactable);let t=this.getFinalColor(e.color,this.colors?.normalColor),i={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(i);let n=this.getFinalColor(e.color,this.colors?.highlightedColor),r={state:"hovered",attributes:{backgroundColor:n,backgroundOpacity:n.alpha}};e.setupState(r);let s=this.getFinalColor(e.color,this.colors?.pressedColor),a={state:"pressed",attributes:{backgroundColor:s,backgroundOpacity:s.alpha}};e.setupState(a);let c=this.getFinalColor(e.color,this.colors?.selectedColor),u={state:"selected",attributes:{backgroundColor:c,backgroundOpacity:c.alpha}};e.setupState(u);let l=this.getFinalColor(e.color,this.colors?.disabledColor),d={state:"disabled",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(d)}getFinalColor(e,t){return t?e.clone().multiply(t):e.clone()}};v([y(de)],qt.prototype,"onClick",2),v([y()],qt.prototype,"colors",2),v([y()],qt.prototype,"transition",2),v([y()],qt.prototype,"animationTriggers",2),v([y(Pe)],qt.prototype,"animator",2),v([y()],qt.prototype,"interactable",1);var qd=class extends kn{set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop}_renderOnTop=!1;set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}_depthWrite=!1;set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}_doubleSided=!0;set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}_castShadows=!0;set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}_receiveShadows=!0;get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}_renderMode=-1;_rootCanvas;set rootCanvas(e){this._rootCanvas instanceof qd||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}_scaleFactor=1;get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}awake(){this.shadowComponent=this.gameObject,super.awake()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this.onRenderSettingsChanged()}previousAspect=-1;onBeforeRender(){this.isScreenSpace&&this.context.mainCameraComponent&&this.context.mainCameraComponent.aspect!==this.previousAspect&&(this.previousAspect=this.context.mainCameraComponent.aspect,this.updateRenderMode())}_updateRenderSettingsRoutine;onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),3))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.updateRenderMode(),os(this.shadowComponent,this);for(let e of R.getComponentsInChildren(this.gameObject,We))os(e.shadowComponent,this)}}_activeRenderMode=-1;get isScreenSpace(){return this._activeRenderMode===1||this._activeRenderMode===0}updateRenderMode(){if(this.renderMode!==this._activeRenderMode)switch(this.renderMode){case 0:case 1:let e=this.context.mainCameraComponent;if(!e)return;let t=this.gameObject;e.gameObject?.add(t);let n=e.farClipPlane;t.position.x=0,t.position.y=0,t.position.z=-n;let r=Math.tan(H.toRadians(e.fieldOfView)*n)*(e.aspect*1.333333),s=r*(this.context.domHeight/this.context.domWidth);t.scale.x=-r,t.scale.y=s;break;case 2:break}}},Xe=qd;v([y()],Xe.prototype,"renderOnTop",1),v([y()],Xe.prototype,"depthWrite",1),v([y()],Xe.prototype,"doubleSided",1),v([y()],Xe.prototype,"castShadows",1),v([y()],Xe.prototype,"receiveShadows",1),v([y()],Xe.prototype,"renderMode",1),v([y(Xe)],Xe.prototype,"rootCanvas",1),v([y()],Xe.prototype,"scaleFactor",1);var Ln=class extends M{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}_alpha=1;interactable=!0;blocksRaycasts=!0;_isDirty=!1;markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),3))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){for(let e of R.getComponentsInChildren(this.gameObject,yt,this._buffer)){let t=e.color;t.alpha=this._alpha,e.color=t}}};v([y()],Ln.prototype,"alpha",1),v([y()],Ln.prototype,"interactable",2),v([y()],Ln.prototype,"blocksRaycasts",2);import{Quaternion as gx,Ray as bx,Vector3 as io}from"three";import*as Wm from"three";import{Color as ux,Object3D as dx,Texture as hx,WebGLRenderTarget as px}from"three";import{WebGLRenderTarget as cx}from"three";var ls=class extends cx{};var Kd=class extends Li{constructor(){super([ux,Q])}onDeserialize(e){if(e!=null)return e.a!==void 0?new Q(e.r,e.g,e.b,e.a):e.alpha!==void 0?new Q(e.r,e.g,e.b,e.alpha):new Wm.Color(e.r,e.g,e.b)}onSerialize(e){if(e!=null)return e.a!==void 0?{r:e.r,g:e.g,b:e.b,a:e.a}:{r:e.r,g:e.g,b:e.b}}},OL=new Kd,Jd=class extends Li{constructor(){super(dx)}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){let i=t.objectToNode[e.uuid];return pe&&console.log(i,e.name,e.uuid),{node:i}}}onDeserialize(e,t){if(e){if(e.node!==void 0&&t.nodeToObject){let i=t.nodeToObject[e.node];return pe&&console.log("Deserialized object reference?",e,i,t?.nodeToObject),i||console.warn("Did not find node: "+e.node,t.nodeToObject,t.object),i}else if(e.guid){if(!t.context){console.error("Missing context");return}let i,n=t.gltf?.scene;return n&&(i=R.findByGuid(e.guid,n)),i||(i=R.findByGuid(e.guid,t.context.scene)),i?pe&&console.log("Deserialized object reference?",e,i,t?.nodeToObject):((Ba()||pe)&&console.warn("Could not resolve object reference",t.path,e,t.target,t.context.scene),e.could_not_resolve=!0),i}}}},fx=new Jd,Zd=class extends Li{constructor(){super([Tt,M])}onSerialize(e,t){if(e?.guid)return{guid:e.guid}}onDeserialize(e,t){if(e?.guid){pe&&console.log(e.guid,t.root,t.object,t.target);let i=this.findObjectForGuid(e.guid,t.root);if(i||t.context&&(i=this.findObjectForGuid(e.guid,t.context?.scene),i))return i;(Ba()||pe)&&console.warn("Could not resolve component reference",t.path,e,t.target),e.could_not_resolve=!0;return}}findObjectForGuid(e,t){if(t.guid===e)return t;let i=R.foreachComponent(t,n=>{if(n.guid===e)return n},!1);if(i!==void 0)return i;for(let n=0;n<t.children.length;n++){let r=t.children[n],s=this.findObjectForGuid(e,r);if(s)return s}}},Yd=new Zd,$d=class extends Li{constructor(){super([de])}onSerialize(e,t){console.log("TODO: SERIALIZE EVENT")}onDeserialize(e,t){if(typeof e=="function")return new de([new vi(e,!0)]);if(e&&e.type==="EventList"){pe&&console.log("DESERIALIZE EVENT",e);let i=new Array;if(e.calls&&Array.isArray(e.calls))for(let s of e.calls){pe&&console.log(s);let a=Yd.findObjectForGuid(s.target,t.root);!a&&t.context?.scene&&(a=Yd.findObjectForGuid(s.target,t.context?.scene));let c=s.method?.length>0;if(a&&c){let h=()=>console.warn(`Could not find method ${s.method} on object ${a.name}`,a,typeof a[s.method]);if(typeof a[s.method]!="function"){let g=!1;s.method.startsWith("set_")&&s.method.length>4&&(s.method=s.method.substring(4),a[s.method]!==void 0&&(g=!0)),!g&&(Ba()||pe)&&h()}}let u,l=s.argument;s.argument!==void 0?(typeof l=="object"&&(l=fx.onDeserialize(s.argument,t),l||(l=Yd.onDeserialize(s.argument,t))),u=new vi(c?(...h)=>d(...h):void 0,s.enabled)):u=new vi(c?(...h)=>d(...h):void 0,s.enabled);let d=(...h)=>{let g=a[s.method];typeof g=="function"?l!==void 0?g?.call(a,l):g?.call(a,...h):a[s.method]=l};if(u.method||(u.__debuginfo=t.object?.name),!a||!u.method){let h=t.object?"Current object: "+t.object.name+", "+t.object.guid:null;a?console.warn('EventList method not found: "'+s.method+'" on',a):console.warn("EventList is missing target - will be ignored",s.target,h,e)}else i.push(u)}let n=new de(i);pe&&console.log(n);let r=t.target;return r!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,r),n}}},kL=new $d,eh=class extends Li{constructor(){super([ls,px])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof hx&&t.type===ls){let i=e,n=new ls(i.image.width,i.image.height);return n.texture=i,n}}};new eh;var Yi=class extends M{center=new io(0,0,0);radius=.5;height=2;_rigidbody=null;get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(J),this._rigidbody||(this._rigidbody=this.gameObject.addNewComponent(J)),this.rigidbody)}onEnable(){let e=this.rigidbody,t=this.gameObject.getComponent(Xt);t||(t=this.gameObject.addNewComponent(Xt)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height,this.gameObject.rotation.x=0,this.gameObject.rotation.z=0,e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}_activeGroundCollisions=new Set;onCollisionEnter(e){for(let t of e.contacts)if(t.normal.y>.1){this._activeGroundCollisions.add(e);break}}onCollisionExit(e){this._activeGroundCollisions.delete(e)}get isGrounded(){return this._activeGroundCollisions.size>0}};v([y(io)],Yi.prototype,"center",2),v([y()],Yi.prototype,"radius",2),v([y()],Yi.prototype,"height",2);var Ti=class extends M{controller;movementSpeed=2;rotationSpeed=2;jumpForce=1;animator;lookForward=!0;_currentSpeed=new io(0,0,0);_currentAngularSpeed=new io(0,0,0);_temp=new io(0,0,0);_jumpCount=0;_currentRotation;awake(){this._currentRotation=new gx}update(){this.controller?.isGrounded&&(this._jumpCount=0,this.animator?.SetBool("doubleJump",!1));let e=this.context.input.isKeyPressed("w"),t=this.context.input.isKeyPressed("s"),i=this.context.input.isKeyPressed("a"),n=this.context.input.isKeyPressed("d"),r=this.context.input.isKeyDown(" "),s=e?1:0+t?-1:0;this._currentSpeed.z+=s*this.movementSpeed*this.context.time.deltaTime,this.animator?.SetBool("running",s!=0),this.animator?.SetBool("jumping",this.controller?.isGrounded===!0&&r),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp);let a=i?1:0+n?-1:0;if(this._currentAngularSpeed.y+=H.toRadians(a*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){let c=this.context.mainCameraComponent.forward;c.y=0,c.normalize(),this._currentRotation.setFromUnitVectors(new io(0,0,1),c),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&&r&&this.jumpForce>0){let c=this.controller?.isGrounded;if(!this.controller?.isGrounded&&this._jumpCount===1&&(c=!0,this.animator?.SetBool("doubleJump",!0)),c){this._jumpCount+=1;let u=this.controller.rigidbody,l=this._jumpCount===2?2:1;u.applyImpulse(new io(0,1,0).multiplyScalar(this.jumpForce*l))}}if(this.controller){let c=this.controller?.rigidbody.getVelocity().y;if(c<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new bx),this._raycastOptions.ray.origin.copy(B(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);let u=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);let l=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(u),(l.length&&l[0].distance>2||c<-10)&&this.animator?.SetBool("falling",!0)}else this.animator?.SetBool("falling",!1)}}_raycastOptions=new be};v([y(Yi)],Ti.prototype,"controller",2),v([y()],Ti.prototype,"movementSpeed",2),v([y()],Ti.prototype,"rotationSpeed",2),v([y()],Ti.prototype,"jumpForce",2),v([y(Pe)],Ti.prototype,"animator",2);import{LinearToneMapping as th,ACESFilmicToneMapping as Nm,ReinhardToneMapping as vx}from"three";var uc=P("debugvolume"),Qm=(i=>(i[i.None=0]="None",i[i.Neutral=1]="Neutral",i[i.ACES=2]="ACES",i))(Qm||{}),cs=class{overrideState=!1;value=0},Ki=class{active=!1;parameters},mr=class extends Ki{mode;get isToneMapping(){return!0}},gr=class extends Ki{postExposure};function yx(o){return"mode"in o?mr:"postExposure"in o?gr:Ki}var Xm=Symbol("volumeprofile"),fr=class{components;apply(e){this.onUpdate(e,!1)}unapply(e){this.onUpdate(e,!0)}onUpdate(e,t){if(!this.components)return;let i=e.renderer,r=i[Xm]!==void 0;if(t){if(!r)return}else i[Xm]=this;for(let s of this.components)if(s instanceof mr){let a=s;if(!s.active||t){e.renderer.toneMapping=th;continue}uc&&console.log("VOLUME:",Qm[a.mode?.value??0]);let c=a.mode;switch((c?.overrideState?c?.value:0)??0){case 0:e.renderer.toneMapping=th;break;case 1:e.renderer.toneMapping=vx;break;case 2:e.renderer.toneMapping=Nm;break}}else if(s instanceof gr){let a=s;uc&&console.log(a.postExposure);let c=1;a.postExposure&&(c=Math.pow(2,a.postExposure.value)),e.renderer.toneMapping,Nm;let u=a.postExposure?.overrideState&&!t;e.renderer.toneMappingExposure=u?c:1,e.renderer.toneMapping||(e.renderer.toneMapping=th)}}};v([y([o=>yx(o),Ki])],fr.prototype,"components",2);var no=class extends M{sharedProfile;awake(){uc&&(console.log(this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",e=>{e.key==="p"&&(console.log("Toggle volume: "+this.name,!this.enabled),this.enabled=!this.enabled)}))}onEnable(){uc&&console.log("APPLY VOLUME",this),this.sharedProfile?.apply(this.context)}onDisable(){this.sharedProfile?.unapply(this.context)}};v([y(fr)],no.prototype,"sharedProfile",2);import{Matrix4 as qm,Quaternion as _x,Vector3 as $e,Vector2 as Ym,Euler as xx}from"three";import{createNoise4D as wx}from"simplex-noise";var Ex=P("debugparticles");var Si=class{alphaKeys;colorKeys;get duration(){return 1}evaluate(e,t){let i,n=0,r=null,s=0;for(let a=0;a<this.alphaKeys.length;a++){let c=this.alphaKeys[a];(c.time<e||!i)&&(i=c,n=a)}for(let a=0;a<this.colorKeys.length;a++){let c=this.colorKeys[a];(c.time<e||!r)&&(r=c,s=a)}if(r)if(s+1<this.colorKeys.length){let c=this.colorKeys[s+1],u=H.remap(e,r.time,c.time,0,1);t.r=H.lerp(r.color.r,c.color.r,u),t.g=H.lerp(r.color.g,c.color.g,u),t.b=H.lerp(r.color.b,c.color.b,u)}else t.r=r.color.r,t.g=r.color.g,t.b=r.color.b;if(i)if(n+1<this.alphaKeys.length){let c=this.alphaKeys[n+1],u=H.remap(e,i.time,c.time,0,1);t.alpha=H.lerp(i.alpha,c.alpha,u)}else t.alpha=i.alpha;return t}};v([y()],Si.prototype,"alphaKeys",2),v([y()],Si.prototype,"colorKeys",2);var Km=(w=>(w[w.Sphere=0]="Sphere",w[w.SphereShell=1]="SphereShell",w[w.Hemisphere=2]="Hemisphere",w[w.HemisphereShell=3]="HemisphereShell",w[w.Cone=4]="Cone",w[w.Box=5]="Box",w[w.Mesh=6]="Mesh",w[w.ConeShell=7]="ConeShell",w[w.ConeVolume=8]="ConeVolume",w[w.ConeVolumeShell=9]="ConeVolumeShell",w[w.Circle=10]="Circle",w[w.CircleEdge=11]="CircleEdge",w[w.SingleSidedEdge=12]="SingleSidedEdge",w[w.MeshRenderer=13]="MeshRenderer",w[w.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",w[w.BoxShell=15]="BoxShell",w[w.BoxEdge=16]="BoxEdge",w[w.Donut=17]="Donut",w[w.Rectangle=18]="Rectangle",w[w.Sprite=19]="Sprite",w[w.SpriteRenderer=20]="SpriteRenderer",w))(Km||{});var U=class{mode;constant;constantMin;constantMax;curve;curveMin;curveMax;curveMultiplier;evaluate(e,t){let i=t===void 0?Math.random():t;switch(this.mode){case 0:return this.constant;case 1:return e=H.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:let n=e*this.curveMin.duration,r=e*this.curveMax.duration;return H.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(r),i%1)*this.curveMultiplier;case 3:return H.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(e)*this.curveMultiplier;break}return 0}};v([y()],U.prototype,"mode",2),v([y()],U.prototype,"constant",2),v([y()],U.prototype,"constantMin",2),v([y()],U.prototype,"constantMax",2),v([y(gi)],U.prototype,"curve",2),v([y(gi)],U.prototype,"curveMin",2),v([y(gi)],U.prototype,"curveMax",2),v([y()],U.prototype,"curveMultiplier",2);var Yt=class{mode;color;colorMin;colorMax;gradient;gradientMin;gradientMax;evaluate(e,t){let i=t===void 0?Math.random():t;switch(this.mode){case 0:return this.color;case 1:return this.gradient.evaluate(e,Yt._temp),Yt._temp;case 2:return Yt._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:return this.gradientMin.evaluate(e,Yt._temp),this.gradientMax.evaluate(e,Yt._temp2),Yt._temp.lerp(Yt._temp2,i)}return Yt._temp.set(16711935),Yt._temp.alpha=1,Yt._temp}},Me=Yt;I(Me,"_temp",new Q(0,0,0,1)),I(Me,"_temp2",new Q(0,0,0,1)),v([y(Q)],Me.prototype,"color",2),v([y(Q)],Me.prototype,"colorMin",2),v([y(Q)],Me.prototype,"colorMax",2),v([y(Si)],Me.prototype,"gradient",2),v([y(Si)],Me.prototype,"gradientMin",2),v([y(Si)],Me.prototype,"gradientMax",2);var _e=class{cullingMode;duration;emitterVelocityMode;flipRotation;gravityModifier;gravityModifierMultiplier;loop;maxParticles;playOnAwake;prewarm;ringBufferLoopRange;ringBufferMode;scalingMode;simulationSpace;simulationSpeed;startColor;startDelay;startDelayMultiplier;startLifetime;startLifetimeMultiplier;startRotation;startRotationMultiplier;startRotation3D;startRotationX;startRotationXMultiplier;startRotationY;startRotationYMultiplier;startRotationZ;startRotationZMultiplier;startSize;startSize3D;startSizeMultiplier;startSizeX;startSizeXMultiplier;startSizeY;startSizeYMultiplier;startSizeZ;startSizeZMultiplier;startSpeed;startSpeedMultiplier;stopAction;useUnscaledTime};v([y(U)],_e.prototype,"gravityModifier",2),v([y(Me)],_e.prototype,"startColor",2),v([y(U)],_e.prototype,"startDelay",2),v([y(U)],_e.prototype,"startLifetime",2),v([y(U)],_e.prototype,"startRotation",2),v([y(U)],_e.prototype,"startRotationX",2),v([y(U)],_e.prototype,"startRotationY",2),v([y(U)],_e.prototype,"startRotationZ",2),v([y(U)],_e.prototype,"startSize",2),v([y(U)],_e.prototype,"startSizeX",2),v([y(U)],_e.prototype,"startSizeY",2),v([y(U)],_e.prototype,"startSizeZ",2),v([y(U)],_e.prototype,"startSpeed",2);var Hn=class{cycleCount;maxCount;minCount;probability;repeatInterval;time;count;_performed=0;reset(){this._performed=0}run(e){if(e<=this.time)return this.reset(),0;let t=0;if(this.cycleCount===0||this._performed<this.cycleCount){let i=this.time+this.repeatInterval*this._performed;if(e>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=H.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:let n=Math.random();t=H.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return t}},_t=class{enabled;get burstCount(){return this.bursts?.length??0}bursts;rateOverTime;rateOverTimeMultiplier;rateOverDistance;rateOverDistanceMultiplier;system;reset(){this.bursts?.forEach(e=>e.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){let i=this.bursts[t];i.time>=this.system.time&&i.reset(),e+=Math.round(i.run(this.system.time))}return e}};v([y()],_t.prototype,"enabled",2),v([y()],_t.prototype,"bursts",2),v([y(U)],_t.prototype,"rateOverTime",2),v([y()],_t.prototype,"rateOverTimeMultiplier",2),v([y(U)],_t.prototype,"rateOverDistance",2),v([y()],_t.prototype,"rateOverDistanceMultiplier",2);var jn=class{enabled;color};v([y(Me)],jn.prototype,"color",2);var Kt=class{enabled;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_time=0;_temp=new $e;evaluate(e,t,i){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,i)*this.xMultiplier,t.y=this.y.evaluate(e,i)*this.yMultiplier,t.z=this.z.evaluate(e,i)*this.zMultiplier;else{let n=this.size.evaluate(e,i)*this.sizeMultiplier;t.x=n}return t}};v([y(U)],Kt.prototype,"size",2),v([y(U)],Kt.prototype,"x",2),v([y(U)],Kt.prototype,"y",2),v([y(U)],Kt.prototype,"z",2);var us=class{get type(){return Km[this.shapeType]}initialize(e){this.getPosition(),e.position.copy(this._vector)}toJSON(){return this}clone(){return new us}shapeType=5;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcSpread;arcSpeedMultiplier;arcMode;boxThickness;position;rotation;_rotation=new xx;scale;radius;radiusThickness;sphericalDirectionAmount;randomDirectionAmount;randomPositionAmount;system;_space;_worldSpaceMatrix=new qm;_worldSpaceMatrixInverse=new qm;update(e,t,i,n){this.system=e,this._space=i,i===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}updateRotation(){let e=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return e&&(this._rotation.x=H.toRadians(this.rotation.x),this._rotation.y=-H.toRadians(this.rotation.y),this._rotation.z=-H.toRadians(this.rotation.z)),e}_vector=new $e(0,0,0);_temp=new $e(0,0,0);get vector(){return this._vector}getPosition(){this._vector.set(0,0,0);let e=this._temp.copy(this.position),t=this._space===1;t&&e.applyQuaternion(this.system.worldQuaternion);let i=this.radius;if(t&&(i*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(e);break;case 4:this.randomConePoint(this.position,this.angle,i,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,i,this.radiusThickness,this.arc,this._vector,this.scale);break;case 10:this._temp.copy(this.scale),this._temp.z=0,this.randomSpherePoint(this.position,i,this.radiusThickness,this.arc,this._vector,this._temp);break;default:this._vector.set(0,0,0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.updateRotation()&&this._vector.applyEuler(this._rotation),t&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos))}_dir=new $e;getDirection(e){if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:let t=e.x,i=e.y,n=e.z;this._dir.set(t,i,n),this._dir.sub(this.position);break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyMatrix4(this._worldSpaceMatrixInverse),this.updateRotation()&&this._dir.applyEuler(this._rotation),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),Ex&&(Et.DrawSphere(e,.01,8925952,.5,!0),Et.DrawDirection(e,this._dir,8925952,.5,!0)),this._dir}randomizePosition(e,t){if(t<=0)return;let i=us._tempVec;i.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),i.x*=t*this.scale.x,i.y*=t*this.scale.y,i.z*=t*this.scale.z,e.add(i)}randomizeDirection(e,t){if(t===0)return;let i=us._randomQuat,n=us._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),e.applyQuaternion(i)}spherizeDirection(e,t){if(t===0)return;let i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),r=Math.sin(n)*Math.cos(i),s=Math.sin(n)*Math.sin(i),a=Math.cos(n),c=new $e(r,s,a);e.lerp(c,t)}randomSpherePoint(e,t,i,n,r,s){let a=Math.random(),c=Math.random(),u=2*Math.PI*a*(n/360),l=Math.acos(2*c-1),d=H.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,h=e.x+s.x*(-d*Math.sin(l)*Math.cos(u)),g=e.y+s.y*(d*Math.sin(l)*Math.sin(u)),E=e.z+s.z*(d*Math.cos(l));r.x=h,r.y=g,r.z=E}_loopTime=0;_loopDirection=1;randomConePoint(e,t,i,n,r,s,a){let c=0,u=0;switch(s){case 0:c=Math.random(),u=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:c=.5,u=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let l=2*Math.PI*c*(r/360);switch(s){case 2:case 1:l+=Math.PI+.5,l+=this._loopTime*Math.PI*2,l%=H.toRadians(r);break}let d=Math.acos(2*u-1),h=H.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,g=e.x+-h*Math.sin(d)*Math.cos(l),E=e.y+h*Math.sin(d)*Math.sin(l),_=e.z;a.x=g*this.scale.x,a.y=E*this.scale.y,a.z=_*this.scale.z}},ne=us;I(ne,"_randomQuat",new _x),I(ne,"_tempVec",new $e),v([y()],ne.prototype,"shapeType",2),v([y()],ne.prototype,"enabled",2),v([y()],ne.prototype,"alignToDirection",2),v([y()],ne.prototype,"angle",2),v([y()],ne.prototype,"arc",2),v([y()],ne.prototype,"arcSpread",2),v([y()],ne.prototype,"arcSpeedMultiplier",2),v([y()],ne.prototype,"arcMode",2),v([y($e)],ne.prototype,"boxThickness",2),v([y($e)],ne.prototype,"position",2),v([y($e)],ne.prototype,"rotation",2),v([y($e)],ne.prototype,"scale",2),v([y()],ne.prototype,"radius",2),v([y()],ne.prototype,"radiusThickness",2),v([y()],ne.prototype,"sphericalDirectionAmount",2),v([y()],ne.prototype,"randomDirectionAmount",2),v([y()],ne.prototype,"randomPositionAmount",2);var K=class{damping;enabled;frequency;octaveCount;octaveMultiplier;octaveScale;positionAmount;quality;remap;remapEnabled;remapMultiplier;remapX;remapXMultiplier;remapY;remapYMultiplier;remapZ;remapZMultiplier;scrollSpeedMultiplier;separateAxes;strengthMultiplier;strengthX;strengthXMultiplier;strengthY;strengthYMultiplier;strengthZ;strengthZMultiplier;_noise;_time=0;update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}_temp=new $e;apply(e,t,i,n,r,s){if(!this.enabled)return;this._noise||(this._noise=wx(()=>0));let a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),c=this._noise(a.x,a.y,a.z,this._time),u=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),l=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(c,u,l).normalize();let d=r/s,h=this.positionAmount.evaluate(d);this.separateAxes?(this._temp.x*=h*this.strengthXMultiplier,this._temp.y*=h*this.strengthYMultiplier,this._temp.z*=h*this.strengthZMultiplier):(this.strengthX&&(h*=this.strengthX.evaluate(d)*1.5),this._temp.multiplyScalar(h)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}};v([y()],K.prototype,"damping",2),v([y()],K.prototype,"enabled",2),v([y()],K.prototype,"frequency",2),v([y()],K.prototype,"octaveCount",2),v([y()],K.prototype,"octaveMultiplier",2),v([y()],K.prototype,"octaveScale",2),v([y(U)],K.prototype,"positionAmount",2),v([y()],K.prototype,"quality",2),v([y(U)],K.prototype,"remap",2),v([y()],K.prototype,"remapEnabled",2),v([y()],K.prototype,"remapMultiplier",2),v([y(U)],K.prototype,"remapX",2),v([y()],K.prototype,"remapXMultiplier",2),v([y(U)],K.prototype,"remapY",2),v([y()],K.prototype,"remapYMultiplier",2),v([y(U)],K.prototype,"remapZ",2),v([y()],K.prototype,"remapZMultiplier",2),v([y()],K.prototype,"scrollSpeedMultiplier",2),v([y()],K.prototype,"separateAxes",2),v([y()],K.prototype,"strengthMultiplier",2),v([y(U)],K.prototype,"strengthX",2),v([y()],K.prototype,"strengthXMultiplier",2),v([y(U)],K.prototype,"strengthY",2),v([y()],K.prototype,"strengthYMultiplier",2),v([y(U)],K.prototype,"strengthZ",2),v([y()],K.prototype,"strengthZMultiplier",2);var te=class{enabled;attachRibbonToTransform=!1;colorOverLifetime;colorOverTrail;dieWithParticles=!0;inheritParticleColor=!0;lifetime;lifetimeMultiplier;minVertexDistance=.2;mode=0;ratio=1;ribbonCount=1;shadowBias=0;sizeAffectsLifetime=!1;sizeAffectsWidth=!1;splitSubEmitterRibbons=!1;textureMode=0;widthOverTrail;widthOverTrailMultiplier;worldSpace=!1;getWidth(e,t,i){let n=this.widthOverTrail.evaluate(i);return i===0&&(n=e),e*=n,e}getColor(e,t,i){let n=this.colorOverTrail.evaluate(i),r=this.colorOverLifetime.evaluate(t);e.x*=n.r*r.r,e.y*=n.g*r.g,e.z*=n.b*r.b,e.w*=n.alpha*r.alpha}};v([y()],te.prototype,"enabled",2),v([y()],te.prototype,"attachRibbonToTransform",2),v([y(Me)],te.prototype,"colorOverLifetime",2),v([y(Me)],te.prototype,"colorOverTrail",2),v([y()],te.prototype,"dieWithParticles",2),v([y()],te.prototype,"inheritParticleColor",2),v([y(U)],te.prototype,"lifetime",2),v([y()],te.prototype,"lifetimeMultiplier",2),v([y()],te.prototype,"minVertexDistance",2),v([y()],te.prototype,"mode",2),v([y()],te.prototype,"ratio",2),v([y()],te.prototype,"ribbonCount",2),v([y()],te.prototype,"shadowBias",2),v([y()],te.prototype,"sizeAffectsLifetime",2),v([y()],te.prototype,"sizeAffectsWidth",2),v([y()],te.prototype,"splitSubEmitterRibbons",2),v([y()],te.prototype,"textureMode",2),v([y(U)],te.prototype,"widthOverTrail",2),v([y()],te.prototype,"widthOverTrailMultiplier",2),v([y()],te.prototype,"worldSpace",2);var He=class{enabled;space=0;speedModifier;speedModifierMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_system;update(e){this._system=e}_temp=new $e;apply(e,t,i,n,r,s){if(!this.enabled)return;let a=r/s,c=this.speedModifier.evaluate(a)*this.speedModifierMultiplier,u=this.x.evaluate(a),l=this.y.evaluate(a),d=this.z.evaluate(a);this._temp.set(-u,l,d),this._system&&(this.space===1&&this._temp.applyQuaternion(this._system.worldQuaternionInverted),this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z,i.x*=c,i.y*=c,i.z*=c}};v([y()],He.prototype,"enabled",2),v([y()],He.prototype,"space",2),v([y(U)],He.prototype,"speedModifier",2),v([y()],He.prototype,"speedModifierMultiplier",2),v([y(U)],He.prototype,"x",2),v([y()],He.prototype,"xMultiplier",2),v([y(U)],He.prototype,"y",2),v([y()],He.prototype,"yMultiplier",2),v([y(U)],He.prototype,"z",2),v([y()],He.prototype,"zMultiplier",2);var xe=class{animation;enabled;cycleCount;frameOverTime;frameOverTimeMultiplier;numTilesX;numTilesY;startFrame;startFrameMultiplier;rowMode;rowIndex;spriteCount;timeMode;sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?this.frameOverTime.evaluate(Math.random()):0}evaluate(e){if(!this.sampleOnceAtStart())return this.getIndex(e)}getIndex(e){let t=this.numTilesX*this.numTilesY,i=this.frameOverTime.evaluate(e%1);return i*=this.frameOverTimeMultiplier,i*=t,i=i%t,i=Math.floor(i),i}};v([y()],xe.prototype,"animation",2),v([y()],xe.prototype,"enabled",2),v([y()],xe.prototype,"cycleCount",2),v([y(U)],xe.prototype,"frameOverTime",2),v([y()],xe.prototype,"frameOverTimeMultiplier",2),v([y()],xe.prototype,"numTilesX",2),v([y()],xe.prototype,"numTilesY",2),v([y(U)],xe.prototype,"startFrame",2),v([y()],xe.prototype,"startFrameMultiplier",2),v([y()],xe.prototype,"rowMode",2),v([y()],xe.prototype,"rowIndex",2),v([y()],xe.prototype,"spriteCount",2),v([y()],xe.prototype,"timeMode",2);var Ze=class{enabled;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}};v([y()],Ze.prototype,"enabled",2),v([y()],Ze.prototype,"separateAxes",2),v([y(U)],Ze.prototype,"x",2),v([y()],Ze.prototype,"xMultiplier",2),v([y(U)],Ze.prototype,"y",2),v([y()],Ze.prototype,"yMultiplier",2),v([y(U)],Ze.prototype,"z",2),v([y()],Ze.prototype,"zMultiplier",2);var Qe=class{enabled;range;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){let i=H.lerp(this.range.x,this.range.y,t);return this.z.evaluate(i)*-1}return 0}};v([y()],Qe.prototype,"enabled",2),v([y()],Qe.prototype,"range",2),v([y()],Qe.prototype,"separateAxes",2),v([y(U)],Qe.prototype,"x",2),v([y()],Qe.prototype,"xMultiplier",2),v([y(U)],Qe.prototype,"y",2),v([y()],Qe.prototype,"yMultiplier",2),v([y(U)],Qe.prototype,"z",2),v([y()],Qe.prototype,"zMultiplier",2);var ue=class{enabled;dampen;drag;dragMultiplier;limit;limitMultiplier;separateAxes;limitX;limitXMultiplier;limitY;limitYMultiplier;limitZ;limitZMultiplier;multiplyDragByParticleSize=!1;multiplyDragByParticleVelocity=!1;space;_temp=new $e;_temp2=new $e;apply(e,t,i,n,r,s,a){if(!!this.enabled){let c=this.limit.evaluate(r)*this.limitMultiplier;if(t.length()>c){this._temp.copy(t).normalize().multiplyScalar(c);let l=this.dampen*.5;t.x=H.lerp(t.x,this._temp.x,l),t.y=H.lerp(t.y,this._temp.y,l),t.z=H.lerp(t.z,this._temp.z,l),i.x=H.lerp(i.x,this._temp.x,l),i.y=H.lerp(i.y,this._temp.y,l),i.z=H.lerp(i.z,this._temp.z,l)}}}};v([y()],ue.prototype,"enabled",2),v([y()],ue.prototype,"dampen",2),v([y(U)],ue.prototype,"drag",2),v([y()],ue.prototype,"dragMultiplier",2),v([y(U)],ue.prototype,"limit",2),v([y()],ue.prototype,"limitMultiplier",2),v([y()],ue.prototype,"separateAxes",2),v([y(U)],ue.prototype,"limitX",2),v([y()],ue.prototype,"limitXMultiplier",2),v([y(U)],ue.prototype,"limitY",2),v([y()],ue.prototype,"limitYMultiplier",2),v([y(U)],ue.prototype,"limitZ",2),v([y()],ue.prototype,"limitZMultiplier",2),v([y()],ue.prototype,"multiplyDragByParticleSize",2),v([y()],ue.prototype,"multiplyDragByParticleVelocity",2),v([y()],ue.prototype,"space",2);var Jt=class{enabled;curve;curveMultiplier;mode;system;_lastWorldPosition;_velocity=new $e;_temp=new $e;update(e){!this.enabled||this.system.worldspace!==!1&&(this._lastWorldPosition?(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)):(this._velocity.set(0,0,0),this._lastWorldPosition=this.system.worldPos.clone()))}applyInitial(e){if(!!this.enabled&&this.system.worldspace!==!1&&this.mode===0){let t=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(t),e.add(this._temp)}}applyCurrent(e,t,i){if(!!this.enabled&&this.system.worldspace!==!1&&this.mode===1){let n=this.curve.evaluate(t,i);this._temp.copy(this._velocity).multiplyScalar(n),e.add(this._temp)}}};v([y()],Jt.prototype,"enabled",2),v([y(U)],Jt.prototype,"curve",2),v([y()],Jt.prototype,"curveMultiplier",2),v([y()],Jt.prototype,"mode",2);var ke=class{enabled;range;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t,i,n){let r=e.length(),s=H.remap(r,this.range.x,this.range.y,0,1),a=this.size.evaluate(s,i);return n*a}};v([y()],ke.prototype,"enabled",2),v([y(Ym)],ke.prototype,"range",2),v([y()],ke.prototype,"separateAxes",2),v([y(U)],ke.prototype,"size",2),v([y()],ke.prototype,"sizeMultiplier",2),v([y(U)],ke.prototype,"x",2),v([y()],ke.prototype,"xMultiplier",2),v([y(U)],ke.prototype,"y",2),v([y()],ke.prototype,"yMultiplier",2),v([y(U)],ke.prototype,"z",2),v([y()],ke.prototype,"zMultiplier",2);var Ri=class{enabled;range;color;evaluate(e,t,i){let n=e.length(),r=H.remap(n,this.range.x,this.range.y,0,1),s=this.color.evaluate(r,t);i.x*=s.r,i.y*=s.g,i.z*=s.b,i.w*=s.alpha}};v([y()],Ri.prototype,"enabled",2),v([y(Ym)],Ri.prototype,"range",2),v([y(Me)],Ri.prototype,"color",2);var ro=class extends Ne{},ds=class extends M{deleteBoxes=[];awake(){this.deleteBoxes=R.findObjectsOfType(ro,this.context)}update(){for(let e of this.deleteBoxes){let t=this.gameObject;e.isInBox(t)===!0&&(R.getComponentInParent(this.gameObject,zt)||So(this.gameObject,this.context.connection))}}};var oo=class extends M{visibleOn;onEnable(){this.apply()}apply(){this.test()||R.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:Cx()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}};v([y()],oo.prototype,"visibleOn",2);var dc;function Cx(){if(dc===!0||dc===!1)return dc;let o=!1;return function(e){(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4)))&&(o=!0)}(navigator.userAgent||navigator.vendor||window.opera),dc=o,o}import*as Y from"three";var ih=!1;var Fn=class extends Vt{static get HasAnySelected(){return this._active>0}transformSelf=!0;orbit=null;selectStartEventListener=[];selectEndEventListener=[];constructor(){super(),this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new Y.Vector2}addDragEventListener(e,t){switch(e){case"selectstart":this.selectStartEventListener.push(t);break;case"selectend":this.selectEndEventListener.push(t);break}}_dragHelper=null;start(){this.orbit=R.findObjectOfType(Ve,this.context)}_draggingRigidbodies=[];allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||V.IsInWebXR)return;let t=R.getComponentInParent(e.object,Fn);!t||t!==this||(Fn.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){!this.allowEdit(this.gameObject)||V.IsInWebXR||Fn.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}_waitingForDragStart=null;onPointerDown(e){!this.allowEdit(this.gameObject)||V.IsInWebXR||(Fn._active+=1,this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation(),this.orbit&&(this.orbit.enabled=!1))}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&(Fn._active>0&&(Fn._active-=1),!V.IsInWebXR&&(this.onDragEnd(e),e.StopPropagation(),this.orbit&&(this.orbit.enabled=!0)))}update(){if(!V.IsInWebXR){if(this._waitingForDragStart){if(!this._didDrag){let t=this.context.input.getPointerPositionDelta(0);if(t&&this._dragDelta.add(t),this._dragDelta.length()>2)this._didDrag=!0;else return}let e=this._waitingForDragStart;this._waitingForDragStart=null,this.onDragStart(e)}this._dragHelper&&this._dragHelper.hasSelected&&this.onUpdateDrag(),this._isDragging&&this._dragHelper?.hasSelected===!1&&this.onDragEnd(null)}}_isDragging=!1;_marker=null;_dragDelta;_didDrag=!1;onDragStart(e){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new hc(this.context.mainCamera);else return;if(!e||!e.object)return;let t=R.getComponentInParent(e.object,Fn);if(!t||t!==this)return;let i=e.object;this.transformSelf&&(i=this.gameObject);let n={selected:i,attached:i};for(let c of this.selectStartEventListener)c(this,n);if(!n.attached)return;n.attached,i=n.attached,this._isDragging=!0,this._dragHelper.setSelected(i,this.context),this.orbit&&(this.orbit.enabled=!1);let r=R.getComponentInChildren(i,Pt);ih&&console.log("DRAG START",r,i),r&&(r.fastMode=!0,r?.requestOwnership()),this._marker=R.addNewComponent(i,zt),this._draggingRigidbodies.length=0;let s=R.getComponentsInChildren(i,J);s&&this._draggingRigidbodies.push(...s);let a=Kc();R.invokeOnChildren(this._dragHelper.selected,a("onDragStart"))}onUpdateDrag(){if(!!this._dragHelper){this._dragHelper.onUpdate(this.context);for(let e of this._draggingRigidbodies)e.wakeUp(),e.resetVelocities()}}onDragEnd(e){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;for(let n of this._draggingRigidbodies)n.setVelocity(n.smoothedVelocity);this._draggingRigidbodies.length=0;let t=this._dragHelper.selected;if(ih&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context),this.orbit&&(this.orbit.enabled=!0),e?.object){let n=R.getComponentInChildren(e.object,Pt);n&&(n.fastMode=!1),this._marker&&this._marker.destroy()}for(let n of this.selectEndEventListener)n(this);let i=Kc();R.invokeOnChildren(t,i("onDragEnd"))}},Ji=Fn;I(Ji,"_active",0),I(Ji,"lastHovered");var nh=class{get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}_selected=null;_context=null;_camera;_cameraPlane=new Y.Plane;_hasGroundPlane=!1;_groundPlane=new Y.Plane;_groundOffset=new Y.Vector3;_groundOffsetFactor=0;_groundDistance=0;_groundPlanePoint=new Y.Vector3;_raycaster=new Y.Raycaster;_cameraPlaneOffset=new Y.Vector3;_intersection=new Y.Vector3;_worldPosition=new Y.Vector3;_inverseMatrix=new Y.Matrix4;_rbs=[];_groundLine;_groundMarker;constructor(e){this._camera=e;let t=new Y.Line(nh.geometry),i=t.material;i.color=new Y.Color(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;let n=new Y.SphereGeometry(.5,22,22),r=new Y.MeshBasicMaterial({color:i.color}),s=new Y.Mesh(n,r);s.visible=!1,s.layers.set(2),this._groundMarker=s}setSelected(e,t){if(this._selected&&t)for(let i of this._rbs)i.wakeUp(),i.setVelocity(0,0,0);if(this._selected&&ye.Remove(t,this._selected),this._selected=e,this._context=t,this._rbs.length=0,e?(t.scene.add(this._groundLine),t.scene.add(this._groundMarker)):(this._groundLine.removeFromParent(),this._groundMarker.removeFromParent()),this._selected){if(!t){console.error("DragHelper: no context");return}ye.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this.onUpdateScreenSpacePlane()}}_groundOffsetVector=new Y.Vector3(0,1,0);_requireUpdateGroundPlane=!0;_didDragOnGroundPlaneLastFrame=!1;onUpdate(e){if(!this._context)return;let t=" ",i="d",n="s",r=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(i),s=this._context.input.getTouchesPressedCount()>=2||r;if(s){let c=this._context.input.getPointerPositionDelta(0);c&&(this._groundOffsetVector.set(0,1,0),this._selected?.rotateOnWorldAxis(this._groundOffsetVector,c.x*this._context.time.deltaTime))}let a=this._context.input.getPointerPositionRC(0);if(!!a&&(this._raycaster.setFromCamera(a,this._camera),this._selected)){ih&&console.log("UPDATE DRAG",this._selected),this._groundOffsetVector.set(0,1,0);let c=B(this._camera).clone().sub(B(this._selected)).normalize(),u=Math.abs(c.dot(this._groundOffsetVector)),l=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(i),d=!s&&u>.2&&!l&&this._context.input.getPointerPressedCount()<=1,h=this._didDragOnGroundPlaneLastFrame!==d;if(this._didDragOnGroundPlaneLastFrame=d,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!d||h)&&this.onUpdateGroundPlane(),this._requireUpdateGroundPlane=!1,this._hasGroundPlane)if(this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection)){let g=this._intersection.y;if(this._groundPlanePoint.copy(this._intersection).sub(this._groundOffset),this._groundPlanePoint.y=g,d){this._groundOffsetVector.set(0,1,0);let E=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(E,this._groundPlanePoint,!1),this.onDidUpdate();return}}else this._groundPlanePoint.set(0,99999,0);h&&this.onUpdateScreenSpacePlane(),this._requireUpdateGroundPlane=!0,this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&(this.onUpdateWorldPosition(this._intersection.sub(this._cameraPlaneOffset),this._groundPlanePoint,!0),this.onDidUpdate())}}onUpdateWorldPosition(e,t,i){if(!!this._selected){if(i){let n=B(this._selected);n.y=e.y,e=n}if(ie(this._selected,e),ie(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=t!==null,t){let n=B(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(n,n,n),ie(this._groundMarker,t)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;let e=this._context.input.getPointerPositionRC(0);!e||(this._raycaster.setFromCamera(e,this._camera),this._cameraPlane.setFromNormalAndCoplanarPoint(this._camera.getWorldDirection(this._cameraPlane.normal),this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld)),this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&this._selected.parent&&(this._inverseMatrix.copy(this._selected.parent.matrixWorld).invert(),this._cameraPlaneOffset.copy(this._intersection).sub(this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld))))}onUpdateGroundPlane(){if(!this._selected||!this._context)return;let e=B(this._selected),t=new Y.Ray(new Y.Vector3(0,.1,0).add(e),new Y.Vector3(0,-1,0)),i=new be;i.ignore=[this._selected];let n=this._context.physics.raycastFromRay(t,i);for(let r=0;r<n.length;r++){let s=n[r];if(!s.face||this.contains(this._selected,s.object))continue;let a=new Y.Vector3(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(a,s.point);break}this._hasGroundPlane=!0,this._groundPlane.setFromNormalAndCoplanarPoint(t.direction.multiplyScalar(-1),t.origin),this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection),this._groundDistance=this._intersection.distanceTo(e),this._groundOffset.copy(this._intersection).sub(e)}onDidUpdate(){oe.markDirty(this._selected);for(let e of this._rbs)e.wakeUp(),e.resetForcesAndTorques(),e.setAngularVelocity(0,0,0)}contains(e,t){if(e===t)return!0;if(e.children){for(let i of e.children)if(this.contains(i,t))return!0}return!1}},hc=nh;I(hc,"geometry",new Y.BufferGeometry().setFromPoints([new Y.Vector3(0,0,0),new Y.Vector3(0,-1,0)]));var Pi=class extends M{url=null;urlParameterName=null;localhost=null;awake(){this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?Pi.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){let r=P(this.urlParameterName);r&&typeof r=="string"&&(e=r)}if(!e)return null;let i=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return i?.groups?i?.groups.socket_prefix?e:"wss://"+i?.groups.url:null}static GetUrl(e,t){let i=e,n=Pi.IsLocalNetwork()&&t;return n&&(i=t),e?.startsWith("/")&&(i=(n?i:window.location.origin)+e),i}static IsLocalNetwork(e=window.location.hostname){return ct(e)}};var br=class extends M{filesBackendUrl;localhost;_dragOver;_drop;onEnable(){this.filesBackendUrl=this.filesBackendUrl?Pi.GetUrl(this.filesBackendUrl,this.localhost):void 0,this._dragOver=this.onDrag.bind(this),this._drop=this.onDrop.bind(this),this.context.domElement.addEventListener("dragover",this._dragOver),this.context.domElement.addEventListener("drop",this._drop)}onDisable(){this.context.domElement.removeEventListener("dragover",this._dragOver),this.context.domElement.removeEventListener("drop",this._drop)}onDrag(e){e.preventDefault()}async addFiles(e){for(let t of e){if(!t)continue;console.log("Register file "+t.name+" to",this.filesBackendUrl,t);let i=await Uu(t,this.context,this.filesBackendUrl);this.dispatchEvent(new CustomEvent("file-dropped",{detail:t})),i&&this.addObject(void 0,i)}}async onDrop(e){if(console.log(e),!e.dataTransfer)return;e.preventDefault();let t=e.dataTransfer.items;if(!!t)for(let i in t){let n=t[i];if(n.kind==="file"){let r=n.getAsFile();if(!r)continue;console.log("Register file "+r.name+" to",this.filesBackendUrl,r);let s=await Uu(r,this.context,this.filesBackendUrl);this.dispatchEvent(new CustomEvent("file-dropped",{detail:r})),s&&this.addObject(e,s)}else n.kind==="string"&&n.type=="text/plain"&&n.getAsString(async r=>{console.log("dropped url",r);try{let s=new URL(r);if(!s)return;let a=await Gf(s,this.context);a&&this.addObject(e,a)}catch{console.log("dropped string is not a valid URL!",r)}})}}async addObject(e,t){console.log("Dropped",t);let i=t.scene;if(e!==void 0){let n=new be;n.setMask(16777215),n.screenPointFromOffset(e.offsetX,e.offsetY);let r=this.context.physics.raycast(n);if(r&&r.length>0)for(let s of r){i.position.copy(s.point);break}}this.gameObject.add(i),this.dispatchEvent(new CustomEvent("object-added",{detail:t}))}};v([y()],br.prototype,"filesBackendUrl",2),v([y()],br.prototype,"localhost",2);import{Vector3 as Tx,Quaternion as Rx,Object3D as Jm}from"three";var Zi=class extends Vt{parent=null;object=null;limitCount=10;limitInterval=60;_currentCount=0;_startPosition=null;_startQuaternion=null;awake(){if(this.object){if(this.object===this.gameObject){console.error("Can not duplicate self");return}this.object.visible=!1,this._startPosition=this.object.position?.clone()??new Tx(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new Rx(0,0,0,1)}let e=R.getComponentInParent(this.gameObject,Ji);e?e.addDragEventListener("selectstart",(t,i)=>{if(this._currentCount>=this.limitCount){i.attached=null;return}let n=this.handleDuplication(i.selected);n&&(console.assert(n!==i.selected,"Duplicated object is original"),i.attached=n)}):console.warn("Could no find drag controls in parent",this.name),$.addEventListener("select-start",(t,i)=>{if(this._currentCount>=this.limitCount){i.grab=null;return}let n=this.handleDuplication(i.selected);n&&(i.grab=n)}),this.cloneLimitIntervalFn()}cloneLimitIntervalFn(){this.destroyed||(this._currentCount>0&&(this._currentCount-=1),setTimeout(()=>{this.cloneLimitIntervalFn()},this.limitInterval/this.limitCount*1e3))}handleDuplication(e){if(this._currentCount>=this.limitCount||!this.object)return null;if(e===this.gameObject||this.handleMultiObject(e)){if(this.object===this.gameObject)return null;this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);let t=new Ue;this.parent||(this.parent=this.gameObject.parent),this.parent&&(t.parent=this.parent.guid??this.parent.userData?.guid,t.keepWorldPosition=!0),t.position=this.worldPosition,t.rotation=this.worldQuaternion,t.context=this.context,this._currentCount+=1;let i=R.instantiateSynced(this.object,t);return console.assert(i!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),i}return null}handleMultiObject(e){return this.gameObject.type==="Group"||this.gameObject.type==="Object3D"?this.isInChildren(this.gameObject,e):!1}isInChildren(e,t){if(!e)return!1;if(e===t)return!0;if(e.children){for(let i of e.children)if(this.isInChildren(i,t))return!0}return!1}};v([y(Jm)],Zi.prototype,"parent",2),v([y(Jm)],Zi.prototype,"object",2),v([y()],Zi.prototype,"limitCount",2),v([y()],Zi.prototype,"limitInterval",2);var ba=class{eventID;callback};v([y()],ba.prototype,"eventID",2),v([y(de)],ba.prototype,"callback",2);var so=class extends M{triggers;invoke(e){if(!!this.triggers)for(let t of this.triggers)t.eventID===e&&t.callback.invoke()}onPointerClick(e){this.invoke(4)}onPointerEnter(e){this.invoke(0)}onPointerExit(e){this.invoke(1)}onPointerDown(e){this.invoke(2)}onPointerUp(e){this.invoke(3)}};v([y(ba)],so.prototype,"triggers",2);import*as en from"three";import*as va from"three";var Bn=class{get lightmap(){return this.lightmapTexture}set lightmap(e){e!==this.lightmapTexture&&(this.lightmapTexture=e,this.setupLightmap())}lightmapIndex=-1;lightmapScaleOffset=new va.Vector4(1,1,0,0);context;gameObject;lightmapTexture=null;lightmapScaleOffsetUniform={value:new va.Vector4(1,1,0,0)};lightmapUniform={value:null};beforeRenderCallback;constructor(e,t){this.gameObject=e,this.context=t}init(e,t,i,n=!1){if(console.assert(this.gameObject!==void 0&&this.gameObject!==null,"Missing gameobject",this),this.lightmapIndex=e,this.lightmapIndex<0)return;this.lightmapScaleOffset=t,this.lightmapTexture=i,n&&this.setLightmapDebugMaterial(),this.setupLightmap()}bindOnBeforeRender(){this.beforeRenderCallback=this.onBeforeRenderThreeComplete.bind(this),this.context.addBeforeRenderListener(this.gameObject,this.beforeRenderCallback)}onBeforeRenderThreeComplete(e,t,i,n,r,s){this.onBeforeRenderThree(r)}setupLightmap(){if(this.gameObject.type==="Object3D")return;if(this.gameObject.type==="Group"){console.warn("Lightmap on multimaterial object is not supported yet... please ask kindly for implementation.");return}console.assert(this.gameObject.type==="Mesh","Lightmap only works on meshes",this);let e=this.gameObject;e.geometry.getAttribute("uv2")||e.geometry.setAttribute("uv2",e.geometry.getAttribute("uv"));let t=this.gameObject.material.clone();if(this.gameObject.material=t,this.gameObject.material.onBeforeCompile=(i,n)=>{i.uniforms.lightmap=this.lightmapUniform,i.uniforms.lightmapScaleOffset=this.lightmapScaleOffsetUniform},this.lightmapIndex>=0){let i=this.lightmapTexture,n=this.gameObject.material;n&&i&&(n.uniforms||(n.uniforms={}),n.lightMap=i,n.uniforms.lightmap={value:i})}}onBeforeRenderThree(e){let t=e.uniforms;t&&t.lightmap&&(this.lightmapScaleOffsetUniform.value=this.lightmapScaleOffset,this.lightmapUniform.value=this.lightmapTexture,t.lightmap=this.lightmapUniform,t.lightmapScaleOffset=this.lightmapScaleOffsetUniform)}setLightmapDebugMaterial(){this.gameObject.material=new va.ShaderMaterial({vertexShader:`
|
|
216
216
|
attribute vec2 uv2;
|
|
217
217
|
varying vec2 vUv2;
|
|
218
218
|
void main()
|