@needle-tools/engine 3.28.3-beta → 3.28.4-beta
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +3 -0
- package/dist/needle-engine.js +1 -1
- package/dist/needle-engine.light.js +1 -1
- package/dist/needle-engine.light.min.js +1 -1
- package/dist/needle-engine.light.umd.cjs +1 -1
- package/dist/needle-engine.min.js +1 -1
- package/dist/needle-engine.umd.cjs +1 -1
- package/lib/engine-components/ui/EventSystem.js +1 -1
- package/lib/engine-components/ui/EventSystem.js.map +1 -1
- package/package.json +1 -1
- package/src/engine/codegen/register_types.ts +2 -2
- package/src/engine-components/ui/EventSystem.ts +1 -1
|
@@ -5093,7 +5093,7 @@ ${I.join(`
|
|
|
5093
5093
|
|
|
5094
5094
|
}
|
|
5095
5095
|
`}function Ov(i){return`(${i.r}, ${i.g}, ${i.b})`}function Pv(i){return`(${i.x}, ${i.y})`}const j2=[1023,33777,33778,33779,35842,35843,37496,37808,37809,37810,37811,37812,37813,37814,37815,37816,37817,37818,37819,37820,37821,36492];sA("debugusdz");const jN=class{constructor(A,e,t){r(this,"id");r(this,"trigger");r(this,"action");r(this,"exclusive",!1);this.id="Behavior_"+by(A)+"_"+jN.global_id++,this.trigger=e,this.action=t}makeExclusive(A){return this.exclusive=A,this}writeTo(A,e,t){if(!this.trigger||!this.action)return;t.beginBlock(`def Preliminary_Behavior "${this.id}"`),t.appendLine(`rel actions = <${this.action.id}>`),t.appendLine(`uniform bool exclusive = ${this.exclusive}`);let g="";if(Array.isArray(this.trigger)){g="[";for(let I=0;I<this.trigger.length;I++){const o=this.trigger[I];g+="<"+o.id+">",I+1<this.trigger.length&&(g+=", ")}g+="]"}else g=`<${this.trigger.id}>`;if(t.appendLine(`rel triggers = ${g} `),t.appendLine(),Array.isArray(this.trigger))for(const I of this.trigger)I.writeTo(e,t),t.appendLine();else this.trigger.writeTo(e,t);t.appendLine(),this.action.writeTo(e,t),t.closeBlock()}};let Xi=jN;r(Xi,"global_id",0);function sM(i,A){var t,g;let e="";if(Array.isArray(i)){let I="[ ";for(let o=0;o<i.length;o++){let s=i[o];if(typeof s=="string")I+=s;else if(typeof s=="object"){s.isObject3D&&(s=A.findById(s.uuid));const n=(t=s.getPath)==null?void 0:t.call(s);I+=n}o+1<i.length&&(I+=", ")}I+=" ]",e=I}else typeof i=="object"&&(i.isObject3D&&(i=A.findById(i.uuid)),e=(g=i.getPath)==null?void 0:g.call(i));return e}const ZN=class{constructor(A,e){r(this,"id");r(this,"targetId");r(this,"tokenId");r(this,"type");r(this,"distance");A&&(this.targetId=A),e?this.id=e:this.id="Trigger_"+ZN.global_id++}writeTo(A,e){e.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=sM(this.targetId,A)),e.appendLine("rel affectedObjects = "+this.targetId)),this.tokenId&&e.appendLine(`token info:id = "${this.tokenId}"`),this.type&&e.appendLine(`token type = "${this.type}"`),typeof this.distance=="number"&&e.appendLine(`double distance = ${this.distance}`),e.closeBlock()}};let pC=ZN;r(pC,"global_id",0);class mg{static sceneStartTrigger(){const A=new pC;return A.targetId=void 0,A.tokenId="SceneTransition",A.type="enter",A}static tapTrigger(A){const e=new pC(A);return e.tokenId="TapGesture",e}static isTapTrigger(A){return(A==null?void 0:A.tokenId)==="TapGesture"}static proximityToCameraTrigger(A,e){const t=new pC(A);return t.tokenId="ProximityToCamera",t.distance=e,t}}class pa{constructor(A,e){r(this,"id");r(this,"actions");r(this,"loops",0);r(this,"performCount",1);r(this,"type","serial");this.id=A,this.actions=e}static getId(){return this.global_id++}addAction(A){return this.actions.push(A),this}makeParallel(){return this.type="parallel",this}makeSequence(){return this.type="serial",this}makeLooping(){return this.loops=1,this}makeRepeat(A){return this.performCount=A,this}writeTo(A,e){e.beginBlock(`def Preliminary_Action "${this.id}"`),e.beginArray("rel actions");for(const t of this.actions){if(!t)continue;const g=t===this.actions[this.actions.length-1];e.appendLine("<"+t.id+">"+(g?"":", "))}e.closeArray(),e.appendLine(),e.appendLine('token info:id = "Group"'),e.appendLine(`bool loops = ${this.loops} `),e.appendLine(`int performCount = ${this.performCount} `),e.appendLine(`token type = "${this.type}"`),e.appendLine();for(const t of this.actions)t&&(t.writeTo(A,e),e.appendLine());e.closeBlock()}}r(pa,"global_id",0);var aF=(i=>(i[i.pop=0]="pop",i[i.blink=1]="blink",i[i.bounce=2]="bounce",i[i.flip=3]="flip",i[i.float=4]="float",i[i.jiggle=5]="jiggle",i[i.pulse=6]="pulse",i[i.spin=7]="spin",i))(aF||{}),nM=(i=>(i.Relative="relative",i.Absolute="absolute",i))(nM||{}),Z2=(i=>(i.Allow="allow",i.Ignore="ignore",i.Stop="stop",i))(Z2||{});const hw=class{constructor(A,e){r(this,"id");r(this,"tokenId");r(this,"affectedObjects");r(this,"easeType");r(this,"motionType");r(this,"duration");r(this,"moveDistance");r(this,"style");r(this,"type");r(this,"front");r(this,"up");r(this,"start");r(this,"animationSpeed");r(this,"reversed");r(this,"pingPong");r(this,"xFormTarget");r(this,"audio");r(this,"gain");r(this,"auralMode");r(this,"multiplePerformOperation");A&&(this.affectedObjects=A),e?this.id=e:this.id="Action",this.id+="_"+hw.global_id++}clone(){const A=new hw,e=A.id;return Object.assign(A,this),A.id=e,A}writeTo(A,e){e.beginBlock(`def Preliminary_Action "${this.id}"`),this.affectedObjects&&(typeof this.affectedObjects!="string"&&(this.affectedObjects=sM(this.affectedObjects,A)),e.appendLine("rel affectedObjects = "+this.affectedObjects)),typeof this.duration=="number"&&e.appendLine(`double duration = ${this.duration} `),this.easeType&&e.appendLine(`token easeType = "${this.easeType}"`),this.tokenId&&e.appendLine(`token info:id = "${this.tokenId}"`),this.motionType&&e.appendLine(`token motionType = "${this.motionType}"`),typeof this.moveDistance=="number"&&e.appendLine(`double moveDistance = ${this.moveDistance} `),this.style&&e.appendLine(`token style = "${this.style}"`),this.type&&e.appendLine(`token type = "${this.type}"`),this.front&&e.appendLine(`vector3d front = (${this.front.x}, ${this.front.y}, ${this.front.z})`),this.up&&e.appendLine(`vector3d upVector = (${this.up.x}, ${this.up.y}, ${this.up.z})`),typeof this.start=="number"&&e.appendLine(`double start = ${this.start} `),typeof this.animationSpeed=="number"&&e.appendLine(`double animationSpeed = ${this.animationSpeed} `),typeof this.reversed=="boolean"&&e.appendLine(`bool reversed = ${this.reversed}`),typeof this.pingPong=="boolean"&&e.appendLine(`bool reverses = ${this.pingPong}`),this.xFormTarget&&(typeof this.xFormTarget!="string"&&(this.xFormTarget=sM(this.xFormTarget,A)),e.appendLine(`rel xformTarget = ${this.xFormTarget}`)),typeof this.audio=="string"&&e.appendLine(`asset audio = @${this.audio}@`),typeof this.gain=="number"&&e.appendLine(`double gain = ${this.gain}`),typeof this.auralMode=="string"&&e.appendLine(`token auralMode = "${this.auralMode}"`),typeof this.multiplePerformOperation=="string"&&e.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),e.closeBlock()}};let to=hw;r(to,"global_id",0);let ZQ=class bQ{constructor(A,e,t){r(this,"x",0);r(this,"y",0);r(this,"z",0);this.x=A,this.y=e,this.z=t}static get up(){return new bQ(0,1,0)}static get right(){return new bQ(1,0,0)}static get forward(){return new bQ(0,0,1)}static get back(){return new bQ(0,0,-1)}static get zero(){return new bQ(0,0,0)}};var CM=(i=>(i.Play="play",i.Pause="pause",i.Stop="stop",i))(CM||{}),aM=(i=>(i.Spatial="spatial",i.NonSpatial="nonSpatial",i.Ambient="ambient",i))(aM||{});class ot{static sequence(...A){return new pa("group_"+pa.getId(),A).makeSequence()}static parallel(...A){return new pa("group_"+pa.getId(),A).makeParallel()}static fadeAction(A,e,t){const g=new to(A);return g.tokenId="Visibility",g.type=t?"show":"hide",g.duration=e,g.style="basic",g.motionType="none",g.moveDistance=0,g.easeType="none",g}static startAnimationAction(A,e,t=0,g=1,I=!1,o=!1){const s=new to(A);if(s.tokenId="StartAnimation",s.start=e,s.duration=t,s.animationSpeed=g,s.reversed=I,s.pingPong=o,s.multiplePerformOperation="allow",I&&(s.start-=t),o){s.pingPong=!1;const n=s.clone();return n.reversed=!I,n.start=s.start,n.reversed&&(n.start-=t),ot.sequence(s,n)}return s}static waitAction(A){const e=new to;return e.tokenId="Wait",e.duration=A,e}static lookAtCameraAction(A,e=9999999999999,t,g){const I=new to(A);return I.tokenId="LookAtCamera",I.duration=e,I.front=t??ZQ.forward,I.up=g??ZQ.up,I}static emphasize(A,e,t=2,g=1,I="basic"){const o=new to(A);return o.tokenId="Emphasize",o.duration=e,o.style=I??"basic",o.motionType=aF[t],o.moveDistance=g,o}static transformAction(A,e,t,g,I="inout"){const o=new to(A);return o.tokenId="Transform",o.duration=t,o.type=g,o.easeType=I,Array.isArray(e)&&console.error("Transform target must not be an array",e),o.xFormTarget=e,o}static playAudioAction(A,e,t="play",g=1,I="spatial"){const o=new to(A);return o.tokenId="Audio",o.type=t,o.audio=e,o.gain=g,o.auralMode=I,o.multiplePerformOperation="allow",o}}class aiA{constructor(A){r(this,"object");r(this,"model");this.object=A}get id(){return this.object.uuid}apply(A){if(!this.model&&(this.model=A.findById(this.object.uuid),!this.model)){console.error("could not find model with id "+this.object.uuid);return}this.onApply(A)}}class rF extends aiA{constructor(e,t,g,I){super(e);r(this,"matrix");r(this,"material");r(this,"geometry");r(this,"_enableAction");r(this,"_disableAction");this.matrix=t,this.material=g,this.geometry=I}onApply(e){var I,o;const t=this.model;if(!t)return;(I=t.parent)!=null&&I.isDynamic||qI.createEmptyParent(t);const g=t.clone();this.matrix&&(g.matrix=this.matrix),this.material&&(g.material=this.material),this.geometry&&(g.geometry=this.geometry),(o=t.parent)==null||o.add(g)}enable(){return this._enableAction?this._enableAction:(this._enableAction=ot.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=ot.fadeAction(this.object,0,!1),this._disableAction)}}class BF{constructor(A){r(this,"actions");r(this,"sortedActions");this.actions=[...A]}organize(){this.sortedActions={};for(const A of this.actions){const e=A.id;this.sortedActions[e]||(this.sortedActions[e]=[]),this.sortedActions[e].push(A)}}getActions(A){return this.sortedActions||this.organize(),this.sortedActions[A.uuid]}}var riA=Object.defineProperty,BiA=Object.getOwnPropertyDescriptor,X2=(i,A,e,t)=>{for(var g=t>1?void 0:t?BiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&riA(A,e,g),g};class Pd extends NA{constructor(){super(...arguments);r(this,"from");r(this,"to");r(this,"width",0);r(this,"centered",!0);r(this,"_centerPos")}awake(){this._centerPos=new w}update(){if(!this.from||!this.to)return;const e=ce(this.from).clone(),t=ce(this.to).clone(),g=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),Mi(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(ce(this.to).clone()),this.gameObject.scale.set(this.width,this.width,g)}}X2([D(IA)],Pd.prototype,"from",2);X2([D(IA)],Pd.prototype,"to",2);var QiA=Object.defineProperty,EiA=Object.getOwnPropertyDescriptor,Wd=(i,A,e,t)=>{for(var g=t>1?void 0:t?EiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&QiA(A,e,g),g};const wQ=sA("debuganimation");class Eo extends NA{constructor(){super(...arguments);r(this,"playAutomatically",!0);r(this,"randomStartTime",!0);r(this,"minMaxSpeed");r(this,"minMaxOffsetNormalized");r(this,"loop",!0);r(this,"clampWhenFinished",!1);r(this,"_tempAnimationClipBeforeGameObjectExisted",null);r(this,"_tempAnimationsArray");r(this,"mixer");r(this,"_actions",[]);r(this,"_currentActions",[]);r(this,"_handles",[]);r(this,"_didInit",!1)}get clip(){var e;return(e=this.animations)!=null&&e.length?this.animations[0]:null}set clip(e){if(!this.__didAwake){wQ&&console.warn("Assign clip during serialization",e),this._tempAnimationClipBeforeGameObjectExisted=e;return}e&&(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){e==null||!Array.isArray(e)||(this.gameObject?this.gameObject.animations=e:this._tempAnimationsArray=e)}get animations(){return this.gameObject.animations||this._tempAnimationsArray||[]}get currentAction(){return this._currentActions[0]}get currentActions(){return this._currentActions}get actions(){return this._actions}set actions(e){this._actions=e}awake(){wQ&&console.log("Animation Awake",this.name,this),this._tempAnimationsArray&&(this.animations=this._tempAnimationsArray,this._tempAnimationsArray=void 0),this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.playAutomatically&&this.init()}onEnable(){var e;if(this.playAutomatically&&((e=this.animations)==null?void 0:e.length)>0&&this.currentActions.length<=0){const t=Math.floor(Math.random()*this.actions.length);this.play(t)}}start(){this.randomStartTime&&this.currentAction&&(this.currentAction.time=Math.random()*this.currentAction.getClip().duration)}update(){this.mixer&&this.mixer.update(this.context.time.deltaTime)}getAction(e){var t;return(t=this.actions)==null?void 0:t.find(g=>g.getClip().name===e)}get isPlaying(){for(let e=0;e<this.actions.length;e++)if(this.actions[e].isRunning())return!0;return!1}play(e=0,t){if(wQ&&console.log("PLAY",e),this.init(),!this.mixer){wQ&&console.warn("Missing mixer",this);return}e===void 0&&(e=0);let g=e;if(typeof e=="number"){if(e>=this.animations.length){wQ&&console.log("No animation at index",e);return}g=this.animations[e]}else typeof e=="string"&&(g=this.animations.find(o=>o.name===e));if(!g){console.error("Could not find clip",e);return}t||(t={}),t.minMaxOffsetNormalized||(t.minMaxOffsetNormalized=this.minMaxOffsetNormalized),t.minMaxSpeed||(t.minMaxSpeed=this.minMaxSpeed),t.loop===void 0&&(t.loop=this.loop),t.clampWhenFinished===void 0&&(t.clampWhenFinished=this.clampWhenFinished);for(const o of this.actions)if(o.getClip()===g)return this.internalOnPlay(o,t);if(!(g instanceof bI)){console.warn("Clip is no AnimationClip",g,"on object: "+this.name);return}const I=this.mixer.clipAction(g);return this.actions.push(I),this.internalOnPlay(I,t)}internalOnPlay(e,t){var g=this.currentAction;if(g===e&&g.isRunning()&&g.time<g.getClip().duration){const n=this.tryFindHandle(e);if(n)return n.getPromise()}const I=(t==null?void 0:t.exclusive)??!0;t!=null&&t.fadeDuration?(I&&(g==null||g.fadeOut(t.fadeDuration)),e.fadeIn(t.fadeDuration)):I&&(g==null||g.stop()),e.reset(),e.enabled=!0,e.time=0,e.timeScale=1;const o=e.getClip();t!=null&&t.minMaxOffsetNormalized&&(e.time=ne.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*o.duration),t!=null&&t.minMaxSpeed&&(e.timeScale=ne.lerp(t.minMaxSpeed.x,t.minMaxSpeed.y,Math.random())),t!=null&&t.clampWhenFinished&&(e.clampWhenFinished=!0),(t==null?void 0:t.startTime)!==void 0&&(e.time=t.startTime),(t==null?void 0:t.loop)!==void 0?e.loop=t.loop?XM:dl:e.loop=dl,e.play(),wQ&&console.log("PLAY",e.getClip().name,e);const s=new ciA(e,this.mixer,t,n=>{this._handles.splice(this._handles.indexOf(s),1)});return this._handles.push(s),s.getPromise()}tryFindHandle(e){for(const t of this._handles)if(t.action===e)return t}init(){this._didInit||(this._didInit=!0,this.gameObject&&(this.actions=[],this.mixer=new iy(this.gameObject)))}}Wd([D()],Eo.prototype,"playAutomatically",2);Wd([D()],Eo.prototype,"randomStartTime",2);Wd([D()],Eo.prototype,"loop",2);Wd([D()],Eo.prototype,"clampWhenFinished",2);Wd([D(bI)],Eo.prototype,"clips",1);class ciA{constructor(A,e,t,g){r(this,"mixer");r(this,"action");r(this,"promise",null);r(this,"resolve",null);r(this,"reject",null);r(this,"_options");r(this,"_resolveCallback",null);r(this,"_rejectCallback",null);r(this,"_loopCallback");r(this,"_finishedCallback");r(this,"_resolvedOrRejectedCallback");this.action=A,this.mixer=e,this._resolvedOrRejectedCallback=g,this._options=t}getPromise(){return this.promise?this.promise:(this.promise=new Promise((A,e)=>{this._resolveCallback=A,this._rejectCallback=e,this.resolve=this.onResolve.bind(this),this.reject=this.onReject.bind(this)}),this._loopCallback=this.onLoop.bind(this),this._finishedCallback=this.onFinished.bind(this),this.mixer.addEventListener("loop",this._loopCallback),this.mixer.addEventListener("finished",this._finishedCallback),this.promise)}_update(){this._options&&this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){var A,e;this.dispose(),(A=this._resolvedOrRejectedCallback)==null||A.call(this,this),(e=this._resolveCallback)==null||e.call(this,this.action)}onReject(A){var e,t;this.dispose(),(e=this._resolvedOrRejectedCallback)==null||e.call(this,this),(t=this._rejectCallback)==null||t.call(this,A)}onLoop(A){}onFinished(A){A.action===this.action&&this.onResolve()}dispose(){this._loopCallback&&this.mixer.removeEventListener("loop",this._loopCallback),this._finishedCallback&&this.mixer.removeEventListener("finished",this._finishedCallback),this._loopCallback=void 0,this._finishedCallback=void 0}}var hiA=Object.defineProperty,liA=Object.getOwnPropertyDescriptor,Za=(i,A,e,t)=>{for(var g=t>1?void 0:t?liA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&hiA(A,e,g),g};class Xa{constructor(){r(this,"time");r(this,"value");r(this,"inTangent");r(this,"inWeight");r(this,"outTangent");r(this,"outWeight");r(this,"weightedMode")}}Za([D()],Xa.prototype,"time",2);Za([D()],Xa.prototype,"value",2);Za([D()],Xa.prototype,"inTangent",2);Za([D()],Xa.prototype,"inWeight",2);Za([D()],Xa.prototype,"outTangent",2);Za([D()],Xa.prototype,"outWeight",2);Za([D()],Xa.prototype,"weightedMode",2);const $2=class{constructor(){r(this,"keys")}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(i){if(!this.keys||this.keys.length==0)return 0;if(this.keys[0].time>=i)return this.keys[0].value;for(let A=0;A<this.keys.length;A++){const e=this.keys[A];if(e.time<=i)if(A+1<this.keys.length){const g=this.keys[A+1];if(g.time<i)continue;return!isFinite(e.outTangent)||!isFinite(g.inTangent)?e.value:$2.interpolateValue(i,e,g)}else return e.value}return this.keys[this.keys.length-1].value}static interpolateValue(i,A,e){const t=A.time,g=A.value,I=A.outTangent,o=e.time,s=e.value,n=e.inTangent,C=o-t,a=C*C,B=a*C,Q=((I+n)*C-2*(s-g))/B,E=(3*(s-g)-(n+2*I)*C)/a,c=I,d=g,l=i-t,h=l*l,p=h*l;return Q*p+E*h+c*l+d}};let SB=$2;Za([D(Xa)],SB.prototype,"keys",2);class diA{constructor(){r(this,"_context")}get context(){return this._context??be.Current}get isStateMachineBehaviour(){return!0}}class Wf{constructor(A,e,t,g){r(this,"_name");r(this,"_nameHash");r(this,"_normalizedTime");r(this,"_length");r(this,"_speed");this._name=A.name,this._nameHash=A.hash,this._normalizedTime=e,this._length=t,this._speed=g}get name(){return this._name}get nameHash(){return this._nameHash}get normalizedTime(){return this._normalizedTime}get length(){return this._length}get speed(){return this._speed}}function AO(i,A){return{name:"",isLooping:!1,guid:(A==null?void 0:A.generateUUID())??Gg.generateUUID(),index:-1,clip:new bI(i,1,[])}}var Ea=(i=>(i[i.If=1]="If",i[i.IfNot=2]="IfNot",i[i.Greater=3]="Greater",i[i.Less=4]="Less",i[i.Equals=6]="Equals",i[i.NotEqual=7]="NotEqual",i))(Ea||{}),QF=(i=>(i[i.Float=1]="Float",i[i.Int=3]="Int",i[i.Bool=4]="Bool",i[i.Trigger=9]="Trigger",i))(QF||{});const Go=sA("debuganimatorcontroller"),Hp=sA("debugrootmotion");class zo{constructor(A){r(this,"normalizedStartOffset",0);r(this,"_speed",1);r(this,"animator");r(this,"model");r(this,"_mixer");r(this,"_activeState");r(this,"_activeStates",[]);r(this,"rootMotionHandler");this.model=A,Go&&console.log(this)}static createFromClips(A,e={looping:!1,autoTransition:!0,transitionDuration:0}){const t=[];for(let o=0;o<A.length;o++){const s=A[o],n=[];if(e.autoTransition!==!1){const a=e.transitionDuration??0,B=a/s.duration;let Q=o;(e.autoTransition===void 0||e.autoTransition===!0)&&(Q=(o+1)%A.length),n.push({exitTime:1-B,offset:0,duration:a,hasExitTime:!0,destinationState:Q,conditions:[]})}const C={name:s.name,hash:o,motion:{name:s.name,clip:s,isLooping:(e==null?void 0:e.looping)??!1},transitions:n,behaviours:[]};t.push(C)}const g={name:"AnimatorController",guid:new Zg(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:t}}]};return new zo(g)}play(A,e=-1,t=Number.NEGATIVE_INFINITY,g=0){if(e<0)e=0;else if(e>=this.model.layers.length){console.warn("invalid layer");return}const o=this.model.layers[e].stateMachine;for(const s of o.states)if(s.name===A||s.hash===A){Go&&console.log("transition to ",s),this.transitionTo(s,g,t);return}console.warn("Could not find "+A+" to play")}reset(){this.setStartTransition()}setBool(A,e){var g,I;const t=typeof A=="string"?"name":"hash";return(I=(g=this.model)==null?void 0:g.parameters)==null?void 0:I.filter(o=>o[t]===A).forEach(o=>o.value=e)}getBool(A){var t,g,I;const e=typeof A=="string"?"name":"hash";return((I=(g=(t=this.model)==null?void 0:t.parameters)==null?void 0:g.find(o=>o[e]===A))==null?void 0:I.value)??!1}setFloat(A,e){var I,o;const t=typeof A=="string"?"name":"hash",g=(o=(I=this.model)==null?void 0:I.parameters)==null?void 0:o.filter(s=>s[t]===A);return g.forEach(s=>s.value=e),(g==null?void 0:g.length)>0}getFloat(A){var t,g,I;const e=typeof A=="string"?"name":"hash";return((I=(g=(t=this.model)==null?void 0:t.parameters)==null?void 0:g.find(o=>o[e]===A))==null?void 0:I.value)??0}setInteger(A,e){var g,I;const t=typeof A=="string"?"name":"hash";return(I=(g=this.model)==null?void 0:g.parameters)==null?void 0:I.filter(o=>o[t]===A).forEach(o=>o.value=e)}getInteger(A){var t,g,I;const e=typeof A=="string"?"name":"hash";return((I=(g=(t=this.model)==null?void 0:t.parameters)==null?void 0:g.find(o=>o[e]===A))==null?void 0:I.value)??0}setTrigger(A){var t,g;Go&&console.log("SET TRIGGER",A);const e=typeof A=="string"?"name":"hash";return(g=(t=this.model)==null?void 0:t.parameters)==null?void 0:g.filter(I=>I[e]===A).forEach(I=>I.value=!0)}resetTrigger(A){var t,g;const e=typeof A=="string"?"name":"hash";return(g=(t=this.model)==null?void 0:t.parameters)==null?void 0:g.filter(I=>I[e]===A).forEach(I=>I.value=!1)}getTrigger(A){var t,g,I;const e=typeof A=="string"?"name":"hash";return((I=(g=(t=this.model)==null?void 0:t.parameters)==null?void 0:g.find(o=>o[e]===A))==null?void 0:I.value)??!1}isInTransition(){return this._activeStates.length>1}setSpeed(A){this._speed=A}FindState(A){return this.findState(A)}findState(A){if(!A)return null;if(Array.isArray(this.model.layers)){for(const e of this.model.layers)for(const t of e.stateMachine.states)if(t.name===A||t.hash==A)return t}return null}get context(){var A;return(A=this.animator)==null?void 0:A.context}get mixer(){return this._mixer}bind(A){A?this.animator!==A&&(this.animator=A,this._mixer=new iy(this.animator.gameObject),this.createActions(this.animator)):console.error("AnimatorController.bind: animator is null")}clone(){if(typeof this.model=="string")return console.warn("AnimatorController has not been resolved, can not create model from string",this.model),null;const A=Sd(this.model,(t,g,I)=>I==null?!0:!(I.type==="Object3D"||I.isObject3D===!0||wT(I)||I.tracks!==void 0));return console.assert(A!==this.model),new zo(A)}update(A){var t,g;if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(A);const e=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((t=this.rootMotionHandler)==null||t.onBeforeUpdate(A)),this._mixer.update(e),this.animator.applyRootMotion&&((g=this.rootMotionHandler)==null||g.onAfterUpdate(A))}get activeState(){return this._activeState}updateActiveStates(A){for(let e=0;e<this._activeStates.length;e++){const t=this._activeStates[e],g=t.motion;if(!g.action)this._activeStates.splice(e,1),e--;else{const I=g.action;I.weight=A,I.getEffectiveWeight()<=0&&!I.isRunning()&&(Go&&console.debug("REMOVE",t.name,I.getEffectiveWeight(),I.isRunning(),I.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(const A of this.model.layers){const e=A.stateMachine;e.defaultState===void 0&&(Go&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",A),e.defaultState=0);const t=e.states[e.defaultState];this.transitionTo(t,0,this.normalizedStartOffset)}}evaluateTransitions(){var I;let A=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;A=!0}const e=this._activeState,t=e.motion.action;for(const o of e.transitions){if(!o.hasExitTime&&o.conditions.length<=0)continue;let s=!0;for(const n of o.conditions)if(!this.evaluateCondition(n)){s=!1;break}if(s)if(t){const n=e.motion.clip.duration,C=n<=0?1:Math.abs(t.time/n);let a=!1;if(o.hasExitTime?t.timeScale>0?a=C>=o.exitTime:t.timeScale<0&&(a=1-C>=o.exitTime):a=!0,a){for(const B of o.conditions){const Q=this.model.parameters.find(E=>E.name===B.parameter);(Q==null?void 0:Q.type)===QF.Trigger&&Q.value&&(Q.value=!1)}t.clampWhenFinished=!0,Go&&console.log("transition to "+o.destinationState,o,C,o.exitTime,o.hasExitTime),this.transitionTo(o.destinationState,o.duration,o.offset);return}}else{this.transitionTo(o.destinationState,o.duration,o.offset);return}}if(t){let o=e.speed??1;e.speedParameter&&(o*=this.getFloat(e.speedParameter)),o!==void 0&&(t.timeScale=o*this._speed)}let g=!1;if(e.motion.isLooping&&t&&(t.time>=t.getClip().duration?(g=!0,t.reset(),t.time=0,t.play()):t.time<=0&&t.timeScale<0&&(g=!0,t.reset(),t.time=t.getClip().duration,t.play())),!g&&e&&!A&&t&&this.animator&&e.behaviours){const o=t==null?void 0:t.getClip().duration,s=t.time/o,n=new Wf(this._activeState,s,o,this._speed);for(const C of e.behaviours)C.instance&&((I=C.instance.onStateUpdate)==null||I.call(C.instance,this.animator,n,0))}}getState(A,e){return typeof A=="number"&&(A==-1&&(A=this.model.layers[e].stateMachine.defaultState,A===void 0&&(Go&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+e),A=0)),A=this.model.layers[e].stateMachine.states[A]),A}transitionTo(A,e,t){var C,a,B,Q,E,c,d,l;if(!this.animator)return;const g=0;if(A=this.getState(A,g),!(A!=null&&A.motion)||!A.motion.clip||!(A.motion.clip instanceof bI))return;const I=this._activeState===A;if(I){const h=A.motion;if(!h.action_loopback&&h.clip){const p=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(h.clip,this.animator.gameObject),p&&p.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),h.action_loopback=this.createAction(h.clip)}}if((C=this._activeState)!=null&&C.behaviours&&this._activeState.motion.action){const h=(a=this._activeState)==null?void 0:a.motion.clip.duration,p=this._activeState.motion.action.time/h,u=new Wf(this._activeState,p,h,this._speed);for(const f of this._activeState.behaviours)(Q=(B=f.instance)==null?void 0:B.onStateExit)==null||Q.call(f.instance,this.animator,u,g)}const o=(E=this._activeState)==null?void 0:E.motion.action;o&&o.fadeOut(e),I&&(A.motion.action=A.motion.action_loopback,A.motion.action_loopback=o);const s=this._activeState;this._activeState=A;const n=(c=A.motion)==null?void 0:c.action;if(n){if(t=Math.max(0,Math.min(1,t)),A.cycleOffsetParameter){let p=this.getFloat(A.cycleOffsetParameter);typeof p=="number"?(p<0&&(p+=1),t+=p,t%=1):Go&&console.warn("AnimatorController cycle offset parameter is not a number",A.cycleOffsetParameter)}else typeof A.cycleOffset=="number"&&(t+=A.cycleOffset,t%=1);n.isRunning()&&n.stop(),n.reset(),n.enabled=!0;const h=A.motion.clip.duration;if(n.time=I?0:t*h,n.timeScale<0&&(n.time=h-n.time),n.clampWhenFinished=!0,n.setLoop(dl,0),e>0?n.fadeIn(e):n.weight=1,n.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(n),this._activeStates.includes(A)||this._activeStates.push(A),this._activeState.behaviours){const p=new Wf(A,t,h,this._speed);for(const u of this._activeState.behaviours)(l=(d=u.instance)==null?void 0:d.onStateEnter)==null||l.call(u.instance,this.animator,p,g)}}else Go&&(A.__warned_no_motion||(A.__warned_no_motion=!0,console.warn("No action",A.motion,this)));Go&&console.log("TRANSITION FROM "+(s==null?void 0:s.name)+" TO "+A.name,e,o,n,n==null?void 0:n.getEffectiveTimeScale(),n==null?void 0:n.getEffectiveWeight(),n==null?void 0:n.isRunning(),n==null?void 0:n.isScheduled(),n==null?void 0:n.paused)}createAction(A){var t,g;if(this._mixer.existingAction(A)&&this._mixer.uncacheAction(A,(t=this.animator)==null?void 0:t.gameObject),(g=this.animator)!=null&&g.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new uiA(this));const I=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,I,A)}else return this._mixer.clipAction(A)}evaluateCondition(A){const e=this.model.parameters.find(t=>t.name===A.parameter);if(!e)return!1;switch(A.mode){case Ea.If:return e.value===!0;case Ea.IfNot:return e.value===!1;case Ea.Greater:return e.value>A.threshold;case Ea.Less:return e.value<A.threshold;case Ea.Equals:return e.value===A.threshold;case Ea.NotEqual:return e.value!==A.threshold}return!1}createActions(A){var e,t;for(const g of this.model.layers){const I=g.stateMachine;for(let o=0;o<I.states.length;o++){const s=I.states[o];s.transitions||(s.transitions=[]);for(const n of s.transitions)n.conditions||(n.conditions=[]);if(s.motion||(s.motion=AO(s.name)),this.animator&&s.motion.clips){const n=(e=s.motion.clips)==null?void 0:e.find(C=>{var a,B;return C.node.name===((B=(a=this.animator)==null?void 0:a.gameObject)==null?void 0:B.name)});s.motion.clip=n==null?void 0:n.clip}if(!s.motion.clip){const n=new bI(void 0,void 0,[]);s.motion.clip=n}if((t=s.motion)!=null&&t.clip){const n=s.motion.clip;if(n instanceof bI){const C=this.createAction(n);s.motion.action=C}else(Go||_e())&&console.warn("No valid animationclip assigned",s)}if(s.behaviours&&Array.isArray(s.behaviours))for(const n of s.behaviours){if(!(n!=null&&n.typeName))continue;const C=j.get(n.typeName),a=new C;a.isStateMachineBehaviour&&(a._context=this.context??void 0,UE(a,n.properties),n.instance=a),Go&&console.log("Created animator controller behaviour",s.name,n.typeName,n.properties,a)}}}}*enumerateActions(){if(this.model.layers)for(const A of this.model.layers){const e=A.stateMachine;for(let t=0;t<e.states.length;t++){const g=e.states[t];g!=null&&g.motion&&(g.motion.action&&(yield g.motion.action),g.motion.action_loopback&&(yield g.motion.action_loopback))}}}}class Wv{constructor(A,e){r(this,"track");r(this,"createdInterpolant");r(this,"originalEvaluate");r(this,"customEvaluate");this.track=A;const t=A,g=t.createInterpolant.bind(A);t.createInterpolant=()=>(t.createInterpolant=g,this.createdInterpolant=g(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=I=>{if(!this.originalEvaluate)return;const o=this.originalEvaluate(I);return e(I,o)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}}const ji=class{constructor(A,e,t,g,I){r(this,"_action");r(this,"root");r(this,"clip");r(this,"positionWrapper",null);r(this,"rotationWrapper",null);r(this,"context");r(this,"positionChange",new w);r(this,"rotationChange",new MA);r(this,"_prevTime",0);if(this.context=A,this.root=e,this.clip=t,ji.firstKeyframeRotation[this.cacheId]||(ji.firstKeyframeRotation[this.cacheId]=new MA),I){const o=I.values;ji.firstKeyframeRotation[this.cacheId].set(o[0],o[1],o[2],o[3])}ji.spaceRotation[this.cacheId]||(ji.spaceRotation[this.cacheId]=new MA),ji.effectiveSpaceRotation[this.cacheId]||(ji.effectiveSpaceRotation[this.cacheId]=new MA),ji.clipOffsetRotation[this.cacheId]=new MA,I&&ji.clipOffsetRotation[this.cacheId].set(I.values[0],I.values[1],I.values[2],I.values[3]).invert(),this.handlePosition(t,g),this.handleRotation(t,I)}set action(A){this._action=A}get action(){return this._action}get cacheId(){return this.root.uuid}onStart(A){if(A.getClip()!==this.clip)return;ji.lastObjRotation[this.cacheId]||(ji.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const e=ji.lastObjRotation[this.cacheId];if(ji.spaceRotation[this.cacheId].copy(e),Hp){const t=new $i().setFromQuaternion(e);console.log("START",this.clip.name,ne.toDegrees(t.y),this.root.position.z)}}getClipRotationOffset(){return ji.clipOffsetRotation[this.cacheId]}handlePosition(A,e){if(e){const t=this.root;Hp&&t.add(new jE),ji.lastObjPosition[this.cacheId]||(ji.lastObjPosition[this.cacheId]=this.root.position.clone());const g=new w,I=new w;this.positionWrapper=new Wv(e,(o,s)=>{const n=this.action.getEffectiveWeight();return Hp&&t.position.length()>8&&t.position.set(0,t.position.y,0),o>this._prevTime&&(g.set(s[0],s[1],s[2]),g.sub(I),g.multiplyScalar(n),g.applyQuaternion(this.getClipRotationOffset()),g.applyQuaternion(t.quaternion),this.positionChange.copy(g)),I.fromArray(s),this._prevTime=o,s[0]=0,s[1]=0,s[2]=0,s})}}handleRotation(A,e){if(e){if(Hp){const o=e.values,s=new $i().setFromQuaternion(new MA(o[0],o[1],o[2],o[3]));console.log(A.name,e.name,"FIRST ROTATION IN TRACK",ne.toDegrees(s.y));const n=e.values.length-4,C=new MA().set(o[n],o[n+1],o[n+2],o[n+3]),a=new $i().setFromQuaternion(C);console.log(A.name,e.name,"LAST ROTATION IN TRACK",ne.toDegrees(a.y))}let t=0;const g=new MA,I=new MA;this.rotationWrapper=new Wv(e,(o,s)=>(o>t&&(I.set(s[0],s[1],s[2],s[3]),g.invert(),I.multiply(g),this.rotationChange.copy(I)),g.fromArray(s),t=o,s[0]=0,s[1]=0,s[2]=0,s[3]=1,s))}}onBeforeUpdate(A){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(A){return!this.action||(A*=this.action.getEffectiveWeight(),A<=0)?!1:(this.positionChange.multiplyScalar(A),this.rotationChange.slerp(ji.identityQuaternion,1-A),!0)}};let Hs=ji;r(Hs,"lastObjPosition",{}),r(Hs,"lastObjRotation",{}),r(Hs,"firstKeyframeRotation",{}),r(Hs,"spaceRotation",{}),r(Hs,"effectiveSpaceRotation",{}),r(Hs,"clipOffsetRotation",{}),r(Hs,"identityQuaternion",new MA);class uiA{constructor(A){r(this,"controller");r(this,"handler",[]);r(this,"root");r(this,"basePosition",new w);r(this,"baseQuaternion",new MA);r(this,"baseRotation",new $i);r(this,"summedPosition",new w);r(this,"summedRotation",new MA);this.controller=A}createClip(A,e,t){this.root=e,e&&"name"in e&&e.name;const g=this.findRootTrack(t,".position"),I=this.findRootTrack(t,".quaternion"),o=new Hs(this.controller.context,e,t,g,I);this.handler.push(o);const s=A.clipAction(t);return o.action=s,s}onStart(A){for(const e of this.handler)e.onStart(A)}onBeforeUpdate(A){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(const e of this.handler)e.onBeforeUpdate(A)}onAfterUpdate(A){if(!(A<=0)){this.root.position.copy(this.basePosition),this.root.quaternion.copy(this.baseQuaternion),this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(const e of this.handler)e.onAfterUpdate(A)&&(this.summedPosition.add(e.positionChange),this.summedRotation.multiply(e.rotationChange));this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation)}}findRootTrack(A,e){const t=A.tracks;if(!t)return null;for(const g of t)if(g.name.endsWith(e))return g;return null}}class piA extends KC{onSerialize(A,e){}onDeserialize(A,e){if(e.type===zo&&(A==null?void 0:A.__type)==="AnimatorController")return new zo(A)}}new piA(zo);class fiA extends yi{constructor(A,e=1,t=16,g=2){const I=new de,o=t+g*2,s=new Float32Array((o*3+3)*3);I.setAttribute("position",new $A(s,3));const n=new Fi({color:65280}),C=new Fi({color:16776960});super(I,[C,n]),this.audio=A,this.range=e,this.divisionsInnerAngle=t,this.divisionsOuterAngle=g,this.type="PositionalAudioHelper",this.update()}update(){const A=this.audio,e=this.range,t=this.divisionsInnerAngle,g=this.divisionsOuterAngle,I=Gg.degToRad(A.panner.coneInnerAngle),o=Gg.degToRad(A.panner.coneOuterAngle),s=I/2,n=o/2;let C=0,a=0,B,Q;const E=this.geometry,c=E.attributes.position;E.clearGroups();function d(l,h,p,u){const f=(h-l)/p;for(c.setXYZ(C,0,0,0),a++,B=l;B<h;B+=f)Q=C+a,c.setXYZ(Q,Math.sin(B)*e,0,Math.cos(B)*e),c.setXYZ(Q+1,Math.sin(Math.min(B+f,h))*e,0,Math.cos(Math.min(B+f,h))*e),c.setXYZ(Q+2,0,0,0),a+=3;E.addGroup(C,a,u),C+=a,a=0}d(-n,-s,g,0),d(-s,s,t,1),d(s,n,g,0),c.needsUpdate=!0,I===o&&(this.material[0].visible=!1)}dispose(){this.geometry.dispose(),this.material[0].dispose(),this.material[1].dispose()}}var DiA=Object.defineProperty,wiA=Object.getOwnPropertyDescriptor,vC=(i,A,e,t)=>{for(var g=t>1?void 0:t?wiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&DiA(A,e,g),g};const ug=sA("debugaudio");let VD=!1;const zD=[];function Ly(){if(VD)return;_e()&&console.log("User interaction registered: audio can now be played"),VD=!0;const i=[...zD];zD.length=0,i.forEach(A=>A())}document.addEventListener("pointerdown",Ly);document.addEventListener("click",Ly);document.addEventListener("dragstart",Ly);document.addEventListener("touchstart",Ly);const Hn=class extends NA{constructor(){super(...arguments);r(this,"clip","");r(this,"playOnAwake",!1);r(this,"_spatialBlend",0);r(this,"_minDistance",1);r(this,"_maxDistance",100);r(this,"_volume",1);r(this,"rollOffMode",0);r(this,"playInBackground",!0);r(this,"_loop",!1);r(this,"sound",null);r(this,"helper",null);r(this,"wasPlaying",!1);r(this,"audioLoader",null);r(this,"shouldPlay",!1);r(this,"_lastClipStartedLoading",null);r(this,"_audioElement",null);r(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||NC())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":ug&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,Hn.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&Hn.userInteractionRegistered&&this.wasPlaying&&this.play();break}});r(this,"onApplicationMuteChanged",()=>{var A,e;this.context.application.muted?(A=this.sound)==null||A.setVolume(0):(e=this.sound)==null||e.setVolume(this.volume)});r(this,"lerp",(A,e,t)=>A*(1-t)+e*t);r(this,"createAudio",A=>{ug&&console.log("audio buffer loaded"),Hn.registerWaitForAllowAudio(()=>{ug&&console.log("finished loading",A);const e=this.Sound;if(!e){console.warn("Failed getting sound",this.name);return}e.isPlaying&&e.stop(),A&&e.setBuffer(A),e.loop=this._loop,this.context.application.muted?e.setVolume(0):e.setVolume(this.volume),e.autoplay=this.shouldPlay,this.applySpatialDistanceSettings(),e.isPlaying&&e.stop(),ug&&console.log(this.name,this.shouldPlay,Hn.userInteractionRegistered,this),this.shouldPlay&&Hn.userInteractionRegistered&&this.play()})});r(this,"_lastContextTime",0);r(this,"_hasEnded",!0);r(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return VD}static registerWaitForAllowAudio(A){if(A!==null){if(VD){A();return}zD.indexOf(A)===-1&&zD.push(A)}}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(A){this._loop=A,this.sound&&this.sound.setLoop(A)}get spatialBlend(){return this._spatialBlend}set spatialBlend(A){A!==this._spatialBlend&&(this._spatialBlend=A,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(A){this._minDistance!==A&&(this._minDistance=A,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(A){this._maxDistance!==A&&(this._maxDistance=A,this._needUpdateSpatialDistanceSettings=!0)}get volume(){return this._volume}set volume(A){this._volume=A,this.sound&&!this.context.application.muted&&(ug&&console.log(this.name,"audio set volume",A),this.sound.setVolume(A))}get Sound(){if(!this.sound&&Hn.userInteractionRegistered){let A=IA.getComponent(this.context.mainCamera,Ga)??IA.findObjectOfType(Ga,this.context);!A&&this.context.mainCamera&&(A=IA.addNewComponent(this.context.mainCamera,Ga)),A!=null&&A.listener?(this.sound=new jx(A.listener),this.gameObject.add(this.sound)):ug&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}awake(){ug&&console.log(this),this.audioLoader=new dD,this.playOnAwake&&(this.shouldPlay=!0)}onEnable(){Hn.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Hn.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(qD.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(qD.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const A=this.sound;if(!A)return;this._needUpdateSpatialDistanceSettings=!1;const e=this.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(ug&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+e),A.setRefDistance(e),A.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:A.setDistanceModel("exponential");break;case 1:A.setDistanceModel("linear");break}this.spatialBlend>0?ug&&!this.helper&&(this.helper=new fiA(A,A.getRefDistance()),A.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}onNewClip(A){if(A&&(this.clip=A),typeof A=="string")if(ug&&console.log(A),A.endsWith(".mp3")||A.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new dD),this.shouldPlay=!0,this._lastClipStartedLoading===A){ug&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=A,ug&&console.log("load audio",A),this.audioLoader.load(A,this.createAudio,()=>{},console.error)}else console.warn("Unsupported audio clip type",A);else this.shouldPlay=!0,this.createAudio()}play(A=void 0){var t,g;!A&&this.clip&&(A=this.clip),A!==void 0&&typeof A!="string"&&!(A instanceof MediaStream)&&(_e()&&console.warn("Called play on AudioSource with unknown argument type:",A+`
|
|
5096
|
-
Using the assigned clip instead:`,this.clip),A=this.clip);let e=!this.sound||A&&A!==this.clip;if(typeof A=="string"&&!this.audioLoader&&(e=!0),(A instanceof MediaStream||typeof A=="string")&&(this.clip=A),e){this.shouldPlay=!0,this.onNewClip(A);return}if(this.shouldPlay=!0,this._hasEnded=!1,ug&&console.log("play",(t=this.sound)==null?void 0:t.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const I=this.context.application.muted;I&&this.sound.setVolume(0),this.clip instanceof MediaStream?(this.sound.setMediaStreamSource(this.clip),this._audioElement||(this._audioElement=document.createElement("audio"),this._audioElement.style.display="none"),this._audioElement.parentNode||(g=this.context.domElement.shadowRoot)==null||g.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(I?.1:0))}}pause(){var A,e;ug&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=(A=this.sound)==null?void 0:A.context.currentTime,this.sound.pause()),(e=this._audioElement)==null||e.remove()}stop(){var A,e;ug&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=(A=this.sound)==null?void 0:A.context.currentTime,ug&&console.log(this._lastContextTime),this.sound.stop()),(e=this._audioElement)==null||e.remove()}get isPlaying(){var A;return((A=this.sound)==null?void 0:A.isPlaying)??!1}set isPlaying(A){}get time(){var A,e;return(A=this.sound)!=null&&A.source?((e=this.sound.source)==null?void 0:e.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(A){if(this.sound){if(A===this.sound.offset)return;const e=this.isPlaying;this.stop(),this.sound.offset=A,e&&this.play()}}update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,ug&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}};let Ki=Hn;vC([D(URL)],Ki.prototype,"clip",2);vC([D()],Ki.prototype,"playOnAwake",2);vC([D()],Ki.prototype,"loop",1);vC([D()],Ki.prototype,"spatialBlend",1);vC([D()],Ki.prototype,"minDistance",1);vC([D()],Ki.prototype,"maxDistance",1);vC([D()],Ki.prototype,"volume",1);vC([D()],Ki.prototype,"rollOffMode",2);vC([D()],Ki.prototype,"playInBackground",2);var yiA=Object.defineProperty,SiA=Object.getOwnPropertyDescriptor,kiA=(i,A,e,t)=>{for(var g=t>1?void 0:t?SiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&yiA(A,e,g),g};class Vd extends NA{constructor(){super(...arguments);r(this,"constraintActive",!0);r(this,"locked",!1);r(this,"sources",[])}}kiA([D(SA)],Vd.prototype,"sources",2);const Vv={type:"change"},Lk={type:"start"},zv={type:"end"};let miA=class extends ig{constructor(A,e){super(),this.object=A,this.domElement=e,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new w,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:Nr.ROTATE,MIDDLE:Nr.DOLLY,RIGHT:Nr.PAN},this.touches={ONE:Kr.ROTATE,TWO:Kr.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this.getPolarAngle=function(){return s.phi},this.getAzimuthalAngle=function(){return s.theta},this.getDistance=function(){return this.object.position.distanceTo(this.target)},this.listenToKeyEvents=function(Z){Z.addEventListener("keydown",Me),this._domElementKeyEvents=Z},this.stopListenToKeyEvents=function(){this._domElementKeyEvents.removeEventListener("keydown",Me),this._domElementKeyEvents=null},this.saveState=function(){t.target0.copy(t.target),t.position0.copy(t.object.position),t.zoom0=t.object.zoom},this.reset=function(){t.target.copy(t.target0),t.object.position.copy(t.position0),t.object.zoom=t.zoom0,t.object.updateProjectionMatrix(),t.dispatchEvent(Vv),t.update(),I=g.NONE},this.update=function(){const Z=new w,hA=new MA().setFromUnitVectors(A.up,new w(0,1,0)),rA=hA.clone().invert(),VA=new w,jA=new MA,OA=new w,bA=2*Math.PI;return function(){const fe=t.object.getWorldPosition(A.position);Z.copy(fe).sub(t.target),Z.applyQuaternion(hA),s.setFromVector3(Z),t.autoRotate&&I===g.NONE&&M(R()),t.enableDamping?(s.theta+=n.theta*t.dampingFactor,s.phi+=n.phi*t.dampingFactor):(s.theta+=n.theta,s.phi+=n.phi);let ye=t.minAzimuthAngle,eA=t.maxAzimuthAngle;return isFinite(ye)&&isFinite(eA)&&(ye<-Math.PI?ye+=bA:ye>Math.PI&&(ye-=bA),eA<-Math.PI?eA+=bA:eA>Math.PI&&(eA-=bA),ye<=eA?s.theta=Math.max(ye,Math.min(eA,s.theta)):s.theta=s.theta>(ye+eA)/2?Math.max(ye,s.theta):Math.min(eA,s.theta)),s.phi=Math.max(t.minPolarAngle,Math.min(t.maxPolarAngle,s.phi)),s.makeSafe(),t.enableDamping?a=Gg.lerp(a,C,t.dampingFactor):a=C,s.radius*=a,s.radius=Math.max(t.minDistance,Math.min(t.maxDistance,s.radius)),t.enableDamping===!0?t.target.addScaledVector(B,t.dampingFactor):t.target.add(B),Z.setFromSpherical(s),Z.applyQuaternion(rA),fe.copy(t.target).add(Z),t.object.parent?t.object.parent.worldToLocal(fe):t.object.position.copy(fe),t.object.lookAt(t.target),t.enableDamping===!0?(n.theta*=1-t.dampingFactor,n.phi*=1-t.dampingFactor,B.multiplyScalar(1-t.dampingFactor)):(n.set(0,0,0),B.set(0,0,0)),C=1,Q||VA.distanceToSquared(t.object.position)>o||8*(1-jA.dot(t.object.quaternion))>o||OA.distanceToSquared(t.target)>0?(t.dispatchEvent(Vv),VA.copy(t.object.position),jA.copy(t.object.quaternion),OA.copy(t.target),Q=!1,!0):!1}}(),this.dispose=function(){t.domElement.removeEventListener("contextmenu",q),t.domElement.removeEventListener("pointerdown",LA),t.domElement.removeEventListener("pointercancel",te),t.domElement.removeEventListener("wheel",ue),t.domElement.removeEventListener("pointermove",GA),t.domElement.removeEventListener("pointerup",te),t._domElementKeyEvents!==null&&(t._domElementKeyEvents.removeEventListener("keydown",Me),t._domElementKeyEvents=null)};const t=this,g={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let I=g.NONE;const o=1e-6,s=new nG,n=new nG;let C=1,a=1;const B=new w;let Q=!1;const E=new tA,c=new tA,d=new tA,l=new tA,h=new tA,p=new tA,u=new tA,f=new tA,k=new tA,m=[],G={};function R(){return 2*Math.PI/60/60*t.autoRotateSpeed}function y(){return Math.pow(.95,t.zoomSpeed)}function M(Z){n.theta-=Z}function K(Z){n.phi-=Z}const P=function(){const Z=new w;return function(rA,VA){Z.setFromMatrixColumn(VA,0),Z.multiplyScalar(-rA),B.add(Z)}}(),b=function(){const Z=new w;return function(rA,VA){t.screenSpacePanning===!0?Z.setFromMatrixColumn(VA,1):(Z.setFromMatrixColumn(VA,0),Z.crossVectors(t.object.up,Z)),Z.multiplyScalar(rA),B.add(Z)}}(),H=function(){const Z=new w,hA=new w;return function(VA,jA){const OA=t.domElement;if(t.object.isPerspectiveCamera){t.object.getWorldPosition(hA),Z.copy(hA).sub(t.target);let bA=Z.length();bA*=Math.tan(t.object.fov/2*Math.PI/180),P(2*VA*bA/OA.clientHeight,t.object.matrixWorld),b(2*jA*bA/OA.clientHeight,t.object.matrixWorld)}else t.object.isOrthographicCamera?(P(VA*(t.object.right-t.object.left)/t.object.zoom/OA.clientWidth,t.object.matrixWorld),b(jA*(t.object.top-t.object.bottom)/t.object.zoom/OA.clientHeight,t.object.matrixWorld)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),t.enablePan=!1)}}();function W(Z){t.object.isPerspectiveCamera?C/=Z:t.object.isOrthographicCamera?(t.object.zoom=Math.max(t.minZoom,Math.min(t.maxZoom,t.object.zoom*Z)),t.object.updateProjectionMatrix(),Q=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),t.enableZoom=!1)}function L(Z){t.object.isPerspectiveCamera?C*=Z:t.object.isOrthographicCamera?(t.object.zoom=Math.max(t.minZoom,Math.min(t.maxZoom,t.object.zoom/Z)),t.object.updateProjectionMatrix(),Q=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),t.enableZoom=!1)}function v(Z){E.set(Z.clientX,Z.clientY)}function Y(Z){u.set(Z.clientX,Z.clientY)}function AA(Z){l.set(Z.clientX,Z.clientY)}function $(Z){c.set(Z.clientX,Z.clientY),d.subVectors(c,E).multiplyScalar(t.rotateSpeed);const hA=t.domElement;M(2*Math.PI*d.x/hA.clientHeight),K(2*Math.PI*d.y/hA.clientHeight),E.copy(c),t.update()}function V(Z){f.set(Z.clientX,Z.clientY),k.subVectors(f,u),k.y>0?W(y()):k.y<0&&L(y()),u.copy(f),t.update()}function gA(Z){h.set(Z.clientX,Z.clientY),p.subVectors(h,l).multiplyScalar(t.panSpeed),H(p.x,p.y),l.copy(h),t.update()}function dA(Z){Z.deltaY<0?L(y()):Z.deltaY>0&&W(y()),t.update()}function fA(Z){let hA=!1;switch(Z.code){case t.keys.UP:Z.ctrlKey||Z.metaKey||Z.shiftKey?K(2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):H(0,t.keyPanSpeed),hA=!0;break;case t.keys.BOTTOM:Z.ctrlKey||Z.metaKey||Z.shiftKey?K(-2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):H(0,-t.keyPanSpeed),hA=!0;break;case t.keys.LEFT:Z.ctrlKey||Z.metaKey||Z.shiftKey?M(2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):H(t.keyPanSpeed,0),hA=!0;break;case t.keys.RIGHT:Z.ctrlKey||Z.metaKey||Z.shiftKey?M(-2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):H(-t.keyPanSpeed,0),hA=!0;break}hA&&(Z.preventDefault(),t.update())}function RA(){if(m.length===1)E.set(m[0].pageX,m[0].pageY);else{const Z=.5*(m[0].pageX+m[1].pageX),hA=.5*(m[0].pageY+m[1].pageY);E.set(Z,hA)}}function UA(){if(m.length===1)l.set(m[0].pageX,m[0].pageY);else{const Z=.5*(m[0].pageX+m[1].pageX),hA=.5*(m[0].pageY+m[1].pageY);l.set(Z,hA)}}function HA(){const Z=m[0].pageX-m[1].pageX,hA=m[0].pageY-m[1].pageY,rA=Math.sqrt(Z*Z+hA*hA);u.set(0,rA)}function PA(){t.enableZoom&&HA(),t.enablePan&&UA()}function Qe(){t.enableZoom&&HA(),t.enableRotate&&RA()}function Ge(Z){if(m.length==1)c.set(Z.pageX,Z.pageY);else{const rA=TA(Z),VA=.5*(Z.pageX+rA.x),jA=.5*(Z.pageY+rA.y);c.set(VA,jA)}d.subVectors(c,E).multiplyScalar(t.rotateSpeed);const hA=t.domElement;M(2*Math.PI*d.x/hA.clientHeight),K(2*Math.PI*d.y/hA.clientHeight),E.copy(c)}function Ie(Z){if(m.length===1)h.set(Z.pageX,Z.pageY);else{const hA=TA(Z),rA=.5*(Z.pageX+hA.x),VA=.5*(Z.pageY+hA.y);h.set(rA,VA)}p.subVectors(h,l).multiplyScalar(t.panSpeed),H(p.x,p.y),l.copy(h)}function z(Z){const hA=TA(Z),rA=Z.pageX-hA.x,VA=Z.pageY-hA.y,jA=Math.sqrt(rA*rA+VA*VA);f.set(0,jA),k.set(0,Math.pow(f.y/u.y,t.zoomSpeed)),W(k.y),u.copy(f)}function xA(Z){t.enableZoom&&z(Z),t.enablePan&&Ie(Z)}function DA(Z){t.enableZoom&&z(Z),t.enableRotate&&Ge(Z)}function LA(Z){t.enabled!==!1&&(m.length===0&&(t.domElement.addEventListener("pointermove",GA),t.domElement.addEventListener("pointerup",te)),EA(Z),Z.pointerType==="touch"?et(Z):zA(Z))}function GA(Z){t.enabled!==!1&&(Z.pointerType==="touch"?_(Z):ZA(Z))}function te(Z){KA(Z),m.length===0&&(t.domElement.removeEventListener("pointermove",GA),t.domElement.removeEventListener("pointerup",te)),t.dispatchEvent(zv),I=g.NONE}function zA(Z){let hA;switch(Z.button){case 0:hA=t.mouseButtons.LEFT;break;case 1:hA=t.mouseButtons.MIDDLE;break;case 2:hA=t.mouseButtons.RIGHT;break;default:hA=-1}switch(hA){case Nr.DOLLY:if(t.enableZoom===!1)return;Y(Z),I=g.DOLLY;break;case Nr.ROTATE:if(Z.ctrlKey||Z.metaKey||Z.shiftKey){if(t.enablePan===!1)return;AA(Z),I=g.PAN}else{if(t.enableRotate===!1)return;v(Z),I=g.ROTATE}break;case Nr.PAN:if(Z.ctrlKey||Z.metaKey||Z.shiftKey){if(t.enableRotate===!1)return;v(Z),I=g.ROTATE}else{if(t.enablePan===!1)return;AA(Z),I=g.PAN}break;default:I=g.NONE}I!==g.NONE&&t.dispatchEvent(Lk)}function ZA(Z){switch(I){case g.ROTATE:if(t.enableRotate===!1)return;$(Z);break;case g.DOLLY:if(t.enableZoom===!1)return;V(Z);break;case g.PAN:if(t.enablePan===!1)return;gA(Z);break}}function ue(Z){t.enabled===!1||t.enableZoom===!1||I!==g.NONE||(Z.preventDefault(),t.dispatchEvent(Lk),dA(Z),t.dispatchEvent(zv))}function Me(Z){t.enabled===!1||t.enablePan===!1||fA(Z)}function et(Z){switch(JA(Z),m.length){case 1:switch(t.touches.ONE){case Kr.ROTATE:if(t.enableRotate===!1)return;RA(),I=g.TOUCH_ROTATE;break;case Kr.PAN:if(t.enablePan===!1)return;UA(),I=g.TOUCH_PAN;break;default:I=g.NONE}break;case 2:switch(t.touches.TWO){case Kr.DOLLY_PAN:if(t.enableZoom===!1&&t.enablePan===!1)return;PA(),I=g.TOUCH_DOLLY_PAN;break;case Kr.DOLLY_ROTATE:if(t.enableZoom===!1&&t.enableRotate===!1)return;Qe(),I=g.TOUCH_DOLLY_ROTATE;break;default:I=g.NONE}break;default:I=g.NONE}I!==g.NONE&&t.dispatchEvent(Lk)}function _(Z){switch(JA(Z),I){case g.TOUCH_ROTATE:if(t.enableRotate===!1)return;Ge(Z),t.update();break;case g.TOUCH_PAN:if(t.enablePan===!1)return;Ie(Z),t.update();break;case g.TOUCH_DOLLY_PAN:if(t.enableZoom===!1&&t.enablePan===!1)return;xA(Z),t.update();break;case g.TOUCH_DOLLY_ROTATE:if(t.enableZoom===!1&&t.enableRotate===!1)return;DA(Z),t.update();break;default:I=g.NONE}}function q(Z){t.enabled!==!1&&Z.preventDefault()}function EA(Z){m.push(Z)}function KA(Z){delete G[Z.pointerId];for(let hA=0;hA<m.length;hA++)if(m[hA].pointerId==Z.pointerId){m.splice(hA,1);return}}function JA(Z){let hA=G[Z.pointerId];hA===void 0&&(hA=new tA,G[Z.pointerId]=hA),hA.set(Z.pageX,Z.pageY)}function TA(Z){const hA=Z.pointerId===m[0].pointerId?m[1]:m[0];return G[hA.pointerId]}t.domElement.addEventListener("contextmenu",q),t.domElement.addEventListener("pointerdown",LA),t.domElement.addEventListener("pointercancel",te),t.domElement.addEventListener("wheel",ue,{passive:!1}),this.update()}};const GiA="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/";class MiA{constructor(A,e,t,g,I=null){this.controller=e,this.handModel=A,this.bones=[],I===null&&(I=new ic,I.setPath(t||GiA)),I.load(`${g}.glb`,o=>{const s=o.scene.children[0];this.handModel.add(s),s.layers.mask=this.handModel.layers.mask;const n=s.getObjectByProperty("type","SkinnedMesh");n.frustumCulled=!1,n.castShadow=!0,n.receiveShadow=!0,["wrist","thumb-metacarpal","thumb-phalanx-proximal","thumb-phalanx-distal","thumb-tip","index-finger-metacarpal","index-finger-phalanx-proximal","index-finger-phalanx-intermediate","index-finger-phalanx-distal","index-finger-tip","middle-finger-metacarpal","middle-finger-phalanx-proximal","middle-finger-phalanx-intermediate","middle-finger-phalanx-distal","middle-finger-tip","ring-finger-metacarpal","ring-finger-phalanx-proximal","ring-finger-phalanx-intermediate","ring-finger-phalanx-distal","ring-finger-tip","pinky-finger-metacarpal","pinky-finger-phalanx-proximal","pinky-finger-phalanx-intermediate","pinky-finger-phalanx-distal","pinky-finger-tip"].forEach(a=>{const B=s.getObjectByName(a);B!==void 0?B.jointName=a:console.warn(`Couldn't find ${a} in ${g} hand mesh`),this.bones.push(B)})})}updateMesh(){const A=this.controller.joints;for(let e=0;e<this.bones.length;e++){const t=this.bones[e];if(t){const g=A[t.jointName];if(g.visible){const I=g.position;t.position.copy(I),t.quaternion.copy(g.quaternion)}}}}}const RiA=.01,UiA="index-finger-tip";class FiA extends SA{constructor(A,e=null){super(),this.controller=A,this.motionController=null,this.envMap=null,this.loader=e,this.mesh=null,A.addEventListener("connected",t=>{const g=t.data;g.hand&&!this.motionController&&(this.xrInputSource=g,this.motionController=new MiA(this,A,this.path,g.handedness,this.loader))}),A.addEventListener("disconnected",()=>{this.clear(),this.motionController=null})}updateMatrixWorld(A){super.updateMatrixWorld(A),this.motionController&&this.motionController.updateMesh()}getPointerPosition(){const A=this.controller.joints[UiA];return A?A.position:null}intersectBoxObject(A){const e=this.getPointerPosition();if(e){const t=new DI(e,RiA),g=new Hi().setFromObject(A);return t.intersectsBox(g)}else return!1}checkButton(A){this.intersectBoxObject(A)?A.onPress():A.onClear(),A.isPressed()&&A.whilePressed()}}const NiA=.05,jv=.02,_p=.01,Zv=.02,Xv=1,yQ=.4,KiA=.002,oh=.01,Op=.003,$v=.035,Mt=16,Mo=12,xk=110,JiA=new w(0,1,0),qiA=new w(0,0,1),viA=.02,biA=1.5;class LiA extends SA{constructor(A,e){super(),this.hand=A,this.controller=e,this.motionController=null,this.envMap=null,this.mesh=null,this.pointerGeometry=null,this.pointerMesh=null,this.pointerObject=null,this.pinched=!1,this.attached=!1,this.cursorObject=null,this.raycaster=null,this._onConnected=this._onConnected.bind(this),this._onDisconnected=this._onDisconnected.bind(this),this.hand.addEventListener("connected",this._onConnected),this.hand.addEventListener("disconnected",this._onDisconnected)}_onConnected(A){const e=A.data;e.hand&&(this.visible=!0,this.xrInputSource=e,this.createPointer())}_onDisconnected(){this.visible=!1,this.xrInputSource=null,this.pointerGeometry&&this.pointerGeometry.dispose(),this.pointerMesh&&this.pointerMesh.material&&this.pointerMesh.material.dispose(),this.clear()}_drawVerticesRing(A,e,t){const g=e.clone();for(let I=0;I<Mt;I++){g.applyAxisAngle(qiA,Math.PI*2/Mt);const o=t*Mt+I;A[3*o]=g.x,A[3*o+1]=g.y,A[3*o+2]=g.z}}_updatePointerVertices(A){const e=this.pointerGeometry.attributes.position.array,t=new w(KiA,0,-1*($v-A));this._drawVerticesRing(e,t,0);const g=new w(Math.sin(Math.PI*xk/180)*A,Math.cos(Math.PI*xk/180)*A,0);for(let C=0;C<Mo;C++)this._drawVerticesRing(e,g,C+1),g.applyAxisAngle(JiA,Math.PI*xk/180/(Mo*-2));const I=Mt*(1+Mo),o=Mt*(1+Mo)+1,s=new w(0,0,-1*($v-A));e[I*3]=s.x,e[I*3+1]=s.y,e[I*3+2]=s.z;const n=new w(0,0,A);e[o*3]=n.x,e[o*3+1]=n.y,e[o*3+2]=n.z,this.pointerGeometry.setAttribute("position",new ae(e,3))}createPointer(){let A,e;const t=new Array(((Mo+1)*Mt+2)*3).fill(0),g=[];for(this.pointerGeometry=new de,this.pointerGeometry.setAttribute("position",new ae(t,3)),this._updatePointerVertices(oh),A=0;A<Mo;A++){for(e=0;e<Mt-1;e++)g.push(A*Mt+e,A*Mt+e+1,(A+1)*Mt+e),g.push(A*Mt+e+1,(A+1)*Mt+e+1,(A+1)*Mt+e);g.push((A+1)*Mt-1,A*Mt,(A+2)*Mt-1),g.push(A*Mt,(A+1)*Mt,(A+2)*Mt-1)}const I=Mt*(1+Mo),o=Mt*(1+Mo)+1;for(A=0;A<Mt-1;A++)g.push(I,A+1,A),g.push(o,A+Mt*Mo,A+Mt*Mo+1);g.push(I,0,Mt-1),g.push(o,Mt*(Mo+1)-1,Mt*Mo);const s=new rt;s.transparent=!0,s.opacity=yQ,this.pointerGeometry.setIndex(g),this.pointerMesh=new pA(this.pointerGeometry,s),this.pointerMesh.position.set(0,0,-1*oh),this.pointerObject=new SA,this.pointerObject.add(this.pointerMesh),this.raycaster=new DB;const n=new $o(viA,10,10),C=new rt;C.transparent=!0,C.opacity=yQ,this.cursorObject=new pA(n,C),this.pointerObject.add(this.cursorObject),this.add(this.pointerObject),this.pointerObject.layers.mask=this.layers.mask,this.pointerMesh.layers.mask=this.layers.mask}_updateRaycaster(){if(this.raycaster){const A=this.pointerObject.matrixWorld,e=new FA;e.identity().extractRotation(A),this.raycaster.ray.origin.setFromMatrixPosition(A),this.raycaster.ray.direction.set(0,0,-1).applyMatrix4(e)}}_updatePointer(){this.pointerObject.visible=this.controller.visible;const A=this.hand.joints["index-finger-tip"],e=this.hand.joints["thumb-tip"],t=A.position.distanceTo(e.position),g=A.position.clone().add(e.position).multiplyScalar(.5);this.pointerObject.position.copy(g),this.pointerObject.quaternion.copy(this.controller.quaternion),this.pinched=t<=jv;const I=(t-_p)/(NiA-_p),o=(t-_p)/(jv-_p);if(I>1)this._updatePointerVertices(oh),this.pointerMesh.position.set(0,0,-1*oh),this.pointerMesh.material.opacity=yQ;else if(I>0){const s=(oh-Op)*I+Op;this._updatePointerVertices(s),o<1?(this.pointerMesh.position.set(0,0,-1*s-(1-o)*Zv),this.pointerMesh.material.opacity=yQ+(1-o)*(Xv-yQ)):(this.pointerMesh.position.set(0,0,-1*s),this.pointerMesh.material.opacity=yQ)}else this._updatePointerVertices(Op),this.pointerMesh.position.set(0,0,-1*Op-Zv),this.pointerMesh.material.opacity=Xv;this.cursorObject.material.opacity=this.pointerMesh.material.opacity}updateMatrixWorld(A){super.updateMatrixWorld(A),this.pointerGeometry&&(this._updatePointer(),this._updateRaycaster())}isPinched(){return this.pinched}setAttached(A){this.attached=A}isAttached(){return this.attached}intersectObject(A,e=!0){if(this.raycaster)return this.raycaster.intersectObject(A,e)}intersectObjects(A,e=!0){if(this.raycaster)return this.raycaster.intersectObjects(A,e)}checkIntersections(A,e=!1){if(this.raycaster&&!this.attached){const t=this.raycaster.intersectObjects(A,e),g=new w(0,0,-1);if(t.length>0){const o=t[0].distance;this.cursorObject.position.copy(g.multiplyScalar(o))}else this.cursorObject.position.copy(g.multiplyScalar(biA))}}setCursor(A){const e=new w(0,0,-1);this.raycaster&&!this.attached&&this.cursorObject.position.copy(e.multiplyScalar(A))}dispose(){this._onDisconnected(),this.hand.removeEventListener("connected",this._onConnected),this.hand.removeEventListener("disconnected",this._onDisconnected)}}const ri={Handedness:Object.freeze({NONE:"none",LEFT:"left",RIGHT:"right"}),ComponentState:Object.freeze({DEFAULT:"default",TOUCHED:"touched",PRESSED:"pressed"}),ComponentProperty:Object.freeze({BUTTON:"button",X_AXIS:"xAxis",Y_AXIS:"yAxis",STATE:"state"}),ComponentType:Object.freeze({TRIGGER:"trigger",SQUEEZE:"squeeze",TOUCHPAD:"touchpad",THUMBSTICK:"thumbstick",BUTTON:"button"}),ButtonTouchThreshold:.05,AxisTouchThreshold:.1,VisualResponseProperty:Object.freeze({TRANSFORM:"transform",VISIBILITY:"visibility"})};async function eO(i){const A=await fetch(i);if(A.ok)return A.json();throw new Error(A.statusText)}async function xiA(i){if(!i)throw new Error("No basePath supplied");return await eO(`${i}/profilesList.json`)}async function TiA(i,A,e=null,t=!0){if(!i)throw new Error("No xrInputSource supplied");if(!A)throw new Error("No basePath supplied");const g=await xiA(A);let I;if(i.profiles.some(n=>{const C=g[n];return C&&(I={profileId:n,profilePath:`${A}/${C.path}`,deprecated:!!C.deprecated}),!!I}),!I){if(!e)throw new Error("No matching profile name found");const n=g[e];if(!n)throw new Error(`No matching profile name found and default profile "${e}" missing.`);I={profileId:e,profilePath:`${A}/${n.path}`,deprecated:!!n.deprecated}}const o=await eO(I.profilePath);let s;if(t){let n;if(i.handedness==="any"?n=o.layouts[Object.keys(o.layouts)[0]]:n=o.layouts[i.handedness],!n)throw new Error(`No matching handedness, ${i.handedness}, in profile ${I.profileId}`);n.assetPath&&(s=I.profilePath.replace("profile.json",n.assetPath))}return{profile:o,assetPath:s}}const YiA={xAxis:0,yAxis:0,button:0,state:ri.ComponentState.DEFAULT};function HiA(i=0,A=0){let e=i,t=A;if(Math.sqrt(i*i+A*A)>1){const o=Math.atan2(A,i);e=Math.cos(o),t=Math.sin(o)}return{normalizedXAxis:e*.5+.5,normalizedYAxis:t*.5+.5}}class _iA{constructor(A){this.componentProperty=A.componentProperty,this.states=A.states,this.valueNodeName=A.valueNodeName,this.valueNodeProperty=A.valueNodeProperty,this.valueNodeProperty===ri.VisualResponseProperty.TRANSFORM&&(this.minNodeName=A.minNodeName,this.maxNodeName=A.maxNodeName),this.value=0,this.updateFromComponent(YiA)}updateFromComponent({xAxis:A,yAxis:e,button:t,state:g}){const{normalizedXAxis:I,normalizedYAxis:o}=HiA(A,e);switch(this.componentProperty){case ri.ComponentProperty.X_AXIS:this.value=this.states.includes(g)?I:.5;break;case ri.ComponentProperty.Y_AXIS:this.value=this.states.includes(g)?o:.5;break;case ri.ComponentProperty.BUTTON:this.value=this.states.includes(g)?t:0;break;case ri.ComponentProperty.STATE:this.valueNodeProperty===ri.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(g):this.value=this.states.includes(g)?1:0;break;default:throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}}class OiA{constructor(A,e){if(!A||!e||!e.visualResponses||!e.gamepadIndices||Object.keys(e.gamepadIndices).length===0)throw new Error("Invalid arguments supplied");this.id=A,this.type=e.type,this.rootNodeName=e.rootNodeName,this.touchPointNodeName=e.touchPointNodeName,this.visualResponses={},Object.keys(e.visualResponses).forEach(t=>{const g=new _iA(e.visualResponses[t]);this.visualResponses[t]=g}),this.gamepadIndices=Object.assign({},e.gamepadIndices),this.values={state:ri.ComponentState.DEFAULT,button:this.gamepadIndices.button!==void 0?0:void 0,xAxis:this.gamepadIndices.xAxis!==void 0?0:void 0,yAxis:this.gamepadIndices.yAxis!==void 0?0:void 0}}get data(){return{id:this.id,...this.values}}updateFromGamepad(A){if(this.values.state=ri.ComponentState.DEFAULT,this.gamepadIndices.button!==void 0&&A.buttons.length>this.gamepadIndices.button){const e=A.buttons[this.gamepadIndices.button];this.values.button=e.value,this.values.button=this.values.button<0?0:this.values.button,this.values.button=this.values.button>1?1:this.values.button,e.pressed||this.values.button===1?this.values.state=ri.ComponentState.PRESSED:(e.touched||this.values.button>ri.ButtonTouchThreshold)&&(this.values.state=ri.ComponentState.TOUCHED)}this.gamepadIndices.xAxis!==void 0&&A.axes.length>this.gamepadIndices.xAxis&&(this.values.xAxis=A.axes[this.gamepadIndices.xAxis],this.values.xAxis=this.values.xAxis<-1?-1:this.values.xAxis,this.values.xAxis=this.values.xAxis>1?1:this.values.xAxis,this.values.state===ri.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>ri.AxisTouchThreshold&&(this.values.state=ri.ComponentState.TOUCHED)),this.gamepadIndices.yAxis!==void 0&&A.axes.length>this.gamepadIndices.yAxis&&(this.values.yAxis=A.axes[this.gamepadIndices.yAxis],this.values.yAxis=this.values.yAxis<-1?-1:this.values.yAxis,this.values.yAxis=this.values.yAxis>1?1:this.values.yAxis,this.values.state===ri.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>ri.AxisTouchThreshold&&(this.values.state=ri.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(e=>{e.updateFromComponent(this.values)})}}class PiA{constructor(A,e,t){if(!A)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No profile supplied");this.xrInputSource=A,this.assetUrl=t,this.id=e.profileId,this.layoutDescription=e.layouts[A.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(g=>{const I=this.layoutDescription.components[g];this.components[g]=new OiA(g,I)}),this.updateFromGamepad()}get gripSpace(){return this.xrInputSource.gripSpace}get targetRaySpace(){return this.xrInputSource.targetRaySpace}get data(){const A=[];return Object.values(this.components).forEach(e=>{A.push(e.data)}),A}updateFromGamepad(){Object.values(this.components).forEach(A=>{A.updateFromGamepad(this.xrInputSource.gamepad)})}}const WiA="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",ViA="generic-trigger";class ziA extends SA{constructor(){super(),this.motionController=null,this.envMap=null}setEnvironmentMap(A){return this.envMap==A?this:(this.envMap=A,this.traverse(e=>{e.isMesh&&(e.material.envMap=this.envMap,e.material.needsUpdate=!0)}),this)}updateMatrixWorld(A){super.updateMatrixWorld(A),this.motionController&&(this.motionController.updateFromGamepad(),Object.values(this.motionController.components).forEach(e=>{Object.values(e.visualResponses).forEach(t=>{const{valueNode:g,minNode:I,maxNode:o,value:s,valueNodeProperty:n}=t;g&&(n===ri.VisualResponseProperty.VISIBILITY?g.visible=s:n===ri.VisualResponseProperty.TRANSFORM&&(g.quaternion.slerpQuaternions(I.quaternion,o.quaternion,s),g.position.lerpVectors(I.position,o.position,s)))})}))}}function jiA(i,A){Object.values(i.components).forEach(e=>{const{type:t,touchPointNodeName:g,visualResponses:I}=e;if(t===ri.ComponentType.TOUCHPAD)if(e.touchPointNode=A.getObjectByName(g),e.touchPointNode){const o=new $o(.001),s=new rt({color:255}),n=new pA(o,s);e.touchPointNode.add(n)}else console.warn(`Could not find touch dot, ${e.touchPointNodeName}, in touchpad component ${e.id}`);Object.values(I).forEach(o=>{const{valueNodeName:s,minNodeName:n,maxNodeName:C,valueNodeProperty:a}=o;if(a===ri.VisualResponseProperty.TRANSFORM){if(o.minNode=A.getObjectByName(n),o.maxNode=A.getObjectByName(C),!o.minNode){console.warn(`Could not find ${n} in the model`);return}if(!o.maxNode){console.warn(`Could not find ${C} in the model`);return}}o.valueNode=A.getObjectByName(s),o.valueNode||console.warn(`Could not find ${s} in the model`)})})}function Ab(i,A){jiA(i.motionController,A),i.envMap&&A.traverse(e=>{e.isMesh&&(e.material.envMap=i.envMap,e.material.needsUpdate=!0)}),i.layers.mask!=0&&A.traverse(e=>{e.layers.mask=i.layers.mask}),i.add(A)}class ZiA{constructor(A=null){this.gltfLoader=A,this.path=WiA,this._assetCache={},this.gltfLoader||(this.gltfLoader=new ic)}createControllerModel(A){const e=new ziA;let t=null;return A.addEventListener("connected",g=>{const I=g.data;I.targetRayMode!=="tracked-pointer"||!I.gamepad||TiA(I,this.path,ViA).then(({profile:o,assetPath:s})=>{e.motionController=new PiA(I,o,s);const n=this._assetCache[e.motionController.assetUrl];if(n)t=n.scene.clone(),Ab(e,t);else{if(!this.gltfLoader)throw new Error("GLTFLoader not set.");this.gltfLoader.setPath(""),this.gltfLoader.load(e.motionController.assetUrl,C=>{this._assetCache[e.motionController.assetUrl]=C,t=C.scene.clone(),Ab(e,t)},null,()=>{throw new Error(`Asset ${e.motionController.assetUrl} missing or malformed.`)})}}).catch(o=>{console.warn(o)})}),A.addEventListener("disconnected",()=>{e.motionController=null,e.remove(t),t=null}),e}}const sh=sA("debugavatar");class xy{constructor(A,e,t,g){r(this,"root");r(this,"head");r(this,"leftHand");r(this,"rigthHand");var I;this.root=A,this.head=e,this.leftHand=t,this.rigthHand=g,(I=this.root)==null||I.traverse(o=>o.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class Ty{constructor(){r(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(A,e){if(!e)return console.error("Can not create avatar: failed to provide id or root object"),null;let t=null;if(typeof e=="string"){if(t=await this.loadAvatar(A,e),!t){const I=new cn;t=IA.instantiate(ME(e,A.scene),I)}}else t=e;if(!t)return null;const g=this.findAvatar(t);return g.isValid?(sh&&console.log("[Custom Avatar] valid config",e,sh?g:""),g):(console.warn("[Custom Avatar] config isn't valid",e,sh?g:""),null)}async loadAvatar(A,e){if(console.assert(e!=null&&typeof e=="string","Avatar id must not be null"),e.length<=0||!e)return null;if(sh&&console.log("[Custom Avatar] "+e+", loading..."),e.endsWith(".glb")||(e+=".glb"),this.avatarRegistryUrl===null){const g=await fetch("./"+e);let I=null;if(g.ok){const s=await g.blob();s&&(I=await s.arrayBuffer())}if(!I&&(I=await lU(e,e,0,"no url here go away",!0),!I))return null;const o=await ks().parseSync(A,I,null,0);return(o==null?void 0:o.scene)??null}const t=new ic;return xd(t,A),new Promise((g,I)=>{const o=this.avatarRegistryUrl+"/"+e;t.load(o,async s=>{await ks().createBuiltinComponents(A,o,s,null,void 0),g(s.scene)},s=>{sh&&console.log("[Custom Avatar] "+s.loaded/s.total*100+"% loaded of "+s.total/1024+"kB")},s=>{console.error("[Custom Avatar] Error when loading: "+s),g(null)})})}cacheModel(A,e){}findAvatar(A){const e=A;let t=e;t.children.length==1&&(t=A.children[0]);let g=this.findAvatarPart(t,["head"]);const I=this.findAvatarPart(t,["left","hand"]),o=this.findAvatarPart(t,["right","hand"]);if(!g){g=e;const n=new w;new Hi().setFromObject(g).getSize(n);const C=Math.max(n.x,n.y,n.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+C+" meters! Should be < 0.3m"),C>.3&&g.scale.multiplyScalar(1/C*.3)}return new xy(e,g,I,o)}findAvatarPart(A,e){const t=A.name.toLowerCase();let g=!0;for(const I of e){if(!g)break;t.indexOf(I)===-1&&(g=!1)}if(g)return A;if(A.children)for(const I of A.children){const o=this.findAvatarPart(I,e);if(o)return o}return null}handleCustomAvatarErrors(A){if(!A.ok)throw Error(A.statusText);return A}}var XiA=Object.defineProperty,$iA=Object.getOwnPropertyDescriptor,AgA=(i,A,e,t)=>{for(var g=t>1?void 0:t?$iA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&XiA(A,e,g),g};const LQ=sA("debugflags");var ki=(i=>(i[i.Never=0]="Never",i[i.Browser=1]="Browser",i[i.AR=2]="AR",i[i.VR=4]="VR",i[i.FirstPerson=8]="FirstPerson",i[i.ThirdPerson=16]="ThirdPerson",i[i.All=4294967295]="All",i))(ki||{});const XN=class{constructor(){r(this,"Mask",17)}Has(A){return(this.Mask&A)!==0}Set(A){LQ&&console.warn("Set XR flag state to",A),this.Mask=A,Io.Apply()}Enable(A){this.Mask|=A,Io.Apply()}Disable(A){this.Mask&=~A,Io.Apply()}Toggle(A){this.Mask^=A,Io.Apply()}EnableAll(){this.Mask=-1,Io.Apply()}DisableAll(){this.Mask=0,Io.Apply()}};let EI=XN;r(EI,"Global",new XN);var hh;const _n=(hh=class extends NA{constructor(){super(...arguments);r(this,"visibleIn")}static Apply(){for(const A of this.registry)A.UpdateVisible(EI.Global)}awake(){_n.registry.push(this)}onEnable(){_n.firstApply?this.UpdateVisible(EI.Global):(_n.firstApply=!0,_n.Apply())}onDestroy(){const A=_n.registry.indexOf(this);A>=0&&_n.registry.splice(A,1)}get isOn(){return this.gameObject.visible}UpdateVisible(A=null){let e;const t=A;t&&typeof t=="number"&&(console.assert(typeof t=="number","XRFlag.UpdateVisible: state must be a number",t),LQ&&console.log(t),_n.buffer.Mask=t,A=_n.buffer);const g=A;if(g?(LQ&&console.warn(this.name,"use passed in mask",g.Mask,this.visibleIn),e=g.Has(this.visibleIn)):(LQ&&console.log(this.name,"use global mask"),EI.Global.Has(this.visibleIn)),e!==void 0)if(e)LQ&&console.log(this.name,"is visible",this.gameObject.uuid),IA.setActive(this.gameObject,!0);else{if(LQ&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},r(hh,"registry",[]),r(hh,"firstApply"),r(hh,"buffer",new EI),hh);let Io=_n;AgA([D()],Io.prototype,"visibleIn",2);const Ca=sA("debugavatar"),Es=class extends NA{constructor(){super(...arguments);r(this,"connectionId");r(this,"avatar")}static getAvatar(e){return e>=0&&e<Es.instances.length?Es.instances[e]:null}static onAvatarMarkerCreated(e){return Es._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return Es._onAvatarMarkerDestroyed.push(e),e}awake(){Es.instances.push(this),Ca&&console.log(this);for(const e of Es._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Es.instances.splice(Es.instances.indexOf(this),1);for(const e of Es._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):IA.setActive(this.avatar,e))}};let Qg=Es;r(Qg,"instances",[]),r(Qg,"_onNewAvatarMarkerAdded",[]),r(Qg,"_onAvatarMarkerDestroyed",[]);const Bl=class{constructor(A,e,t){r(this,"_isVisible",!0);r(this,"guid");r(this,"root",null);r(this,"head",null);r(this,"handLeft",null);r(this,"handRight",null);r(this,"lastUpdate",-1);r(this,"isLocalAvatar",!1);r(this,"flags",null);r(this,"headScale",new w(1,1,1));r(this,"handLeftScale",new w(1,1,1));r(this,"handRightScale",new w(1,1,1));r(this,"webxr");r(this,"lastAvatarId",null);r(this,"hasAvatarOverride",!1);r(this,"context");r(this,"avatarMarker",null);r(this,"_headTarget",new SA);r(this,"_handLeftTarget",new SA);r(this,"_handRightTarget",new SA);r(this,"_canInterpolate",!1);this.context=A,this.guid=e,this.webxr=t,this.setupCustomAvatar(this.webxr.defaultAvatar)}setVisible(A){this._isVisible=A,this.updateVisibility()}get isWebXRAvatar(){return!0}updateFlags(){if(!this.flags)return;let A=this.isLocalAvatar?ki.FirstPerson:ki.ThirdPerson;this.context.isInVR?A|=ki.VR:this.context.isInAR?A|=ki.AR:A|=ki.Browser;for(const e of this.flags)e.gameObject.visible=!0,e.UpdateVisible(A)}async setAvatarOverride(A){return this.hasAvatarOverride=A!==null,this.hasAvatarOverride&&this.lastAvatarId!==A&&(this.lastAvatarId=A,A!=null&&A.length>0)?await this.setupCustomAvatar(A):null}tryUpdate(A,e){if(A.guid===this.guid&&(this.lastAvatarId!==A.avatarId&&A.avatarId&&A.avatarId.length>0&&(this.lastAvatarId=A.avatarId,this.setupCustomAvatar(A.avatarId)),this.lastUpdate=A.time,this.head)){const t=this.webxr.IsInAR?rn.Handheld:rn.Headset,g=this.head;this.context.players.setPlayerView(A.guid,g,t),Xg.markDirty(this.head),this._canInterpolate=!0;const I=this.isLocalAvatar?this.head:this._headTarget;if(I.position.set(A.position.x,A.position.y,A.position.z),I.quaternion.set(A.rotation.x,A.rotation.y,A.rotation.z,A.rotation.w),I.scale.set(A.scale,A.scale,A.scale),I.scale.multiply(this.headScale),this.handLeft){const o=this.isLocalAvatar?this.handLeft:this._handLeftTarget;o.position.set(A.posLeftHand.x,A.posLeftHand.y,A.posLeftHand.z),o.quaternion.set(A.rotLeftHand._x,A.rotLeftHand._y,A.rotLeftHand._z,A.rotLeftHand._w),o.quaternion.multiply(Bl.invertRotation),o.scale.set(A.scale,A.scale,A.scale),o.scale.multiply(this.handLeftScale),Xg.markDirty(this.handLeft)}if(this.handRight){const o=this.isLocalAvatar?this.handRight:this._handRightTarget;o.position.set(A.posRightHand.x,A.posRightHand.y,A.posRightHand.z),o.quaternion.set(A.rotRightHand._x,A.rotRightHand._y,A.rotRightHand._z,A.rotRightHand._w),o.quaternion.multiply(Bl.invertRotation),o.scale.set(A.scale,A.scale,A.scale),o.scale.multiply(this.handRightScale),Xg.markDirty(this.handRight)}}}update(){if(this.isLocalAvatar||!this._canInterpolate)return;const A=this.context.time.deltaTime/.1;this.head&&(this.head.position.lerp(this._headTarget.position,A),this.head.quaternion.slerp(this._headTarget.quaternion,A),this.head.scale.lerp(this._headTarget.scale,A)),this.handLeft&&this._handLeftTarget&&(this.handLeft.position.lerp(this._handLeftTarget.position,A),this.handLeft.quaternion.slerp(this._handLeftTarget.quaternion,A),this.handLeft.scale.lerp(this._handLeftTarget.scale,A)),this.handRight&&this._handRightTarget&&(this.handRight.position.lerp(this._handRightTarget.position,A),this.handRight.quaternion.slerp(this._handRightTarget.quaternion,A),this.handRight.scale.lerp(this._handRightTarget.scale,A))}destroy(){var A,e;Ca&&console.log("Destroy avatar",this.guid),(A=this.root)==null||A.removeFromParent(),(e=this.avatarMarker)==null||e.destroy(),this.lastAvatarId=null,this.head&&lI.Remove(this.context,this.head)}updateVisibility(){const A=this.root;A&&IA.setActive(A,this._isVisible)}async setupCustomAvatar(A){var g,I,o;if(Ca&&console.log("LOAD",A,this),!A||typeof A=="string"&&A.length<=0)return!1;this.head&&lI.Remove(this.context,this.head);const e=A;if((e==null?void 0:e.loadAssetAsync)!==void 0){await e.loadAssetAsync();const s=e.asset;IA.setActive(s,!1),A=IA.instantiate(s),IA.setActive(A,!0)}Ca&&console.log(A);const t=await Bl.loader.getOrCreateNewAvatarInstance(this.context,A);if(Ca&&console.log(t,t==null?void 0:t.isValid,this.lastAvatarId,A),t!=null&&t.isValid){if(this.root=t.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=IA.addNewComponent(this.root,Qg),this.avatarMarker.connectionId=this.guid,this.avatarMarker.avatar=this,this.head&&this.head!==t.head&&((g=this.head)==null||g.removeFromParent()),this.head=t.head,this.headScale.copy(this.head.scale),this.head&&!this.isLocalAvatar&&lI.Add(this.context,this.head,this.avatarMarker),t.leftHand&&((I=this.handLeft)==null||I.removeFromParent()),this.handLeft=t.leftHand??this.handLeft,this.handLeft?this.handLeftScale.copy(this.handLeft.scale):this.handLeftScale.set(1,1,1),t.rigthHand&&((o=this.handRight)==null||o.removeFromParent()),this.handRight=t.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(...IA.getComponentsInChildren(this.root,Io)),this.flags.length<=0&&this.head){const s=IA.addNewComponent(this.head,Io);s.visibleIn=ki.ThirdPerson|ki.VR,this.flags.push(s),Ca&&console.log("Added flag to head: "+s.visibleIn,this.head.name)}return Ca&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return Ca&&console.warn("build avatar failed"),!1}};let In=Bl;r(In,"loader",new Ty),r(In,"invertRotation",new MA().setFromAxisAngle(new w(0,1,0),Math.PI));class lI{static Add(A,e,t=null){if(e){for(const g of this.Pois)if(g.obj===e)return;this.Pois.push({obj:e,avatar:t}),this.LastChangeTime=A.time.time}}static Remove(A,e){var t;if(e){for(const g of this.Pois)if(g.obj===e){this.Pois.splice(this.Pois.indexOf(g),1),this.LastChangeTime=(A==null?void 0:A.time.time)??((t=be.Current)==null?void 0:t.time.time);return}}}}r(lI,"Pois",[]),r(lI,"LastChangeTime",0);class egA{constructor(){r(this,"guid");r(this,"position",new w)}}class _l extends NA{constructor(){super(...arguments);r(this,"target",null);r(this,"avatar",null);r(this,"_model",null);r(this,"_targetModel",new egA);r(this,"_currentTargetObject",null);r(this,"_lastUpdateTime",0);r(this,"_lookDuration",0);r(this,"_lastPoiChangedTime",0)}set controlledTarget(e){this.target=e;const t=j.get("MoveRandom");if(t&&this.target){const g=IA.getComponent(this.target,t);g&&g.destroy()}}awake(){if(this.avatar=IA.getComponentInParent(this.gameObject,Qg),this.avatar){const e=IA.getComponentInParent(this.gameObject,Qg);this._model=new Cy(this.context.connection,this.guid),e!=null&&e.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{var t;this.target&&e&&e.guid===((t=this.avatar)==null?void 0:t.guid)&&Mi(this.target,e.position)})}update(){var t;if((!this.context.connection.isConnected||(t=this._model)!=null&&t.hasOwnership)&&(lI.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=lI.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const g=ce(this._currentTargetObject);Mi(this.target,g),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(g))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const t=lI.Pois;if(t.length>0){const g=t[Math.floor(Math.random()*t.length)];if(g&&g.obj){if(g.avatar&&g.avatar===this.avatar)return;this._currentTargetObject=g.obj}}}}}class Cc extends NA{constructor(){super(...arguments);r(this,"canGrab",!0)}onPointerClick(e){}}class ac extends NA{constructor(){super(...arguments);r(this,"isUsed",!0);r(this,"usedBy",null)}}var ng=(i=>(i[i.Average=0]="Average",i[i.Multiply=1]="Multiply",i[i.Minimum=2]="Minimum",i[i.Maximum=3]="Maximum",i))(ng||{}),Yy=(i=>(i[i.Discrete=0]="Discrete",i[i.Continuous=1]="Continuous",i))(Yy||{}),li=(i=>(i[i.None=0]="None",i[i.FreezePositionX=2]="FreezePositionX",i[i.FreezePositionY=4]="FreezePositionY",i[i.FreezePositionZ=8]="FreezePositionZ",i[i.FreezePosition=14]="FreezePosition",i[i.FreezeRotationX=16]="FreezeRotationX",i[i.FreezeRotationY=32]="FreezeRotationY",i[i.FreezeRotationZ=64]="FreezeRotationZ",i[i.FreezeRotation=112]="FreezeRotation",i[i.FreezeAll=126]="FreezeAll",i))(li||{}),XQ=(i=>(i[i.None=0]="None",i[i.X=2]="X",i[i.Y=4]="Y",i[i.Z=8]="Z",i[i.All=-1]="All",i))(XQ||{});const vg=function(i,A){return function(e,t,g){tgA(e,t,g,i,A)}};function tgA(i,A,e,t,g){if(!g&&!t&&!i.onValidate)return;if(e!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",i,A,e),mi("Invalid usage of validate decorator. Only fields can be validated. Property: "+A,Vo.Error);return}let I="";if(typeof A=="string"?I=A:I=A.name,i.__internalAwake){const o=Symbol(I),s=i.__internalAwake;i.__internalAwake=function(){var n;if(!this.onValidate){_e()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((n=i.constructor)==null?void 0:n.name)+'"');return}if(this[o]===void 0){this[o]=this[I];const C=this[I];if(C instanceof tA||C instanceof w||C instanceof Ae||C instanceof MA){const a=this[I];LR(a,()=>{this.onValidate(I)})}Object.defineProperty(this,I,{set:function(a){var B;if(this[NG]===!0)this[o]=a;else{t==null||t.call(this,a);const Q=this[o];this[o]=a,(B=this.onValidate)==null||B.call(this,I,Q)}},get:function(){return g==null||g.call(this),this[o]}})}s.call(this)}}}const igA=function(i){return function(A,e,t){let g="";typeof e=="string"?g=e:g=e.name;const I=i.prototype,o=Object.getOwnPropertyDescriptor(I,g);if(!(o!=null&&o.value)){console.warn("Can not apply prefix: type does not have method named",e,i);return}const s=o.value,n=A[g];Object.defineProperty(I,g,{value:function(...C){const a=n==null?void 0:n.call(this,...C);if(a instanceof Promise){a.then(B=>{if(B!==!1)return s.call(this,...C)});return}if(a!==!1)return s.call(this,...C)}})}};var ggA=Object.defineProperty,IgA=Object.getOwnPropertyDescriptor,es=(i,A,e,t)=>{for(var g=t>1?void 0:t?IgA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&ggA(A,e,g),g};class ogA{constructor(A,e){r(this,"positionChanged",!1);r(this,"rotationChanged",!1);r(this,"position");r(this,"quaternion");r(this,"_positionKeys",["x","y","z"]);r(this,"_quaternionKeys",["_x","_y","_z","_w"]);r(this,"mute",!1);r(this,"context");r(this,"obj");r(this,"_positionWatch");r(this,"_rotationWatch");this.context=e,this.obj=A}get isDirty(){return this.positionChanged||this.rotationChanged}reset(A=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,A){if(this.position)for(const e of this._positionKeys)delete this.position[e];if(this.quaternion)for(const e of this._quaternionKeys)delete this.quaternion[e]}}syncValues(){for(const A of this._positionKeys)this.position[A]=this.obj.position[A];for(const A of this._quaternionKeys)this.quaternion[A]=this.obj.quaternion[A]}applyValues(){if(this.positionChanged&&this.position)for(const A of this._positionKeys){const e=this.position[A];e!==void 0&&(this.obj.position[A]=e)}if(this.rotationChanged&&this.quaternion)for(const A of this._quaternionKeys){const e=this.quaternion[A];e!==void 0&&(this.obj.quaternion[A]=e)}}start(A,e){this.reset(),A&&(this._positionWatch||(this._positionWatch=new cC(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((I,o)=>{var n;if((n=this.context.physics.engine)!=null&&n.isUpdating||this.mute)return;const s=this.position[o];Math.abs(s-I)<1e-5||(this.position[o]=I,this.positionChanged=!0)})),e&&(this._rotationWatch||(this._rotationWatch=new cC(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((I,o)=>{var n;if((n=this.context.physics.engine)!=null&&n.isUpdating||this.mute)return;const s=this.quaternion[o];Math.abs(s-I)<1e-5||(this.quaternion[o]=I,this.rotationChanged=!0)}));const t=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),g=new FA;this.obj.matrixWorld.multiplyMatrices=(I,o)=>(g.equals(I)||(this.positionChanged=!0,this.rotationChanged=!0,g.copy(I)),t(I,o))}stop(){var A,e;(A=this._positionWatch)==null||A.revoke(),(e=this._rotationWatch)==null||e.revoke()}}var fm;const rM=(fm=class extends NA{constructor(){super(...arguments);r(this,"autoMass",!0);r(this,"_mass",0);r(this,"useGravity",!0);r(this,"constraints",li.None);r(this,"isKinematic",!1);r(this,"drag",0);r(this,"angularDrag",1);r(this,"detectCollisions",!0);r(this,"sleepThreshold",.01);r(this,"collisionDetectionMode",Yy.Discrete);r(this,"_gravityScale",1);r(this,"dominanceGroup",0);r(this,"_propertiesChanged",!1);r(this,"_currentVelocity",new w);r(this,"_smoothedVelocity",new w);r(this,"_smoothedVelocityGetter",new w);r(this,"_lastPosition",new w);r(this,"_watch")}set mass(A){A!==this._mass&&(this._mass=A,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var A,e;return this.autoMass?((e=(A=this.context.physics.engine)==null?void 0:A.getBody(this))==null?void 0:e.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&li.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&li.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&li.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&li.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&li.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&li.FreezeRotationZ)!==0}set lockPositionX(A){A?this.constraints|=li.FreezePositionX:this.constraints&=~li.FreezePositionX}set lockPositionY(A){A?this.constraints|=li.FreezePositionY:this.constraints&=~li.FreezePositionY}set lockPositionZ(A){A?this.constraints|=li.FreezePositionZ:this.constraints&=~li.FreezePositionZ}set lockRotationX(A){A?this.constraints|=li.FreezeRotationX:this.constraints&=~li.FreezeRotationX}set lockRotationY(A){A?this.constraints|=li.FreezeRotationY:this.constraints&=~li.FreezeRotationY}set lockRotationZ(A){A?this.constraints|=li.FreezeRotationZ:this.constraints&=~li.FreezeRotationZ}set gravityScale(A){this._gravityScale=A}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new ogA(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),Eg.LateUpdate)}onDisable(){var A,e;(A=this._watch)==null||A.stop(),(e=this.context.physics.engine)==null||e.removeBody(this)}onDestroy(){var A;(A=this.context.physics.engine)==null||A.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){var A,e,t,g;for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,(A=this.context.physics.engine)==null||A.updateProperties(this)),(e=this._watch)!=null&&e.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(t=this.context.physics.engine)==null||t.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(g=this._watch)==null||g.syncValues(),this.captureVelocity(),yield}teleport(A,e=!0){var t;(t=this._watch)==null||t.reset(!0),e?this.gameObject.position.set(A.x,A.y,A.z):this.setWorldPosition(A.x,A.y,A.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(A=!0){var e;(e=this.context.physics.engine)==null||e.resetForces(this,A)}resetTorques(A=!0){var e;(e=this.context.physics.engine)==null||e.resetTorques(this,A)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var A;(A=this.context.physics.engine)==null||A.wakeup(this)}applyForce(A,e,t=!0){var g;(g=this.context.physics.engine)==null||g.addForce(this,A,t)}applyImpulse(A,e=!0){var t;(t=this.context.physics.engine)==null||t.applyImpulse(this,A,e)}setForce(A,e,t,g=!0){var I,o,s;(I=this.context.physics.engine)==null||I.resetForces(this,g),typeof A=="number"?(e??(e=0),t??(t=0),(o=this.context.physics.engine)==null||o.addForce(this,{x:A,y:e,z:t},g)):(s=this.context.physics.engine)==null||s.addForce(this,A,g)}getVelocity(){var e;const A=(e=this.context.physics.engine)==null?void 0:e.getLinearVelocity(this);return A?(this._currentVelocity.x=A.x,this._currentVelocity.y=A.y,this._currentVelocity.z=A.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(A,e,t,g=!0){var I,o;if(A instanceof w){const s=A;(I=this.context.physics.engine)==null||I.setLinearVelocity(this,s,g);return}e===void 0||t===void 0||(o=this.context.physics.engine)==null||o.setLinearVelocity(this,{x:A,y:e,z:t},g)}getAngularVelocity(){var e;const A=(e=this.context.physics.engine)==null?void 0:e.getAngularVelocity(this);return A?(this._currentVelocity.x=A.x,this._currentVelocity.y=A.y,this._currentVelocity.z=A.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(A,e,t,g=!0){var I,o;if(A instanceof w){const s=A;(I=this.context.physics.engine)==null||I.setAngularVelocity(this,s,g);return}e===void 0||t===void 0||(o=this.context.physics.engine)==null||o.setAngularVelocity(this,{x:A,y:e,z:t},g)}setTorque(A,e,t){this.setAngularVelocity(A,e,t)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(A=null){}captureVelocity(){const A=ce(this.gameObject);rM.tempPosition.copy(A);const e=A.sub(this._lastPosition);this._lastPosition.copy(rM.tempPosition),this._smoothedVelocity.lerp(e,this.context.time.deltaTime/.1)}},r(fm,"tempPosition",new w),fm);let vt=rM;es([vg()],vt.prototype,"autoMass",2);es([D()],vt.prototype,"mass",1);es([vg(),D()],vt.prototype,"useGravity",2);es([vg(),D()],vt.prototype,"constraints",2);es([vg(),D()],vt.prototype,"isKinematic",2);es([vg(),D()],vt.prototype,"drag",2);es([vg(),D()],vt.prototype,"angularDrag",2);es([vg(),D()],vt.prototype,"detectCollisions",2);es([vg(),D()],vt.prototype,"sleepThreshold",2);es([vg(),D()],vt.prototype,"collisionDetectionMode",2);es([vg()],vt.prototype,"_gravityScale",2);es([vg()],vt.prototype,"dominanceGroup",2);class Qo{constructor(){r(this,"bb",null);r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(A,e,t,g){return A.prep(4,12),A.writeFloat32(g),A.writeFloat32(t),A.writeFloat32(e),A.offset()}}class tO{constructor(){r(this,"bb",null);r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}position(A){return(A||new Qo).__init(this.bb_pos,this.bb)}rotation(A){return(A||new Qo).__init(this.bb_pos+12,this.bb)}scale(A){return(A||new Qo).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(A,e,t,g,I,o,s,n,C,a){return A.prep(4,36),A.prep(4,12),A.writeFloat32(a),A.writeFloat32(C),A.writeFloat32(n),A.prep(4,12),A.writeFloat32(s),A.writeFloat32(o),A.writeFloat32(I),A.prep(4,12),A.writeFloat32(g),A.writeFloat32(t),A.writeFloat32(e),A.offset()}}class iC{constructor(){r(this,"bb",null);r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}static getRootAsSyncedTransformModel(A,e){return(e||new iC).__init(A.readInt32(A.position())+A.position(),A)}static getSizePrefixedRootAsSyncedTransformModel(A,e){return A.setPosition(A.position()+oy),(e||new iC).__init(A.readInt32(A.position())+A.position(),A)}guid(A){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,A):null}fast(){const A=this.bb.__offset(this.bb_pos,6);return A?!!this.bb.readInt8(this.bb_pos+A):!1}transform(A){const e=this.bb.__offset(this.bb_pos,8);return e?(A||new tO).__init(this.bb_pos+e,this.bb):null}dontSave(){const A=this.bb.__offset(this.bb_pos,10);return A?!!this.bb.readInt8(this.bb_pos+A):!1}static startSyncedTransformModel(A){A.startObject(4)}static addGuid(A,e){A.addFieldOffset(0,e,0)}static addFast(A,e){A.addFieldInt8(1,+e,0)}static addTransform(A,e){A.addFieldStruct(2,e,0)}static addDontSave(A,e){A.addFieldInt8(3,+e,0)}static endSyncedTransformModel(A){return A.endObject()}static finishSyncedTransformModelBuffer(A,e){A.finish(e)}static finishSizePrefixedSyncedTransformModelBuffer(A,e){A.finish(e,void 0,!0)}}const ga=sA("debugsync"),Ol="STRS";sy(Ol,iC.getRootAsSyncedTransformModel);const Ts=new ZE;function iO(i,A,e=!0){Ts.clear();const t=Ts.createString(i);iC.startSyncedTransformModel(Ts),iC.addGuid(Ts,t),iC.addFast(Ts,e);const g=A.worldPosition,I=A.worldEuler,o=A.gameObject.scale;iC.addTransform(Ts,tO.createTransform(Ts,g.x,g.y,g.z,I.x,I.y,I.z,o.x,o.y,o.z));const s=iC.endSyncedTransformModel(Ts);return Ts.finish(s,Ol),Ts.asUint8Array()}class ba extends NA{constructor(){super(...arguments);r(this,"overridePhysics",!0);r(this,"interpolatePosition",!0);r(this,"interpolateRotation",!0);r(this,"fastMode",!1);r(this,"syncDestroy",!1);r(this,"_model",null);r(this,"_needsUpdate",!0);r(this,"rb",null);r(this,"_wasKinematic",!1);r(this,"_receivedDataBefore",!1);r(this,"_targetPosition");r(this,"_targetRotation");r(this,"_receivedFastUpdate",!1);r(this,"_shouldRequestOwnership",!1);r(this,"joinedRoomCallback",null);r(this,"receivedDataCallback",null);r(this,"tempEuler",new $i);r(this,"receivedUpdate",!1);r(this,"lastWorldPos");r(this,"lastWorldRotation")}requestOwnership(){ga&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){var e;return((e=this._model)==null?void 0:e.hasOwnership)??void 0}isOwned(){var e;return(e=this._model)==null?void 0:e.isOwned}awake(){ga&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new w,this._targetRotation=new MA,this.lastWorldPos=new w,this.lastWorldRotation=new MA,this.rb=IA.getComponentInChildren(this.gameObject,vt),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Cy(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(Ht.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(Ol,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&mY(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(Ht.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(Ol,this.receivedDataCallback)}tryGetLastState(){const e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}onReceivedData(e){var t;if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){ga&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();const g=e.transform();if(g){Xg.markDirty(this.gameObject,!0);const I=g.position();I&&(this.interpolatePosition&&((t=this._targetPosition)==null||t.set(I.x(),I.y(),I.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(I.x(),I.y(),I.z()));const o=g.rotation();o&&(this.tempEuler.set(o.x(),o.y(),o.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&WR(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){ga&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const e=this.worldPosition,t=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const o=e.distanceTo(this.lastWorldPos),s=t.angleTo(this.lastWorldRotation),n=this._model.hasOwnership||this.fastMode?1e-4:.001;(o>n||s>n)&&(this._model.hasOwnership?this._needsUpdate=!0:(ga&&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),Xg.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const s=this._receivedFastUpdate||this.fastMode?.5:.3;let n=!1;if(this.interpolatePosition&&this._targetPosition){const C=this.worldPosition;C.lerp(this._targetPosition,s),this.worldPosition=C,n=!0}if(this.interpolateRotation&&this._targetRotation){const C=this.worldQuaternion;C.slerp(this._targetRotation,s),this.worldQuaternion=C,n=!0}n&&Xg.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&&(ga&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new w(0,0,0))>1e3&&(ga&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0)));const g=10,I=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%g===0||I)){ga&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this.overridePhysics&&this.rb,this._needsUpdate=!1;const o=iO(this.guid,this,!!I);this.context.connection.sendBinary(o)}}}const sgA=sA("debugshadowcomponents");IF.prototype.interactable={get(){return this.interactive},set(i){this.interactable=i}};const Yo=Symbol("shadowDomOwner");class ms extends NA{constructor(){super(...arguments);r(this,"shadowComponent",null);r(this,"_controlsChildLayout",!0);r(this,"_root");r(this,"_parentComponent")}isRoot(){var e;return((e=this.Root)==null?void 0:e.gameObject)===this.gameObject}get canvas(){const e=this.Root;return e!=null&&e.isCanvas?e:null}markDirty(){cI.markUIDirty(this.context)}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}get Root(){return this._root===void 0&&(this._root=IA.getComponentInParent(this.gameObject,zd)),this._root}get Canvas(){return this.canvas}__internalNewInstanceCreated(){super.__internalNewInstanceCreated(),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0}onEnable(){super.onEnable()}addShadowComponent(e,t){var o;this.removeShadowComponent();const g=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=IA.getComponentInParent(g,ms),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[Yo]=this,this.setShadowComponentOwner(e);let I=!1;if(((o=this.Root)==null?void 0:o.gameObject)===this.gameObject)this.gameObject.add(e);else{const s=this._parentComponent.shadowComponent;s&&(s==null||s.add(e),I=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),qd&&e.add(new jE(.5)),this.onAfterAddedToScene(),I&&L2(),sgA&&console.log(this.shadowComponent)}set(e){}setShadowComponentOwner(e){if(e&&(e[Yo]===void 0||e[Yo]===this)&&(e[Yo]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,g){if(e&&e[Yo]===t){g(e);for(const I of e.children)this.traverseOwnedShadowComponents(I,t,g)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class zd extends ms{awake(){super.awake()}}class LE{static getObject(A){const e=A[Yo];return e&&(e.isComponent===!0?A=e.gameObject:A=e),A}static isInteractable(A,e){if(e&&(e.canvasGroup=void 0,e.graphic=void 0),A==null||!A.visible||(A=this.getObject(A),!A.visible))return!1;const t=this.tryFindCanvasGroup(A);if((t==null?void 0:t.isCanvasGroup)===!0&&(e&&(e.canvasGroup=t),t.blocksRaycasts===!1||t.interactable===!1))return!1;const g=EB(A,I=>{if(I.isGraphic===!0)return I},!1);return e&&(g==null?void 0:g.isGraphic)===!0&&(e.graphic=g),!((g==null?void 0:g.raycastTarget)===!1||(g==null?void 0:g.layer)===2)}static tryFindCanvasGroup(A){if(!A)return null;const e=EB(A,t=>{const g=t;if(g.blocksRaycasts!==void 0&&g.interactable!==void 0)return g},!1);return e!==void 0?e:this.tryFindCanvasGroup(A.parent)}}const Mh=sA("debugwebxrcontroller");var EE=(i=>(i[i.PhysicalDevice=0]="PhysicalDevice",i[i.Touch=1]="Touch",i))(EE||{}),jn=(i=>(i.SelectStart="select-start",i.SelectEnd="select-end",i.Update="update",i))(jn||{});class Hy extends NA{}const Cg=class extends NA{constructor(){super(...arguments);r(this,"webXR");r(this,"index",-1);r(this,"controllerModel");r(this,"controller");r(this,"controllerGrip");r(this,"hand");r(this,"handPointerModel");r(this,"grabbed",null);r(this,"input",null);r(this,"type",0);r(this,"showRaycastLine",!0);r(this,"enableRaycasts",!0);r(this,"enableDefaultControls",!0);r(this,"_wristQuaternion",null);r(this,"movementVector",new w);r(this,"worldRot",new MA);r(this,"joystick",new tA);r(this,"didRotate",!1);r(this,"didTeleport",!1);r(this,"didChangeScale",!1);r(this,"lastHit",null);r(this,"raycastLine",null);r(this,"_raycastHitPoint",null);r(this,"_connnectedCallback",null);r(this,"_disconnectedCallback",null);r(this,"_selectStartEvt",null);r(this,"_selectEndEvt",null);r(this,"_selectionPressed",!1);r(this,"_selectionPressedLastFrame",!1);r(this,"_selectionStartTime",0);r(this,"_selectionEndTime",0);r(this,"_useSmoothing",!0);r(this,"_isConnected",!1);r(this,"rayRotation",new MA);r(this,"_pinchStartTime");r(this,"selectStartCallback",null);r(this,"lastSelectStartObject",null);r(this,"_didNotEndSelection",!1);r(this,"closeGrabBoundingBoxHelper")}static CreateRaycastLine(){const e=new yi(this.geometry),t=e.material;return t.color=this.raycastColor,e.layers.set(2),e.name="line",e.scale.z=1,e}static CreateRaycastHitPoint(){const e=new $o(.5,22,22),t=new rt({color:this.raycastColor}),g=new pA(e,t);return g.visible=!1,g.layers.set(2),g}static Create(e,t,g,I){const o=g?IA.addNewComponent(g,Cg,!1):new Cg;o.webXR=e,o.index=t,o.type=I;const s=e.context;o.controller=s.renderer.xr.getController(t),o.controllerGrip=s.renderer.xr.getControllerGrip(t),o.controllerModel=this.Factory.createControllerModel(o.controller),o.controllerGrip.add(o.controllerModel),o.hand=s.renderer.xr.getHand(t);const n=new ic;xd(n,s),o.webXR.handModelPath&&o.webXR.handModelPath!==""?n.setPath(FC(e.sourceId,o.webXR.handModelPath)):n.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/");const C=new FiA(o.hand,n);return o.hand.add(C),o.hand.traverse(a=>a.layers.set(2)),o.handPointerModel=new LiA(o.hand,o.controller),o.controller.addEventListener("connected",a=>{o.setControllerLayers(o.controllerModel,2),o.setControllerLayers(o.controllerGrip,2),o.setControllerLayers(o.hand,2),setTimeout(()=>{o.setControllerLayers(o.controllerModel,2),o.setControllerLayers(o.controllerGrip,2),o.setControllerLayers(o.hand,2)},1e3)}),o.hand.addEventListener("connected",a=>{var Q;if(a.data.hand){e.Rig&&e.Rig.add(o.hand),o.type=0,o.handPointerModel.traverse(c=>c.layers.set(2)),(Q=o.handPointerModel.pointerObject)==null||Q.traverse(c=>c.layers.set(2));const E=o.hand.joints;if(E)for(const c of Object.keys(E)){const d=E[c];d.parent||o.hand.add(d)}}}),o}static addEventListener(e,t){const g=this.eventSubs[e]??[];g.push(t),this.eventSubs[e]=g}static removeEventListener(e,t){if(!t)return;const g=this.eventSubs[e]??[],I=g.indexOf(t);I>=0&&g.splice(I,1),this.eventSubs[e]=g}get isUsingHands(){var t;const e=(t=this.input)==null?void 0:t.hand;return e!=null}get wrist(){if(!this.hand)return null;const e=this.hand.joints;return e?e.wrist:null}getWristQuaternion(){const e=this.wrist;return e?(this._wristQuaternion||(this._wristQuaternion=new MA),Ft(e).multiply(this._wristQuaternion.setFromEuler(new $i(-Math.PI/4,0,0)))):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}get useSmoothing(){return this._useSmoothing}awake(){if(!this.controller){console.warn("WebXRController: Missing controller object.",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(){var e,t,g;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)),(e=this.hand)==null||e.clear(),(t=this.controllerGrip)==null||t.clear(),(g=this.controller)==null||g.clear()}onEnable(){var e,t,g,I,o;if(!this.webXR){console.warn("No WebXR component assigned to WebXRController.");return}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=Cg.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=Cg.CreateRaycastHitPoint()),(e=this.webXR.Rig)==null||e.add(this.hand),(t=this.webXR.Rig)==null||t.add(this.controllerGrip),(g=this.webXR.Rig)==null||g.add(this.controller),(I=this.webXR.Rig)==null||I.add(this.raycastLine),(o=this.raycastLine)==null||o.add(this._raycastHitPoint),this._raycastHitPoint.visible=!1,this.hand.add(this.handPointerModel),Mh&&console.log("ADDED TO RIG",this.webXR.Rig)}onDisable(){var e,t,g,I,o;if((e=this.hand)==null||e.removeFromParent(),(t=this.controllerGrip)==null||t.removeFromParent(),(g=this.controller)==null||g.removeFromParent(),(I=this.raycastLine)==null||I.removeFromParent(),(o=this._raycastHitPoint)==null||o.removeFromParent(),this.webXR){const s=this.webXR.Controllers.indexOf(this);s>=0&&this.webXR.Controllers.splice(s,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()}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.input=null}createPointerEvent(e){switch(e){case"down":this.context.input.createPointerDown(new Vn(wi.PointerDown,null,{clientX:0,clientY:0,button:this.index,pointerType:RE.Touch}));break;case"move":break;case"up":this.context.input.createPointerUp(new Vn(wi.PointerUp,null,{clientX:0,clientY:0,button:this.index,pointerType:RE.Touch}));break}}raycastUpdate(e,t){const g=this.showRaycastLine&&this.type!==1;if(this.type===1)e.visible=!1;else if(this.isUsingHands){e.visible=!this.grabbed&&g,Mi(e,t);const I=this.hand.joints;if(I&&I.wrist&&this.grabbed&&this.grabbed.isCloseGrab){const s=this.getWristQuaternion();s&&this.rayRotation.copy(s)}uI(e,this.rayRotation)}else e.visible=g,uI(e,this.rayRotation),Mi(e,t)}update(){if(!this.webXR)return;this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));const e=Cg.eventSubs.update;if(e&&e.length>0)for(const I of e)I(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(Ft(this.controller),this.useSmoothing?t:1);const g=ce(this.controller);this.isUsingHands&&this.handPointerModel.cursorObject&&(this.handPointerModel.cursorObject.visible=!1),this.enableRaycasts?(this.raycastLine&&this.raycastUpdate(this.raycastLine,g),this.lastHit=this.updateLastHit(),this.grabbed&&this.grabbed.update()):this.raycastLine&&(this.raycastLine.visible=!1),this._selectionPressedLastFrame=this._selectionPressed,this.selectStartCallback&&this.selectStartCallback()}onUpdate(e){var I,o;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;const t=this.webXR.Rig;if(!t)return;this._didNotEndSelection&&!this.handPointerModel.pinched&&(this._didNotEndSelection=!1,this.onSelectEnd()),this.updateStick(this.input);const g=(o=(I=this.input)==null?void 0:I.gamepad)==null?void 0:o.buttons;if(this.enableDefaultControls)switch(this.input.handedness){case"left":this.movementUpdate(t,g);break;case"right":this.rotationUpdate(t,g);break}}movementUpdate(e,t){const g=3*Cg.MovementSpeedFactor,I=2,o=ne.clamp01(this.joystick.length()*2),s=this.joystick.x>0?1:-1;let n=Math.pow(this.joystick.x,I);n*=s,n*=o;const C=this.joystick.y>0?1:-1;let a=Math.pow(this.joystick.y,I);a*=C,n*=o,e.getWorldQuaternion(this.worldRot),this.movementVector.set(n,0,a),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),this.movementVector.multiplyScalar(g*this.context.time.deltaTime),e.position.add(this.movementVector),this.isUsingHands&&this.runTeleport(e,t)}rotationUpdate(e,t){const g=this.joystick.x,I=Math.abs(g);if(I<.4)this.didRotate=!1;else if(I>.5&&!this.didRotate){const o=g>0?-1:1;e.rotateY(ne.toRadians(30*o)),this.didRotate=!0}this.runTeleport(e,t)}runTeleport(e,t){var a,B;let g=-this.joystick.y;if((a=this.hand)!=null&&a.visible&&!this.grabbed){const Q=this.handPointerModel.isPinched();Q&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),Q&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(g=this.handPointerModel.isPinched()?1:0),Q||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;const I=this.webXR.IsInVR,o=this.webXR.Rig;let s=g>.5&&I,n=o?((B=o==null?void 0:o.scale)==null?void 0:B.x)<.999:!1,C=null;if(t&&this.input&&!this.input.hand)for(let Q=0;Q<t.length;Q++){const E=t[Q];if(Q===4)if(E.pressed&&!this.didChangeScale&&I){this.didChangeScale=!0;const c=o;if(c){const d=this.switchScale(c,s,n,C);s=d.doTeleport,n=d.isInMiniatureMode,C=d.newRigScale}}else E.pressed||(this.didChangeScale=!1)}if(s){if(!this.didTeleport){const Q=this.raycast();if(this.didTeleport=!0,Q&&Q.length>0){const E=Q[0];if(n||this.isValidTeleportTarget(E.object)){const c=E.point;Mi(e,c)}}}}else g<.1&&(this.didTeleport=!1);C!==null&&(e.scale.set(C,C,C),e.updateMatrixWorld())}isValidTeleportTarget(e){return IA.getComponentInParent(e,Hy)!=null}switchScale(e,t,g,I){if(g){g=!1,e.scale.set(1,1,1),I=1,Cg.MovementSpeedFactor=1;const o=this.context.mainCamera;Cg.PreviousCameraFarDistance&&(o.far=Cg.PreviousCameraFarDistance)}else{g=!0,t=!0,I=.1,Cg.MovementSpeedFactor=I*2;const o=this.context.mainCamera;Cg.PreviousCameraFarDistance=o.far,o.far/=I}return{doTeleport:t,isInMiniatureMode:g,newRigScale:I}}updateStick(e){var t;!e||!e.gamepad||((t=e.gamepad.axes)==null?void 0:t.length)<4||(this.joystick.x=e.gamepad.axes[2],this.joystick.y=e.gamepad.axes[3])}updateLastHit(){var I;const e=this.raycast(),t=e?e[0]:null;this.lastHit=t;let g=1;if(this.webXR.Rig&&(g/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=g*(((I=this.lastHit)==null?void 0:I.distance)??9999);const o=this.raycastLine.material;t!=null?o.color=Cg.raycastColor:o.color=Cg.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;const o=ne.clamp(this.lastHit.distance*.01*g,.015,.1);this._raycastHitPoint.scale.set(o,o,o)}this._raycastHitPoint.visible=this.lastHit!==null&&this.lastHit!==void 0}return t}onSelectStart(){this.context.connection.allowEditing&&(this.selectStartCallback=()=>this.onHandleSelectStart())}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(),Mh&&console.log("onHandleSelectStart","close grab? "+t,"intersections",e),e&&e.length>0)for(const g of e){const I=g.object;this.lastSelectStartObject=I;const o={selected:I,grab:I},s=Cg.eventSubs["select-start"];if(s&&s.length>0)for(const n of s)n(this,o);o.grab!==I&&Mh&&console.log("Grabbed object changed","original",I,"new",o.grab),o.grab&&(this.grabbed=Oo.TryTake(this,o.grab,g,t));break}else{const g=Cg.eventSubs["select-start"],I={selected:null,grab:null};if(g&&g.length>0)for(const o of g)o(this,I)}}onSelectEnd(){var g;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;const e={grab:((g=this.grabbed)==null?void 0:g.selected)??this.lastSelectStartObject},t=Cg.eventSubs["select-end"];if(t&&t.length>0)for(const I of t)I(this,e);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(e){return!(!e||IA.isActiveInHierarchy(e)===!1||LE.isInteractable(e)===!1)}setControllerLayers(e,t){var g,I;if(e&&(e.layers.set(t),e.children))for(const o of e.children)((g=this.grabbed)==null?void 0:g.selected)===o||((I=this.grabbed)==null?void 0:I.selectedMesh)===o||this.setControllerLayers(o,t)}getRay(){const e=new Us;return e.origin.copy(ce(this.controller)),e.direction.set(0,0,-1).applyQuaternion(this.rayRotation),e}overlap(){const e=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(Mh&&(!this.closeGrabBoundingBoxHelper&&e&&(this.closeGrabBoundingBoxHelper=new gy(e,16776960),this.scene.add(this.closeGrabBoundingBoxHelper)),this.closeGrabBoundingBoxHelper&&e&&this.closeGrabBoundingBoxHelper.setFromObject(e)),!e)return new Array;const t=ce(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){const e=new ro;e.layerMask=new jg,e.layerMask.enableAll(),e.layerMask.disable(2),e.ray=this.getRay();const t=this.context.physics.raycast(e);for(let g=0;g<t.length;g++){const I=t[g],o=I.object;if(!this.testIsVisible(o)){t.splice(g,1),g--;continue}I.object=LE.getObject(o);break}return t}};let Bi=Cg;r(Bi,"Factory",new ZiA),r(Bi,"raycastColor",new yA(.9,.3,.3)),r(Bi,"raycastNoHitColor",new yA(.6,.6,.6)),r(Bi,"geometry",new de().setFromPoints([new w(0,0,0),new w(0,0,-1)])),r(Bi,"handModels",{}),r(Bi,"eventSubs",{}),r(Bi,"PreviousCameraFarDistance"),r(Bi,"MovementSpeedFactor",1);var jD=(i=>(i.WillTake="WillTake",i.DidTake="DidTake",i.WillFree="WillFree",i.DidFree="DidFree",i))(jD||{});const CI=class{constructor(){r(this,"sync",null);r(this,"selected",null);r(this,"selectedParent",null);r(this,"selectedMesh",null);r(this,"controller",null);r(this,"grabTime",0);r(this,"grabUUID","");r(this,"isCloseGrab",!1);r(this,"originalMaterial",null);r(this,"usageMarker",null);r(this,"rigidbodies",null);r(this,"didReparent",!1);r(this,"grabDistance",0);r(this,"interactable",null);r(this,"positionSource",null);r(this,"grabPoint",new w);r(this,"localPositionOffsetToGrab",null);r(this,"localPositionOffsetToGrab_worldSpace",new w);r(this,"localQuaternionToGrab",new MA(0,0,0,1));r(this,"targetDir",null);r(this,"quaternionLerp",null);r(this,"controllerDir",new w);r(this,"controllerWorldPos",new w);r(this,"lastControllerWorldPos",new w);r(this,"controllerPosDelta",new w);r(this,"totalChangeAlongDirection",0);r(this,"rigPositionLastFrame",new w)}static AddEventListener(A,e){return CI.Events[A]||(CI.Events[A]=[]),CI.Events[A].push(e),e}static RemoveEventListener(A,e){if(!e||!CI.Events[A])return;const t=CI.Events[A].indexOf(e);t>=0&&CI.Events[A].splice(t,1)}static Register(A){this.Current.find(e=>e===A)||this.Current.push(A)}static Remove(A){const e=this.Current.indexOf(A);e>=0&&this.Current.splice(e,1)}static TryTake(A,e,t,g){const I=IA.getComponentInParent(e,Cc);if(I)e=I.gameObject;else return Mh&&console.warn("Prevented taking object that is not interactable",e),null;let o=e;const s=IA.getComponentInParent(e,ba);s&&(s.requestOwnership(),o=s.gameObject);for(const C of this.Current)if(C.selected===o)return C.controller===A||(C.free(),C.Take(A,o,e,s,I,t,g)),C;const n=new CI;return n.Take(A,o,e,s,I,t,g),n}Take(A,e,t,g,I,o,s){var E,c;if(console.assert(e!==null,"Expected object to be taken but was",e),A.isUsingHands?this.positionSource=s?A.wrist:A.controller:this.positionSource=A.controller,!this.positionSource)return console.warn("No position source"),this;const n={controller:A,take:e,hit:t,sync:g,interactable:I};(E=CI.Events.WillTake)==null||E.forEach(d=>d(this,n));const C=t;C!=null&&C.material&&(this.originalMaterial=C.material,Array.isArray(C.material)||(C.material=C.material.clone(),C.material&&C.material.emissive&&(C.material.emissive.b=.2))),this.selected=e,this.selectedParent||(this.selectedParent=e.parent),this.selectedMesh=C,this.controller=A,this.interactable=I,this.isCloseGrab=s,this.didReparent=!1,this.sync=g,this.grabTime=A.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=IA.addNewComponent(this.selected,ac),this.rigidbodies=IA.getComponentsInChildren(this.selected,vt),ce(this.positionSource,this.lastControllerWorldPos);const a=()=>s?this.lastControllerWorldPos.clone():o.point.clone();this.grabDistance=a().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(a());const B=A.isUsingHands&&s?this.controller.getWristQuaternion().clone():A.rayRotation.clone();Ft(this.selected,this.localQuaternionToGrab).premultiply(B.invert());const Q=this.controller.webXR.Rig;return Q&&this.rigPositionLastFrame.copy(ce(Q)),lI.Add(A.context,this.selected),CI.Register(this),this.sync&&(this.sync.fastMode=!0),(c=CI.Events.DidTake)==null||c.forEach(d=>d(this,n)),this}free(){var g,I,o,s;if(!this.selected)return;const A={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};(g=CI.Events.WillFree)==null||g.forEach(n=>n(this,A)),lI.Remove(this.controller.context,this.selected),CI.Remove(this),this.sync&&(this.sync.fastMode=!1);const e=this.selectedMesh;e&&this.originalMaterial&&e.material&&(e.material=this.originalMaterial);const t=this.selected;if(this.didReparent&&t.parent){const n=this.selectedParent;n?n.attach(t):(I=this.controller)==null||I.context.scene.attach(t)}if((o=this.usageMarker)==null||o.destroy(),this.controller&&(this.controller.grabbed=null),this.selected=null,this.selectedParent=null,this.selectedMesh=null,this.sync=null,this.rigidbodies)for(const n of this.rigidbodies)n.wakeUp(),n.setVelocity(n.smoothedVelocity);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,(s=CI.Events.DidFree)==null||s.forEach(n=>n(this,A))}controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),ce(this.positionSource,this.controllerWorldPos),this.controllerPosDelta.copy(this.controllerWorldPos),this.controllerPosDelta.sub(this.lastControllerWorldPos),this.lastControllerWorldPos.copy(this.controllerWorldPos);const A=this.controller.webXR.Rig;if(A){const t=ce(A),g=this.rigPositionLastFrame.sub(t);this.controllerPosDelta.add(g),this.rigPositionLastFrame.copy(t)}return this.controllerDir.dot(this.controllerPosDelta)}update(){var A;if(this.rigidbodies)for(const 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){const e=((A=this.controller.webXR.Rig)==null?void 0:A.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 w),this.targetDir.set(0,0,-this.grabDistance*t);const g=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),I=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=I.clone()),this.quaternionLerp.slerp(I,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),uI(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(g),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(ce(this.selected)),g.sub(this.localPositionOffsetToGrab_worldSpace)),Mi(this.selected,g)}if(this.rigidbodies!=null)for(const e of this.rigidbodies)e.wakeUp();Xg.markDirty(this.selected,!0)}}};let Oo=CI;r(Oo,"Events",{}),r(Oo,"Current",[]);class CC{constructor(A,e){r(this,"used",!1);r(this,"inputSource");r(this,"object");r(this,"point");r(this,"normal");r(this,"face");r(this,"distance");r(this,"instanceId");r(this,"pointerId");r(this,"isDown");r(this,"isUp");r(this,"isPressed");r(this,"isClicked");r(this,"button");r(this,"input");r(this,"_event");this._event=e,this.input=A,this.button=(e==null?void 0:e.button)??0}use(){this.used=!0,this.pointerId!==void 0&&this.input.setPointerUsed(this.pointerId)}stopPropagation(){var A;(A=this._event)==null||A.stopImmediatePropagation()}Use(){this.use()}StopPropagation(){var A;(A=this._event)==null||A.stopImmediatePropagation()}get event(){return this._event}clone(){const A=new CC(this.input,this._event);return Object.assign(A,this),A}}function BM(i){return IA.foreachComponent(i,e=>{const t=e;if(t.onPointerDown||t.onPointerUp||t.onPointerEnter||t.onPointerExit||t.onPointerClick)return!0},!1)===!0}var ngA=Object.defineProperty,CgA=Object.getOwnPropertyDescriptor,agA=(i,A,e,t)=>{for(var g=t>1?void 0:t?CgA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&ngA(A,e,g),g};class $a extends NA{awake(){cI.createIfNoneExists(this.context)}onEnable(){var A;(A=cI.get(this.context))==null||A.register(this)}onDisable(){var A;(A=cI.get(this.context))==null||A.unregister(this)}performRaycast(A=null){return null}}class Gs extends $a{constructor(){super(...arguments);r(this,"targets",null);r(this,"raycastHits",[]);r(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??(e=new ro),e.targets=this.targets,e.results=this.raycastHits;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=I=>I instanceof ws?"continue in children":t?t(I):!0);const g=this.context.physics.raycast(e);return e.testObject=t,g}}agA([D()],Gs.prototype,"ignoreSkinnedMeshes",2);class _y extends Gs{constructor(){super(),this.ignoreSkinnedMeshes=!0}}function Oy(i){const A=i[Yo];return A||(i.parent?Oy(i.parent):null)}function rgA(i){return i.isUI===!0||typeof i[Yo]=="object"}function ZD(i,A){if(!i)return;const e=i.material;if((e==null?void 0:e.isMaterial)===!0){const t=i.parent;t&&t.isText,e.side=A.doubleSided??!0?St:$g,e.shadowSide=A.doubleSided?St:$g,i.castShadow=A.castShadows?A.castShadows:!1,i.receiveShadow=A.receiveShadows?A.receiveShadows:!1}for(const t of i.children)ZD(t,A)}function xQ(i,A,e){i[A]===void 0&&console.warn("Field",A,"is undefined on",i);const t=Proxy.revocable(i[A],{set(o,s,n,C){const a=o[s],B=Reflect.set(o,s,n,C);return e(n,a),B}}),g=t.revoke,I=i[A];return t.revoke=()=>{i[A]=I,g()},i[A]=t.proxy,t}const eb=Symbol("Scheduled action");function BgA(i,A,e=Eg.OnBeforeRender){let t=i[eb];t||(t=i[eb]={});const g=A.name;t[e]||(t[e]={});const I=t[e];if(I[g])return;function*s(){A==null||A.call(i),I[g]=null}const n=i.startCoroutine(s(),e);I[g]=n}const br=sA("debugeventsystem");var QM=(i=>(i.BeforeHandleInput="BeforeHandleInput",i.AfterHandleInput="AfterHandleInput",i))(QM||{});const Ps=class extends NA{constructor(){super();r(this,"raycaster",[]);r(this,"_selectStartFn");r(this,"_selectEndFn");r(this,"_selectUpdateFn");r(this,"_handleEventCycleFn");r(this,"_handleInputFn");r(this,"pressedByID",new Map);r(this,"hoveredByID",new Map);r(this,"_sortedHits",[]);r(this,"_testObjectsCache",new Map);r(this,"shouldRaycastObject",e=>{var I;let t=null;if(rgA(e)&&(t=(I=e[Yo])==null?void 0:I.gameObject),this._testObjectsCache.has(e)||t&&this._testObjectsCache.has(t))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let o=BM(e);return!o&&t&&(o=BM(t)),o?(this._testObjectsCache.set(e,!0),e.traverse(s=>{this._testObjectsCache.set(s,!0)}),!0):(this._testObjectsCache.set(e,!1),"continue in children")}});r(this,"_sortingBuffer",[]);r(this,"_noDepthTestingResults",[]);r(this,"out",{});r(this,"currentActiveMeshUIComponents",[]);Ps.systems.push(this)}static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Ps.systems.length<=0&&Ps.systems.push(...IA.findObjectsOfType(Ps,e)));for(const g of Ps.systems)if(g.context===e)return;const t=new SA;IA.addNewComponent(t,Ps),e.scene.add(t)}static get systems(){const e=be.Current;return this._eventSystemMap.has(e)||this._eventSystemMap.set(e,[]),this._eventSystemMap.get(e)}static get(e){const t=this._eventSystemMap.get(e);return t&&t.length>0?t[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(e,t,g=!1){Zn.update(e,t,g)}static markUIDirty(e){Zn.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}onDestroy(){Ps.systems.splice(Ps.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!IA.findObjectOfType($a,this.context)){const t=IA.addNewComponent(this.context.scene,Gs);t.ignoreSkinnedMeshes=!0,this.raycaster.push(t),(_e()||br)&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found. Skinnedmeshes will be ignored for better performance")}}register(e){var t;e&&this.raycaster&&!this.raycaster.includes(e)&&((t=this.raycaster)==null||t.push(e))}unregister(e){var g,I;const t=(g=this.raycaster)==null?void 0:g.indexOf(e);t!==void 0&&t!==-1&&((I=this.raycaster)==null||I.splice(t,1))}onEnable(){const e=new Map;this._selectStartFn??(this._selectStartFn=(g,I)=>{if(!I.grab)return;Zn.resetLastSelected();const o=new CC(this.context.input);o.inputSource=g,o.pointerId=0,o.isDown=g.selectionDown,o.isUp=g.selectionUp,o.isPressed=g.selectionPressed,o.isClicked=!1,e.set(g,I.grab),I.grab&&!this.handleEventOnObject(I.grab,o)&&(I.grab=null)}),this._selectEndFn??(this._selectEndFn=(g,I)=>{var n;if(!I.grab)return;const o=new CC(this.context.input);o.inputSource=g,o.pointerId=0,o.isDown=g.selectionDown,o.isUp=g.selectionUp,o.isPressed=g.selectionPressed,o.isClicked=g.selectionClick,this.handleEventOnObject(I.grab,o);const s=e.get(g);if(e.set(g,null),s)for(const C of this.pressedByID.keys()){const a=this.pressedByID[C];a.obj===s&&a.handler&&((n=a.handler.onPointerUp)==null||n.call(a.handler,o),this.pressedByID.delete(C))}});const t=new ro;this._selectUpdateFn??(this._selectUpdateFn=g=>{var s;t.ray=g.getRay();const I=this.performRaycast(t);if(!I)return;const o=new CC(this.context.input);o.inputSource=g,o.pointerId=((s=g.input)==null?void 0:s.handedness)==="right"?0:1,o.isDown=g.selectionDown,o.isUp=g.selectionUp,o.isPressed=g.selectionPressed,o.isClicked=g.selectionClick,this.handleIntersections(I,o)}),Bi.addEventListener(jn.SelectStart,this._selectStartFn),Bi.addEventListener(jn.SelectEnd,this._selectEndFn),Bi.addEventListener(jn.Update,this._selectUpdateFn),this._handleInputFn=this.onPointerEvent.bind(this),this.context.input.addEventListener(wi.PointerDown,this._handleInputFn),this.context.input.addEventListener(wi.PointerUp,this._handleInputFn),this.context.input.addEventListener(wi.PointerMove,this._handleInputFn)}onDisable(){Bi.removeEventListener(jn.SelectStart,this._selectStartFn),Bi.removeEventListener(jn.SelectEnd,this._selectEndFn),Bi.removeEventListener(jn.Update,this._selectUpdateFn),this.context.input.removeEventListener(wi.PointerDown,this._handleInputFn),this.context.input.removeEventListener(wi.PointerUp,this._handleInputFn),this.context.input.removeEventListener(wi.PointerMove,this._handleInputFn)}onBeforeRender(){this.resetMeshUIStates()}onPointerEvent(e){if(e===void 0)return;const t=e.pointerType==RE.Touch?e.button:0,g=new CC(this.context.input,e);g.inputSource=this.context.input,g.pointerId=e.button,g.isClicked=e.type==wi.PointerUp&&this.context.input.getPointerClicked(e.button),g.isDown=e.type==wi.PointerDown,g.isUp=e.type==wi.PointerUp,g.isPressed=this.context.input.getPointerPressed(e.button),br&&g.isClicked&&console.log("CLICK",g.pointerId);const I=new ro;I.screenPoint=this.context.input.getPointerPositionRC(t);const o=this.performRaycast(I);if(!o)return;br&&g.isClicked&&mi("EventSystem: "+g.pointerId+" - "+this.context.time.frame+" - Up:"+g.isUp+", Down:"+g.isDown);const s={sender:this,args:g,hasActiveUI:this.currentActiveMeshUIComponents.length>0};if(this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:s})),!this.handleIntersections(o,g)){const n=this.hoveredByID.get(t);if(n&&this.triggerOnExit(n.obj,n.data),this.hoveredByID.delete(t),g.isUp){const C=this.pressedByID.get(t);C==null||C.handlers.forEach(a=>{var B;return(B=a.onPointerUp)==null?void 0:B.call(a,g)}),this.pressedByID.delete(t)}}this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:s}))}performRaycast(e){if(!this.raycaster)return null;this._sortedHits.length=0,e||(e=new ro),this._testObjectsCache.clear(),e.testObject=this.shouldRaycastObject;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;const g=t.performRaycast(e);g&&g.length>0&&this._sortedHits.push(...g)}return this._sortedHits.sort((t,g)=>t.distance-g.distance),this._sortedHits}handleIntersections(e,t){if(!e||e.length<=0)return!1;e=this.sortCandidates(e);for(const g of e){const{object:I}=g;if(t.point=g.point,t.normal=g.normal,t.face=g.face,t.distance=g.distance,t.instanceId=g.instanceId,this.handleEventOnObject(I,t))return!0}return!1}sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const g=e[t],I=g.object;if(I.material&&I.material.depthTest===!1){this._noDepthTestingResults.push(g);continue}this._sortingBuffer.push(g)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClicked&&br&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return br&&console.warn("Event without pointer can't be handled",t),!1;t.object=e;const g=e.parent;let I=!1;const o=t.isClicked??!1;let s=null;if(g&&g.isUI){const B=(t.isPressed||t.isClicked)??!1;if(g[Yo]){const Q=g[Yo].gameObject;if(Q){if(!LE.isInteractable(Q,this.out))return!1;s=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,B),e=Q,I=!0}}if(!I&&this.handleMeshUiObjectWithoutShadowDom(g,B))return!0}o&&br&&console.log(this.context.time.frame,e);const n=this.hoveredByID.get(t.pointerId),C=(n==null?void 0:n.obj)!==e;C&&(n!=null&&n.obj)&&this.triggerOnExit(n.obj,n.data);const a=this.hoveredByID.get(t.pointerId);if(a?(a.obj=e,a.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const B=this.pressedByID.get(t.pointerId);B?(B.obj=e,B.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(s===null||s.interactable)&&this.handleMainInteraction(e,t,C),!0}propagate(e,t,g){for(;;){if(t.used)return;if(IA.foreachComponent(e,I=>{g(I)},!1),!e.parent)break;e=e.parent}}handleMainInteraction(e,t,g){if(t.pointerId===void 0)return;const I=this.pressedByID.get(t.pointerId);this.propagate(e,t,o=>{var B;const s=o;if(s.interactable===!1)return;s.onPointerEnter&&g&&s.onPointerEnter(t),t.isDown&&s.onPointerDown&&(s.onPointerDown(t),I==null||I.handlers.add(s));const n=this.context.input.getPointerPositionLastFrame(t.pointerId),C=this.context.input.getPointerPosition(t.pointerId);n&&!ne.approximately(n,C)&&s.onPointerMove&&s.onPointerMove(t),t.isUp&&(s.onPointerUp&&(s.onPointerUp(t),I==null||I.handlers.delete(s)),s.onPointerExit&&((B=t.event)==null?void 0:B.pointerType)===RE.Touch&&(s.onPointerExit(t),this.hoveredByID.delete(t.pointerId))),t.isClicked&&s.onPointerClick&&s.onPointerClick(t)}),t.isUp&&(I==null||I.handlers.forEach(o=>{o.onPointerUp&&o.onPointerUp(t)}),this.pressedByID.delete(t.pointerId))}triggerOnExit(e,t){t.used=!1,this.propagate(e,t,g=>{if(!g.gameObject||g.destroyed)return;const I=g;I.onPointerExit&&I.onPointerExit(t)})}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}handleMeshUIIntersection(e,t){const g=Zn.updateState(e,t);return g&&this.currentActiveMeshUIComponents.push(g),g!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Zn.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];Zn.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?IA.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}};let cI=Ps;r(cI,"_eventSystemMap",new Map),r(cI,"didSearchEventSystem",!1);class Zn{static markDirty(){this.needsUpdate=!0}static update(A,e,t=!1){if(t){A.update();return}const g=e.time.frameCount;for(const I of this.lastUpdateFrame)if(I.context===e){if(g===I.frame)return;I.frame=g;let o=this.needsUpdate||g<1;I.nextUpdate===e.time.frameCount&&(o=!0),o&&(br&&console.log("Update threemeshui"),this.needsUpdate=!1,A.update());return}this.lastUpdateFrame=[{context:e,frame:g,nextUpdate:g}],A.update()}static updateState(A,e){let t=null;if(A&&(t=this.findBlockInParent(A),t&&t!==this.lastSelected)){if(t.interactable===!1)return null;this.needsUpdate=!0}return t}static resetLastSelected(){const A=this.lastSelected;A&&(this.lastSelected=null,this.resetState(A))}static resetState(A){A&&(this.needsUpdate=!0)}static findBlockInParent(A){return A?A.isBlock?A:this.findBlockInParent(A.parent):null}}r(Zn,"lastSelected",null),r(Zn,"lastUpdateFrame",[]),r(Zn,"needsUpdate",!1);const Vf=Symbol("cameraController");function QgA(i){return i[Vf]}function tb(i,A,e){e?i[Vf]=A:i[Vf]===A&&(i[Vf]=null)}const ib=Symbol("camera autofit");function EgA(i){return i[ib]===void 0?!0:i[ib]!==!1}class gO extends pA{constructor(A,e={}){const g=[A.isCubeTexture?"#define ENVMAP_TYPE_CUBE":""],I=`
|
|
5096
|
+
Using the assigned clip instead:`,this.clip),A=this.clip);let e=!this.sound||A&&A!==this.clip;if(typeof A=="string"&&!this.audioLoader&&(e=!0),(A instanceof MediaStream||typeof A=="string")&&(this.clip=A),e){this.shouldPlay=!0,this.onNewClip(A);return}if(this.shouldPlay=!0,this._hasEnded=!1,ug&&console.log("play",(t=this.sound)==null?void 0:t.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const I=this.context.application.muted;I&&this.sound.setVolume(0),this.clip instanceof MediaStream?(this.sound.setMediaStreamSource(this.clip),this._audioElement||(this._audioElement=document.createElement("audio"),this._audioElement.style.display="none"),this._audioElement.parentNode||(g=this.context.domElement.shadowRoot)==null||g.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(I?.1:0))}}pause(){var A,e;ug&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=(A=this.sound)==null?void 0:A.context.currentTime,this.sound.pause()),(e=this._audioElement)==null||e.remove()}stop(){var A,e;ug&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=(A=this.sound)==null?void 0:A.context.currentTime,ug&&console.log(this._lastContextTime),this.sound.stop()),(e=this._audioElement)==null||e.remove()}get isPlaying(){var A;return((A=this.sound)==null?void 0:A.isPlaying)??!1}set isPlaying(A){}get time(){var A,e;return(A=this.sound)!=null&&A.source?((e=this.sound.source)==null?void 0:e.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(A){if(this.sound){if(A===this.sound.offset)return;const e=this.isPlaying;this.stop(),this.sound.offset=A,e&&this.play()}}update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,ug&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}};let Ki=Hn;vC([D(URL)],Ki.prototype,"clip",2);vC([D()],Ki.prototype,"playOnAwake",2);vC([D()],Ki.prototype,"loop",1);vC([D()],Ki.prototype,"spatialBlend",1);vC([D()],Ki.prototype,"minDistance",1);vC([D()],Ki.prototype,"maxDistance",1);vC([D()],Ki.prototype,"volume",1);vC([D()],Ki.prototype,"rollOffMode",2);vC([D()],Ki.prototype,"playInBackground",2);var yiA=Object.defineProperty,SiA=Object.getOwnPropertyDescriptor,kiA=(i,A,e,t)=>{for(var g=t>1?void 0:t?SiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&yiA(A,e,g),g};class Vd extends NA{constructor(){super(...arguments);r(this,"constraintActive",!0);r(this,"locked",!1);r(this,"sources",[])}}kiA([D(SA)],Vd.prototype,"sources",2);const Vv={type:"change"},Lk={type:"start"},zv={type:"end"};let miA=class extends ig{constructor(A,e){super(),this.object=A,this.domElement=e,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new w,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:Nr.ROTATE,MIDDLE:Nr.DOLLY,RIGHT:Nr.PAN},this.touches={ONE:Kr.ROTATE,TWO:Kr.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this.getPolarAngle=function(){return s.phi},this.getAzimuthalAngle=function(){return s.theta},this.getDistance=function(){return this.object.position.distanceTo(this.target)},this.listenToKeyEvents=function(Z){Z.addEventListener("keydown",Me),this._domElementKeyEvents=Z},this.stopListenToKeyEvents=function(){this._domElementKeyEvents.removeEventListener("keydown",Me),this._domElementKeyEvents=null},this.saveState=function(){t.target0.copy(t.target),t.position0.copy(t.object.position),t.zoom0=t.object.zoom},this.reset=function(){t.target.copy(t.target0),t.object.position.copy(t.position0),t.object.zoom=t.zoom0,t.object.updateProjectionMatrix(),t.dispatchEvent(Vv),t.update(),I=g.NONE},this.update=function(){const Z=new w,hA=new MA().setFromUnitVectors(A.up,new w(0,1,0)),rA=hA.clone().invert(),VA=new w,jA=new MA,OA=new w,bA=2*Math.PI;return function(){const fe=t.object.getWorldPosition(A.position);Z.copy(fe).sub(t.target),Z.applyQuaternion(hA),s.setFromVector3(Z),t.autoRotate&&I===g.NONE&&M(R()),t.enableDamping?(s.theta+=n.theta*t.dampingFactor,s.phi+=n.phi*t.dampingFactor):(s.theta+=n.theta,s.phi+=n.phi);let ye=t.minAzimuthAngle,eA=t.maxAzimuthAngle;return isFinite(ye)&&isFinite(eA)&&(ye<-Math.PI?ye+=bA:ye>Math.PI&&(ye-=bA),eA<-Math.PI?eA+=bA:eA>Math.PI&&(eA-=bA),ye<=eA?s.theta=Math.max(ye,Math.min(eA,s.theta)):s.theta=s.theta>(ye+eA)/2?Math.max(ye,s.theta):Math.min(eA,s.theta)),s.phi=Math.max(t.minPolarAngle,Math.min(t.maxPolarAngle,s.phi)),s.makeSafe(),t.enableDamping?a=Gg.lerp(a,C,t.dampingFactor):a=C,s.radius*=a,s.radius=Math.max(t.minDistance,Math.min(t.maxDistance,s.radius)),t.enableDamping===!0?t.target.addScaledVector(B,t.dampingFactor):t.target.add(B),Z.setFromSpherical(s),Z.applyQuaternion(rA),fe.copy(t.target).add(Z),t.object.parent?t.object.parent.worldToLocal(fe):t.object.position.copy(fe),t.object.lookAt(t.target),t.enableDamping===!0?(n.theta*=1-t.dampingFactor,n.phi*=1-t.dampingFactor,B.multiplyScalar(1-t.dampingFactor)):(n.set(0,0,0),B.set(0,0,0)),C=1,Q||VA.distanceToSquared(t.object.position)>o||8*(1-jA.dot(t.object.quaternion))>o||OA.distanceToSquared(t.target)>0?(t.dispatchEvent(Vv),VA.copy(t.object.position),jA.copy(t.object.quaternion),OA.copy(t.target),Q=!1,!0):!1}}(),this.dispose=function(){t.domElement.removeEventListener("contextmenu",q),t.domElement.removeEventListener("pointerdown",LA),t.domElement.removeEventListener("pointercancel",te),t.domElement.removeEventListener("wheel",ue),t.domElement.removeEventListener("pointermove",GA),t.domElement.removeEventListener("pointerup",te),t._domElementKeyEvents!==null&&(t._domElementKeyEvents.removeEventListener("keydown",Me),t._domElementKeyEvents=null)};const t=this,g={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let I=g.NONE;const o=1e-6,s=new nG,n=new nG;let C=1,a=1;const B=new w;let Q=!1;const E=new tA,c=new tA,d=new tA,l=new tA,h=new tA,p=new tA,u=new tA,f=new tA,k=new tA,m=[],G={};function R(){return 2*Math.PI/60/60*t.autoRotateSpeed}function y(){return Math.pow(.95,t.zoomSpeed)}function M(Z){n.theta-=Z}function K(Z){n.phi-=Z}const P=function(){const Z=new w;return function(rA,VA){Z.setFromMatrixColumn(VA,0),Z.multiplyScalar(-rA),B.add(Z)}}(),b=function(){const Z=new w;return function(rA,VA){t.screenSpacePanning===!0?Z.setFromMatrixColumn(VA,1):(Z.setFromMatrixColumn(VA,0),Z.crossVectors(t.object.up,Z)),Z.multiplyScalar(rA),B.add(Z)}}(),H=function(){const Z=new w,hA=new w;return function(VA,jA){const OA=t.domElement;if(t.object.isPerspectiveCamera){t.object.getWorldPosition(hA),Z.copy(hA).sub(t.target);let bA=Z.length();bA*=Math.tan(t.object.fov/2*Math.PI/180),P(2*VA*bA/OA.clientHeight,t.object.matrixWorld),b(2*jA*bA/OA.clientHeight,t.object.matrixWorld)}else t.object.isOrthographicCamera?(P(VA*(t.object.right-t.object.left)/t.object.zoom/OA.clientWidth,t.object.matrixWorld),b(jA*(t.object.top-t.object.bottom)/t.object.zoom/OA.clientHeight,t.object.matrixWorld)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),t.enablePan=!1)}}();function W(Z){t.object.isPerspectiveCamera?C/=Z:t.object.isOrthographicCamera?(t.object.zoom=Math.max(t.minZoom,Math.min(t.maxZoom,t.object.zoom*Z)),t.object.updateProjectionMatrix(),Q=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),t.enableZoom=!1)}function L(Z){t.object.isPerspectiveCamera?C*=Z:t.object.isOrthographicCamera?(t.object.zoom=Math.max(t.minZoom,Math.min(t.maxZoom,t.object.zoom/Z)),t.object.updateProjectionMatrix(),Q=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),t.enableZoom=!1)}function v(Z){E.set(Z.clientX,Z.clientY)}function Y(Z){u.set(Z.clientX,Z.clientY)}function AA(Z){l.set(Z.clientX,Z.clientY)}function $(Z){c.set(Z.clientX,Z.clientY),d.subVectors(c,E).multiplyScalar(t.rotateSpeed);const hA=t.domElement;M(2*Math.PI*d.x/hA.clientHeight),K(2*Math.PI*d.y/hA.clientHeight),E.copy(c),t.update()}function V(Z){f.set(Z.clientX,Z.clientY),k.subVectors(f,u),k.y>0?W(y()):k.y<0&&L(y()),u.copy(f),t.update()}function gA(Z){h.set(Z.clientX,Z.clientY),p.subVectors(h,l).multiplyScalar(t.panSpeed),H(p.x,p.y),l.copy(h),t.update()}function dA(Z){Z.deltaY<0?L(y()):Z.deltaY>0&&W(y()),t.update()}function fA(Z){let hA=!1;switch(Z.code){case t.keys.UP:Z.ctrlKey||Z.metaKey||Z.shiftKey?K(2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):H(0,t.keyPanSpeed),hA=!0;break;case t.keys.BOTTOM:Z.ctrlKey||Z.metaKey||Z.shiftKey?K(-2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):H(0,-t.keyPanSpeed),hA=!0;break;case t.keys.LEFT:Z.ctrlKey||Z.metaKey||Z.shiftKey?M(2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):H(t.keyPanSpeed,0),hA=!0;break;case t.keys.RIGHT:Z.ctrlKey||Z.metaKey||Z.shiftKey?M(-2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):H(-t.keyPanSpeed,0),hA=!0;break}hA&&(Z.preventDefault(),t.update())}function RA(){if(m.length===1)E.set(m[0].pageX,m[0].pageY);else{const Z=.5*(m[0].pageX+m[1].pageX),hA=.5*(m[0].pageY+m[1].pageY);E.set(Z,hA)}}function UA(){if(m.length===1)l.set(m[0].pageX,m[0].pageY);else{const Z=.5*(m[0].pageX+m[1].pageX),hA=.5*(m[0].pageY+m[1].pageY);l.set(Z,hA)}}function HA(){const Z=m[0].pageX-m[1].pageX,hA=m[0].pageY-m[1].pageY,rA=Math.sqrt(Z*Z+hA*hA);u.set(0,rA)}function PA(){t.enableZoom&&HA(),t.enablePan&&UA()}function Qe(){t.enableZoom&&HA(),t.enableRotate&&RA()}function Ge(Z){if(m.length==1)c.set(Z.pageX,Z.pageY);else{const rA=TA(Z),VA=.5*(Z.pageX+rA.x),jA=.5*(Z.pageY+rA.y);c.set(VA,jA)}d.subVectors(c,E).multiplyScalar(t.rotateSpeed);const hA=t.domElement;M(2*Math.PI*d.x/hA.clientHeight),K(2*Math.PI*d.y/hA.clientHeight),E.copy(c)}function Ie(Z){if(m.length===1)h.set(Z.pageX,Z.pageY);else{const hA=TA(Z),rA=.5*(Z.pageX+hA.x),VA=.5*(Z.pageY+hA.y);h.set(rA,VA)}p.subVectors(h,l).multiplyScalar(t.panSpeed),H(p.x,p.y),l.copy(h)}function z(Z){const hA=TA(Z),rA=Z.pageX-hA.x,VA=Z.pageY-hA.y,jA=Math.sqrt(rA*rA+VA*VA);f.set(0,jA),k.set(0,Math.pow(f.y/u.y,t.zoomSpeed)),W(k.y),u.copy(f)}function xA(Z){t.enableZoom&&z(Z),t.enablePan&&Ie(Z)}function DA(Z){t.enableZoom&&z(Z),t.enableRotate&&Ge(Z)}function LA(Z){t.enabled!==!1&&(m.length===0&&(t.domElement.addEventListener("pointermove",GA),t.domElement.addEventListener("pointerup",te)),EA(Z),Z.pointerType==="touch"?et(Z):zA(Z))}function GA(Z){t.enabled!==!1&&(Z.pointerType==="touch"?_(Z):ZA(Z))}function te(Z){KA(Z),m.length===0&&(t.domElement.removeEventListener("pointermove",GA),t.domElement.removeEventListener("pointerup",te)),t.dispatchEvent(zv),I=g.NONE}function zA(Z){let hA;switch(Z.button){case 0:hA=t.mouseButtons.LEFT;break;case 1:hA=t.mouseButtons.MIDDLE;break;case 2:hA=t.mouseButtons.RIGHT;break;default:hA=-1}switch(hA){case Nr.DOLLY:if(t.enableZoom===!1)return;Y(Z),I=g.DOLLY;break;case Nr.ROTATE:if(Z.ctrlKey||Z.metaKey||Z.shiftKey){if(t.enablePan===!1)return;AA(Z),I=g.PAN}else{if(t.enableRotate===!1)return;v(Z),I=g.ROTATE}break;case Nr.PAN:if(Z.ctrlKey||Z.metaKey||Z.shiftKey){if(t.enableRotate===!1)return;v(Z),I=g.ROTATE}else{if(t.enablePan===!1)return;AA(Z),I=g.PAN}break;default:I=g.NONE}I!==g.NONE&&t.dispatchEvent(Lk)}function ZA(Z){switch(I){case g.ROTATE:if(t.enableRotate===!1)return;$(Z);break;case g.DOLLY:if(t.enableZoom===!1)return;V(Z);break;case g.PAN:if(t.enablePan===!1)return;gA(Z);break}}function ue(Z){t.enabled===!1||t.enableZoom===!1||I!==g.NONE||(Z.preventDefault(),t.dispatchEvent(Lk),dA(Z),t.dispatchEvent(zv))}function Me(Z){t.enabled===!1||t.enablePan===!1||fA(Z)}function et(Z){switch(JA(Z),m.length){case 1:switch(t.touches.ONE){case Kr.ROTATE:if(t.enableRotate===!1)return;RA(),I=g.TOUCH_ROTATE;break;case Kr.PAN:if(t.enablePan===!1)return;UA(),I=g.TOUCH_PAN;break;default:I=g.NONE}break;case 2:switch(t.touches.TWO){case Kr.DOLLY_PAN:if(t.enableZoom===!1&&t.enablePan===!1)return;PA(),I=g.TOUCH_DOLLY_PAN;break;case Kr.DOLLY_ROTATE:if(t.enableZoom===!1&&t.enableRotate===!1)return;Qe(),I=g.TOUCH_DOLLY_ROTATE;break;default:I=g.NONE}break;default:I=g.NONE}I!==g.NONE&&t.dispatchEvent(Lk)}function _(Z){switch(JA(Z),I){case g.TOUCH_ROTATE:if(t.enableRotate===!1)return;Ge(Z),t.update();break;case g.TOUCH_PAN:if(t.enablePan===!1)return;Ie(Z),t.update();break;case g.TOUCH_DOLLY_PAN:if(t.enableZoom===!1&&t.enablePan===!1)return;xA(Z),t.update();break;case g.TOUCH_DOLLY_ROTATE:if(t.enableZoom===!1&&t.enableRotate===!1)return;DA(Z),t.update();break;default:I=g.NONE}}function q(Z){t.enabled!==!1&&Z.preventDefault()}function EA(Z){m.push(Z)}function KA(Z){delete G[Z.pointerId];for(let hA=0;hA<m.length;hA++)if(m[hA].pointerId==Z.pointerId){m.splice(hA,1);return}}function JA(Z){let hA=G[Z.pointerId];hA===void 0&&(hA=new tA,G[Z.pointerId]=hA),hA.set(Z.pageX,Z.pageY)}function TA(Z){const hA=Z.pointerId===m[0].pointerId?m[1]:m[0];return G[hA.pointerId]}t.domElement.addEventListener("contextmenu",q),t.domElement.addEventListener("pointerdown",LA),t.domElement.addEventListener("pointercancel",te),t.domElement.addEventListener("wheel",ue,{passive:!1}),this.update()}};const GiA="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/";class MiA{constructor(A,e,t,g,I=null){this.controller=e,this.handModel=A,this.bones=[],I===null&&(I=new ic,I.setPath(t||GiA)),I.load(`${g}.glb`,o=>{const s=o.scene.children[0];this.handModel.add(s),s.layers.mask=this.handModel.layers.mask;const n=s.getObjectByProperty("type","SkinnedMesh");n.frustumCulled=!1,n.castShadow=!0,n.receiveShadow=!0,["wrist","thumb-metacarpal","thumb-phalanx-proximal","thumb-phalanx-distal","thumb-tip","index-finger-metacarpal","index-finger-phalanx-proximal","index-finger-phalanx-intermediate","index-finger-phalanx-distal","index-finger-tip","middle-finger-metacarpal","middle-finger-phalanx-proximal","middle-finger-phalanx-intermediate","middle-finger-phalanx-distal","middle-finger-tip","ring-finger-metacarpal","ring-finger-phalanx-proximal","ring-finger-phalanx-intermediate","ring-finger-phalanx-distal","ring-finger-tip","pinky-finger-metacarpal","pinky-finger-phalanx-proximal","pinky-finger-phalanx-intermediate","pinky-finger-phalanx-distal","pinky-finger-tip"].forEach(a=>{const B=s.getObjectByName(a);B!==void 0?B.jointName=a:console.warn(`Couldn't find ${a} in ${g} hand mesh`),this.bones.push(B)})})}updateMesh(){const A=this.controller.joints;for(let e=0;e<this.bones.length;e++){const t=this.bones[e];if(t){const g=A[t.jointName];if(g.visible){const I=g.position;t.position.copy(I),t.quaternion.copy(g.quaternion)}}}}}const RiA=.01,UiA="index-finger-tip";class FiA extends SA{constructor(A,e=null){super(),this.controller=A,this.motionController=null,this.envMap=null,this.loader=e,this.mesh=null,A.addEventListener("connected",t=>{const g=t.data;g.hand&&!this.motionController&&(this.xrInputSource=g,this.motionController=new MiA(this,A,this.path,g.handedness,this.loader))}),A.addEventListener("disconnected",()=>{this.clear(),this.motionController=null})}updateMatrixWorld(A){super.updateMatrixWorld(A),this.motionController&&this.motionController.updateMesh()}getPointerPosition(){const A=this.controller.joints[UiA];return A?A.position:null}intersectBoxObject(A){const e=this.getPointerPosition();if(e){const t=new DI(e,RiA),g=new Hi().setFromObject(A);return t.intersectsBox(g)}else return!1}checkButton(A){this.intersectBoxObject(A)?A.onPress():A.onClear(),A.isPressed()&&A.whilePressed()}}const NiA=.05,jv=.02,_p=.01,Zv=.02,Xv=1,yQ=.4,KiA=.002,oh=.01,Op=.003,$v=.035,Mt=16,Mo=12,xk=110,JiA=new w(0,1,0),qiA=new w(0,0,1),viA=.02,biA=1.5;class LiA extends SA{constructor(A,e){super(),this.hand=A,this.controller=e,this.motionController=null,this.envMap=null,this.mesh=null,this.pointerGeometry=null,this.pointerMesh=null,this.pointerObject=null,this.pinched=!1,this.attached=!1,this.cursorObject=null,this.raycaster=null,this._onConnected=this._onConnected.bind(this),this._onDisconnected=this._onDisconnected.bind(this),this.hand.addEventListener("connected",this._onConnected),this.hand.addEventListener("disconnected",this._onDisconnected)}_onConnected(A){const e=A.data;e.hand&&(this.visible=!0,this.xrInputSource=e,this.createPointer())}_onDisconnected(){this.visible=!1,this.xrInputSource=null,this.pointerGeometry&&this.pointerGeometry.dispose(),this.pointerMesh&&this.pointerMesh.material&&this.pointerMesh.material.dispose(),this.clear()}_drawVerticesRing(A,e,t){const g=e.clone();for(let I=0;I<Mt;I++){g.applyAxisAngle(qiA,Math.PI*2/Mt);const o=t*Mt+I;A[3*o]=g.x,A[3*o+1]=g.y,A[3*o+2]=g.z}}_updatePointerVertices(A){const e=this.pointerGeometry.attributes.position.array,t=new w(KiA,0,-1*($v-A));this._drawVerticesRing(e,t,0);const g=new w(Math.sin(Math.PI*xk/180)*A,Math.cos(Math.PI*xk/180)*A,0);for(let C=0;C<Mo;C++)this._drawVerticesRing(e,g,C+1),g.applyAxisAngle(JiA,Math.PI*xk/180/(Mo*-2));const I=Mt*(1+Mo),o=Mt*(1+Mo)+1,s=new w(0,0,-1*($v-A));e[I*3]=s.x,e[I*3+1]=s.y,e[I*3+2]=s.z;const n=new w(0,0,A);e[o*3]=n.x,e[o*3+1]=n.y,e[o*3+2]=n.z,this.pointerGeometry.setAttribute("position",new ae(e,3))}createPointer(){let A,e;const t=new Array(((Mo+1)*Mt+2)*3).fill(0),g=[];for(this.pointerGeometry=new de,this.pointerGeometry.setAttribute("position",new ae(t,3)),this._updatePointerVertices(oh),A=0;A<Mo;A++){for(e=0;e<Mt-1;e++)g.push(A*Mt+e,A*Mt+e+1,(A+1)*Mt+e),g.push(A*Mt+e+1,(A+1)*Mt+e+1,(A+1)*Mt+e);g.push((A+1)*Mt-1,A*Mt,(A+2)*Mt-1),g.push(A*Mt,(A+1)*Mt,(A+2)*Mt-1)}const I=Mt*(1+Mo),o=Mt*(1+Mo)+1;for(A=0;A<Mt-1;A++)g.push(I,A+1,A),g.push(o,A+Mt*Mo,A+Mt*Mo+1);g.push(I,0,Mt-1),g.push(o,Mt*(Mo+1)-1,Mt*Mo);const s=new rt;s.transparent=!0,s.opacity=yQ,this.pointerGeometry.setIndex(g),this.pointerMesh=new pA(this.pointerGeometry,s),this.pointerMesh.position.set(0,0,-1*oh),this.pointerObject=new SA,this.pointerObject.add(this.pointerMesh),this.raycaster=new DB;const n=new $o(viA,10,10),C=new rt;C.transparent=!0,C.opacity=yQ,this.cursorObject=new pA(n,C),this.pointerObject.add(this.cursorObject),this.add(this.pointerObject),this.pointerObject.layers.mask=this.layers.mask,this.pointerMesh.layers.mask=this.layers.mask}_updateRaycaster(){if(this.raycaster){const A=this.pointerObject.matrixWorld,e=new FA;e.identity().extractRotation(A),this.raycaster.ray.origin.setFromMatrixPosition(A),this.raycaster.ray.direction.set(0,0,-1).applyMatrix4(e)}}_updatePointer(){this.pointerObject.visible=this.controller.visible;const A=this.hand.joints["index-finger-tip"],e=this.hand.joints["thumb-tip"],t=A.position.distanceTo(e.position),g=A.position.clone().add(e.position).multiplyScalar(.5);this.pointerObject.position.copy(g),this.pointerObject.quaternion.copy(this.controller.quaternion),this.pinched=t<=jv;const I=(t-_p)/(NiA-_p),o=(t-_p)/(jv-_p);if(I>1)this._updatePointerVertices(oh),this.pointerMesh.position.set(0,0,-1*oh),this.pointerMesh.material.opacity=yQ;else if(I>0){const s=(oh-Op)*I+Op;this._updatePointerVertices(s),o<1?(this.pointerMesh.position.set(0,0,-1*s-(1-o)*Zv),this.pointerMesh.material.opacity=yQ+(1-o)*(Xv-yQ)):(this.pointerMesh.position.set(0,0,-1*s),this.pointerMesh.material.opacity=yQ)}else this._updatePointerVertices(Op),this.pointerMesh.position.set(0,0,-1*Op-Zv),this.pointerMesh.material.opacity=Xv;this.cursorObject.material.opacity=this.pointerMesh.material.opacity}updateMatrixWorld(A){super.updateMatrixWorld(A),this.pointerGeometry&&(this._updatePointer(),this._updateRaycaster())}isPinched(){return this.pinched}setAttached(A){this.attached=A}isAttached(){return this.attached}intersectObject(A,e=!0){if(this.raycaster)return this.raycaster.intersectObject(A,e)}intersectObjects(A,e=!0){if(this.raycaster)return this.raycaster.intersectObjects(A,e)}checkIntersections(A,e=!1){if(this.raycaster&&!this.attached){const t=this.raycaster.intersectObjects(A,e),g=new w(0,0,-1);if(t.length>0){const o=t[0].distance;this.cursorObject.position.copy(g.multiplyScalar(o))}else this.cursorObject.position.copy(g.multiplyScalar(biA))}}setCursor(A){const e=new w(0,0,-1);this.raycaster&&!this.attached&&this.cursorObject.position.copy(e.multiplyScalar(A))}dispose(){this._onDisconnected(),this.hand.removeEventListener("connected",this._onConnected),this.hand.removeEventListener("disconnected",this._onDisconnected)}}const ri={Handedness:Object.freeze({NONE:"none",LEFT:"left",RIGHT:"right"}),ComponentState:Object.freeze({DEFAULT:"default",TOUCHED:"touched",PRESSED:"pressed"}),ComponentProperty:Object.freeze({BUTTON:"button",X_AXIS:"xAxis",Y_AXIS:"yAxis",STATE:"state"}),ComponentType:Object.freeze({TRIGGER:"trigger",SQUEEZE:"squeeze",TOUCHPAD:"touchpad",THUMBSTICK:"thumbstick",BUTTON:"button"}),ButtonTouchThreshold:.05,AxisTouchThreshold:.1,VisualResponseProperty:Object.freeze({TRANSFORM:"transform",VISIBILITY:"visibility"})};async function eO(i){const A=await fetch(i);if(A.ok)return A.json();throw new Error(A.statusText)}async function xiA(i){if(!i)throw new Error("No basePath supplied");return await eO(`${i}/profilesList.json`)}async function TiA(i,A,e=null,t=!0){if(!i)throw new Error("No xrInputSource supplied");if(!A)throw new Error("No basePath supplied");const g=await xiA(A);let I;if(i.profiles.some(n=>{const C=g[n];return C&&(I={profileId:n,profilePath:`${A}/${C.path}`,deprecated:!!C.deprecated}),!!I}),!I){if(!e)throw new Error("No matching profile name found");const n=g[e];if(!n)throw new Error(`No matching profile name found and default profile "${e}" missing.`);I={profileId:e,profilePath:`${A}/${n.path}`,deprecated:!!n.deprecated}}const o=await eO(I.profilePath);let s;if(t){let n;if(i.handedness==="any"?n=o.layouts[Object.keys(o.layouts)[0]]:n=o.layouts[i.handedness],!n)throw new Error(`No matching handedness, ${i.handedness}, in profile ${I.profileId}`);n.assetPath&&(s=I.profilePath.replace("profile.json",n.assetPath))}return{profile:o,assetPath:s}}const YiA={xAxis:0,yAxis:0,button:0,state:ri.ComponentState.DEFAULT};function HiA(i=0,A=0){let e=i,t=A;if(Math.sqrt(i*i+A*A)>1){const o=Math.atan2(A,i);e=Math.cos(o),t=Math.sin(o)}return{normalizedXAxis:e*.5+.5,normalizedYAxis:t*.5+.5}}class _iA{constructor(A){this.componentProperty=A.componentProperty,this.states=A.states,this.valueNodeName=A.valueNodeName,this.valueNodeProperty=A.valueNodeProperty,this.valueNodeProperty===ri.VisualResponseProperty.TRANSFORM&&(this.minNodeName=A.minNodeName,this.maxNodeName=A.maxNodeName),this.value=0,this.updateFromComponent(YiA)}updateFromComponent({xAxis:A,yAxis:e,button:t,state:g}){const{normalizedXAxis:I,normalizedYAxis:o}=HiA(A,e);switch(this.componentProperty){case ri.ComponentProperty.X_AXIS:this.value=this.states.includes(g)?I:.5;break;case ri.ComponentProperty.Y_AXIS:this.value=this.states.includes(g)?o:.5;break;case ri.ComponentProperty.BUTTON:this.value=this.states.includes(g)?t:0;break;case ri.ComponentProperty.STATE:this.valueNodeProperty===ri.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(g):this.value=this.states.includes(g)?1:0;break;default:throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}}class OiA{constructor(A,e){if(!A||!e||!e.visualResponses||!e.gamepadIndices||Object.keys(e.gamepadIndices).length===0)throw new Error("Invalid arguments supplied");this.id=A,this.type=e.type,this.rootNodeName=e.rootNodeName,this.touchPointNodeName=e.touchPointNodeName,this.visualResponses={},Object.keys(e.visualResponses).forEach(t=>{const g=new _iA(e.visualResponses[t]);this.visualResponses[t]=g}),this.gamepadIndices=Object.assign({},e.gamepadIndices),this.values={state:ri.ComponentState.DEFAULT,button:this.gamepadIndices.button!==void 0?0:void 0,xAxis:this.gamepadIndices.xAxis!==void 0?0:void 0,yAxis:this.gamepadIndices.yAxis!==void 0?0:void 0}}get data(){return{id:this.id,...this.values}}updateFromGamepad(A){if(this.values.state=ri.ComponentState.DEFAULT,this.gamepadIndices.button!==void 0&&A.buttons.length>this.gamepadIndices.button){const e=A.buttons[this.gamepadIndices.button];this.values.button=e.value,this.values.button=this.values.button<0?0:this.values.button,this.values.button=this.values.button>1?1:this.values.button,e.pressed||this.values.button===1?this.values.state=ri.ComponentState.PRESSED:(e.touched||this.values.button>ri.ButtonTouchThreshold)&&(this.values.state=ri.ComponentState.TOUCHED)}this.gamepadIndices.xAxis!==void 0&&A.axes.length>this.gamepadIndices.xAxis&&(this.values.xAxis=A.axes[this.gamepadIndices.xAxis],this.values.xAxis=this.values.xAxis<-1?-1:this.values.xAxis,this.values.xAxis=this.values.xAxis>1?1:this.values.xAxis,this.values.state===ri.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>ri.AxisTouchThreshold&&(this.values.state=ri.ComponentState.TOUCHED)),this.gamepadIndices.yAxis!==void 0&&A.axes.length>this.gamepadIndices.yAxis&&(this.values.yAxis=A.axes[this.gamepadIndices.yAxis],this.values.yAxis=this.values.yAxis<-1?-1:this.values.yAxis,this.values.yAxis=this.values.yAxis>1?1:this.values.yAxis,this.values.state===ri.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>ri.AxisTouchThreshold&&(this.values.state=ri.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(e=>{e.updateFromComponent(this.values)})}}class PiA{constructor(A,e,t){if(!A)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No profile supplied");this.xrInputSource=A,this.assetUrl=t,this.id=e.profileId,this.layoutDescription=e.layouts[A.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(g=>{const I=this.layoutDescription.components[g];this.components[g]=new OiA(g,I)}),this.updateFromGamepad()}get gripSpace(){return this.xrInputSource.gripSpace}get targetRaySpace(){return this.xrInputSource.targetRaySpace}get data(){const A=[];return Object.values(this.components).forEach(e=>{A.push(e.data)}),A}updateFromGamepad(){Object.values(this.components).forEach(A=>{A.updateFromGamepad(this.xrInputSource.gamepad)})}}const WiA="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",ViA="generic-trigger";class ziA extends SA{constructor(){super(),this.motionController=null,this.envMap=null}setEnvironmentMap(A){return this.envMap==A?this:(this.envMap=A,this.traverse(e=>{e.isMesh&&(e.material.envMap=this.envMap,e.material.needsUpdate=!0)}),this)}updateMatrixWorld(A){super.updateMatrixWorld(A),this.motionController&&(this.motionController.updateFromGamepad(),Object.values(this.motionController.components).forEach(e=>{Object.values(e.visualResponses).forEach(t=>{const{valueNode:g,minNode:I,maxNode:o,value:s,valueNodeProperty:n}=t;g&&(n===ri.VisualResponseProperty.VISIBILITY?g.visible=s:n===ri.VisualResponseProperty.TRANSFORM&&(g.quaternion.slerpQuaternions(I.quaternion,o.quaternion,s),g.position.lerpVectors(I.position,o.position,s)))})}))}}function jiA(i,A){Object.values(i.components).forEach(e=>{const{type:t,touchPointNodeName:g,visualResponses:I}=e;if(t===ri.ComponentType.TOUCHPAD)if(e.touchPointNode=A.getObjectByName(g),e.touchPointNode){const o=new $o(.001),s=new rt({color:255}),n=new pA(o,s);e.touchPointNode.add(n)}else console.warn(`Could not find touch dot, ${e.touchPointNodeName}, in touchpad component ${e.id}`);Object.values(I).forEach(o=>{const{valueNodeName:s,minNodeName:n,maxNodeName:C,valueNodeProperty:a}=o;if(a===ri.VisualResponseProperty.TRANSFORM){if(o.minNode=A.getObjectByName(n),o.maxNode=A.getObjectByName(C),!o.minNode){console.warn(`Could not find ${n} in the model`);return}if(!o.maxNode){console.warn(`Could not find ${C} in the model`);return}}o.valueNode=A.getObjectByName(s),o.valueNode||console.warn(`Could not find ${s} in the model`)})})}function Ab(i,A){jiA(i.motionController,A),i.envMap&&A.traverse(e=>{e.isMesh&&(e.material.envMap=i.envMap,e.material.needsUpdate=!0)}),i.layers.mask!=0&&A.traverse(e=>{e.layers.mask=i.layers.mask}),i.add(A)}class ZiA{constructor(A=null){this.gltfLoader=A,this.path=WiA,this._assetCache={},this.gltfLoader||(this.gltfLoader=new ic)}createControllerModel(A){const e=new ziA;let t=null;return A.addEventListener("connected",g=>{const I=g.data;I.targetRayMode!=="tracked-pointer"||!I.gamepad||TiA(I,this.path,ViA).then(({profile:o,assetPath:s})=>{e.motionController=new PiA(I,o,s);const n=this._assetCache[e.motionController.assetUrl];if(n)t=n.scene.clone(),Ab(e,t);else{if(!this.gltfLoader)throw new Error("GLTFLoader not set.");this.gltfLoader.setPath(""),this.gltfLoader.load(e.motionController.assetUrl,C=>{this._assetCache[e.motionController.assetUrl]=C,t=C.scene.clone(),Ab(e,t)},null,()=>{throw new Error(`Asset ${e.motionController.assetUrl} missing or malformed.`)})}}).catch(o=>{console.warn(o)})}),A.addEventListener("disconnected",()=>{e.motionController=null,e.remove(t),t=null}),e}}const sh=sA("debugavatar");class xy{constructor(A,e,t,g){r(this,"root");r(this,"head");r(this,"leftHand");r(this,"rigthHand");var I;this.root=A,this.head=e,this.leftHand=t,this.rigthHand=g,(I=this.root)==null||I.traverse(o=>o.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class Ty{constructor(){r(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(A,e){if(!e)return console.error("Can not create avatar: failed to provide id or root object"),null;let t=null;if(typeof e=="string"){if(t=await this.loadAvatar(A,e),!t){const I=new cn;t=IA.instantiate(ME(e,A.scene),I)}}else t=e;if(!t)return null;const g=this.findAvatar(t);return g.isValid?(sh&&console.log("[Custom Avatar] valid config",e,sh?g:""),g):(console.warn("[Custom Avatar] config isn't valid",e,sh?g:""),null)}async loadAvatar(A,e){if(console.assert(e!=null&&typeof e=="string","Avatar id must not be null"),e.length<=0||!e)return null;if(sh&&console.log("[Custom Avatar] "+e+", loading..."),e.endsWith(".glb")||(e+=".glb"),this.avatarRegistryUrl===null){const g=await fetch("./"+e);let I=null;if(g.ok){const s=await g.blob();s&&(I=await s.arrayBuffer())}if(!I&&(I=await lU(e,e,0,"no url here go away",!0),!I))return null;const o=await ks().parseSync(A,I,null,0);return(o==null?void 0:o.scene)??null}const t=new ic;return xd(t,A),new Promise((g,I)=>{const o=this.avatarRegistryUrl+"/"+e;t.load(o,async s=>{await ks().createBuiltinComponents(A,o,s,null,void 0),g(s.scene)},s=>{sh&&console.log("[Custom Avatar] "+s.loaded/s.total*100+"% loaded of "+s.total/1024+"kB")},s=>{console.error("[Custom Avatar] Error when loading: "+s),g(null)})})}cacheModel(A,e){}findAvatar(A){const e=A;let t=e;t.children.length==1&&(t=A.children[0]);let g=this.findAvatarPart(t,["head"]);const I=this.findAvatarPart(t,["left","hand"]),o=this.findAvatarPart(t,["right","hand"]);if(!g){g=e;const n=new w;new Hi().setFromObject(g).getSize(n);const C=Math.max(n.x,n.y,n.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+C+" meters! Should be < 0.3m"),C>.3&&g.scale.multiplyScalar(1/C*.3)}return new xy(e,g,I,o)}findAvatarPart(A,e){const t=A.name.toLowerCase();let g=!0;for(const I of e){if(!g)break;t.indexOf(I)===-1&&(g=!1)}if(g)return A;if(A.children)for(const I of A.children){const o=this.findAvatarPart(I,e);if(o)return o}return null}handleCustomAvatarErrors(A){if(!A.ok)throw Error(A.statusText);return A}}var XiA=Object.defineProperty,$iA=Object.getOwnPropertyDescriptor,AgA=(i,A,e,t)=>{for(var g=t>1?void 0:t?$iA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&XiA(A,e,g),g};const LQ=sA("debugflags");var ki=(i=>(i[i.Never=0]="Never",i[i.Browser=1]="Browser",i[i.AR=2]="AR",i[i.VR=4]="VR",i[i.FirstPerson=8]="FirstPerson",i[i.ThirdPerson=16]="ThirdPerson",i[i.All=4294967295]="All",i))(ki||{});const XN=class{constructor(){r(this,"Mask",17)}Has(A){return(this.Mask&A)!==0}Set(A){LQ&&console.warn("Set XR flag state to",A),this.Mask=A,Io.Apply()}Enable(A){this.Mask|=A,Io.Apply()}Disable(A){this.Mask&=~A,Io.Apply()}Toggle(A){this.Mask^=A,Io.Apply()}EnableAll(){this.Mask=-1,Io.Apply()}DisableAll(){this.Mask=0,Io.Apply()}};let EI=XN;r(EI,"Global",new XN);var hh;const _n=(hh=class extends NA{constructor(){super(...arguments);r(this,"visibleIn")}static Apply(){for(const A of this.registry)A.UpdateVisible(EI.Global)}awake(){_n.registry.push(this)}onEnable(){_n.firstApply?this.UpdateVisible(EI.Global):(_n.firstApply=!0,_n.Apply())}onDestroy(){const A=_n.registry.indexOf(this);A>=0&&_n.registry.splice(A,1)}get isOn(){return this.gameObject.visible}UpdateVisible(A=null){let e;const t=A;t&&typeof t=="number"&&(console.assert(typeof t=="number","XRFlag.UpdateVisible: state must be a number",t),LQ&&console.log(t),_n.buffer.Mask=t,A=_n.buffer);const g=A;if(g?(LQ&&console.warn(this.name,"use passed in mask",g.Mask,this.visibleIn),e=g.Has(this.visibleIn)):(LQ&&console.log(this.name,"use global mask"),EI.Global.Has(this.visibleIn)),e!==void 0)if(e)LQ&&console.log(this.name,"is visible",this.gameObject.uuid),IA.setActive(this.gameObject,!0);else{if(LQ&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},r(hh,"registry",[]),r(hh,"firstApply"),r(hh,"buffer",new EI),hh);let Io=_n;AgA([D()],Io.prototype,"visibleIn",2);const Ca=sA("debugavatar"),Es=class extends NA{constructor(){super(...arguments);r(this,"connectionId");r(this,"avatar")}static getAvatar(e){return e>=0&&e<Es.instances.length?Es.instances[e]:null}static onAvatarMarkerCreated(e){return Es._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return Es._onAvatarMarkerDestroyed.push(e),e}awake(){Es.instances.push(this),Ca&&console.log(this);for(const e of Es._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Es.instances.splice(Es.instances.indexOf(this),1);for(const e of Es._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):IA.setActive(this.avatar,e))}};let Qg=Es;r(Qg,"instances",[]),r(Qg,"_onNewAvatarMarkerAdded",[]),r(Qg,"_onAvatarMarkerDestroyed",[]);const Bl=class{constructor(A,e,t){r(this,"_isVisible",!0);r(this,"guid");r(this,"root",null);r(this,"head",null);r(this,"handLeft",null);r(this,"handRight",null);r(this,"lastUpdate",-1);r(this,"isLocalAvatar",!1);r(this,"flags",null);r(this,"headScale",new w(1,1,1));r(this,"handLeftScale",new w(1,1,1));r(this,"handRightScale",new w(1,1,1));r(this,"webxr");r(this,"lastAvatarId",null);r(this,"hasAvatarOverride",!1);r(this,"context");r(this,"avatarMarker",null);r(this,"_headTarget",new SA);r(this,"_handLeftTarget",new SA);r(this,"_handRightTarget",new SA);r(this,"_canInterpolate",!1);this.context=A,this.guid=e,this.webxr=t,this.setupCustomAvatar(this.webxr.defaultAvatar)}setVisible(A){this._isVisible=A,this.updateVisibility()}get isWebXRAvatar(){return!0}updateFlags(){if(!this.flags)return;let A=this.isLocalAvatar?ki.FirstPerson:ki.ThirdPerson;this.context.isInVR?A|=ki.VR:this.context.isInAR?A|=ki.AR:A|=ki.Browser;for(const e of this.flags)e.gameObject.visible=!0,e.UpdateVisible(A)}async setAvatarOverride(A){return this.hasAvatarOverride=A!==null,this.hasAvatarOverride&&this.lastAvatarId!==A&&(this.lastAvatarId=A,A!=null&&A.length>0)?await this.setupCustomAvatar(A):null}tryUpdate(A,e){if(A.guid===this.guid&&(this.lastAvatarId!==A.avatarId&&A.avatarId&&A.avatarId.length>0&&(this.lastAvatarId=A.avatarId,this.setupCustomAvatar(A.avatarId)),this.lastUpdate=A.time,this.head)){const t=this.webxr.IsInAR?rn.Handheld:rn.Headset,g=this.head;this.context.players.setPlayerView(A.guid,g,t),Xg.markDirty(this.head),this._canInterpolate=!0;const I=this.isLocalAvatar?this.head:this._headTarget;if(I.position.set(A.position.x,A.position.y,A.position.z),I.quaternion.set(A.rotation.x,A.rotation.y,A.rotation.z,A.rotation.w),I.scale.set(A.scale,A.scale,A.scale),I.scale.multiply(this.headScale),this.handLeft){const o=this.isLocalAvatar?this.handLeft:this._handLeftTarget;o.position.set(A.posLeftHand.x,A.posLeftHand.y,A.posLeftHand.z),o.quaternion.set(A.rotLeftHand._x,A.rotLeftHand._y,A.rotLeftHand._z,A.rotLeftHand._w),o.quaternion.multiply(Bl.invertRotation),o.scale.set(A.scale,A.scale,A.scale),o.scale.multiply(this.handLeftScale),Xg.markDirty(this.handLeft)}if(this.handRight){const o=this.isLocalAvatar?this.handRight:this._handRightTarget;o.position.set(A.posRightHand.x,A.posRightHand.y,A.posRightHand.z),o.quaternion.set(A.rotRightHand._x,A.rotRightHand._y,A.rotRightHand._z,A.rotRightHand._w),o.quaternion.multiply(Bl.invertRotation),o.scale.set(A.scale,A.scale,A.scale),o.scale.multiply(this.handRightScale),Xg.markDirty(this.handRight)}}}update(){if(this.isLocalAvatar||!this._canInterpolate)return;const A=this.context.time.deltaTime/.1;this.head&&(this.head.position.lerp(this._headTarget.position,A),this.head.quaternion.slerp(this._headTarget.quaternion,A),this.head.scale.lerp(this._headTarget.scale,A)),this.handLeft&&this._handLeftTarget&&(this.handLeft.position.lerp(this._handLeftTarget.position,A),this.handLeft.quaternion.slerp(this._handLeftTarget.quaternion,A),this.handLeft.scale.lerp(this._handLeftTarget.scale,A)),this.handRight&&this._handRightTarget&&(this.handRight.position.lerp(this._handRightTarget.position,A),this.handRight.quaternion.slerp(this._handRightTarget.quaternion,A),this.handRight.scale.lerp(this._handRightTarget.scale,A))}destroy(){var A,e;Ca&&console.log("Destroy avatar",this.guid),(A=this.root)==null||A.removeFromParent(),(e=this.avatarMarker)==null||e.destroy(),this.lastAvatarId=null,this.head&&lI.Remove(this.context,this.head)}updateVisibility(){const A=this.root;A&&IA.setActive(A,this._isVisible)}async setupCustomAvatar(A){var g,I,o;if(Ca&&console.log("LOAD",A,this),!A||typeof A=="string"&&A.length<=0)return!1;this.head&&lI.Remove(this.context,this.head);const e=A;if((e==null?void 0:e.loadAssetAsync)!==void 0){await e.loadAssetAsync();const s=e.asset;IA.setActive(s,!1),A=IA.instantiate(s),IA.setActive(A,!0)}Ca&&console.log(A);const t=await Bl.loader.getOrCreateNewAvatarInstance(this.context,A);if(Ca&&console.log(t,t==null?void 0:t.isValid,this.lastAvatarId,A),t!=null&&t.isValid){if(this.root=t.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=IA.addNewComponent(this.root,Qg),this.avatarMarker.connectionId=this.guid,this.avatarMarker.avatar=this,this.head&&this.head!==t.head&&((g=this.head)==null||g.removeFromParent()),this.head=t.head,this.headScale.copy(this.head.scale),this.head&&!this.isLocalAvatar&&lI.Add(this.context,this.head,this.avatarMarker),t.leftHand&&((I=this.handLeft)==null||I.removeFromParent()),this.handLeft=t.leftHand??this.handLeft,this.handLeft?this.handLeftScale.copy(this.handLeft.scale):this.handLeftScale.set(1,1,1),t.rigthHand&&((o=this.handRight)==null||o.removeFromParent()),this.handRight=t.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(...IA.getComponentsInChildren(this.root,Io)),this.flags.length<=0&&this.head){const s=IA.addNewComponent(this.head,Io);s.visibleIn=ki.ThirdPerson|ki.VR,this.flags.push(s),Ca&&console.log("Added flag to head: "+s.visibleIn,this.head.name)}return Ca&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return Ca&&console.warn("build avatar failed"),!1}};let In=Bl;r(In,"loader",new Ty),r(In,"invertRotation",new MA().setFromAxisAngle(new w(0,1,0),Math.PI));class lI{static Add(A,e,t=null){if(e){for(const g of this.Pois)if(g.obj===e)return;this.Pois.push({obj:e,avatar:t}),this.LastChangeTime=A.time.time}}static Remove(A,e){var t;if(e){for(const g of this.Pois)if(g.obj===e){this.Pois.splice(this.Pois.indexOf(g),1),this.LastChangeTime=(A==null?void 0:A.time.time)??((t=be.Current)==null?void 0:t.time.time);return}}}}r(lI,"Pois",[]),r(lI,"LastChangeTime",0);class egA{constructor(){r(this,"guid");r(this,"position",new w)}}class _l extends NA{constructor(){super(...arguments);r(this,"target",null);r(this,"avatar",null);r(this,"_model",null);r(this,"_targetModel",new egA);r(this,"_currentTargetObject",null);r(this,"_lastUpdateTime",0);r(this,"_lookDuration",0);r(this,"_lastPoiChangedTime",0)}set controlledTarget(e){this.target=e;const t=j.get("MoveRandom");if(t&&this.target){const g=IA.getComponent(this.target,t);g&&g.destroy()}}awake(){if(this.avatar=IA.getComponentInParent(this.gameObject,Qg),this.avatar){const e=IA.getComponentInParent(this.gameObject,Qg);this._model=new Cy(this.context.connection,this.guid),e!=null&&e.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{var t;this.target&&e&&e.guid===((t=this.avatar)==null?void 0:t.guid)&&Mi(this.target,e.position)})}update(){var t;if((!this.context.connection.isConnected||(t=this._model)!=null&&t.hasOwnership)&&(lI.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=lI.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const g=ce(this._currentTargetObject);Mi(this.target,g),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(g))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const t=lI.Pois;if(t.length>0){const g=t[Math.floor(Math.random()*t.length)];if(g&&g.obj){if(g.avatar&&g.avatar===this.avatar)return;this._currentTargetObject=g.obj}}}}}class Cc extends NA{constructor(){super(...arguments);r(this,"canGrab",!0)}onPointerClick(e){}}class ac extends NA{constructor(){super(...arguments);r(this,"isUsed",!0);r(this,"usedBy",null)}}var ng=(i=>(i[i.Average=0]="Average",i[i.Multiply=1]="Multiply",i[i.Minimum=2]="Minimum",i[i.Maximum=3]="Maximum",i))(ng||{}),Yy=(i=>(i[i.Discrete=0]="Discrete",i[i.Continuous=1]="Continuous",i))(Yy||{}),li=(i=>(i[i.None=0]="None",i[i.FreezePositionX=2]="FreezePositionX",i[i.FreezePositionY=4]="FreezePositionY",i[i.FreezePositionZ=8]="FreezePositionZ",i[i.FreezePosition=14]="FreezePosition",i[i.FreezeRotationX=16]="FreezeRotationX",i[i.FreezeRotationY=32]="FreezeRotationY",i[i.FreezeRotationZ=64]="FreezeRotationZ",i[i.FreezeRotation=112]="FreezeRotation",i[i.FreezeAll=126]="FreezeAll",i))(li||{}),XQ=(i=>(i[i.None=0]="None",i[i.X=2]="X",i[i.Y=4]="Y",i[i.Z=8]="Z",i[i.All=-1]="All",i))(XQ||{});const vg=function(i,A){return function(e,t,g){tgA(e,t,g,i,A)}};function tgA(i,A,e,t,g){if(!g&&!t&&!i.onValidate)return;if(e!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",i,A,e),mi("Invalid usage of validate decorator. Only fields can be validated. Property: "+A,Vo.Error);return}let I="";if(typeof A=="string"?I=A:I=A.name,i.__internalAwake){const o=Symbol(I),s=i.__internalAwake;i.__internalAwake=function(){var n;if(!this.onValidate){_e()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((n=i.constructor)==null?void 0:n.name)+'"');return}if(this[o]===void 0){this[o]=this[I];const C=this[I];if(C instanceof tA||C instanceof w||C instanceof Ae||C instanceof MA){const a=this[I];LR(a,()=>{this.onValidate(I)})}Object.defineProperty(this,I,{set:function(a){var B;if(this[NG]===!0)this[o]=a;else{t==null||t.call(this,a);const Q=this[o];this[o]=a,(B=this.onValidate)==null||B.call(this,I,Q)}},get:function(){return g==null||g.call(this),this[o]}})}s.call(this)}}}const igA=function(i){return function(A,e,t){let g="";typeof e=="string"?g=e:g=e.name;const I=i.prototype,o=Object.getOwnPropertyDescriptor(I,g);if(!(o!=null&&o.value)){console.warn("Can not apply prefix: type does not have method named",e,i);return}const s=o.value,n=A[g];Object.defineProperty(I,g,{value:function(...C){const a=n==null?void 0:n.call(this,...C);if(a instanceof Promise){a.then(B=>{if(B!==!1)return s.call(this,...C)});return}if(a!==!1)return s.call(this,...C)}})}};var ggA=Object.defineProperty,IgA=Object.getOwnPropertyDescriptor,es=(i,A,e,t)=>{for(var g=t>1?void 0:t?IgA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&ggA(A,e,g),g};class ogA{constructor(A,e){r(this,"positionChanged",!1);r(this,"rotationChanged",!1);r(this,"position");r(this,"quaternion");r(this,"_positionKeys",["x","y","z"]);r(this,"_quaternionKeys",["_x","_y","_z","_w"]);r(this,"mute",!1);r(this,"context");r(this,"obj");r(this,"_positionWatch");r(this,"_rotationWatch");this.context=e,this.obj=A}get isDirty(){return this.positionChanged||this.rotationChanged}reset(A=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,A){if(this.position)for(const e of this._positionKeys)delete this.position[e];if(this.quaternion)for(const e of this._quaternionKeys)delete this.quaternion[e]}}syncValues(){for(const A of this._positionKeys)this.position[A]=this.obj.position[A];for(const A of this._quaternionKeys)this.quaternion[A]=this.obj.quaternion[A]}applyValues(){if(this.positionChanged&&this.position)for(const A of this._positionKeys){const e=this.position[A];e!==void 0&&(this.obj.position[A]=e)}if(this.rotationChanged&&this.quaternion)for(const A of this._quaternionKeys){const e=this.quaternion[A];e!==void 0&&(this.obj.quaternion[A]=e)}}start(A,e){this.reset(),A&&(this._positionWatch||(this._positionWatch=new cC(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((I,o)=>{var n;if((n=this.context.physics.engine)!=null&&n.isUpdating||this.mute)return;const s=this.position[o];Math.abs(s-I)<1e-5||(this.position[o]=I,this.positionChanged=!0)})),e&&(this._rotationWatch||(this._rotationWatch=new cC(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((I,o)=>{var n;if((n=this.context.physics.engine)!=null&&n.isUpdating||this.mute)return;const s=this.quaternion[o];Math.abs(s-I)<1e-5||(this.quaternion[o]=I,this.rotationChanged=!0)}));const t=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),g=new FA;this.obj.matrixWorld.multiplyMatrices=(I,o)=>(g.equals(I)||(this.positionChanged=!0,this.rotationChanged=!0,g.copy(I)),t(I,o))}stop(){var A,e;(A=this._positionWatch)==null||A.revoke(),(e=this._rotationWatch)==null||e.revoke()}}var fm;const rM=(fm=class extends NA{constructor(){super(...arguments);r(this,"autoMass",!0);r(this,"_mass",0);r(this,"useGravity",!0);r(this,"constraints",li.None);r(this,"isKinematic",!1);r(this,"drag",0);r(this,"angularDrag",1);r(this,"detectCollisions",!0);r(this,"sleepThreshold",.01);r(this,"collisionDetectionMode",Yy.Discrete);r(this,"_gravityScale",1);r(this,"dominanceGroup",0);r(this,"_propertiesChanged",!1);r(this,"_currentVelocity",new w);r(this,"_smoothedVelocity",new w);r(this,"_smoothedVelocityGetter",new w);r(this,"_lastPosition",new w);r(this,"_watch")}set mass(A){A!==this._mass&&(this._mass=A,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var A,e;return this.autoMass?((e=(A=this.context.physics.engine)==null?void 0:A.getBody(this))==null?void 0:e.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&li.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&li.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&li.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&li.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&li.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&li.FreezeRotationZ)!==0}set lockPositionX(A){A?this.constraints|=li.FreezePositionX:this.constraints&=~li.FreezePositionX}set lockPositionY(A){A?this.constraints|=li.FreezePositionY:this.constraints&=~li.FreezePositionY}set lockPositionZ(A){A?this.constraints|=li.FreezePositionZ:this.constraints&=~li.FreezePositionZ}set lockRotationX(A){A?this.constraints|=li.FreezeRotationX:this.constraints&=~li.FreezeRotationX}set lockRotationY(A){A?this.constraints|=li.FreezeRotationY:this.constraints&=~li.FreezeRotationY}set lockRotationZ(A){A?this.constraints|=li.FreezeRotationZ:this.constraints&=~li.FreezeRotationZ}set gravityScale(A){this._gravityScale=A}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new ogA(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),Eg.LateUpdate)}onDisable(){var A,e;(A=this._watch)==null||A.stop(),(e=this.context.physics.engine)==null||e.removeBody(this)}onDestroy(){var A;(A=this.context.physics.engine)==null||A.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){var A,e,t,g;for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,(A=this.context.physics.engine)==null||A.updateProperties(this)),(e=this._watch)!=null&&e.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(t=this.context.physics.engine)==null||t.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(g=this._watch)==null||g.syncValues(),this.captureVelocity(),yield}teleport(A,e=!0){var t;(t=this._watch)==null||t.reset(!0),e?this.gameObject.position.set(A.x,A.y,A.z):this.setWorldPosition(A.x,A.y,A.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(A=!0){var e;(e=this.context.physics.engine)==null||e.resetForces(this,A)}resetTorques(A=!0){var e;(e=this.context.physics.engine)==null||e.resetTorques(this,A)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var A;(A=this.context.physics.engine)==null||A.wakeup(this)}applyForce(A,e,t=!0){var g;(g=this.context.physics.engine)==null||g.addForce(this,A,t)}applyImpulse(A,e=!0){var t;(t=this.context.physics.engine)==null||t.applyImpulse(this,A,e)}setForce(A,e,t,g=!0){var I,o,s;(I=this.context.physics.engine)==null||I.resetForces(this,g),typeof A=="number"?(e??(e=0),t??(t=0),(o=this.context.physics.engine)==null||o.addForce(this,{x:A,y:e,z:t},g)):(s=this.context.physics.engine)==null||s.addForce(this,A,g)}getVelocity(){var e;const A=(e=this.context.physics.engine)==null?void 0:e.getLinearVelocity(this);return A?(this._currentVelocity.x=A.x,this._currentVelocity.y=A.y,this._currentVelocity.z=A.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(A,e,t,g=!0){var I,o;if(A instanceof w){const s=A;(I=this.context.physics.engine)==null||I.setLinearVelocity(this,s,g);return}e===void 0||t===void 0||(o=this.context.physics.engine)==null||o.setLinearVelocity(this,{x:A,y:e,z:t},g)}getAngularVelocity(){var e;const A=(e=this.context.physics.engine)==null?void 0:e.getAngularVelocity(this);return A?(this._currentVelocity.x=A.x,this._currentVelocity.y=A.y,this._currentVelocity.z=A.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(A,e,t,g=!0){var I,o;if(A instanceof w){const s=A;(I=this.context.physics.engine)==null||I.setAngularVelocity(this,s,g);return}e===void 0||t===void 0||(o=this.context.physics.engine)==null||o.setAngularVelocity(this,{x:A,y:e,z:t},g)}setTorque(A,e,t){this.setAngularVelocity(A,e,t)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(A=null){}captureVelocity(){const A=ce(this.gameObject);rM.tempPosition.copy(A);const e=A.sub(this._lastPosition);this._lastPosition.copy(rM.tempPosition),this._smoothedVelocity.lerp(e,this.context.time.deltaTime/.1)}},r(fm,"tempPosition",new w),fm);let vt=rM;es([vg()],vt.prototype,"autoMass",2);es([D()],vt.prototype,"mass",1);es([vg(),D()],vt.prototype,"useGravity",2);es([vg(),D()],vt.prototype,"constraints",2);es([vg(),D()],vt.prototype,"isKinematic",2);es([vg(),D()],vt.prototype,"drag",2);es([vg(),D()],vt.prototype,"angularDrag",2);es([vg(),D()],vt.prototype,"detectCollisions",2);es([vg(),D()],vt.prototype,"sleepThreshold",2);es([vg(),D()],vt.prototype,"collisionDetectionMode",2);es([vg()],vt.prototype,"_gravityScale",2);es([vg()],vt.prototype,"dominanceGroup",2);class Qo{constructor(){r(this,"bb",null);r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(A,e,t,g){return A.prep(4,12),A.writeFloat32(g),A.writeFloat32(t),A.writeFloat32(e),A.offset()}}class tO{constructor(){r(this,"bb",null);r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}position(A){return(A||new Qo).__init(this.bb_pos,this.bb)}rotation(A){return(A||new Qo).__init(this.bb_pos+12,this.bb)}scale(A){return(A||new Qo).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(A,e,t,g,I,o,s,n,C,a){return A.prep(4,36),A.prep(4,12),A.writeFloat32(a),A.writeFloat32(C),A.writeFloat32(n),A.prep(4,12),A.writeFloat32(s),A.writeFloat32(o),A.writeFloat32(I),A.prep(4,12),A.writeFloat32(g),A.writeFloat32(t),A.writeFloat32(e),A.offset()}}class iC{constructor(){r(this,"bb",null);r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}static getRootAsSyncedTransformModel(A,e){return(e||new iC).__init(A.readInt32(A.position())+A.position(),A)}static getSizePrefixedRootAsSyncedTransformModel(A,e){return A.setPosition(A.position()+oy),(e||new iC).__init(A.readInt32(A.position())+A.position(),A)}guid(A){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,A):null}fast(){const A=this.bb.__offset(this.bb_pos,6);return A?!!this.bb.readInt8(this.bb_pos+A):!1}transform(A){const e=this.bb.__offset(this.bb_pos,8);return e?(A||new tO).__init(this.bb_pos+e,this.bb):null}dontSave(){const A=this.bb.__offset(this.bb_pos,10);return A?!!this.bb.readInt8(this.bb_pos+A):!1}static startSyncedTransformModel(A){A.startObject(4)}static addGuid(A,e){A.addFieldOffset(0,e,0)}static addFast(A,e){A.addFieldInt8(1,+e,0)}static addTransform(A,e){A.addFieldStruct(2,e,0)}static addDontSave(A,e){A.addFieldInt8(3,+e,0)}static endSyncedTransformModel(A){return A.endObject()}static finishSyncedTransformModelBuffer(A,e){A.finish(e)}static finishSizePrefixedSyncedTransformModelBuffer(A,e){A.finish(e,void 0,!0)}}const ga=sA("debugsync"),Ol="STRS";sy(Ol,iC.getRootAsSyncedTransformModel);const Ts=new ZE;function iO(i,A,e=!0){Ts.clear();const t=Ts.createString(i);iC.startSyncedTransformModel(Ts),iC.addGuid(Ts,t),iC.addFast(Ts,e);const g=A.worldPosition,I=A.worldEuler,o=A.gameObject.scale;iC.addTransform(Ts,tO.createTransform(Ts,g.x,g.y,g.z,I.x,I.y,I.z,o.x,o.y,o.z));const s=iC.endSyncedTransformModel(Ts);return Ts.finish(s,Ol),Ts.asUint8Array()}class ba extends NA{constructor(){super(...arguments);r(this,"overridePhysics",!0);r(this,"interpolatePosition",!0);r(this,"interpolateRotation",!0);r(this,"fastMode",!1);r(this,"syncDestroy",!1);r(this,"_model",null);r(this,"_needsUpdate",!0);r(this,"rb",null);r(this,"_wasKinematic",!1);r(this,"_receivedDataBefore",!1);r(this,"_targetPosition");r(this,"_targetRotation");r(this,"_receivedFastUpdate",!1);r(this,"_shouldRequestOwnership",!1);r(this,"joinedRoomCallback",null);r(this,"receivedDataCallback",null);r(this,"tempEuler",new $i);r(this,"receivedUpdate",!1);r(this,"lastWorldPos");r(this,"lastWorldRotation")}requestOwnership(){ga&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){var e;return((e=this._model)==null?void 0:e.hasOwnership)??void 0}isOwned(){var e;return(e=this._model)==null?void 0:e.isOwned}awake(){ga&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new w,this._targetRotation=new MA,this.lastWorldPos=new w,this.lastWorldRotation=new MA,this.rb=IA.getComponentInChildren(this.gameObject,vt),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Cy(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(Ht.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(Ol,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&mY(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(Ht.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(Ol,this.receivedDataCallback)}tryGetLastState(){const e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}onReceivedData(e){var t;if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){ga&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();const g=e.transform();if(g){Xg.markDirty(this.gameObject,!0);const I=g.position();I&&(this.interpolatePosition&&((t=this._targetPosition)==null||t.set(I.x(),I.y(),I.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(I.x(),I.y(),I.z()));const o=g.rotation();o&&(this.tempEuler.set(o.x(),o.y(),o.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&WR(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){ga&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const e=this.worldPosition,t=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const o=e.distanceTo(this.lastWorldPos),s=t.angleTo(this.lastWorldRotation),n=this._model.hasOwnership||this.fastMode?1e-4:.001;(o>n||s>n)&&(this._model.hasOwnership?this._needsUpdate=!0:(ga&&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),Xg.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const s=this._receivedFastUpdate||this.fastMode?.5:.3;let n=!1;if(this.interpolatePosition&&this._targetPosition){const C=this.worldPosition;C.lerp(this._targetPosition,s),this.worldPosition=C,n=!0}if(this.interpolateRotation&&this._targetRotation){const C=this.worldQuaternion;C.slerp(this._targetRotation,s),this.worldQuaternion=C,n=!0}n&&Xg.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&&(ga&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new w(0,0,0))>1e3&&(ga&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0)));const g=10,I=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%g===0||I)){ga&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this.overridePhysics&&this.rb,this._needsUpdate=!1;const o=iO(this.guid,this,!!I);this.context.connection.sendBinary(o)}}}const sgA=sA("debugshadowcomponents");IF.prototype.interactable={get(){return this.interactive},set(i){this.interactable=i}};const Yo=Symbol("shadowDomOwner");class ms extends NA{constructor(){super(...arguments);r(this,"shadowComponent",null);r(this,"_controlsChildLayout",!0);r(this,"_root");r(this,"_parentComponent")}isRoot(){var e;return((e=this.Root)==null?void 0:e.gameObject)===this.gameObject}get canvas(){const e=this.Root;return e!=null&&e.isCanvas?e:null}markDirty(){cI.markUIDirty(this.context)}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}get Root(){return this._root===void 0&&(this._root=IA.getComponentInParent(this.gameObject,zd)),this._root}get Canvas(){return this.canvas}__internalNewInstanceCreated(){super.__internalNewInstanceCreated(),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0}onEnable(){super.onEnable()}addShadowComponent(e,t){var o;this.removeShadowComponent();const g=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=IA.getComponentInParent(g,ms),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[Yo]=this,this.setShadowComponentOwner(e);let I=!1;if(((o=this.Root)==null?void 0:o.gameObject)===this.gameObject)this.gameObject.add(e);else{const s=this._parentComponent.shadowComponent;s&&(s==null||s.add(e),I=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),qd&&e.add(new jE(.5)),this.onAfterAddedToScene(),I&&L2(),sgA&&console.log(this.shadowComponent)}set(e){}setShadowComponentOwner(e){if(e&&(e[Yo]===void 0||e[Yo]===this)&&(e[Yo]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,g){if(e&&e[Yo]===t){g(e);for(const I of e.children)this.traverseOwnedShadowComponents(I,t,g)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class zd extends ms{awake(){super.awake()}}class LE{static getObject(A){const e=A[Yo];return e&&(e.isComponent===!0?A=e.gameObject:A=e),A}static isInteractable(A,e){if(e&&(e.canvasGroup=void 0,e.graphic=void 0),A==null||!A.visible||(A=this.getObject(A),!A.visible))return!1;const t=this.tryFindCanvasGroup(A);if((t==null?void 0:t.isCanvasGroup)===!0&&(e&&(e.canvasGroup=t),t.blocksRaycasts===!1||t.interactable===!1))return!1;const g=EB(A,I=>{if(I.isGraphic===!0)return I},!1);return e&&(g==null?void 0:g.isGraphic)===!0&&(e.graphic=g),!((g==null?void 0:g.raycastTarget)===!1||(g==null?void 0:g.layer)===2)}static tryFindCanvasGroup(A){if(!A)return null;const e=EB(A,t=>{const g=t;if(g.blocksRaycasts!==void 0&&g.interactable!==void 0)return g},!1);return e!==void 0?e:this.tryFindCanvasGroup(A.parent)}}const Mh=sA("debugwebxrcontroller");var EE=(i=>(i[i.PhysicalDevice=0]="PhysicalDevice",i[i.Touch=1]="Touch",i))(EE||{}),jn=(i=>(i.SelectStart="select-start",i.SelectEnd="select-end",i.Update="update",i))(jn||{});class Hy extends NA{}const Cg=class extends NA{constructor(){super(...arguments);r(this,"webXR");r(this,"index",-1);r(this,"controllerModel");r(this,"controller");r(this,"controllerGrip");r(this,"hand");r(this,"handPointerModel");r(this,"grabbed",null);r(this,"input",null);r(this,"type",0);r(this,"showRaycastLine",!0);r(this,"enableRaycasts",!0);r(this,"enableDefaultControls",!0);r(this,"_wristQuaternion",null);r(this,"movementVector",new w);r(this,"worldRot",new MA);r(this,"joystick",new tA);r(this,"didRotate",!1);r(this,"didTeleport",!1);r(this,"didChangeScale",!1);r(this,"lastHit",null);r(this,"raycastLine",null);r(this,"_raycastHitPoint",null);r(this,"_connnectedCallback",null);r(this,"_disconnectedCallback",null);r(this,"_selectStartEvt",null);r(this,"_selectEndEvt",null);r(this,"_selectionPressed",!1);r(this,"_selectionPressedLastFrame",!1);r(this,"_selectionStartTime",0);r(this,"_selectionEndTime",0);r(this,"_useSmoothing",!0);r(this,"_isConnected",!1);r(this,"rayRotation",new MA);r(this,"_pinchStartTime");r(this,"selectStartCallback",null);r(this,"lastSelectStartObject",null);r(this,"_didNotEndSelection",!1);r(this,"closeGrabBoundingBoxHelper")}static CreateRaycastLine(){const e=new yi(this.geometry),t=e.material;return t.color=this.raycastColor,e.layers.set(2),e.name="line",e.scale.z=1,e}static CreateRaycastHitPoint(){const e=new $o(.5,22,22),t=new rt({color:this.raycastColor}),g=new pA(e,t);return g.visible=!1,g.layers.set(2),g}static Create(e,t,g,I){const o=g?IA.addNewComponent(g,Cg,!1):new Cg;o.webXR=e,o.index=t,o.type=I;const s=e.context;o.controller=s.renderer.xr.getController(t),o.controllerGrip=s.renderer.xr.getControllerGrip(t),o.controllerModel=this.Factory.createControllerModel(o.controller),o.controllerGrip.add(o.controllerModel),o.hand=s.renderer.xr.getHand(t);const n=new ic;xd(n,s),o.webXR.handModelPath&&o.webXR.handModelPath!==""?n.setPath(FC(e.sourceId,o.webXR.handModelPath)):n.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/");const C=new FiA(o.hand,n);return o.hand.add(C),o.hand.traverse(a=>a.layers.set(2)),o.handPointerModel=new LiA(o.hand,o.controller),o.controller.addEventListener("connected",a=>{o.setControllerLayers(o.controllerModel,2),o.setControllerLayers(o.controllerGrip,2),o.setControllerLayers(o.hand,2),setTimeout(()=>{o.setControllerLayers(o.controllerModel,2),o.setControllerLayers(o.controllerGrip,2),o.setControllerLayers(o.hand,2)},1e3)}),o.hand.addEventListener("connected",a=>{var Q;if(a.data.hand){e.Rig&&e.Rig.add(o.hand),o.type=0,o.handPointerModel.traverse(c=>c.layers.set(2)),(Q=o.handPointerModel.pointerObject)==null||Q.traverse(c=>c.layers.set(2));const E=o.hand.joints;if(E)for(const c of Object.keys(E)){const d=E[c];d.parent||o.hand.add(d)}}}),o}static addEventListener(e,t){const g=this.eventSubs[e]??[];g.push(t),this.eventSubs[e]=g}static removeEventListener(e,t){if(!t)return;const g=this.eventSubs[e]??[],I=g.indexOf(t);I>=0&&g.splice(I,1),this.eventSubs[e]=g}get isUsingHands(){var t;const e=(t=this.input)==null?void 0:t.hand;return e!=null}get wrist(){if(!this.hand)return null;const e=this.hand.joints;return e?e.wrist:null}getWristQuaternion(){const e=this.wrist;return e?(this._wristQuaternion||(this._wristQuaternion=new MA),Ft(e).multiply(this._wristQuaternion.setFromEuler(new $i(-Math.PI/4,0,0)))):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}get useSmoothing(){return this._useSmoothing}awake(){if(!this.controller){console.warn("WebXRController: Missing controller object.",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(){var e,t,g;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)),(e=this.hand)==null||e.clear(),(t=this.controllerGrip)==null||t.clear(),(g=this.controller)==null||g.clear()}onEnable(){var e,t,g,I,o;if(!this.webXR){console.warn("No WebXR component assigned to WebXRController.");return}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=Cg.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=Cg.CreateRaycastHitPoint()),(e=this.webXR.Rig)==null||e.add(this.hand),(t=this.webXR.Rig)==null||t.add(this.controllerGrip),(g=this.webXR.Rig)==null||g.add(this.controller),(I=this.webXR.Rig)==null||I.add(this.raycastLine),(o=this.raycastLine)==null||o.add(this._raycastHitPoint),this._raycastHitPoint.visible=!1,this.hand.add(this.handPointerModel),Mh&&console.log("ADDED TO RIG",this.webXR.Rig)}onDisable(){var e,t,g,I,o;if((e=this.hand)==null||e.removeFromParent(),(t=this.controllerGrip)==null||t.removeFromParent(),(g=this.controller)==null||g.removeFromParent(),(I=this.raycastLine)==null||I.removeFromParent(),(o=this._raycastHitPoint)==null||o.removeFromParent(),this.webXR){const s=this.webXR.Controllers.indexOf(this);s>=0&&this.webXR.Controllers.splice(s,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()}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.input=null}createPointerEvent(e){switch(e){case"down":this.context.input.createPointerDown(new Vn(wi.PointerDown,null,{clientX:0,clientY:0,button:this.index,pointerType:RE.Touch}));break;case"move":break;case"up":this.context.input.createPointerUp(new Vn(wi.PointerUp,null,{clientX:0,clientY:0,button:this.index,pointerType:RE.Touch}));break}}raycastUpdate(e,t){const g=this.showRaycastLine&&this.type!==1;if(this.type===1)e.visible=!1;else if(this.isUsingHands){e.visible=!this.grabbed&&g,Mi(e,t);const I=this.hand.joints;if(I&&I.wrist&&this.grabbed&&this.grabbed.isCloseGrab){const s=this.getWristQuaternion();s&&this.rayRotation.copy(s)}uI(e,this.rayRotation)}else e.visible=g,uI(e,this.rayRotation),Mi(e,t)}update(){if(!this.webXR)return;this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));const e=Cg.eventSubs.update;if(e&&e.length>0)for(const I of e)I(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(Ft(this.controller),this.useSmoothing?t:1);const g=ce(this.controller);this.isUsingHands&&this.handPointerModel.cursorObject&&(this.handPointerModel.cursorObject.visible=!1),this.enableRaycasts?(this.raycastLine&&this.raycastUpdate(this.raycastLine,g),this.lastHit=this.updateLastHit(),this.grabbed&&this.grabbed.update()):this.raycastLine&&(this.raycastLine.visible=!1),this._selectionPressedLastFrame=this._selectionPressed,this.selectStartCallback&&this.selectStartCallback()}onUpdate(e){var I,o;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;const t=this.webXR.Rig;if(!t)return;this._didNotEndSelection&&!this.handPointerModel.pinched&&(this._didNotEndSelection=!1,this.onSelectEnd()),this.updateStick(this.input);const g=(o=(I=this.input)==null?void 0:I.gamepad)==null?void 0:o.buttons;if(this.enableDefaultControls)switch(this.input.handedness){case"left":this.movementUpdate(t,g);break;case"right":this.rotationUpdate(t,g);break}}movementUpdate(e,t){const g=3*Cg.MovementSpeedFactor,I=2,o=ne.clamp01(this.joystick.length()*2),s=this.joystick.x>0?1:-1;let n=Math.pow(this.joystick.x,I);n*=s,n*=o;const C=this.joystick.y>0?1:-1;let a=Math.pow(this.joystick.y,I);a*=C,n*=o,e.getWorldQuaternion(this.worldRot),this.movementVector.set(n,0,a),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),this.movementVector.multiplyScalar(g*this.context.time.deltaTime),e.position.add(this.movementVector),this.isUsingHands&&this.runTeleport(e,t)}rotationUpdate(e,t){const g=this.joystick.x,I=Math.abs(g);if(I<.4)this.didRotate=!1;else if(I>.5&&!this.didRotate){const o=g>0?-1:1;e.rotateY(ne.toRadians(30*o)),this.didRotate=!0}this.runTeleport(e,t)}runTeleport(e,t){var a,B;let g=-this.joystick.y;if((a=this.hand)!=null&&a.visible&&!this.grabbed){const Q=this.handPointerModel.isPinched();Q&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),Q&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(g=this.handPointerModel.isPinched()?1:0),Q||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;const I=this.webXR.IsInVR,o=this.webXR.Rig;let s=g>.5&&I,n=o?((B=o==null?void 0:o.scale)==null?void 0:B.x)<.999:!1,C=null;if(t&&this.input&&!this.input.hand)for(let Q=0;Q<t.length;Q++){const E=t[Q];if(Q===4)if(E.pressed&&!this.didChangeScale&&I){this.didChangeScale=!0;const c=o;if(c){const d=this.switchScale(c,s,n,C);s=d.doTeleport,n=d.isInMiniatureMode,C=d.newRigScale}}else E.pressed||(this.didChangeScale=!1)}if(s){if(!this.didTeleport){const Q=this.raycast();if(this.didTeleport=!0,Q&&Q.length>0){const E=Q[0];if(n||this.isValidTeleportTarget(E.object)){const c=E.point;Mi(e,c)}}}}else g<.1&&(this.didTeleport=!1);C!==null&&(e.scale.set(C,C,C),e.updateMatrixWorld())}isValidTeleportTarget(e){return IA.getComponentInParent(e,Hy)!=null}switchScale(e,t,g,I){if(g){g=!1,e.scale.set(1,1,1),I=1,Cg.MovementSpeedFactor=1;const o=this.context.mainCamera;Cg.PreviousCameraFarDistance&&(o.far=Cg.PreviousCameraFarDistance)}else{g=!0,t=!0,I=.1,Cg.MovementSpeedFactor=I*2;const o=this.context.mainCamera;Cg.PreviousCameraFarDistance=o.far,o.far/=I}return{doTeleport:t,isInMiniatureMode:g,newRigScale:I}}updateStick(e){var t;!e||!e.gamepad||((t=e.gamepad.axes)==null?void 0:t.length)<4||(this.joystick.x=e.gamepad.axes[2],this.joystick.y=e.gamepad.axes[3])}updateLastHit(){var I;const e=this.raycast(),t=e?e[0]:null;this.lastHit=t;let g=1;if(this.webXR.Rig&&(g/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=g*(((I=this.lastHit)==null?void 0:I.distance)??9999);const o=this.raycastLine.material;t!=null?o.color=Cg.raycastColor:o.color=Cg.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;const o=ne.clamp(this.lastHit.distance*.01*g,.015,.1);this._raycastHitPoint.scale.set(o,o,o)}this._raycastHitPoint.visible=this.lastHit!==null&&this.lastHit!==void 0}return t}onSelectStart(){this.context.connection.allowEditing&&(this.selectStartCallback=()=>this.onHandleSelectStart())}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(),Mh&&console.log("onHandleSelectStart","close grab? "+t,"intersections",e),e&&e.length>0)for(const g of e){const I=g.object;this.lastSelectStartObject=I;const o={selected:I,grab:I},s=Cg.eventSubs["select-start"];if(s&&s.length>0)for(const n of s)n(this,o);o.grab!==I&&Mh&&console.log("Grabbed object changed","original",I,"new",o.grab),o.grab&&(this.grabbed=Oo.TryTake(this,o.grab,g,t));break}else{const g=Cg.eventSubs["select-start"],I={selected:null,grab:null};if(g&&g.length>0)for(const o of g)o(this,I)}}onSelectEnd(){var g;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;const e={grab:((g=this.grabbed)==null?void 0:g.selected)??this.lastSelectStartObject},t=Cg.eventSubs["select-end"];if(t&&t.length>0)for(const I of t)I(this,e);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(e){return!(!e||IA.isActiveInHierarchy(e)===!1||LE.isInteractable(e)===!1)}setControllerLayers(e,t){var g,I;if(e&&(e.layers.set(t),e.children))for(const o of e.children)((g=this.grabbed)==null?void 0:g.selected)===o||((I=this.grabbed)==null?void 0:I.selectedMesh)===o||this.setControllerLayers(o,t)}getRay(){const e=new Us;return e.origin.copy(ce(this.controller)),e.direction.set(0,0,-1).applyQuaternion(this.rayRotation),e}overlap(){const e=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(Mh&&(!this.closeGrabBoundingBoxHelper&&e&&(this.closeGrabBoundingBoxHelper=new gy(e,16776960),this.scene.add(this.closeGrabBoundingBoxHelper)),this.closeGrabBoundingBoxHelper&&e&&this.closeGrabBoundingBoxHelper.setFromObject(e)),!e)return new Array;const t=ce(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){const e=new ro;e.layerMask=new jg,e.layerMask.enableAll(),e.layerMask.disable(2),e.ray=this.getRay();const t=this.context.physics.raycast(e);for(let g=0;g<t.length;g++){const I=t[g],o=I.object;if(!this.testIsVisible(o)){t.splice(g,1),g--;continue}I.object=LE.getObject(o);break}return t}};let Bi=Cg;r(Bi,"Factory",new ZiA),r(Bi,"raycastColor",new yA(.9,.3,.3)),r(Bi,"raycastNoHitColor",new yA(.6,.6,.6)),r(Bi,"geometry",new de().setFromPoints([new w(0,0,0),new w(0,0,-1)])),r(Bi,"handModels",{}),r(Bi,"eventSubs",{}),r(Bi,"PreviousCameraFarDistance"),r(Bi,"MovementSpeedFactor",1);var jD=(i=>(i.WillTake="WillTake",i.DidTake="DidTake",i.WillFree="WillFree",i.DidFree="DidFree",i))(jD||{});const CI=class{constructor(){r(this,"sync",null);r(this,"selected",null);r(this,"selectedParent",null);r(this,"selectedMesh",null);r(this,"controller",null);r(this,"grabTime",0);r(this,"grabUUID","");r(this,"isCloseGrab",!1);r(this,"originalMaterial",null);r(this,"usageMarker",null);r(this,"rigidbodies",null);r(this,"didReparent",!1);r(this,"grabDistance",0);r(this,"interactable",null);r(this,"positionSource",null);r(this,"grabPoint",new w);r(this,"localPositionOffsetToGrab",null);r(this,"localPositionOffsetToGrab_worldSpace",new w);r(this,"localQuaternionToGrab",new MA(0,0,0,1));r(this,"targetDir",null);r(this,"quaternionLerp",null);r(this,"controllerDir",new w);r(this,"controllerWorldPos",new w);r(this,"lastControllerWorldPos",new w);r(this,"controllerPosDelta",new w);r(this,"totalChangeAlongDirection",0);r(this,"rigPositionLastFrame",new w)}static AddEventListener(A,e){return CI.Events[A]||(CI.Events[A]=[]),CI.Events[A].push(e),e}static RemoveEventListener(A,e){if(!e||!CI.Events[A])return;const t=CI.Events[A].indexOf(e);t>=0&&CI.Events[A].splice(t,1)}static Register(A){this.Current.find(e=>e===A)||this.Current.push(A)}static Remove(A){const e=this.Current.indexOf(A);e>=0&&this.Current.splice(e,1)}static TryTake(A,e,t,g){const I=IA.getComponentInParent(e,Cc);if(I)e=I.gameObject;else return Mh&&console.warn("Prevented taking object that is not interactable",e),null;let o=e;const s=IA.getComponentInParent(e,ba);s&&(s.requestOwnership(),o=s.gameObject);for(const C of this.Current)if(C.selected===o)return C.controller===A||(C.free(),C.Take(A,o,e,s,I,t,g)),C;const n=new CI;return n.Take(A,o,e,s,I,t,g),n}Take(A,e,t,g,I,o,s){var E,c;if(console.assert(e!==null,"Expected object to be taken but was",e),A.isUsingHands?this.positionSource=s?A.wrist:A.controller:this.positionSource=A.controller,!this.positionSource)return console.warn("No position source"),this;const n={controller:A,take:e,hit:t,sync:g,interactable:I};(E=CI.Events.WillTake)==null||E.forEach(d=>d(this,n));const C=t;C!=null&&C.material&&(this.originalMaterial=C.material,Array.isArray(C.material)||(C.material=C.material.clone(),C.material&&C.material.emissive&&(C.material.emissive.b=.2))),this.selected=e,this.selectedParent||(this.selectedParent=e.parent),this.selectedMesh=C,this.controller=A,this.interactable=I,this.isCloseGrab=s,this.didReparent=!1,this.sync=g,this.grabTime=A.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=IA.addNewComponent(this.selected,ac),this.rigidbodies=IA.getComponentsInChildren(this.selected,vt),ce(this.positionSource,this.lastControllerWorldPos);const a=()=>s?this.lastControllerWorldPos.clone():o.point.clone();this.grabDistance=a().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(a());const B=A.isUsingHands&&s?this.controller.getWristQuaternion().clone():A.rayRotation.clone();Ft(this.selected,this.localQuaternionToGrab).premultiply(B.invert());const Q=this.controller.webXR.Rig;return Q&&this.rigPositionLastFrame.copy(ce(Q)),lI.Add(A.context,this.selected),CI.Register(this),this.sync&&(this.sync.fastMode=!0),(c=CI.Events.DidTake)==null||c.forEach(d=>d(this,n)),this}free(){var g,I,o,s;if(!this.selected)return;const A={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};(g=CI.Events.WillFree)==null||g.forEach(n=>n(this,A)),lI.Remove(this.controller.context,this.selected),CI.Remove(this),this.sync&&(this.sync.fastMode=!1);const e=this.selectedMesh;e&&this.originalMaterial&&e.material&&(e.material=this.originalMaterial);const t=this.selected;if(this.didReparent&&t.parent){const n=this.selectedParent;n?n.attach(t):(I=this.controller)==null||I.context.scene.attach(t)}if((o=this.usageMarker)==null||o.destroy(),this.controller&&(this.controller.grabbed=null),this.selected=null,this.selectedParent=null,this.selectedMesh=null,this.sync=null,this.rigidbodies)for(const n of this.rigidbodies)n.wakeUp(),n.setVelocity(n.smoothedVelocity);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,(s=CI.Events.DidFree)==null||s.forEach(n=>n(this,A))}controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),ce(this.positionSource,this.controllerWorldPos),this.controllerPosDelta.copy(this.controllerWorldPos),this.controllerPosDelta.sub(this.lastControllerWorldPos),this.lastControllerWorldPos.copy(this.controllerWorldPos);const A=this.controller.webXR.Rig;if(A){const t=ce(A),g=this.rigPositionLastFrame.sub(t);this.controllerPosDelta.add(g),this.rigPositionLastFrame.copy(t)}return this.controllerDir.dot(this.controllerPosDelta)}update(){var A;if(this.rigidbodies)for(const 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){const e=((A=this.controller.webXR.Rig)==null?void 0:A.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 w),this.targetDir.set(0,0,-this.grabDistance*t);const g=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),I=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=I.clone()),this.quaternionLerp.slerp(I,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),uI(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(g),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(ce(this.selected)),g.sub(this.localPositionOffsetToGrab_worldSpace)),Mi(this.selected,g)}if(this.rigidbodies!=null)for(const e of this.rigidbodies)e.wakeUp();Xg.markDirty(this.selected,!0)}}};let Oo=CI;r(Oo,"Events",{}),r(Oo,"Current",[]);class CC{constructor(A,e){r(this,"used",!1);r(this,"inputSource");r(this,"object");r(this,"point");r(this,"normal");r(this,"face");r(this,"distance");r(this,"instanceId");r(this,"pointerId");r(this,"isDown");r(this,"isUp");r(this,"isPressed");r(this,"isClicked");r(this,"button");r(this,"input");r(this,"_event");this._event=e,this.input=A,this.button=(e==null?void 0:e.button)??0}use(){this.used=!0,this.pointerId!==void 0&&this.input.setPointerUsed(this.pointerId)}stopPropagation(){var A;(A=this._event)==null||A.stopImmediatePropagation()}Use(){this.use()}StopPropagation(){var A;(A=this._event)==null||A.stopImmediatePropagation()}get event(){return this._event}clone(){const A=new CC(this.input,this._event);return Object.assign(A,this),A}}function BM(i){return IA.foreachComponent(i,e=>{const t=e;if(t.onPointerDown||t.onPointerUp||t.onPointerEnter||t.onPointerExit||t.onPointerClick)return!0},!1)===!0}var ngA=Object.defineProperty,CgA=Object.getOwnPropertyDescriptor,agA=(i,A,e,t)=>{for(var g=t>1?void 0:t?CgA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&ngA(A,e,g),g};class $a extends NA{awake(){cI.createIfNoneExists(this.context)}onEnable(){var A;(A=cI.get(this.context))==null||A.register(this)}onDisable(){var A;(A=cI.get(this.context))==null||A.unregister(this)}performRaycast(A=null){return null}}class Gs extends $a{constructor(){super(...arguments);r(this,"targets",null);r(this,"raycastHits",[]);r(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??(e=new ro),e.targets=this.targets,e.results=this.raycastHits;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=I=>I instanceof ws?"continue in children":t?t(I):!0);const g=this.context.physics.raycast(e);return e.testObject=t,g}}agA([D()],Gs.prototype,"ignoreSkinnedMeshes",2);class _y extends Gs{constructor(){super(),this.ignoreSkinnedMeshes=!0}}function Oy(i){const A=i[Yo];return A||(i.parent?Oy(i.parent):null)}function rgA(i){return i.isUI===!0||typeof i[Yo]=="object"}function ZD(i,A){if(!i)return;const e=i.material;if((e==null?void 0:e.isMaterial)===!0){const t=i.parent;t&&t.isText,e.side=A.doubleSided??!0?St:$g,e.shadowSide=A.doubleSided?St:$g,i.castShadow=A.castShadows?A.castShadows:!1,i.receiveShadow=A.receiveShadows?A.receiveShadows:!1}for(const t of i.children)ZD(t,A)}function xQ(i,A,e){i[A]===void 0&&console.warn("Field",A,"is undefined on",i);const t=Proxy.revocable(i[A],{set(o,s,n,C){const a=o[s],B=Reflect.set(o,s,n,C);return e(n,a),B}}),g=t.revoke,I=i[A];return t.revoke=()=>{i[A]=I,g()},i[A]=t.proxy,t}const eb=Symbol("Scheduled action");function BgA(i,A,e=Eg.OnBeforeRender){let t=i[eb];t||(t=i[eb]={});const g=A.name;t[e]||(t[e]={});const I=t[e];if(I[g])return;function*s(){A==null||A.call(i),I[g]=null}const n=i.startCoroutine(s(),e);I[g]=n}const br=sA("debugeventsystem");var QM=(i=>(i.BeforeHandleInput="BeforeHandleInput",i.AfterHandleInput="AfterHandleInput",i))(QM||{});const Ps=class extends NA{constructor(){super();r(this,"raycaster",[]);r(this,"_selectStartFn");r(this,"_selectEndFn");r(this,"_selectUpdateFn");r(this,"_handleEventCycleFn");r(this,"_handleInputFn");r(this,"pressedByID",new Map);r(this,"hoveredByID",new Map);r(this,"_sortedHits",[]);r(this,"_testObjectsCache",new Map);r(this,"shouldRaycastObject",e=>{var I;let t=null;if(rgA(e)&&(t=(I=e[Yo])==null?void 0:I.gameObject),this._testObjectsCache.has(e)||t&&this._testObjectsCache.has(t))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let o=BM(e);return!o&&t&&(o=BM(t)),o?(this._testObjectsCache.set(e,!0),e.traverse(s=>{this._testObjectsCache.set(s,!0)}),!0):(this._testObjectsCache.set(e,!1),"continue in children")}});r(this,"_sortingBuffer",[]);r(this,"_noDepthTestingResults",[]);r(this,"out",{});r(this,"currentActiveMeshUIComponents",[]);Ps.systems.push(this)}static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Ps.systems.length<=0&&Ps.systems.push(...IA.findObjectsOfType(Ps,e)));for(const g of Ps.systems)if(g.context===e)return;const t=new SA;IA.addNewComponent(t,Ps),e.scene.add(t)}static get systems(){const e=be.Current;return this._eventSystemMap.has(e)||this._eventSystemMap.set(e,[]),this._eventSystemMap.get(e)}static get(e){const t=this._eventSystemMap.get(e);return t&&t.length>0?t[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(e,t,g=!1){Zn.update(e,t,g)}static markUIDirty(e){Zn.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}onDestroy(){Ps.systems.splice(Ps.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!IA.findObjectOfType($a,this.context)){const t=IA.addNewComponent(this.context.scene,Gs);t.ignoreSkinnedMeshes=!0,this.raycaster.push(t),(_e()||br)&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found. Skinnedmeshes will be ignored for better performance")}}register(e){var t;e&&this.raycaster&&!this.raycaster.includes(e)&&((t=this.raycaster)==null||t.push(e))}unregister(e){var g,I;const t=(g=this.raycaster)==null?void 0:g.indexOf(e);t!==void 0&&t!==-1&&((I=this.raycaster)==null||I.splice(t,1))}onEnable(){const e=new Map;this._selectStartFn??(this._selectStartFn=(g,I)=>{if(!I.grab)return;Zn.resetLastSelected();const o=new CC(this.context.input);o.inputSource=g,o.pointerId=0,o.isDown=g.selectionDown,o.isUp=g.selectionUp,o.isPressed=g.selectionPressed,o.isClicked=!1,e.set(g,I.grab),I.grab&&!this.handleEventOnObject(I.grab,o)&&(I.grab=null)}),this._selectEndFn??(this._selectEndFn=(g,I)=>{var n;if(!I.grab)return;const o=new CC(this.context.input);o.inputSource=g,o.pointerId=0,o.isDown=g.selectionDown,o.isUp=g.selectionUp,o.isPressed=g.selectionPressed,o.isClicked=g.selectionClick,this.handleEventOnObject(I.grab,o);const s=e.get(g);if(e.set(g,null),s)for(const C of this.pressedByID.keys()){const a=this.pressedByID[C];a.obj===s&&a.handler&&((n=a.handler.onPointerUp)==null||n.call(a.handler,o),this.pressedByID.delete(C))}});const t=new ro;this._selectUpdateFn??(this._selectUpdateFn=g=>{var s;t.ray=g.getRay();const I=this.performRaycast(t);if(!I)return;const o=new CC(this.context.input);o.inputSource=g,o.pointerId=((s=g.input)==null?void 0:s.handedness)==="right"?0:1,o.isDown=g.selectionDown,o.isUp=g.selectionUp,o.isPressed=g.selectionPressed,o.isClicked=!1,this.handleIntersections(I,o)}),Bi.addEventListener(jn.SelectStart,this._selectStartFn),Bi.addEventListener(jn.SelectEnd,this._selectEndFn),Bi.addEventListener(jn.Update,this._selectUpdateFn),this._handleInputFn=this.onPointerEvent.bind(this),this.context.input.addEventListener(wi.PointerDown,this._handleInputFn),this.context.input.addEventListener(wi.PointerUp,this._handleInputFn),this.context.input.addEventListener(wi.PointerMove,this._handleInputFn)}onDisable(){Bi.removeEventListener(jn.SelectStart,this._selectStartFn),Bi.removeEventListener(jn.SelectEnd,this._selectEndFn),Bi.removeEventListener(jn.Update,this._selectUpdateFn),this.context.input.removeEventListener(wi.PointerDown,this._handleInputFn),this.context.input.removeEventListener(wi.PointerUp,this._handleInputFn),this.context.input.removeEventListener(wi.PointerMove,this._handleInputFn)}onBeforeRender(){this.resetMeshUIStates()}onPointerEvent(e){if(e===void 0)return;const t=e.pointerType==RE.Touch?e.button:0,g=new CC(this.context.input,e);g.inputSource=this.context.input,g.pointerId=e.button,g.isClicked=e.type==wi.PointerUp&&this.context.input.getPointerClicked(e.button),g.isDown=e.type==wi.PointerDown,g.isUp=e.type==wi.PointerUp,g.isPressed=this.context.input.getPointerPressed(e.button),br&&g.isClicked&&console.log("CLICK",g.pointerId);const I=new ro;I.screenPoint=this.context.input.getPointerPositionRC(t);const o=this.performRaycast(I);if(!o)return;br&&g.isClicked&&mi("EventSystem: "+g.pointerId+" - "+this.context.time.frame+" - Up:"+g.isUp+", Down:"+g.isDown);const s={sender:this,args:g,hasActiveUI:this.currentActiveMeshUIComponents.length>0};if(this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:s})),!this.handleIntersections(o,g)){const n=this.hoveredByID.get(t);if(n&&this.triggerOnExit(n.obj,n.data),this.hoveredByID.delete(t),g.isUp){const C=this.pressedByID.get(t);C==null||C.handlers.forEach(a=>{var B;return(B=a.onPointerUp)==null?void 0:B.call(a,g)}),this.pressedByID.delete(t)}}this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:s}))}performRaycast(e){if(!this.raycaster)return null;this._sortedHits.length=0,e||(e=new ro),this._testObjectsCache.clear(),e.testObject=this.shouldRaycastObject;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;const g=t.performRaycast(e);g&&g.length>0&&this._sortedHits.push(...g)}return this._sortedHits.sort((t,g)=>t.distance-g.distance),this._sortedHits}handleIntersections(e,t){if(!e||e.length<=0)return!1;e=this.sortCandidates(e);for(const g of e){const{object:I}=g;if(t.point=g.point,t.normal=g.normal,t.face=g.face,t.distance=g.distance,t.instanceId=g.instanceId,this.handleEventOnObject(I,t))return!0}return!1}sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const g=e[t],I=g.object;if(I.material&&I.material.depthTest===!1){this._noDepthTestingResults.push(g);continue}this._sortingBuffer.push(g)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClicked&&br&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return br&&console.warn("Event without pointer can't be handled",t),!1;t.object=e;const g=e.parent;let I=!1;const o=t.isClicked??!1;let s=null;if(g&&g.isUI){const B=(t.isPressed||t.isClicked)??!1;if(g[Yo]){const Q=g[Yo].gameObject;if(Q){if(!LE.isInteractable(Q,this.out))return!1;s=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,B),e=Q,I=!0}}if(!I&&this.handleMeshUiObjectWithoutShadowDom(g,B))return!0}o&&br&&console.log(this.context.time.frame,e);const n=this.hoveredByID.get(t.pointerId),C=(n==null?void 0:n.obj)!==e;C&&(n!=null&&n.obj)&&this.triggerOnExit(n.obj,n.data);const a=this.hoveredByID.get(t.pointerId);if(a?(a.obj=e,a.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const B=this.pressedByID.get(t.pointerId);B?(B.obj=e,B.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(s===null||s.interactable)&&this.handleMainInteraction(e,t,C),!0}propagate(e,t,g){for(;;){if(t.used)return;if(IA.foreachComponent(e,I=>{g(I)},!1),!e.parent)break;e=e.parent}}handleMainInteraction(e,t,g){if(t.pointerId===void 0)return;const I=this.pressedByID.get(t.pointerId);this.propagate(e,t,o=>{var B;const s=o;if(s.interactable===!1)return;s.onPointerEnter&&g&&s.onPointerEnter(t),t.isDown&&s.onPointerDown&&(s.onPointerDown(t),I==null||I.handlers.add(s));const n=this.context.input.getPointerPositionLastFrame(t.pointerId),C=this.context.input.getPointerPosition(t.pointerId);n&&!ne.approximately(n,C)&&s.onPointerMove&&s.onPointerMove(t),t.isUp&&(s.onPointerUp&&(s.onPointerUp(t),I==null||I.handlers.delete(s)),s.onPointerExit&&((B=t.event)==null?void 0:B.pointerType)===RE.Touch&&(s.onPointerExit(t),this.hoveredByID.delete(t.pointerId))),t.isClicked&&s.onPointerClick&&s.onPointerClick(t)}),t.isUp&&(I==null||I.handlers.forEach(o=>{o.onPointerUp&&o.onPointerUp(t)}),this.pressedByID.delete(t.pointerId))}triggerOnExit(e,t){t.used=!1,this.propagate(e,t,g=>{if(!g.gameObject||g.destroyed)return;const I=g;I.onPointerExit&&I.onPointerExit(t)})}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}handleMeshUIIntersection(e,t){const g=Zn.updateState(e,t);return g&&this.currentActiveMeshUIComponents.push(g),g!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Zn.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];Zn.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?IA.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}};let cI=Ps;r(cI,"_eventSystemMap",new Map),r(cI,"didSearchEventSystem",!1);class Zn{static markDirty(){this.needsUpdate=!0}static update(A,e,t=!1){if(t){A.update();return}const g=e.time.frameCount;for(const I of this.lastUpdateFrame)if(I.context===e){if(g===I.frame)return;I.frame=g;let o=this.needsUpdate||g<1;I.nextUpdate===e.time.frameCount&&(o=!0),o&&(br&&console.log("Update threemeshui"),this.needsUpdate=!1,A.update());return}this.lastUpdateFrame=[{context:e,frame:g,nextUpdate:g}],A.update()}static updateState(A,e){let t=null;if(A&&(t=this.findBlockInParent(A),t&&t!==this.lastSelected)){if(t.interactable===!1)return null;this.needsUpdate=!0}return t}static resetLastSelected(){const A=this.lastSelected;A&&(this.lastSelected=null,this.resetState(A))}static resetState(A){A&&(this.needsUpdate=!0)}static findBlockInParent(A){return A?A.isBlock?A:this.findBlockInParent(A.parent):null}}r(Zn,"lastSelected",null),r(Zn,"lastUpdateFrame",[]),r(Zn,"needsUpdate",!1);const Vf=Symbol("cameraController");function QgA(i){return i[Vf]}function tb(i,A,e){e?i[Vf]=A:i[Vf]===A&&(i[Vf]=null)}const ib=Symbol("camera autofit");function EgA(i){return i[ib]===void 0?!0:i[ib]!==!1}class gO extends pA{constructor(A,e={}){const g=[A.isCubeTexture?"#define ENVMAP_TYPE_CUBE":""],I=`
|
|
5097
5097
|
varying vec3 vWorldPosition;
|
|
5098
5098
|
|
|
5099
5099
|
void main() {
|