@needle-tools/engine 3.7.1-alpha → 3.7.2-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4176,7 +4176,7 @@ ${o.join(`
4176
4176
  `)}
4177
4177
 
4178
4178
  }
4179
- `}function o3(i){return`(${i.r}, ${i.g}, ${i.b})`}function a3(i){return`(${i.x}, ${i.y})`}const l3=class{constructor(i,e,t){h(this,"id"),h(this,"trigger"),h(this,"action"),h(this,"exclusive",!1),this.id="Behavior_"+zS(i)+"_"+l3.global_id++,this.trigger=e,this.action=t}makeExclusive(i){return this.exclusive=i,this}writeTo(i,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 s="";if(Array.isArray(this.trigger)){s="[";for(let r=0;r<this.trigger.length;r++){const n=this.trigger[r];s+="<"+n.id+">",r+1<this.trigger.length&&(s+=", ")}s+="]"}else s=`<${this.trigger.id}>`;if(t.appendLine(`rel triggers = ${s} `),t.appendLine(),Array.isArray(this.trigger))for(const r of this.trigger)r.writeTo(e,t),t.appendLine();else this.trigger.writeTo(e,t);t.appendLine(),this.action.writeTo(e,t),t.closeBlock()}};let Dr=l3;h(Dr,"global_id",0);function QS(i,e){var t,s;let r="";if(Array.isArray(i)){let n="[ ";for(let o=0;o<i.length;o++){let a=i[o];if(typeof a=="string")n+=a;else if(typeof a=="object"){a.isObject3D&&(a=e.findById(a.uuid));const l=(t=a.getPath)==null?void 0:t.call(a);n+=l}o+1<i.length&&(n+=", ")}n+=" ]",r=n}else typeof i=="object"&&(i.isObject3D&&(i=e.findById(i.uuid)),r=(s=i.getPath)==null?void 0:s.call(i));return r=r.replace(e.name,e.name+"/Scenes/Scene"),r}const c3=class{constructor(i,e){h(this,"id"),h(this,"targetId"),h(this,"tokenId"),h(this,"type"),h(this,"distance"),i&&(this.targetId=i),e?this.id=e:this.id="Trigger_"+c3.global_id++}writeTo(i,e){e.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=QS(this.targetId,i)),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 tu=c3;h(tu,"global_id",0);class Zr{static sceneStartTrigger(){const e=new tu;return e.targetId=void 0,e.tokenId="SceneTransition",e.type="enter",e}static tapTrigger(e){const t=new tu(e);return t.tokenId="TapGesture",t}static isTapTrigger(e){return e?.tokenId==="TapGesture"}static proximityToCameraTrigger(e,t){const s=new tu(e);return s.tokenId="ProximityToCamera",s.distance=t,s}}class Bc{constructor(e,t){h(this,"id"),h(this,"actions"),h(this,"loops",0),h(this,"performCount",1),h(this,"type","serial"),this.id=e,this.actions=t}static getId(){return this.global_id++}addAction(e){return this.actions.push(e),this}makeParallel(){return this.type="parallel",this}makeSequence(){return this.type="serial",this}makeLooping(){return this.loops=1,this}makeRepeat(e){return this.performCount=e,this}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),t.beginArray("rel actions");for(const s of this.actions)s&&t.appendLine("<"+s.id+">,");t.closeArray(),t.appendLine(),t.appendLine('token info:id = "Group"'),t.appendLine(`bool loops = ${this.loops} `),t.appendLine(`int performCount = ${this.performCount} `),t.appendLine(`token type = "${this.type}"`),t.appendLine();for(const s of this.actions)s&&(s.writeTo(e,t),t.appendLine());t.closeBlock()}}h(Bc,"global_id",0);var jS=(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))(jS||{}),GS=(i=>(i.Relative="relative",i.Absolute="absolute",i))(GS||{});const HS=class{constructor(i,e){h(this,"id"),h(this,"tokenId"),h(this,"affectedObjects"),h(this,"easeType"),h(this,"motionType"),h(this,"duration"),h(this,"moveDistance"),h(this,"style"),h(this,"type"),h(this,"front"),h(this,"up"),h(this,"start"),h(this,"animationSpeed"),h(this,"reversed"),h(this,"pingPong"),h(this,"xFormTarget"),h(this,"audio"),h(this,"gain"),h(this,"auralMode"),h(this,"multiplePerformOperation"),i&&(this.affectedObjects=i),e?this.id=e:this.id="Action",this.id+="_"+HS.global_id++}clone(){const i=new HS,e=i.id;return Object.assign(i,this),i.id=e,i}writeTo(i,e){e.beginBlock(`def Preliminary_Action "${this.id}"`),this.affectedObjects&&(typeof this.affectedObjects!="string"&&(this.affectedObjects=QS(this.affectedObjects,i)),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=QS(this.xFormTarget,i)),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 Po=HS;h(Po,"global_id",0);let lp=class cf{constructor(e,t,s){h(this,"x",0),h(this,"y",0),h(this,"z",0),this.x=e,this.y=t,this.z=s}static get up(){return new cf(0,1,0)}static get right(){return new cf(1,0,0)}static get forward(){return new cf(0,0,1)}static get back(){return new cf(0,0,-1)}static get zero(){return new cf(0,0,0)}};var h3=(i=>(i.Play="play",i.Pause="pause",i.Stop="stop",i))(h3||{}),VS=(i=>(i.Spatial="spatial",i.NonSpatial="nonSpatial",i.Ambient="ambient",i))(VS||{});class ni{static sequence(...e){return new Bc("group_"+Bc.getId(),e).makeSequence()}static parallel(...e){return new Bc("group_"+Bc.getId(),e).makeParallel()}static fadeAction(e,t,s){const r=new Po(e);return r.tokenId="Visibility",r.type=s?"show":"hide",r.duration=t,r.style="basic",r.motionType="none",r.moveDistance=0,r.easeType="none",r}static startAnimationAction(e,t,s=0,r=1,n=!1,o=!1){const a=new Po(e);if(a.tokenId="StartAnimation",a.start=t,a.duration=s,a.animationSpeed=r,a.reversed=n,a.pingPong=o,n&&(a.start-=s),o){a.pingPong=!1;const l=a.clone();return l.reversed=!n,l.start=a.start,l.reversed&&(l.start-=s),ni.sequence(a,l)}return a}static waitAction(e){const t=new Po;return t.tokenId="Wait",t.duration=e,t}static lookAtCameraAction(e,t=9999999999999,s,r){const n=new Po(e);return n.tokenId="LookAtCamera",n.duration=t,n.front=s??lp.forward,n.up=r??lp.up,n}static emphasize(e,t,s=2,r=1,n="basic"){const o=new Po(e);return o.tokenId="Emphasize",o.duration=t,o.style=n??"basic",o.motionType=jS[s],o.moveDistance=r,o}static transformAction(e,t,s,r,n="inout"){const o=new Po(e);return o.tokenId="Transform",o.duration=s,o.type=r,o.easeType=n,Array.isArray(t)&&console.error("Transform target must not be an array",t),o.xFormTarget=t,o}static playAudioAction(e,t,s="play",r=1,n="spatial"){const o=new Po(e);return o.tokenId="Audio",o.type=s,o.audio=t,o.gain=r,o.auralMode=n,o.multiplePerformOperation="allow",o}}class FY{constructor(e){h(this,"object"),h(this,"model"),this.object=e}get id(){return this.object.uuid}apply(e){if(!this.model&&(this.model=e.findById(this.object.uuid),!this.model)){console.error("could not find model with id "+this.object.uuid);return}this.onApply(e)}}class WS extends FY{constructor(e,t,s,r){super(e),h(this,"matrix"),h(this,"material"),h(this,"geometry"),h(this,"_enableAction"),h(this,"_disableAction"),this.matrix=t,this.material=s,this.geometry=r}onApply(e){var t,s;const r=this.model;if(!r)return;(t=r.parent)!=null&&t.isDynamic||na.createEmptyParent(r);const n=r.clone();this.matrix&&(n.matrix=this.matrix),this.material&&(n.material=this.material),this.geometry&&(n.geometry=this.geometry),(s=r.parent)==null||s.add(n)}enable(){return this._enableAction?this._enableAction:(this._enableAction=ni.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=ni.fadeAction(this.object,0,!1),this._disableAction)}}class qS{constructor(e){h(this,"actions"),h(this,"sortedActions"),this.actions=[...e]}organize(){this.sortedActions={};for(const e of this.actions){const t=e.id;this.sortedActions[t]||(this.sortedActions[t]=[]),this.sortedActions[t].push(e)}}getActions(e){return this.sortedActions||this.organize(),this.sortedActions[e.uuid]}}var UY=Object.defineProperty,NY=Object.getOwnPropertyDescriptor,u3=(i,e,t,s)=>{for(var r=s>1?void 0:s?NY(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&UY(e,t,r),r};class em extends Ee{constructor(){super(...arguments),h(this,"from"),h(this,"to"),h(this,"width",0),h(this,"centered",!0),h(this,"_centerPos")}awake(){this._centerPos=new S}update(){if(!this.from||!this.to)return;const e=xt(this.from).clone(),t=xt(this.to).clone(),s=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),Ki(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(xt(this.to).clone()),this.gameObject.scale.set(this.width,this.width,s)}}u3([w($)],em.prototype,"from",2),u3([w($)],em.prototype,"to",2);var zY=Object.defineProperty,QY=Object.getOwnPropertyDescriptor,tm=(i,e,t,s)=>{for(var r=s>1?void 0:s?QY(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&zY(e,t,r),r};const kc=re("debuganimation");class Jn extends Ee{constructor(){super(...arguments),h(this,"playAutomatically",!0),h(this,"randomStartTime",!0),h(this,"minMaxSpeed"),h(this,"minMaxOffsetNormalized"),h(this,"loop",!0),h(this,"clampWhenFinished",!1),h(this,"_tempAnimationClipBeforeGameObjectExisted",null),h(this,"mixer"),h(this,"_actions",[]),h(this,"_currentActions",[]),h(this,"_handles",[]),h(this,"_didInit",!1)}get clip(){var e;return(e=this.animations)!=null&&e.length?this.animations[0]:null}set clip(e){if(!this.__didAwake){kc&&console.log("Assign clip during serialization",e),this._tempAnimationClipBeforeGameObjectExisted=e;return}e&&(kc&&console.log("Assign clip",e,!!this.gameObject),this.gameObject.animations||(this.gameObject.animations=[]),!this.animations.includes(e)&&(this.animations.length>0?this.animations.splice(0,0,e):this.animations.push(e)))}set clips(e){this.animations=e}set animations(e){kc&&console.log("assign animations",e),this.gameObject.animations=e}get animations(){return this.gameObject.animations}get currentAction(){return this._currentActions[0]}get currentActions(){return this._currentActions}get actions(){return this._actions}set actions(e){this._actions=e}awake(){kc&&console.log(this),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(s=>s.getClip().name===e)}get isPlaying(){for(let e=0;e<this._currentActions.length;e++)if(this._currentActions[e].isRunning())return!0;return!1}play(e=0,t){if(kc&&console.log("PLAY",e),this.init(),!this.mixer){kc&&console.warn("Missing mixer",this);return}e===void 0&&(e=0);let s=e;if(typeof e=="number"){if(e>=this.animations.length){kc&&console.log("No animation at index",e);return}s=this.animations[e]}else typeof e=="string"&&(s=this.animations.find(n=>n.name===e));if(!s){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 n of this.actions)if(n.getClip()===s)return this.internalOnPlay(n,t);if(!(s instanceof Qn)){console.warn("Clip is no AnimationClip",s,"on object: "+this.name);return}const r=this.mixer.clipAction(s);return this.actions.push(r),this.internalOnPlay(r,t)}internalOnPlay(e,t){var s=this.currentAction;if(s===e&&s.isRunning()&&s.time<s.getClip().duration){const a=this.tryFindHandle(e);if(a)return a.getPromise()}const r=t?.exclusive??!0;t!=null&&t.fadeDuration?(r&&s?.fadeOut(t.fadeDuration),e.fadeIn(t.fadeDuration)):r&&s?.stop(),e.reset(),e.enabled=!0,e.time=0,e.timeScale=1;const n=e.getClip();t!=null&&t.minMaxOffsetNormalized&&(e.time=Je.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*n.duration),t!=null&&t.minMaxSpeed&&(e.timeScale=Je.lerp(t.minMaxSpeed.x,t.minMaxSpeed.y,Math.random())),t!=null&&t.clampWhenFinished&&(e.clampWhenFinished=!0),t?.startTime!==void 0&&(e.time=t.startTime),t?.loop!==void 0?e.loop=t.loop?Zw:Rf:e.loop=Rf,e.play(),kc&&console.log("PLAY",e.getClip().name,e);const o=new jY(e,this.mixer,t,a=>{this._handles.splice(this._handles.indexOf(o),1)});return this._handles.push(o),o.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 x0(this.gameObject)))}}tm([w()],Jn.prototype,"playAutomatically",2),tm([w()],Jn.prototype,"randomStartTime",2),tm([w()],Jn.prototype,"loop",2),tm([w()],Jn.prototype,"clampWhenFinished",2),tm([w(Qn)],Jn.prototype,"clips",1);class jY{constructor(e,t,s,r){h(this,"mixer"),h(this,"action"),h(this,"promise",null),h(this,"resolve",null),h(this,"reject",null),h(this,"_options"),h(this,"_resolveCallback",null),h(this,"_rejectCallback",null),h(this,"_loopCallback"),h(this,"_finishedCallback"),h(this,"_resolvedOrRejectedCallback"),this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=r,this._options=s}getPromise(){return this.promise?this.promise:(this.promise=new Promise((e,t)=>{this._resolveCallback=e,this._rejectCallback=t,this.resolve=this.onResolve.bind(this),this.reject=this.onReject.bind(this)}),this._loopCallback=this.onLoop.bind(this),this._finishedCallback=this.onFinished.bind(this),this.mixer.addEventListener("loop",this._loopCallback),this.mixer.addEventListener("finished",this._finishedCallback),this.promise)}_update(){this._options&&this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){var e,t;this.dispose(),(e=this._resolvedOrRejectedCallback)==null||e.call(this,this),(t=this._resolveCallback)==null||t.call(this,this.action)}onReject(e){var t,s;this.dispose(),(t=this._resolvedOrRejectedCallback)==null||t.call(this,this),(s=this._rejectCallback)==null||s.call(this,e)}onLoop(e){}onFinished(e){e.action===this.action&&this.onResolve()}dispose(){this._loopCallback&&this.mixer.removeEventListener("loop",this._loopCallback),this._finishedCallback&&this.mixer.removeEventListener("finished",this._finishedCallback),this._loopCallback=void 0,this._finishedCallback=void 0}}var GY=Object.defineProperty,HY=Object.getOwnPropertyDescriptor,Dc=(i,e,t,s)=>{for(var r=s>1?void 0:s?HY(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&GY(e,t,r),r};class Oc{constructor(){h(this,"time"),h(this,"value"),h(this,"inTangent"),h(this,"inWeight"),h(this,"outTangent"),h(this,"outWeight"),h(this,"weightedMode")}}Dc([w()],Oc.prototype,"time",2),Dc([w()],Oc.prototype,"value",2),Dc([w()],Oc.prototype,"inTangent",2),Dc([w()],Oc.prototype,"inWeight",2),Dc([w()],Oc.prototype,"outTangent",2),Dc([w()],Oc.prototype,"outWeight",2),Dc([w()],Oc.prototype,"weightedMode",2);const d3=class{constructor(){h(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 e=0;e<this.keys.length;e++){const t=this.keys[e];if(t.time<=i)if(e+1<this.keys.length){const s=this.keys[e+1];if(s.time<i)continue;return!isFinite(t.outTangent)||!isFinite(s.inTangent)?t.value:d3.interpolateValue(i,t,s)}else return t.value}return this.keys[this.keys.length-1].value}static interpolateValue(i,e,t){const s=e.time,r=e.value,n=e.outTangent,o=t.time,a=t.value,l=t.inTangent,c=o-s,u=c*c,d=u*c,p=((n+l)*c-2*(a-r))/d,f=(3*(a-r)-(l+2*n)*c)/u,g=n,m=r,v=i-s,A=v*v,b=A*v;return p*b+f*A+g*v+m}};let iu=d3;Dc([w(Oc)],iu.prototype,"keys",2);const cp=re("debugusdzanimation");class ib{constructor(e,t,s){h(this,"ext"),h(this,"root"),h(this,"clip"),this.ext=e,this.root=t,this.clip=s}get start(){return this.ext.getStartTime01(this.root,this.clip)}get duration(){return this.clip.duration}}class sb{constructor(e,t,s,r){h(this,"clip"),h(this,"pos"),h(this,"rot"),h(this,"scale"),h(this,"ext"),h(this,"root"),h(this,"target"),this.ext=e,this.root=t,this.target=s,this.clip=r}get frameRate(){return 60}addTrack(e){e.name.endsWith("position")&&(this.pos=e),e.name.endsWith("quaternion")&&(this.rot=e),e.name.endsWith("scale")&&(this.scale=e)}getFrames(){var e,t,s,r,n,o;return Math.max(((t=(e=this.pos)==null?void 0:e.times)==null?void 0:t.length)??0,((r=(s=this.rot)==null?void 0:s.times)==null?void 0:r.length)??0,((o=(n=this.scale)==null?void 0:n.times)==null?void 0:o.length)??0)}getDuration(){var e,t,s;const r=((e=this.pos)==null?void 0:e.times)??((t=this.rot)==null?void 0:t.times)??((s=this.scale)==null?void 0:s.times);return r?r[r.length-1]:0}getStartTime(e){let t=0;for(let s=0;s<e.length;s++){const r=e[s];if(r===this)return t;t+=r.getDuration()}return t}}class rb{constructor(){h(this,"dict",new Map),h(this,"rootTargetMap",new Map),h(this,"serializers",[])}get extensionName(){return"animation"}getStartTime01(e,t){const s=this.rootTargetMap.get(e);if(!s)return 1/0;let r=-1;for(const n of s){const o=this.dict.get(n);let a=0;if(o!=null&&o.length){for(const l of o){if(l.clip===t)break;a+=l.getDuration()}r=Math.max(r,a)}else console.warn("No animation found on root",e,t,o)}return r}registerAnimation(e,t){if(!t||!e)return null;this.rootTargetMap.has(e)||this.rootTargetMap.set(e,[]);for(const s of t.tracks){const r=s.name.split(".")[2],n=e.getObjectByName(r);if(!n){console.warn("no object found for track",s.name,"using "+e.name+" instead");continue}this.dict.has(n)||this.dict.set(n,[]);const o=this.dict.get(n);if(!o)continue;let a=o.find(c=>c.clip===t);a||(a=new sb(this,e,n,t),o.push(a)),a.addTrack(s);const l=this.rootTargetMap.get(e);l!=null&&l.includes(n)||l==null||l.push(n)}return new ib(this,e,t)}onAfterHierarchy(e){cp&&console.log(this.dict)}onAfterBuildDocument(e){var t,s;for(const r of this.serializers){const n=(t=r.model)==null?void 0:t.parent,o=n?.isDynamic===!0;cp&&console.log(o,(s=r.model)==null?void 0:s.parent),o&&r.registerCallback(n)}}onExportObject(e,t,s){$.foreachComponent(e,n=>{const o=n;typeof o.createAnimation=="function"&&o.createAnimation(this,t,s)},!1);const r=new VY(e,this.dict);this.serializers.push(r),r.registerCallback(t)}}class VY{constructor(e,t){h(this,"object"),h(this,"dict"),h(this,"model"),h(this,"callback"),this.object=e,this.dict=t}registerCallback(e){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),cp&&console.log("REPARENT",e),this.model=e,this.model.addEventListener("serialize",this.callback)}onSerialize(e,t){var s,r,n,o,a,l;if(!this.model)return;cp&&console.log("SERIALIZE",this.model.name,this.object.type);const c=this.object,u=this.dict.get(c);if(!u)return;const d=new Pe,p=new S,f=new Ce,g=new S(1,1,1);e.appendLine("matrix4d xformOp:transform.timeSamples = {"),e.indent++;for(const m of u){let v=(s=m.pos)==null?void 0:s.times,A=(r=m.rot)==null?void 0:r.times,b=(n=m.scale)==null?void 0:n.times,y=[];if(v)for(const C of v)y.push(C);if(A)for(const C of A)y.push(C);if(b)for(const C of b)y.push(C);if(y.sort((C,R)=>C-R),y=[...new Set(y)],!y||y.length===0){console.error("got an animated object but no time values??",c,m);continue}const x=m.getStartTime(u);cp&&e.appendLine(m.clip.name+": start="+x.toFixed(3)+", length="+m.getDuration().toFixed(3)+", frames="+m.getFrames());const _=(o=m.pos)==null?void 0:o.createInterpolant(),M=(a=m.rot)==null?void 0:a.createInterpolant(),P=(l=m.scale)==null?void 0:l.createInterpolant();_||p.set(c.position.x,c.position.y,c.position.z),M||f.set(c.quaternion.x,c.quaternion.y,c.quaternion.z,c.quaternion.w),P||g.set(c.scale.x,c.scale.y,c.scale.z);for(let C=0;C<y.length;C++){const R=y[C];if(_){const z=_.evaluate(R);p.set(z[0],z[1],z[2])}if(M){const z=M.evaluate(R);f.set(z[0],z[1],z[2],z[3])}if(P){const z=P.evaluate(R);g.set(z[0],z[1],z[2])}d.compose(p,f,g);let T=`${(x+R)*m.frameRate}: ${s3(d)},`;cp&&(T="#"+C+" "+T),e.appendLine(T)}}e.indent--,e.appendLine("}")}}class WY{constructor(){h(this,"_context")}get context(){return this._context??Lt.Current}get isStateMachineBehaviour(){return!0}}class nb{constructor(e,t,s,r){h(this,"_name"),h(this,"_nameHash"),h(this,"_normalizedTime"),h(this,"_length"),h(this,"_speed"),this._name=e.name,this._nameHash=e.hash,this._normalizedTime=t,this._length=s,this._speed=r}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 p3(i,e){return{name:"",isLooping:!1,guid:e?.generateUUID()??Cr.generateUUID(),index:-1,clip:new Qn(i,1,[])}}var Lc=(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))(Lc||{}),XS=(i=>(i[i.Float=1]="Float",i[i.Int=3]="Int",i[i.Bool=4]="Bool",i[i.Trigger=9]="Trigger",i))(XS||{});const oa=re("debuganimatorcontroller"),ob=re("debugrootmotion");class Uu{constructor(e){h(this,"normalizedStartOffset",0),h(this,"_speed",1),h(this,"animator"),h(this,"model"),h(this,"_mixer"),h(this,"_activeState"),h(this,"_activeStates",[]),h(this,"rootMotionHandler"),this.model=e,oa&&console.log(this)}play(e,t=-1,s=Number.NEGATIVE_INFINITY,r=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}const n=this.model.layers[t].stateMachine;for(const o of n.states)if(o.name===e||o.hash===e){oa&&console.log("transition to ",o),this.transitionTo(o,r,s);return}console.warn("Could not find "+e+" to play")}reset(){this.setStartTransition()}setBool(e,t){var s,r;const n=typeof e=="string"?"name":"hash";return(r=(s=this.model)==null?void 0:s.parameters)==null?void 0:r.filter(o=>o[n]===e).forEach(o=>o.value=t)}getBool(e){var t,s,r;const n=typeof e=="string"?"name":"hash";return((r=(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.find(o=>o[n]===e))==null?void 0:r.value)??!1}setFloat(e,t){var s,r;const n=typeof e=="string"?"name":"hash";return(r=(s=this.model)==null?void 0:s.parameters)==null?void 0:r.filter(o=>o[n]===e).forEach(o=>o.value=t)}getFloat(e){var t,s,r;const n=typeof e=="string"?"name":"hash";return((r=(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.find(o=>o[n]===e))==null?void 0:r.value)??0}setInteger(e,t){var s,r;const n=typeof e=="string"?"name":"hash";return(r=(s=this.model)==null?void 0:s.parameters)==null?void 0:r.filter(o=>o[n]===e).forEach(o=>o.value=t)}getInteger(e){var t,s,r;const n=typeof e=="string"?"name":"hash";return((r=(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.find(o=>o[n]===e))==null?void 0:r.value)??0}setTrigger(e){var t,s;oa&&console.log("SET TRIGGER",e);const r=typeof e=="string"?"name":"hash";return(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.filter(n=>n[r]===e).forEach(n=>n.value=!0)}resetTrigger(e){var t,s;const r=typeof e=="string"?"name":"hash";return(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.filter(n=>n[r]===e).forEach(n=>n.value=!1)}isInTransition(){return this._activeStates.length>1}setSpeed(e){this._speed=e}FindState(e){return this.findState(e)}findState(e){if(!e)return null;if(Array.isArray(this.model.layers)){for(const t of this.model.layers)for(const s of t.stateMachine.states)if(s.name===e)return s}return null}get context(){var e;return(e=this.animator)==null?void 0:e.context}bind(e){this.animator=e,this._mixer=new x0(this.animator.gameObject),this.createActions(this.animator)}clone(){if(typeof this.model=="string")return console.warn("AnimatorController has not been resolved, can not create model from string",this.model),null;const e=$v(this.model,(t,s,r)=>r==null?!0:!(r.type==="Object3D"||r.isObject3D===!0||qB(r)||r.tracks!==void 0));return console.assert(e!==this.model),new Uu(e)}update(){var e,t;if(!this.animator||(this.evaluateTransitions(),this.updateActiveStates(),!this._activeState))return;const s=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((e=this.rootMotionHandler)==null||e.onBeforeUpdate()),this._mixer.update(s),this.animator.applyRootMotion&&((t=this.rootMotionHandler)==null||t.onAfterUpdate())}updateActiveStates(){for(let e=0;e<this._activeStates.length;e++){const t=this._activeStates[e],s=t.motion;if(!s.action)this._activeStates.splice(e,1),e--;else{const r=s.action;r.getEffectiveWeight()<=0&&!r.isRunning()&&(oa&&console.debug("REMOVE",t.name,r.getEffectiveWeight(),r.isRunning(),r.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(const e of this.model.layers){const t=e.stateMachine;t.defaultState===void 0&&(oa&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",e),t.defaultState=0);const s=t.states[t.defaultState];this.transitionTo(s,0,this.normalizedStartOffset)}}evaluateTransitions(){var e;let t=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;t=!0}const s=this._activeState,r=s.motion.action;for(const o of s.transitions){if(!o.hasExitTime&&o.conditions.length<=0)continue;let a=!0;for(const l of o.conditions)if(!this.evaluateCondition(l)){a=!1;break}if(a){for(const l of o.conditions){const c=this.model.parameters.find(u=>u.name===l.parameter);c?.type===XS.Trigger&&(c.value=!1)}if(r){const l=s.motion.clip.duration,c=l<=0?1:Math.abs(r.time/l);let u=!1;if(o.hasExitTime?r.timeScale>0?u=c>=o.exitTime:r.timeScale<0&&(u=1-c>=o.exitTime):u=!0,u){r.clampWhenFinished=!0,oa&&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}}}let n=!1;if(s.motion.isLooping&&r&&(r.time>=r.getClip().duration?(n=!0,r.reset(),r.time=0,r.play()):r.time<=0&&r.timeScale<0&&(n=!0,r.reset(),r.time=r.getClip().duration,r.play())),!n&&s&&!t&&r&&this.animator&&s.behaviours){const o=r?.getClip().duration,a=r.time/o,l=new nb(this._activeState,a,o,this._speed);for(const c of s.behaviours)c.instance&&((e=c.instance.onStateUpdate)==null||e.call(c.instance,this.animator,l,0))}}getState(e,t){return typeof e=="number"&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState,e===void 0&&(oa&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+t),e=0)),e=this.model.layers[t].stateMachine.states[e]),e}transitionTo(e,t,s){var r,n,o,a,l,c,u,d;if(!this.animator)return;const p=0;if(e=this.getState(e,p),!(e!=null&&e.motion)||!e.motion.clip)return;const f=this._activeState===e;if(f){const A=e.motion;!A.action_loopback&&A.clip&&(this._mixer.uncacheAction(A.clip,this.animator.gameObject),A.action_loopback=this.createAction(A.clip))}if((r=this._activeState)!=null&&r.behaviours&&this._activeState.motion.action){const A=(n=this._activeState)==null?void 0:n.motion.clip.duration,b=this._activeState.motion.action.time/A,y=new nb(this._activeState,b,A,this._speed);for(const x of this._activeState.behaviours)(a=(o=x.instance)==null?void 0:o.onStateExit)==null||a.call(x.instance,this.animator,y,p)}const g=(l=this._activeState)==null?void 0:l.motion.action;g&&g.fadeOut(t),f&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=g);const m=this._activeState;this._activeState=e;const v=(c=e.motion)==null?void 0:c.action;if(v){s=Math.max(0,Math.min(1,s)),v.isRunning()&&v.stop(),v.reset(),v.timeScale=this._speed,e.speed!==void 0&&(v.timeScale*=e.speed),v.enabled=!0;const A=e.motion.clip.duration;if(v.time=s*A,v.timeScale<0&&(v.time=A-v.time),v.clampWhenFinished=!0,v.setLoop(Rf,0),t>0?v.fadeIn(t):v.setEffectiveWeight(1),v.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(v),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){const b=new nb(e,s,A,this._speed);for(const y of this._activeState.behaviours)(d=(u=y.instance)==null?void 0:u.onStateEnter)==null||d.call(y.instance,this.animator,b,p)}}else oa&&(e.__warned_no_motion||(e.__warned_no_motion=!0,console.warn("No action",e.motion,this)));oa&&console.log("TRANSITION FROM "+m?.name+" TO "+e.name,t,g,v,v?.getEffectiveTimeScale(),v?.getEffectiveWeight(),v?.isRunning(),v?.isScheduled(),v?.paused)}createAction(e){var t,s;if(this._mixer.existingAction(e)&&this._mixer.uncacheAction(e,(t=this.animator)==null?void 0:t.gameObject),(s=this.animator)!=null&&s.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new qY(this));const r=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,r,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){const t=this.model.parameters.find(s=>s.name===e.parameter);if(!t)return!1;switch(e.mode){case Lc.If:return t.value===!0;case Lc.IfNot:return t.value===!1;case Lc.Greater:return t.value>e.threshold;case Lc.Less:return t.value<e.threshold;case Lc.Equals:return t.value===e.threshold;case Lc.NotEqual:return t.value!==e.threshold}return!1}createActions(e){var t,s;for(const r of this.model.layers){const n=r.stateMachine;for(let o=0;o<n.states.length;o++){const a=n.states[o];a.transitions||(a.transitions=[]);for(const l of a.transitions)l.conditions||(l.conditions=[]);if(a.motion||(a.motion=p3(a.name)),this.animator&&a.motion.clips){const l=(t=a.motion.clips)==null?void 0:t.find(c=>{var u,d;return c.node.name===((d=(u=this.animator)==null?void 0:u.gameObject)==null?void 0:d.name)});a.motion.clip=l?.clip}if(!a.motion.clip){const l=new Qn(void 0,void 0,[]);a.motion.clip=l}if((s=a.motion)!=null&&s.clip){const l=a.motion.clip,c=this.createAction(l);a.motion.action=c}if(a.behaviours&&Array.isArray(a.behaviours))for(const l of a.behaviours){if(!(l!=null&&l.typeName))continue;const c=j.get(l.typeName),u=new c;u.isStateMachineBehaviour&&(u._context=this.context??void 0,jh(u,l.properties),l.instance=u),oa&&console.log("Created animator controller behaviour",a.name,l.typeName,l.properties,u)}}}}*enumerateActions(){for(const e of this.model.layers){const t=e.stateMachine;for(let s=0;s<t.states.length;s++){const r=t.states[s];r!=null&&r.motion&&(r.motion.action&&(yield r.motion.action),r.motion.action_loopback&&(yield r.motion.action_loopback))}}}}class f3{constructor(e,t){h(this,"track"),h(this,"createdInterpolant"),h(this,"originalEvaluate"),h(this,"customEvaluate"),this.track=e;const s=e,r=s.createInterpolant.bind(e);s.createInterpolant=()=>(s.createInterpolant=r,this.createdInterpolant=r(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=n=>{if(!this.originalEvaluate)return;const o=this.originalEvaluate(n);return t(n,o)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}evaluate(e){this.customEvaluate&&this.customEvaluate(e)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}}const Ms=class{constructor(i,e,t,s,r){if(h(this,"_action"),h(this,"root"),h(this,"clip"),h(this,"positionWrapper",null),h(this,"rotationWrapper",null),h(this,"context"),h(this,"positionChange",new S),h(this,"rotationChange",new Ce),this.context=i,this.root=e,this.clip=t,Ms.firstKeyframeRotation[t.uuid]||(Ms.firstKeyframeRotation[t.uuid]=new Ce),r){const n=r.values;Ms.firstKeyframeRotation[t.uuid].set(n[0],n[1],n[2],n[3])}Ms.spaceRotation[t.uuid]||(Ms.spaceRotation[t.uuid]=new Ce),Ms.effectiveSpaceRotation[t.uuid]||(Ms.effectiveSpaceRotation[t.uuid]=new Ce),Ms.clipOffsetRotation[t.uuid]=new Ce,r&&Ms.clipOffsetRotation[t.uuid].set(r.values[0],r.values[1],r.values[2],r.values[3]).invert(),this.handlePosition(t,s),this.handleRotation(t,r)}set action(i){this._action=i}get action(){return this._action}onStart(i){if(i.getClip()!==this.clip)return;const e=Ms.lastObjRotation[this.root.uuid];if(Ms.spaceRotation[this.clip.uuid].copy(e),ob){const t=new vs().setFromQuaternion(e);console.log("START",this.clip.name,Je.toDegrees(t.y))}}getClipRotationOffset(){return Ms.clipOffsetRotation[this.clip.uuid]}handlePosition(i,e){if(e){const t=this.root;ob&&t.add(new Cd),Ms.lastObjPosition[t.uuid]||(Ms.lastObjPosition[t.uuid]=new S);const s=new S,r=new S;let n=0;this.positionWrapper=new f3(e,(o,a)=>{const l=this.action.getEffectiveWeight();if(ob&&t.position.length()>8&&t.position.set(0,t.position.y,0),o>n){s.set(a[0],a[1],a[2]),s.sub(r),s.multiplyScalar(l),s.applyQuaternion(this.getClipRotationOffset());const c=this.clip.uuid;s.applyQuaternion(Ms.spaceRotation[c]),this.positionChange.copy(s)}return r.fromArray(a),n=o,a[0]=0,a[1]=0,a[2]=0,a})}}handleRotation(i,e){if(e){if(ob){const o=e.values,a=new vs().setFromQuaternion(new Ce(o[0],o[1],o[2],o[3]));console.log(i.name,e.name,"FIRST ROTATION IN TRACK",Je.toDegrees(a.y));const l=e.values.length-4,c=new Ce().set(o[l],o[l+1],o[l+2],o[l+3]),u=new vs().setFromQuaternion(c);console.log(i.name,e.name,"LAST ROTATION IN TRACK",Je.toDegrees(u.y))}const t=this.root;Ms.lastObjRotation[t.uuid]||(Ms.lastObjRotation[t.uuid]=new Ce);let s=0;const r=new Ce,n=new Ce;this.rotationWrapper=new f3(e,(o,a)=>(o>s&&(n.set(a[0],a[1],a[2],a[3]),r.invert(),n.multiply(r),this.rotationChange.copy(n)),r.fromArray(a),s=o,a[0]=0,a[1]=0,a[2]=0,a[3]=1,a))}}onBeforeUpdate(){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(){if(!this.action)return;const i=this.action.getEffectiveWeight();this.positionChange.multiplyScalar(i),this.rotationChange.slerp(Ms.identityQuaternion,1-i)}};let vl=Ms;h(vl,"lastObjPosition",{}),h(vl,"lastObjRotation",{}),h(vl,"firstKeyframeRotation",{}),h(vl,"spaceRotation",{}),h(vl,"effectiveSpaceRotation",{}),h(vl,"clipOffsetRotation",{}),h(vl,"identityQuaternion",new Ce);class qY{constructor(e){h(this,"controller"),h(this,"handler",[]),h(this,"root"),h(this,"summedPosition",new S),h(this,"summedRotation",new Ce),this.controller=e}createClip(e,t,s){this.root=t,t&&"name"in t&&t.name;const r=this.findRootTrack(s,".position"),n=this.findRootTrack(s,".quaternion"),o=new vl(this.controller.context,t,s,r,n);this.handler.push(o);const a=e.clipAction(s);return o.action=a,a}onStart(e){for(const t of this.handler)t.onStart(e)}onBeforeUpdate(){for(const e of this.handler)e.onBeforeUpdate()}onAfterUpdate(){this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(const e of this.handler)e.onAfterUpdate(),this.summedPosition.add(e.positionChange),this.summedRotation.multiply(e.rotationChange);this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation),vl.lastObjRotation[this.root.uuid].copy(this.root.quaternion)}findRootTrack(e,t){const s=e.tracks;if(!s)return null;for(const r of s)if(r.name.endsWith(t))return r;return null}}var XY=Object.defineProperty,YY=Object.getOwnPropertyDescriptor,ab=(i,e,t,s)=>{for(var r=s>1?void 0:s?YY(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&XY(e,t,r),r};const YS=re("debuganimator");class Or extends Ee{constructor(){super(...arguments),h(this,"applyRootMotion",!1),h(this,"hasRootMotion",!1),h(this,"keepAnimatorControllerStateOnDisable",!1),h(this,"speed",1),h(this,"normalizedStartOffset",0),h(this,"_animatorController",null)}set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof Uu?this._animatorController=e:(YS&&console.log("Assign animator controller",e,this),this._animatorController=new Uu(e)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}Play(e,t=-1,s=Number.NEGATIVE_INFINITY,r=0){this.play(e,t,s,r)}play(e,t=-1,s=Number.NEGATIVE_INFINITY,r=0){var n;(n=this.runtimeAnimatorController)==null||n.play(e,t,s,r)}Reset(){this.reset()}reset(){var e;(e=this._animatorController)==null||e.reset()}SetBool(e,t){this.setBool(e,t)}setBool(e,t){var s;(s=this.runtimeAnimatorController)==null||s.setBool(e,t)}GetBool(e){return this.getBool(e)}getBool(e){var t;return((t=this.runtimeAnimatorController)==null?void 0:t.getBool(e))??!1}SetFloat(e,t){this.setFloat(e,t)}setFloat(e,t){var s;(s=this.runtimeAnimatorController)==null||s.setFloat(e,t)}GetFloat(e){return this.getFloat(e)}getFloat(e){var t;return((t=this.runtimeAnimatorController)==null?void 0:t.getFloat(e))??-1}SetInteger(e,t){this.setInteger(e,t)}setInteger(e,t){var s;(s=this.runtimeAnimatorController)==null||s.setInteger(e,t)}GetInteger(e){return this.getInteger(e)}getInteger(e){var t;return((t=this.runtimeAnimatorController)==null?void 0:t.getInteger(e))??-1}SetTrigger(e){this.setTrigger(e)}setTrigger(e){var t;YS&&console.log("SetTrigger",e),(t=this.runtimeAnimatorController)==null||t.setTrigger(e)}ResetTrigger(e){this.resetTrigger(e)}resetTrigger(e){var t;(t=this.runtimeAnimatorController)==null||t.resetTrigger(e)}IsInTransition(){return this.isInTransition()}isInTransition(){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.isInTransition())??!1}SetSpeed(e){return this.setSpeed(e)}setSpeed(e){var t;e!==this.speed&&(this.speed=e,(t=this._animatorController)==null||t.setSpeed(e))}set minMaxSpeed(e){this.speed=Je.lerp(e.x,e.y,Math.random())}set minMaxOffsetNormalized(e){this.normalizedStartOffset=Je.lerp(e.x,e.y,Math.random()),this.runtimeAnimatorController&&(this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset)}awake(){if(YS&&console.log("ANIMATOR",this.name,this),!!this.gameObject&&this.runtimeAnimatorController){const e=this.runtimeAnimatorController.clone();e?(console.assert(this.runtimeAnimatorController!==e),this.runtimeAnimatorController=e,console.assert(this.runtimeAnimatorController===e),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.setSpeed(this.speed),this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset):console.warn("Could not clone animator controller",this.runtimeAnimatorController)}}onDisable(){var e;this.keepAnimatorControllerStateOnDisable||(e=this._animatorController)==null||e.reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}}ab([w()],Or.prototype,"applyRootMotion",2),ab([w()],Or.prototype,"hasRootMotion",2),ab([w()],Or.prototype,"keepAnimatorControllerStateOnDisable",2),ab([w()],Or.prototype,"runtimeAnimatorController",1);class KY extends Xi{constructor(e,t=1,s=16,r=2){const n=new mt,o=s+r*2,a=new Float32Array((o*3+3)*3);n.setAttribute("position",new tt(a,3));const l=new qi({color:65280}),c=new qi({color:16776960});super(n,[c,l]),this.audio=e,this.range=t,this.divisionsInnerAngle=s,this.divisionsOuterAngle=r,this.type="PositionalAudioHelper",this.update()}update(){const e=this.audio,t=this.range,s=this.divisionsInnerAngle,r=this.divisionsOuterAngle,n=Cr.degToRad(e.panner.coneInnerAngle),o=Cr.degToRad(e.panner.coneOuterAngle),a=n/2,l=o/2;let c=0,u=0,d,p;const f=this.geometry,g=f.attributes.position;f.clearGroups();function m(v,A,b,y){const x=(A-v)/b;for(g.setXYZ(c,0,0,0),u++,d=v;d<A;d+=x)p=c+u,g.setXYZ(p,Math.sin(d)*t,0,Math.cos(d)*t),g.setXYZ(p+1,Math.sin(Math.min(d+x,A))*t,0,Math.cos(Math.min(d+x,A))*t),g.setXYZ(p+2,0,0,0),u+=3;f.addGroup(c,u,y),c+=u,u=0}m(-l,-a,r,0),m(-a,a,s,1),m(a,l,r,0),g.needsUpdate=!0,n===o&&(this.material[0].visible=!1)}dispose(){this.geometry.dispose(),this.material[0].dispose(),this.material[1].dispose()}}var JY=Object.defineProperty,ZY=Object.getOwnPropertyDescriptor,Fc=(i,e,t,s)=>{for(var r=s>1?void 0:s?ZY(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&JY(e,t,r),r};const pr=re("debugaudio");var im;const Ds=(im=class extends Ee{constructor(){super(...arguments),h(this,"clip",""),h(this,"playOnAwake",!1),h(this,"_spatialBlend",0),h(this,"_minDistance",1),h(this,"_maxDistance",100),h(this,"_volume",1),h(this,"rollOffMode",0),h(this,"playInBackground",!0),h(this,"_loop",!1),h(this,"sound",null),h(this,"helper",null),h(this,"wasPlaying",!1),h(this,"audioLoader",null),h(this,"shouldPlay",!1),h(this,"_lastClipStartedLoading",null),h(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||dh())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":pr&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,Ds._userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&Ds._userInteractionRegistered&&this.wasPlaying&&this.play();break}}),h(this,"onApplicationMuteChanged",()=>{var i,e;this.context.application.muted?(i=this.sound)==null||i.setVolume(0):(e=this.sound)==null||e.setVolume(this.volume)}),h(this,"lerp",(i,e,t)=>i*(1-t)+e*t),h(this,"_lastContextTime",0),h(this,"_hasEnded",!0),h(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return Ds._didCallBeginWaitForUserInteraction||(Ds._didCallBeginWaitForUserInteraction=!0,Ds._beginWaitForUserInteraction()),Ds._userInteractionRegistered}static registerWaitForAllowAudio(i){if(i!==null){if(this._userInteractionRegistered){i();return}this.callbacks.indexOf(i)===-1&&this.callbacks.push(i),Ds._didCallBeginWaitForUserInteraction||(Ds._didCallBeginWaitForUserInteraction=!0,Ds._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(i=null){if(this._userInteractionRegistered){i&&i();return}i!==null&&this.registerWaitForAllowAudio(i);const e=(()=>{if(e!=null&&!Ds._userInteractionRegistered){Ds._userInteractionRegistered=!0,pr&&console.log("\u{1F50A} registered interaction, can play audio now"),document.removeEventListener("pointerdown",e),document.removeEventListener("click",e),document.removeEventListener("dragstart",e),document.removeEventListener("touchstart",e);for(const t of this.callbacks)t();this.callbacks.length=0}}).bind(this);document.addEventListener("pointerdown",e),document.addEventListener("click",e),document.addEventListener("dragstart",e),document.addEventListener("touchstart",e)}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(i){this._loop=i,this.sound&&this.sound.setLoop(i)}get spatialBlend(){return this._spatialBlend}set spatialBlend(i){i!==this._spatialBlend&&(this._spatialBlend=i,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(i){this._minDistance!==i&&(this._minDistance=i,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(i){this._maxDistance!==i&&(this._maxDistance=i,this._needUpdateSpatialDistanceSettings=!0)}get volume(){return this._volume}set volume(i){this._volume=i,this.sound&&!this.context.application.muted&&(pr&&console.log(this.name,"audio set volume",i),this.sound.setVolume(i))}get Sound(){if(!this.sound&&Ds._userInteractionRegistered){const i=$.getComponent(this.context.mainCamera,Ep)??$.findObjectOfType(Ep,this.context);i!=null&&i.listener&&(this.sound=new hB(i.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}awake(){this.audioLoader=new A0,this.playOnAwake&&(this.shouldPlay=!0)}onEnable(){Ds._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Ds._beginWaitForUserInteraction(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.loadAndPlay(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(Py.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(Py.MuteChanged,this.onApplicationMuteChanged),this.stop()}onLoaded(i){pr&&console.log("audio buffer loaded"),Ds.registerWaitForAllowAudio(()=>{pr&&console.log("finished loading",i);const e=this.Sound;if(!e){console.warn("Failed getting sound",this.name);return}e.isPlaying&&e.stop(),e.setBuffer(i),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(),pr&&console.log(this.name,this.shouldPlay,Ds.userInteractionRegistered,this),this.shouldPlay&&Ds._userInteractionRegistered&&this.play()})}applySpatialDistanceSettings(){const i=this.sound;if(!i)return;this._needUpdateSpatialDistanceSettings=!1;const e=this.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(pr&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+e),i.setRefDistance(e),i.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:i.setDistanceModel("exponential");break;case 1:i.setDistanceModel("linear");break}this.spatialBlend>0?pr&&!this.helper&&(this.helper=new KY(i,i.getRefDistance()),i.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(i){if(i&&(this.clip=i),this.clip&&(pr&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new A0),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){pr&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,pr&&console.log("load audio",this.clip),this.audioLoader.load(this.clip,this.onLoaded.bind(this),()=>{},console.error)}}play(i=void 0){var e;if(!this.audioLoader||!this.sound||i&&i!==this.clip){this.loadAndPlay(i);return}if(this.shouldPlay=!0,this._hasEnded=!1,pr&&console.log("play",(e=this.sound)==null?void 0:e.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const t=this.context.application.muted;t&&this.sound.setVolume(0),this.sound.play(t?.1:0)}}pause(){var i;pr&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=(i=this.sound)==null?void 0:i.context.currentTime,this.sound.pause())}stop(){var i;pr&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=(i=this.sound)==null?void 0:i.context.currentTime,pr&&console.log(this._lastContextTime),this.sound.stop())}get isPlaying(){var i;return((i=this.sound)==null?void 0:i.isPlaying)??!1}set isPlaying(i){}get time(){var i,e;return(i=this.sound)!=null&&i.source?((e=this.sound.source)==null?void 0:e.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(i){if(this.sound){if(i===this.sound.offset)return;const e=this.isPlaying;this.stop(),this.sound.offset=i,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,pr&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},h(im,"_didCallBeginWaitForUserInteraction",!1),h(im,"callbacks",[]),h(im,"_userInteractionRegistered",!1),im);let as=Ds;Fc([w(URL)],as.prototype,"clip",2),Fc([w()],as.prototype,"playOnAwake",2),Fc([w()],as.prototype,"loop",1),Fc([w()],as.prototype,"spatialBlend",1),Fc([w()],as.prototype,"minDistance",1),Fc([w()],as.prototype,"maxDistance",1),Fc([w()],as.prototype,"volume",1),Fc([w()],as.prototype,"rollOffMode",2);var $Y=Object.defineProperty,eK=Object.getOwnPropertyDescriptor,tK=(i,e,t,s)=>{for(var r=s>1?void 0:s?eK(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&$Y(e,t,r),r};class sm extends Ee{constructor(){super(...arguments),h(this,"constraintActive",!0),h(this,"locked",!1),h(this,"sources",[])}}tK([w(Me)],sm.prototype,"sources",2);const g3={type:"change"},KS={type:"start"},m3={type:"end"};let iK=class extends bs{constructor(i,e){super(),this.object=i,this.domElement=e,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new S,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:ph.ROTATE,MIDDLE:ph.DOLLY,RIGHT:ph.PAN},this.touches={ONE:fh.ROTATE,TWO:fh.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this.getPolarAngle=function(){return o.phi},this.getAzimuthalAngle=function(){return o.theta},this.getDistance=function(){return this.object.position.distanceTo(this.target)},this.listenToKeyEvents=function(Q){Q.addEventListener("keydown",si),this._domElementKeyEvents=Q},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(g3),t.update(),r=s.NONE},this.update=function(){const Q=new S,K=new Ce().setFromUnitVectors(i.up,new S(0,1,0)),Ve=K.clone().invert(),qe=new S,Qe=new Ce,ge=2*Math.PI;return function(){const at=t.object.getWorldPosition(i.position);Q.copy(at).sub(t.target),Q.applyQuaternion(K),o.setFromVector3(Q),t.autoRotate&&r===s.NONE&&R(P()),t.enableDamping?(o.theta+=a.theta*t.dampingFactor,o.phi+=a.phi*t.dampingFactor):(o.theta+=a.theta,o.phi+=a.phi);let It=t.minAzimuthAngle,E=t.maxAzimuthAngle;return isFinite(It)&&isFinite(E)&&(It<-Math.PI?It+=ge:It>Math.PI&&(It-=ge),E<-Math.PI?E+=ge:E>Math.PI&&(E-=ge),It<=E?o.theta=Math.max(It,Math.min(E,o.theta)):o.theta=o.theta>(It+E)/2?Math.max(It,o.theta):Math.min(E,o.theta)),o.phi=Math.max(t.minPolarAngle,Math.min(t.maxPolarAngle,o.phi)),o.makeSafe(),c=Cr.lerp(c,l,t.enableDamping?t.dampingFactor:1),o.radius*=c,o.radius=Math.max(t.minDistance,Math.min(t.maxDistance,o.radius)),t.enableDamping===!0?t.target.addScaledVector(u,t.dampingFactor):t.target.add(u),Q.setFromSpherical(o),Q.applyQuaternion(Ve),at.copy(t.target).add(Q),t.object.parent?t.object.parent.worldToLocal(at):t.object.position.copy(at),t.object.lookAt(t.target),t.enableDamping===!0?(a.theta*=1-t.dampingFactor,a.phi*=1-t.dampingFactor,u.multiplyScalar(1-t.dampingFactor)):(a.set(0,0,0),u.set(0,0,0)),l=1,d||qe.distanceToSquared(t.object.position)>n||8*(1-Qe.dot(t.object.quaternion))>n?(t.dispatchEvent(g3),qe.copy(t.object.position),Qe.copy(t.object.quaternion),d=!1,!0):!1}}(),this.dispose=function(){t.domElement.removeEventListener("contextmenu",le),t.domElement.removeEventListener("pointerdown",Ne),t.domElement.removeEventListener("pointercancel",me),t.domElement.removeEventListener("wheel",kt),t.domElement.removeEventListener("pointermove",Be),t.domElement.removeEventListener("pointerup",ct),t._domElementKeyEvents!==null&&t._domElementKeyEvents.removeEventListener("keydown",si)};const t=this,s={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let r=s.NONE;const n=1e-6,o=new S1,a=new S1;let l=1,c=1;const u=new S;let d=!1;const p=new W,f=new W,g=new W,m=new W,v=new W,A=new W,b=new W,y=new W,x=new W,_=[],M={};function P(){return 2*Math.PI/60/60*t.autoRotateSpeed}function C(){return Math.pow(.95,t.zoomSpeed)}function R(Q){a.theta-=Q}function T(Q){a.phi-=Q}const z=function(){const Q=new S;return function(K,Ve){Q.setFromMatrixColumn(Ve,0),Q.multiplyScalar(-K),u.add(Q)}}(),G=function(){const Q=new S;return function(K,Ve){t.screenSpacePanning===!0?Q.setFromMatrixColumn(Ve,1):(Q.setFromMatrixColumn(Ve,0),Q.crossVectors(t.object.up,Q)),Q.multiplyScalar(K),u.add(Q)}}(),N=function(){const Q=new S,K=new S;return function(Ve,qe){const Qe=t.domElement;if(t.object.isPerspectiveCamera){t.object.getWorldPosition(K),Q.copy(K).sub(t.target);let ge=Q.length();ge*=Math.tan(t.object.fov/2*Math.PI/180),z(2*Ve*ge/Qe.clientHeight,t.object.matrixWorld),G(2*qe*ge/Qe.clientHeight,t.object.matrixWorld)}else t.object.isOrthographicCamera?(z(Ve*(t.object.right-t.object.left)/t.object.zoom/Qe.clientWidth,t.object.matrixWorld),G(qe*(t.object.top-t.object.bottom)/t.object.zoom/Qe.clientHeight,t.object.matrixWorld)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),t.enablePan=!1)}}();function F(Q){t.object.isPerspectiveCamera?l/=Q:t.object.isOrthographicCamera?(t.object.zoom=Math.max(t.minZoom,Math.min(t.maxZoom,t.object.zoom*Q)),t.object.updateProjectionMatrix(),d=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),t.enableZoom=!1)}function X(Q){t.object.isPerspectiveCamera?l*=Q:t.object.isOrthographicCamera?(t.object.zoom=Math.max(t.minZoom,Math.min(t.maxZoom,t.object.zoom/Q)),t.object.updateProjectionMatrix(),d=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),t.enableZoom=!1)}function te(Q){p.set(Q.clientX,Q.clientY)}function ne(Q){b.set(Q.clientX,Q.clientY)}function Z(Q){m.set(Q.clientX,Q.clientY)}function fe(Q){f.set(Q.clientX,Q.clientY),g.subVectors(f,p).multiplyScalar(t.rotateSpeed);const K=t.domElement;R(2*Math.PI*g.x/K.clientHeight),T(2*Math.PI*g.y/K.clientHeight),p.copy(f),t.update()}function ae(Q){y.set(Q.clientX,Q.clientY),x.subVectors(y,b),x.y>0?F(C()):x.y<0&&X(C()),b.copy(y),t.update()}function Le(Q){v.set(Q.clientX,Q.clientY),A.subVectors(v,m).multiplyScalar(t.panSpeed),N(A.x,A.y),m.copy(v),t.update()}function Se(Q){Q.deltaY<0?X(C()):Q.deltaY>0&&F(C()),t.update()}function ie(Q){let K=!1;switch(Q.code){case t.keys.UP:Q.ctrlKey||Q.metaKey||Q.shiftKey?T(2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):N(0,t.keyPanSpeed),K=!0;break;case t.keys.BOTTOM:Q.ctrlKey||Q.metaKey||Q.shiftKey?T(-2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):N(0,-t.keyPanSpeed),K=!0;break;case t.keys.LEFT:Q.ctrlKey||Q.metaKey||Q.shiftKey?R(2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):N(t.keyPanSpeed,0),K=!0;break;case t.keys.RIGHT:Q.ctrlKey||Q.metaKey||Q.shiftKey?R(-2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):N(-t.keyPanSpeed,0),K=!0;break}K&&(Q.preventDefault(),t.update())}function ce(){if(_.length===1)p.set(_[0].pageX,_[0].pageY);else{const Q=.5*(_[0].pageX+_[1].pageX),K=.5*(_[0].pageY+_[1].pageY);p.set(Q,K)}}function Re(){if(_.length===1)m.set(_[0].pageX,_[0].pageY);else{const Q=.5*(_[0].pageX+_[1].pageX),K=.5*(_[0].pageY+_[1].pageY);m.set(Q,K)}}function J(){const Q=_[0].pageX-_[1].pageX,K=_[0].pageY-_[1].pageY,Ve=Math.sqrt(Q*Q+K*K);b.set(0,Ve)}function je(){t.enableZoom&&J(),t.enablePan&&Re()}function ze(){t.enableZoom&&J(),t.enableRotate&&ce()}function ke(Q){if(_.length==1)f.set(Q.pageX,Q.pageY);else{const Ve=rt(Q),qe=.5*(Q.pageX+Ve.x),Qe=.5*(Q.pageY+Ve.y);f.set(qe,Qe)}g.subVectors(f,p).multiplyScalar(t.rotateSpeed);const K=t.domElement;R(2*Math.PI*g.x/K.clientHeight),T(2*Math.PI*g.y/K.clientHeight),p.copy(f)}function Ae(Q){if(_.length===1)v.set(Q.pageX,Q.pageY);else{const K=rt(Q),Ve=.5*(Q.pageX+K.x),qe=.5*(Q.pageY+K.y);v.set(Ve,qe)}A.subVectors(v,m).multiplyScalar(t.panSpeed),N(A.x,A.y),m.copy(v)}function de(Q){const K=rt(Q),Ve=Q.pageX-K.x,qe=Q.pageY-K.y,Qe=Math.sqrt(Ve*Ve+qe*qe);y.set(0,Qe),x.set(0,Math.pow(y.y/b.y,t.zoomSpeed)),F(x.y),b.copy(y)}function ye(Q){t.enableZoom&&de(Q),t.enablePan&&Ae(Q)}function pe(Q){t.enableZoom&&de(Q),t.enableRotate&&ke(Q)}function Ne(Q){t.enabled!==!1&&(_.length===0&&(t.domElement.addEventListener("pointermove",Be),t.domElement.addEventListener("pointerup",ct)),Te(Q),Q.pointerType==="touch"?U(Q):ht(Q))}function Be(Q){t.enabled!==!1&&(Q.pointerType==="touch"?D(Q):ut(Q))}function ct(Q){De(Q),_.length===0&&(t.domElement.removeEventListener("pointermove",Be),t.domElement.removeEventListener("pointerup",ct)),t.dispatchEvent(m3),r=s.NONE}function me(Q){De(Q)}function ht(Q){let K;switch(Q.button){case 0:K=t.mouseButtons.LEFT;break;case 1:K=t.mouseButtons.MIDDLE;break;case 2:K=t.mouseButtons.RIGHT;break;default:K=-1}switch(K){case ph.DOLLY:if(t.enableZoom===!1)return;ne(Q),r=s.DOLLY;break;case ph.ROTATE:if(Q.ctrlKey||Q.metaKey||Q.shiftKey){if(t.enablePan===!1)return;Z(Q),r=s.PAN}else{if(t.enableRotate===!1)return;te(Q),r=s.ROTATE}break;case ph.PAN:if(Q.ctrlKey||Q.metaKey||Q.shiftKey){if(t.enableRotate===!1)return;te(Q),r=s.ROTATE}else{if(t.enablePan===!1)return;Z(Q),r=s.PAN}break;default:r=s.NONE}r!==s.NONE&&t.dispatchEvent(KS)}function ut(Q){switch(r){case s.ROTATE:if(t.enableRotate===!1)return;fe(Q);break;case s.DOLLY:if(t.enableZoom===!1)return;ae(Q);break;case s.PAN:if(t.enablePan===!1)return;Le(Q);break}}function kt(Q){t.enabled===!1||t.enableZoom===!1||r!==s.NONE||(Q.preventDefault(),t.dispatchEvent(KS),Se(Q),t.dispatchEvent(m3))}function si(Q){t.enabled===!1||t.enablePan===!1||ie(Q)}function U(Q){switch(Ge(Q),_.length){case 1:switch(t.touches.ONE){case fh.ROTATE:if(t.enableRotate===!1)return;ce(),r=s.TOUCH_ROTATE;break;case fh.PAN:if(t.enablePan===!1)return;Re(),r=s.TOUCH_PAN;break;default:r=s.NONE}break;case 2:switch(t.touches.TWO){case fh.DOLLY_PAN:if(t.enableZoom===!1&&t.enablePan===!1)return;je(),r=s.TOUCH_DOLLY_PAN;break;case fh.DOLLY_ROTATE:if(t.enableZoom===!1&&t.enableRotate===!1)return;ze(),r=s.TOUCH_DOLLY_ROTATE;break;default:r=s.NONE}break;default:r=s.NONE}r!==s.NONE&&t.dispatchEvent(KS)}function D(Q){switch(Ge(Q),r){case s.TOUCH_ROTATE:if(t.enableRotate===!1)return;ke(Q),t.update();break;case s.TOUCH_PAN:if(t.enablePan===!1)return;Ae(Q),t.update();break;case s.TOUCH_DOLLY_PAN:if(t.enableZoom===!1&&t.enablePan===!1)return;ye(Q),t.update();break;case s.TOUCH_DOLLY_ROTATE:if(t.enableZoom===!1&&t.enableRotate===!1)return;pe(Q),t.update();break;default:r=s.NONE}}function le(Q){t.enabled!==!1&&Q.preventDefault()}function Te(Q){_.push(Q)}function De(Q){delete M[Q.pointerId];for(let K=0;K<_.length;K++)if(_[K].pointerId==Q.pointerId){_.splice(K,1);return}}function Ge(Q){let K=M[Q.pointerId];K===void 0&&(K=new W,M[Q.pointerId]=K),K.set(Q.pageX,Q.pageY)}function rt(Q){const K=Q.pointerId===_[0].pointerId?_[1]:_[0];return M[K.pointerId]}t.domElement.addEventListener("contextmenu",le),t.domElement.addEventListener("pointerdown",Ne),t.domElement.addEventListener("pointercancel",me),t.domElement.addEventListener("wheel",kt,{passive:!1}),this.update()}};class sK{static createButton(e,t={},s){const r=document.createElement("button");let n=!1;function o(){if(t.optionalFeatures=t.optionalFeatures||[],t.domOverlay===void 0){var u=document.createElement("div");u.style.display="none",document.body.appendChild(u);var d=document.createElementNS("http://www.w3.org/2000/svg","svg");d.setAttribute("width",38),d.setAttribute("height",38),d.style.position="absolute",d.style.right="20px",d.style.top="20px",d.addEventListener("click",function(){f.end()}),u.appendChild(d);var p=document.createElementNS("http://www.w3.org/2000/svg","path");p.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),p.setAttribute("stroke","#fff"),p.setAttribute("stroke-width",2),d.appendChild(p),t.optionalFeatures.push("dom-overlay"),t.domOverlay={root:u},n=!0}let f=null,g=null;async function m(A){var b;const y=/WebXRViewer\//i.test(navigator.userAgent),x=t.domOverlay.root;y&&((b=t.domOverlay)!=null&&b.root?(g=x.parentNode,g&&(console.log("Reparent DOM Overlay to body",x,x.style.display),x.style.display="",x.style.visibility="",document.body.appendChild(x))):console.warn("WebXRViewer: No DOM Overlay found")),A.addEventListener("end",v),await e.xr.setSession(A),r.textContent="STOP AR",n&&(t.domOverlay.root.style.display=""),f=A}function v(){f.removeEventListener("end",v),r.textContent="START AR";const A=t.domOverlay.root;g&&g.appendChild(A),n&&(A.style.display="none"),f=null}r.style.display="",r.style.cursor="pointer",r.style.left="calc(50% - 50px)",r.style.width="100px",r.textContent="START AR",r.onmouseenter=function(){r.style.opacity="1.0"},r.onmouseleave=function(){r.style.opacity="0.5"},r.onclick=function(){f===null?(s?.call(this,t),navigator.xr.requestSession("immersive-ar",t).then(m)):f.end()}}function a(){r.disabled=!0,r.style.display="",r.style.cursor="auto",r.style.left="calc(50% - 75px)",r.style.width="150px",r.onmouseenter=null,r.onmouseleave=null,r.onclick=null}function l(){a(),r.textContent="AR NOT SUPPORTED"}function c(u){u.style.position="absolute",u.style.bottom="20px",u.style.padding="12px 6px",u.style.border="1px solid #fff",u.style.borderRadius="4px",u.style.background="rgba(0,0,0,0.1)",u.style.color="#fff",u.style.font="normal 13px sans-serif",u.style.textAlign="center",u.style.opacity="0.5",u.style.outline="none",u.style.zIndex="999"}if("xr"in navigator)return r.id="ARButton",r.style.display="none",c(r),navigator.xr.isSessionSupported("immersive-ar").then(function(u){u?o():l()}).catch(l),r;{const u=document.createElement("a");return window.isSecureContext===!1?(u.href=document.location.href.replace(/^http:/,"https:"),u.innerHTML="WEBXR NEEDS HTTPS"):(u.href="https://immersiveweb.dev/",u.innerHTML="WEBXR NOT AVAILABLE"),u.style.left="calc(50% - 90px)",u.style.width="180px",u.style.textDecoration="none",c(u),u}}}const JS=class{static createButton(i,e){const t=document.createElement("button");function s(){let a=null;async function l(u){u.addEventListener("end",c),await i.xr.setSession(u),t.textContent="EXIT VR",a=u}function c(){a.removeEventListener("end",c),t.textContent="ENTER VR",a=null}t.style.display="",t.style.cursor="pointer",t.style.left="calc(50% - 50px)",t.style.width="100px",t.textContent="ENTER VR",t.onmouseenter=function(){t.style.opacity="1.0"},t.onmouseleave=function(){t.style.opacity="0.5"},t.onclick=function(){if(a===null){const u={optionalFeatures:e.optionalFeatures};navigator.xr.requestSession("immersive-vr",u).then(l)}else a.end()}}function r(){t.disabled=!0,t.style.display="",t.style.cursor="auto",t.style.left="calc(50% - 75px)",t.style.width="150px",t.onmouseenter=null,t.onmouseleave=null,t.onclick=null}function n(){r(),t.textContent="VR NOT SUPPORTED"}function o(a){a.style.position="absolute",a.style.bottom="20px",a.style.padding="12px 6px",a.style.border="1px solid #fff",a.style.borderRadius="4px",a.style.background="rgba(0,0,0,0.1)",a.style.color="#fff",a.style.font="normal 13px sans-serif",a.style.textAlign="center",a.style.opacity="0.5",a.style.outline="none",a.style.zIndex="999"}if("xr"in navigator)return t.id="VRButton",t.style.display="none",o(t),navigator.xr.isSessionSupported("immersive-vr").then(function(a){a?s():n(),JS.xrSessionIsGranted&&(console.log("XR session is granted - will enter immersive web now"),t.click())}),t;{const a=document.createElement("a");return window.isSecureContext===!1?(a.href=document.location.href.replace(/^http:/,"https:"),a.innerHTML="WEBXR NEEDS HTTPS"):(a.href="https://immersiveweb.dev/",a.innerHTML="WEBXR NOT AVAILABLE"),a.style.left="calc(50% - 90px)",a.style.width="180px",a.style.textDecoration="none",o(a),a}}static registerSessionGrantedListener(){if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent))return;navigator.xr.addEventListener("sessiongranted",()=>{JS.xrSessionIsGranted=!0})}}};let ZS=JS;h(ZS,"xrSessionIsGranted",!1),ZS.registerSessionGrantedListener();const lb="noVoip",$r=re("debugvoip"),rK=re("voip");class nK{constructor(e){h(this,"id"),this.id=e}}class oK{constructor(e,t,s,r){h(this,"peer"),h(this,"voip"),h(this,"userId"),h(this,"peerId"),h(this,"call",null),h(this,"callErrorListener",null),h(this,"stream",null),this.voip=e,this.peer=t,this.userId=s,this.peerId=r}close(){var e;$r&&console.log("close voip call"),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.open&&this.call.close(),(e=this.stream)==null||e.getTracks().forEach(function(t){t.stop()})}updateMute(e){var t;if(!this.stream)return;const s=(t=this.stream)==null?void 0:t.getAudioTracks();for(const r of s)r.enabled=!e}async startVoipCall(){if(!await Gl.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}$r&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),$r&&console.log(this.stream),this.call=this.peer.call(this.peerId,this.stream,{metadata:{userId:this.userId}}),this.call.on("error",e=>{console.error(e)}),this.call.on("stream",e=>{$r&&console.log("received stream from remote again",e)}),this.peer.on("close",this.onCallClose.bind(this)),this.callErrorListener=e=>{var t;e.message.includes(this.peerId)?(console.log("Could not connect to "+this.peerId),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.close(),(t=this.stream)==null||t.getTracks().forEach(function(s){s.stop()}),this.stream=null):console.error(e)},this.peer.on("error",this.callErrorListener)}onCallClose(e){$r&&console.log("call closed",e)}}class aK{constructor(e,t,s){h(this,"voip"),h(this,"call"),h(this,"audio",null),h(this,"stream",null),h(this,"obj"),h(this,"analyzer",null),h(this,"waitingForStart",!1),h(this,"closed",!1),h(this,"audioElement",null),this.voip=e,this.obj=t,this.call=s}get currentStream(){return this.stream}get currentAudio(){return this.audio}get currentAnalyzer(){return this.analyzer}openAudioStream(e){const t=e.getAudioTracks();for(const s of t)if(s.kind==="audio"&&s.readyState==="live"){this.open(s);return}console.warn("failed finding valid audio stream to begin call")}open(e){console.assert(e.kind==="audio","invalid track kind, expected audio but received "+e.kind),!this.waitingForStart&&(this.waitingForStart=!0,as.userInteractionRegistered||$r&&console.log("Incoming call, waiting for user interaction before opening audio"),as.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){$r&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);const t=new x1;this.audio=new b0(t),this.audio.setVolume(this.voip.muteInput?0:1),this.audio.setMediaStreamSource(this.stream);const s=document.createElement("audio");this.audioElement=s,s.style.display="none",document.body.appendChild(s),s.srcObject=this.stream,s.sinkId!==void 0&&navigator.mediaDevices.enumerateDevices().then(r=>{if(s){console.log(r);for(const n of r)if(n.label==="Speakerphone"){s.sinkId=n.deviceId;break}}}),$r&&console.log("call is setup, you should hear something now"),this.analyzer=new uB(this.audio,32)}}))}close(){var e,t,s;this.closed=!0,(e=this.call)!=null&&e.open&&this.call.close(),(t=this.audio)==null||t.disconnect(),(s=this.stream)==null||s.getTracks().forEach(r=>{r.stop()}),this.stream=null,this.audioElement&&this.audioElement.remove()}}class Gl extends Ee{constructor(){super(...arguments),h(this,"requireParam",!1),h(this,"peer",null),h(this,"model",null),h(this,"connections",{}),h(this,"currentIncomingCalls",{}),h(this,"_inputMuted",!1),h(this,"_outputMuted",!1)}set muteInput(e){var t;if(e===this._inputMuted||(this._inputMuted=e,!this.currentIncomingCalls))return;const s=this._inputMuted?0:1;for(const r in this.currentIncomingCalls){const n=this.currentIncomingCalls[r];(t=n?.currentAudio)==null||t.setVolume(s)}}get muteInput(){return this._inputMuted}set muteOutput(e){if(e!==this._outputMuted&&(this._outputMuted=e,!!this.connections))for(const t in this.connections){const s=this.connections[t];s?.updateMute(e)}}get muteOutput(){return this._outputMuted}getFrequency(e){if(e===null){for(const s in this.currentIncomingCalls){const r=this.currentIncomingCalls[s];if(r&&r.currentAnalyzer)return r.currentAnalyzer.getAverageFrequency()}return null}const t=this.currentIncomingCalls[e];return t&&t.currentAnalyzer?t.currentAnalyzer.getAverageFrequency():null}awake(){if(re(lb)){console.log("VOIP is disabled by url parameter: "+lb);return}if(this.requireParam&&!rK){console.debug("VOIP must be enabled explicitly by url parameter");return}if(wf()&&Da()){console.log("VOIP is currently not supported on Safari iOS");return}this.peer=new ry,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,this.context.connection.beginListen(ji.JoinedRoom,e=>{navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}),this.context.connection.beginListen("peer-update-id",e=>{if(e.id!==this.context.connection.connectionId){const t=this.connections[e.id];if(t&&t.close(),this.peer&&this.context.connection.connectionId){const s=new oK(this,this.peer,this.context.connection.connectionId,e.peerId);this.connections[e.id]=s,s.startVoipCall()}}}),this.context.connection.beginListen(ji.UserLeftRoom,e=>{const{userId:t}=e,s=this.connections[t];this.connections[t]=null,s&&s.close();const r=this.currentIncomingCalls[t];$r&&console.log("UserLeftRoom",e,t,r),r&&(r.close(),this.currentIncomingCalls[t]=null)}),this.peer.on("open",this.onOpenPeerConnection.bind(this))}onEnable(){}onDisable(){console.log("TODO: close all");for(const e in this.currentIncomingCalls)try{const t=this.currentIncomingCalls[e];t?.close();const s=this.connections[e];s?.close()}catch(t){console.error(t)}}async onOpenPeerConnection(e){$r&&console.log("Peer connection established and received id"),this.model=new nK(e),this.context.connection.send("peer-update-id",this.model,Xr.OnRoomJoin),this.peer&&(this.peer.on("call",this.onReceiveCall.bind(this)),this.peer.on("connection",function(t){$r&&console.log("CONNECTION",t),t.on("data",function(s){$r&&console.log("Received",s)})}))}async onReceiveCall(e){const{metadata:t}=e;console.assert(t.userId);const{userId:s}=t,r=this.currentIncomingCalls[s];if(r&&r.close(),$r&&console.log("received call"),await Gl.HasMicrophonePermissions()){const n=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(n)}else e.answer(null);this.currentIncomingCalls[s]=new aK(this,this.gameObject,e),e.on("stream",n=>{var o;$r&&console.log("receive caller stream, will setup audio now"),(o=this.currentIncomingCalls[s])==null||o.openAudioStream(n)}),e.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}}var lK=Object.defineProperty,cK=Object.getOwnPropertyDescriptor,v3=(i,e,t,s)=>{for(var r=s>1?void 0:s?cK(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&lK(e,t,r),r};class Uc extends Ee{constructor(){super(...arguments),h(this,"webAR",null),h(this,"invertForward",!1),h(this,"_initalMatrix",new Pe),h(this,"_selectStartFn",this.onSelectStart.bind(this)),h(this,"_selectEndFn",this.onSelectEnd.bind(this)),h(this,"_arScale",5),h(this,"_rig",null),h(this,"_startPose",null),h(this,"_placementPose",null),h(this,"_isTouching",!1),h(this,"_rigStartPose",null),h(this,"_gotFirstHitTestResult",!1)}get rig(){var e;return(e=this.webAR)==null?void 0:e.webxr.Rig}get arScale(){return this._arScale}set arScale(e){e!==this._arScale&&(this._arScale=e,this.setScale(e))}start(){const e=$.findObjectOfType(_t);e&&(e.Rig.updateMatrix(),this._initalMatrix.copy(e.Rig.matrix))}onBegin(e){var t;this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose=this.gameObject.matrix.clone(),this._rigStartPose=(t=this.rig)==null?void 0:t.matrix.clone(),this._gotFirstHitTestResult=!1,e.addEventListener("selectstart",this._selectStartFn),e.addEventListener("selectend",this._selectEndFn),this.gameObject.visible=!1,this.rig&&(this.rig.matrixAutoUpdate=!0,this._initalMatrix.decompose(this.rig.position,this.rig.quaternion,this.rig.scale)),this.dispatchEvent(new CustomEvent("onBeginSession"))}onUpdate(e,t,s){if(s&&!this._placementPose&&(this._gotFirstHitTestResult||(this._gotFirstHitTestResult=!0,this.dispatchEvent(new CustomEvent("canPlaceSession",{detail:{pose:s}}))),this._isTouching)){const r=new Pe().fromArray(s.transform.matrix).invert();return this.dispatchEvent(new CustomEvent("placedSession",{detail:{pose:s,poseMatrix:r}})),this.webAR&&this.webAR.setReticleActive(!1),this.placeAt(e,r),!0}return!1}placeAt(e,t){this._placementPose||(this._placementPose=new Pe),this._placementPose.copy(t);const s=this.gameObject.matrixWorld.clone().invert();if(this._placementPose.premultiply(s),e){if(this.invertForward){const r=new Pe().makeRotationY(Math.PI);this._placementPose.premultiply(r)}this._rig=e,this.setScale(this.arScale)}else this._rig=null;this.gameObject.visible=!0}onEnd(e,t){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose&&this.gameObject.matrix.copy(this._startPose),e&&(e.matrixAutoUpdate=!0,this._rigStartPose&&this._rigStartPose.decompose(e.position,e.quaternion,e.scale)),on.markDirty(this.gameObject,!0),setTimeout(()=>{this.gameObject.matrixAutoUpdate=!0,this.gameObject.visible=!0},100)}onSelectStart(){this._isTouching=!0}onSelectEnd(){this._isTouching=!1}setScale(e){const t=this._rig;!t||!this._placementPose||(this._rigStartPose||(this._rigStartPose=t.matrix.clone()),t.matrixAutoUpdate=!1,t.matrix.multiplyMatrices(new Pe().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld(),console.log("Place",t.position))}}v3([w()],Uc.prototype,"invertForward",2),v3([w()],Uc.prototype,"arScale",1);const hK="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/";class uK{constructor(e,t,s,r,n=null){this.controller=t,this.handModel=e,this.bones=[],n===null&&(n=new zd,n.setPath(s||hK)),n.load(`${r}.glb`,o=>{const a=o.scene.children[0];this.handModel.add(a),a.layers.mask=this.handModel.layers.mask;const l=a.getObjectByProperty("type","SkinnedMesh");l.frustumCulled=!1,l.castShadow=!0,l.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(c=>{const u=a.getObjectByName(c);u!==void 0?u.jointName=c:console.warn(`Couldn't find ${c} in ${r} hand mesh`),this.bones.push(u)})})}updateMesh(){const e=this.controller.joints;for(let t=0;t<this.bones.length;t++){const s=this.bones[t];if(s){const r=e[s.jointName];if(r.visible){const n=r.position;s.position.copy(n),s.quaternion.copy(r.quaternion)}}}}}const dK=.01,pK="index-finger-tip";class fK extends Me{constructor(e,t=null){super(),this.controller=e,this.motionController=null,this.envMap=null,this.loader=t,this.mesh=null,e.addEventListener("connected",s=>{const r=s.data;r.hand&&!this.motionController&&(this.xrInputSource=r,this.motionController=new uK(this,e,this.path,r.handedness,this.loader))}),e.addEventListener("disconnected",()=>{this.clear(),this.motionController=null})}updateMatrixWorld(e){super.updateMatrixWorld(e),this.motionController&&this.motionController.updateMesh()}getPointerPosition(){const e=this.controller.joints[pK];return e?e.position:null}intersectBoxObject(e){const t=this.getPointerPosition();if(t){const s=new Ao(t,dK),r=new or().setFromObject(e);return s.intersectsBox(r)}else return!1}checkButton(e){this.intersectBoxObject(e)?e.onPress():e.onClear(),e.isPressed()&&e.whilePressed()}}const gK=.05,A3=.02,cb=.01,y3=.02,b3=1,hp=.4,mK=.002,rm=.01,hb=.003,x3=.035,Ai=16,Zn=12,$S=110,vK=new S(0,1,0),AK=new S(0,0,1),yK=.02,bK=1.5;class xK extends Me{constructor(e,t){super(),this.hand=e,this.controller=t,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,e.addEventListener("connected",s=>{const r=s.data;r.hand&&(this.visible=!0,this.xrInputSource=r,this.pointerObject===null&&this.createPointer())})}_drawVerticesRing(e,t,s){const r=t.clone();for(let n=0;n<Ai;n++){r.applyAxisAngle(AK,Math.PI*2/Ai);const o=s*Ai+n;e[3*o]=r.x,e[3*o+1]=r.y,e[3*o+2]=r.z}}_updatePointerVertices(e){const t=this.pointerGeometry.attributes.position.array,s=new S(mK,0,-1*(x3-e));this._drawVerticesRing(t,s,0);const r=new S(Math.sin(Math.PI*$S/180)*e,Math.cos(Math.PI*$S/180)*e,0);for(let c=0;c<Zn;c++)this._drawVerticesRing(t,r,c+1),r.applyAxisAngle(vK,Math.PI*$S/180/(Zn*-2));const n=Ai*(1+Zn),o=Ai*(1+Zn)+1,a=new S(0,0,-1*(x3-e));t[n*3]=a.x,t[n*3+1]=a.y,t[n*3+2]=a.z;const l=new S(0,0,e);t[o*3]=l.x,t[o*3+1]=l.y,t[o*3+2]=l.z,this.pointerGeometry.setAttribute("position",new $e(t,3))}createPointer(){let e,t;const s=new Array(((Zn+1)*Ai+2)*3).fill(0),r=[];for(this.pointerGeometry=new mt,this.pointerGeometry.setAttribute("position",new $e(s,3)),this._updatePointerVertices(rm),e=0;e<Zn;e++){for(t=0;t<Ai-1;t++)r.push(e*Ai+t,e*Ai+t+1,(e+1)*Ai+t),r.push(e*Ai+t+1,(e+1)*Ai+t+1,(e+1)*Ai+t);r.push((e+1)*Ai-1,e*Ai,(e+2)*Ai-1),r.push(e*Ai,(e+1)*Ai,(e+2)*Ai-1)}const n=Ai*(1+Zn),o=Ai*(1+Zn)+1;for(e=0;e<Ai-1;e++)r.push(n,e+1,e),r.push(o,e+Ai*Zn,e+Ai*Zn+1);r.push(n,0,Ai-1),r.push(o,Ai*(Zn+1)-1,Ai*Zn);const a=new pi;a.transparent=!0,a.opacity=hp,this.pointerGeometry.setIndex(r),this.pointerMesh=new ve(this.pointerGeometry,a),this.pointerMesh.position.set(0,0,-1*rm),this.pointerObject=new Me,this.pointerObject.add(this.pointerMesh),this.raycaster=new _d;const l=new Bn(yK,10,10),c=new pi;c.transparent=!0,c.opacity=hp,this.cursorObject=new ve(l,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 e=this.pointerObject.matrixWorld,t=new Pe;t.identity().extractRotation(e),this.raycaster.ray.origin.setFromMatrixPosition(e),this.raycaster.ray.direction.set(0,0,-1).applyMatrix4(t)}}_updatePointer(){this.pointerObject.visible=this.controller.visible;const e=this.hand.joints["index-finger-tip"],t=this.hand.joints["thumb-tip"],s=e.position.distanceTo(t.position),r=e.position.clone().add(t.position).multiplyScalar(.5);this.pointerObject.position.copy(r),this.pointerObject.quaternion.copy(this.controller.quaternion),this.pinched=s<=A3;const n=(s-cb)/(gK-cb),o=(s-cb)/(A3-cb);if(n>1)this._updatePointerVertices(rm),this.pointerMesh.position.set(0,0,-1*rm),this.pointerMesh.material.opacity=hp;else if(n>0){const a=(rm-hb)*n+hb;this._updatePointerVertices(a),o<1?(this.pointerMesh.position.set(0,0,-1*a-(1-o)*y3),this.pointerMesh.material.opacity=hp+(1-o)*(b3-hp)):(this.pointerMesh.position.set(0,0,-1*a),this.pointerMesh.material.opacity=hp)}else this._updatePointerVertices(hb),this.pointerMesh.position.set(0,0,-1*hb-y3),this.pointerMesh.material.opacity=b3;this.cursorObject.material.opacity=this.pointerMesh.material.opacity}updateMatrixWorld(e){super.updateMatrixWorld(e),this.pointerGeometry&&(this._updatePointer(),this._updateRaycaster())}isPinched(){return this.pinched}setAttached(e){this.attached=e}isAttached(){return this.attached}intersectObject(e,t=!0){if(this.raycaster)return this.raycaster.intersectObject(e,t)}intersectObjects(e,t=!0){if(this.raycaster)return this.raycaster.intersectObjects(e,t)}checkIntersections(e,t=!1){if(this.raycaster&&!this.attached){const s=this.raycaster.intersectObjects(e,t),r=new S(0,0,-1);if(s.length>0){const n=s[0].distance;this.cursorObject.position.copy(r.multiplyScalar(n))}else this.cursorObject.position.copy(r.multiplyScalar(bK))}}setCursor(e){const t=new S(0,0,-1);this.raycaster&&!this.attached&&this.cursorObject.position.copy(t.multiplyScalar(e))}}const Gi={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 w3(i){const e=await fetch(i);if(e.ok)return e.json();throw new Error(e.statusText)}async function wK(i){if(!i)throw new Error("No basePath supplied");return await w3(`${i}/profilesList.json`)}async function _K(i,e,t=null,s=!0){if(!i)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No basePath supplied");const r=await wK(e);let n;if(i.profiles.some(l=>{const c=r[l];return c&&(n={profileId:l,profilePath:`${e}/${c.path}`,deprecated:!!c.deprecated}),!!n}),!n){if(!t)throw new Error("No matching profile name found");const l=r[t];if(!l)throw new Error(`No matching profile name found and default profile "${t}" missing.`);n={profileId:t,profilePath:`${e}/${l.path}`,deprecated:!!l.deprecated}}const o=await w3(n.profilePath);let a;if(s){let l;if(i.handedness==="any"?l=o.layouts[Object.keys(o.layouts)[0]]:l=o.layouts[i.handedness],!l)throw new Error(`No matching handedness, ${i.handedness}, in profile ${n.profileId}`);l.assetPath&&(a=n.profilePath.replace("profile.json",l.assetPath))}return{profile:o,assetPath:a}}const CK={xAxis:0,yAxis:0,button:0,state:Gi.ComponentState.DEFAULT};function SK(i=0,e=0){let t=i,s=e;if(Math.sqrt(i*i+e*e)>1){const r=Math.atan2(e,i);t=Math.cos(r),s=Math.sin(r)}return{normalizedXAxis:t*.5+.5,normalizedYAxis:s*.5+.5}}class EK{constructor(e){this.componentProperty=e.componentProperty,this.states=e.states,this.valueNodeName=e.valueNodeName,this.valueNodeProperty=e.valueNodeProperty,this.valueNodeProperty===Gi.VisualResponseProperty.TRANSFORM&&(this.minNodeName=e.minNodeName,this.maxNodeName=e.maxNodeName),this.value=0,this.updateFromComponent(CK)}updateFromComponent({xAxis:e,yAxis:t,button:s,state:r}){const{normalizedXAxis:n,normalizedYAxis:o}=SK(e,t);switch(this.componentProperty){case Gi.ComponentProperty.X_AXIS:this.value=this.states.includes(r)?n:.5;break;case Gi.ComponentProperty.Y_AXIS:this.value=this.states.includes(r)?o:.5;break;case Gi.ComponentProperty.BUTTON:this.value=this.states.includes(r)?s:0;break;case Gi.ComponentProperty.STATE:this.valueNodeProperty===Gi.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(r):this.value=this.states.includes(r)?1:0;break;default:throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}}class MK{constructor(e,t){if(!e||!t||!t.visualResponses||!t.gamepadIndices||Object.keys(t.gamepadIndices).length===0)throw new Error("Invalid arguments supplied");this.id=e,this.type=t.type,this.rootNodeName=t.rootNodeName,this.touchPointNodeName=t.touchPointNodeName,this.visualResponses={},Object.keys(t.visualResponses).forEach(s=>{const r=new EK(t.visualResponses[s]);this.visualResponses[s]=r}),this.gamepadIndices=Object.assign({},t.gamepadIndices),this.values={state:Gi.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(e){if(this.values.state=Gi.ComponentState.DEFAULT,this.gamepadIndices.button!==void 0&&e.buttons.length>this.gamepadIndices.button){const t=e.buttons[this.gamepadIndices.button];this.values.button=t.value,this.values.button=this.values.button<0?0:this.values.button,this.values.button=this.values.button>1?1:this.values.button,t.pressed||this.values.button===1?this.values.state=Gi.ComponentState.PRESSED:(t.touched||this.values.button>Gi.ButtonTouchThreshold)&&(this.values.state=Gi.ComponentState.TOUCHED)}this.gamepadIndices.xAxis!==void 0&&e.axes.length>this.gamepadIndices.xAxis&&(this.values.xAxis=e.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===Gi.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>Gi.AxisTouchThreshold&&(this.values.state=Gi.ComponentState.TOUCHED)),this.gamepadIndices.yAxis!==void 0&&e.axes.length>this.gamepadIndices.yAxis&&(this.values.yAxis=e.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===Gi.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>Gi.AxisTouchThreshold&&(this.values.state=Gi.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(t=>{t.updateFromComponent(this.values)})}}class IK{constructor(e,t,s){if(!e)throw new Error("No xrInputSource supplied");if(!t)throw new Error("No profile supplied");this.xrInputSource=e,this.assetUrl=s,this.id=t.profileId,this.layoutDescription=t.layouts[e.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(r=>{const n=this.layoutDescription.components[r];this.components[r]=new MK(r,n)}),this.updateFromGamepad()}get gripSpace(){return this.xrInputSource.gripSpace}get targetRaySpace(){return this.xrInputSource.targetRaySpace}get data(){const e=[];return Object.values(this.components).forEach(t=>{e.push(t.data)}),e}updateFromGamepad(){Object.values(this.components).forEach(e=>{e.updateFromGamepad(this.xrInputSource.gamepad)})}}const TK="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",RK="generic-trigger";class PK extends Me{constructor(){super(),this.motionController=null,this.envMap=null}setEnvironmentMap(e){return this.envMap==e?this:(this.envMap=e,this.traverse(t=>{t.isMesh&&(t.material.envMap=this.envMap,t.material.needsUpdate=!0)}),this)}updateMatrixWorld(e){super.updateMatrixWorld(e),this.motionController&&(this.motionController.updateFromGamepad(),Object.values(this.motionController.components).forEach(t=>{Object.values(t.visualResponses).forEach(s=>{const{valueNode:r,minNode:n,maxNode:o,value:a,valueNodeProperty:l}=s;r&&(l===Gi.VisualResponseProperty.VISIBILITY?r.visible=a:l===Gi.VisualResponseProperty.TRANSFORM&&(r.quaternion.slerpQuaternions(n.quaternion,o.quaternion,a),r.position.lerpVectors(n.position,o.position,a)))})}))}}function BK(i,e){Object.values(i.components).forEach(t=>{const{type:s,touchPointNodeName:r,visualResponses:n}=t;if(s===Gi.ComponentType.TOUCHPAD)if(t.touchPointNode=e.getObjectByName(r),t.touchPointNode){const o=new Bn(.001),a=new pi({color:255}),l=new ve(o,a);t.touchPointNode.add(l)}else console.warn(`Could not find touch dot, ${t.touchPointNodeName}, in touchpad component ${t.id}`);Object.values(n).forEach(o=>{const{valueNodeName:a,minNodeName:l,maxNodeName:c,valueNodeProperty:u}=o;if(u===Gi.VisualResponseProperty.TRANSFORM){if(o.minNode=e.getObjectByName(l),o.maxNode=e.getObjectByName(c),!o.minNode){console.warn(`Could not find ${l} in the model`);return}if(!o.maxNode){console.warn(`Could not find ${c} in the model`);return}}o.valueNode=e.getObjectByName(a),o.valueNode||console.warn(`Could not find ${a} in the model`)})})}function _3(i,e){BK(i.motionController,e),i.envMap&&e.traverse(t=>{t.isMesh&&(t.material.envMap=i.envMap,t.material.needsUpdate=!0)}),i.layers.mask!=0&&e.traverse(t=>{t.layers.mask=i.layers.mask}),i.add(e)}class kK{constructor(e=null){this.gltfLoader=e,this.path=TK,this._assetCache={},this.gltfLoader||(this.gltfLoader=new zd)}createControllerModel(e){const t=new PK;let s=null;return e.addEventListener("connected",r=>{const n=r.data;n.targetRayMode!=="tracked-pointer"||!n.gamepad||_K(n,this.path,RK).then(({profile:o,assetPath:a})=>{t.motionController=new IK(n,o,a);const l=this._assetCache[t.motionController.assetUrl];if(l)s=l.scene.clone(),_3(t,s);else{if(!this.gltfLoader)throw new Error("GLTFLoader not set.");this.gltfLoader.setPath(""),this.gltfLoader.load(t.motionController.assetUrl,c=>{this._assetCache[t.motionController.assetUrl]=c,s=c.scene.clone(),_3(t,s)},null,()=>{throw new Error(`Asset ${t.motionController.assetUrl} missing or malformed.`)})}}).catch(o=>{console.warn(o)})}),e.addEventListener("disconnected",()=>{t.motionController=null,t.remove(s),s=null}),t}}const nm=re("debugavatar");class ub{constructor(e,t,s,r){h(this,"root"),h(this,"head"),h(this,"leftHand"),h(this,"rigthHand");var n;this.root=e,this.head=t,this.leftHand=s,this.rigthHand=r,(n=this.root)==null||n.traverse(o=>o.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class db{constructor(){h(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let s=null;if(typeof t=="string"){if(s=await this.loadAvatar(e,t),!s){const n=new Jo;s=$.instantiate(zu(t,e.scene),n)}}else s=t;if(!s)return null;const r=this.findAvatar(s);return r.isValid?(nm&&console.log("[Custom Avatar] valid config",t,nm?r:""),r):(console.warn("[Custom Avatar] config isn't valid",t,nm?r:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(nm&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const r=await fetch("./"+t);let n=null;if(r.ok){const a=await r.blob();a&&(n=await a.arrayBuffer())}if(!n&&(n=await DC(t,t,0,"no url here go away",!0),!n))return null;const o=await Eo().parseSync(e,n,null,0);return o?.scene??null}const s=new zd;return zg(s,e),new Promise((r,n)=>{const o=this.avatarRegistryUrl+"/"+t;s.load(o,async a=>{await Eo().createBuiltinComponents(e,o,a,null,void 0),r(a.scene)},a=>{nm&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),r(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let s=t;s.children.length==1&&(s=e.children[0]);let r=this.findAvatarPart(s,["head"]);const n=this.findAvatarPart(s,["left","hand"]),o=this.findAvatarPart(s,["right","hand"]);if(!r){r=t;const a=new S;new or().setFromObject(r).getSize(a);const l=Math.max(a.x,a.y,a.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+l+" meters! Should be < 0.3m"),l>.3&&r.scale.multiplyScalar(1/l*.3)}return new ub(t,r,n,o)}findAvatarPart(e,t){const s=e.name.toLowerCase();let r=!0;for(const n of t){if(!r)break;s.indexOf(n)===-1&&(r=!1)}if(r)return e;if(e.children)for(const n of e.children){const o=this.findAvatarPart(n,t);if(o)return o}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}const up=re("debugflags");var ls=(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))(ls||{});const C3=class{constructor(){h(this,"Mask",17)}Has(i){return(this.Mask&i)!==0}Set(i){up&&console.warn("Set XR flag state to",i),this.Mask=i,Lr.Apply()}Enable(i){this.Mask|=i,Lr.Apply()}Disable(i){this.Mask&=~i,Lr.Apply()}Toggle(i){this.Mask^=i,Lr.Apply()}EnableAll(){this.Mask=-1,Lr.Apply()}DisableAll(){this.Mask=0,Lr.Apply()}};let aa=C3;h(aa,"Global",new C3);const Al=class extends Ee{constructor(){super(...arguments),h(this,"visibleIn")}static Apply(){for(const i of this.registry)i.UpdateVisible(aa.Global)}awake(){Al.registry.push(this)}onEnable(){Al.firstApply?this.UpdateVisible(aa.Global):(Al.firstApply=!0,Al.Apply())}onDestroy(){const i=Al.registry.indexOf(this);i>=0&&Al.registry.splice(i,1)}get isOn(){return this.gameObject.visible}UpdateVisible(i=null){let e;const t=i;t&&typeof t=="number"&&(console.assert(typeof t=="number","XRFlag.UpdateVisible: state must be a number",t),up&&console.log(t),Al.buffer.Mask=t,i=Al.buffer);const s=i;if(s?(up&&console.warn(this.name,"use passed in mask",s.Mask,this.visibleIn),e=s.Has(this.visibleIn)):(up&&console.log(this.name,"use global mask"),aa.Global.Has(this.visibleIn)),e!==void 0)if(e)up&&console.log(this.name,"is visible",this.gameObject.uuid),$.setActive(this.gameObject,!0);else{if(up&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}};let Lr=Al;h(Lr,"registry",[]),h(Lr,"firstApply"),h(Lr,"buffer",new aa);const Nc=re("debugavatar"),la=class extends Ee{constructor(){super(...arguments),h(this,"connectionId"),h(this,"avatar")}static getAvatar(i){return i>=0&&i<la.instances.length?la.instances[i]:null}static onAvatarMarkerCreated(i){return la._onNewAvatarMarkerAdded.push(i),i}static onAvatarMarkerDestroyed(i){return la._onAvatarMarkerDestroyed.push(i),i}awake(){la.instances.push(this),Nc&&console.log(this);for(const i of la._onNewAvatarMarkerAdded)i({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){la.instances.splice(la.instances.indexOf(this),1);for(const i of la._onAvatarMarkerDestroyed)i({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}setVisible(i){this.avatar&&("setVisible"in this.avatar?this.avatar.setVisible(i):$.setActive(this.avatar,i))}};let fr=la;h(fr,"instances",[]),h(fr,"_onNewAvatarMarkerAdded",[]),h(fr,"_onAvatarMarkerDestroyed",[]);const pb=class{constructor(i,e,t){h(this,"_isVisible",!0),h(this,"guid"),h(this,"root",null),h(this,"head",null),h(this,"handLeft",null),h(this,"handRight",null),h(this,"lastUpdate",-1),h(this,"isLocalAvatar",!1),h(this,"flags",null),h(this,"headScale",new S(1,1,1)),h(this,"handLeftScale",new S(1,1,1)),h(this,"handRightScale",new S(1,1,1)),h(this,"webxr"),h(this,"lastAvatarId",null),h(this,"hasAvatarOverride",!1),h(this,"context"),h(this,"avatarMarker",null),h(this,"_headTarget",new Me),h(this,"_handLeftTarget",new Me),h(this,"_handRightTarget",new Me),h(this,"_canInterpolate",!1),this.context=i,this.guid=e,this.webxr=t,this.setupCustomAvatar(this.webxr.defaultAvatar)}setVisible(i){this._isVisible=i,this.updateVisibility()}get isWebXRAvatar(){return!0}updateFlags(){if(!this.flags)return;let i=this.isLocalAvatar?ls.FirstPerson:ls.ThirdPerson;this.context.isInVR?i|=ls.VR:this.context.isInAR?i|=ls.AR:i|=ls.Browser;for(const e of this.flags)e.gameObject.visible=!0,e.UpdateVisible(i)}async setAvatarOverride(i){return this.hasAvatarOverride=i!==null,this.hasAvatarOverride&&this.lastAvatarId!==i&&(this.lastAvatarId=i,i!=null&&i.length>0)?await this.setupCustomAvatar(i):null}tryUpdate(i,e){if(i.guid===this.guid&&(this.lastAvatarId!==i.avatarId&&i.avatarId&&i.avatarId.length>0&&(this.lastAvatarId=i.avatarId,this.setupCustomAvatar(i.avatarId)),this.lastUpdate=i.time,this.head)){const t=this.webxr.IsInAR?$o.Handheld:$o.Headset;let s=this.head;this.context.players.setPlayerView(i.guid,s,t),on.markDirty(this.head),this._canInterpolate=!0;const r=this.isLocalAvatar?this.head:this._headTarget;if(r.position.set(i.position.x,i.position.y,i.position.z),r.quaternion.set(i.rotation.x,i.rotation.y,i.rotation.z,i.rotation.w),r.scale.set(i.scale,i.scale,i.scale),r.scale.multiply(this.headScale),this.handLeft){const n=this.isLocalAvatar?this.handLeft:this._handLeftTarget;n.position.set(i.posLeftHand.x,i.posLeftHand.y,i.posLeftHand.z),n.quaternion.set(i.rotLeftHand._x,i.rotLeftHand._y,i.rotLeftHand._z,i.rotLeftHand._w),n.quaternion.multiply(pb.invertRotation),n.scale.set(i.scale,i.scale,i.scale),n.scale.multiply(this.handLeftScale),on.markDirty(this.handLeft)}if(this.handRight){const n=this.isLocalAvatar?this.handRight:this._handRightTarget;n.position.set(i.posRightHand.x,i.posRightHand.y,i.posRightHand.z),n.quaternion.set(i.rotRightHand._x,i.rotRightHand._y,i.rotRightHand._z,i.rotRightHand._w),n.quaternion.multiply(pb.invertRotation),n.scale.set(i.scale,i.scale,i.scale),n.scale.multiply(this.handRightScale),on.markDirty(this.handRight)}}}update(){if(this.isLocalAvatar||!this._canInterpolate)return;const i=this.context.time.deltaTime/.1;this.head&&(this.head.position.lerp(this._headTarget.position,i),this.head.quaternion.slerp(this._headTarget.quaternion,i),this.head.scale.lerp(this._headTarget.scale,i)),this.handLeft&&this._handLeftTarget&&(this.handLeft.position.lerp(this._handLeftTarget.position,i),this.handLeft.quaternion.slerp(this._handLeftTarget.quaternion,i),this.handLeft.scale.lerp(this._handLeftTarget.scale,i)),this.handRight&&this._handRightTarget&&(this.handRight.position.lerp(this._handRightTarget.position,i),this.handRight.quaternion.slerp(this._handRightTarget.quaternion,i),this.handRight.scale.lerp(this._handRightTarget.scale,i))}destroy(){var i,e;Nc&&console.log("Destroy avatar",this.guid),(i=this.root)==null||i.removeFromParent(),(e=this.avatarMarker)==null||e.destroy(),this.lastAvatarId=null,this.head&&Fr.Remove(this.context,this.head)}updateVisibility(){const i=this.root;i&&$.setActive(i,this._isVisible)}async setupCustomAvatar(i){var e,t,s;if(Nc&&console.log("LOAD",i,this),!i||typeof i=="string"&&i.length<=0)return!1;this.head&&Fr.Remove(this.context,this.head);const r=i;if(r?.loadAssetAsync!==void 0){await r.loadAssetAsync();const o=r.asset;$.setActive(o,!1),i=$.instantiate(o),$.setActive(i,!0)}Nc&&console.log(i);const n=await pb.loader.getOrCreateNewAvatarInstance(this.context,i);if(Nc&&console.log(n,n?.isValid,this.lastAvatarId,i),n!=null&&n.isValid){if(this.root=n.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=$.addNewComponent(this.root,fr),this.avatarMarker.connectionId=this.guid,this.avatarMarker.avatar=this,this.head&&this.head!==n.head&&((e=this.head)==null||e.removeFromParent()),this.head=n.head,this.headScale.copy(this.head.scale),this.head&&!this.isLocalAvatar&&Fr.Add(this.context,this.head,this.avatarMarker),n.leftHand&&((t=this.handLeft)==null||t.removeFromParent()),this.handLeft=n.leftHand??this.handLeft,this.handLeft?this.handLeftScale.copy(this.handLeft.scale):this.handLeftScale.set(1,1,1),n.rigthHand&&((s=this.handRight)==null||s.removeFromParent()),this.handRight=n.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(...$.getComponentsInChildren(this.root,Lr)),this.flags.length<=0&&this.head){const o=$.addNewComponent(this.head,Lr);o.visibleIn=ls.ThirdPerson|ls.VR,this.flags.push(o),Nc&&console.log("Added flag to head: "+o.visibleIn,this.head.name)}return Nc&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return Nc&&console.warn("build avatar failed"),!1}};let zc=pb;h(zc,"loader",new db),h(zc,"invertRotation",new Ce().setFromAxisAngle(new S(0,1,0),Math.PI));class Fr{static Add(e,t,s=null){if(t){for(const r of this.Pois)if(r.obj===t)return;this.Pois.push({obj:t,avatar:s}),this.LastChangeTime=e.time.time}}static Remove(e,t){var s;if(t){for(const r of this.Pois)if(r.obj===t){this.Pois.splice(this.Pois.indexOf(r),1),this.LastChangeTime=e?.time.time??((s=Lt.Current)==null?void 0:s.time.time);return}}}}h(Fr,"Pois",[]),h(Fr,"LastChangeTime",0);class DK{constructor(){h(this,"guid"),h(this,"position",new S)}}class om extends Ee{constructor(){super(...arguments),h(this,"target",null),h(this,"avatar",null),h(this,"_model",null),h(this,"_targetModel",new DK),h(this,"_currentTargetObject",null),h(this,"_lastUpdateTime",0),h(this,"_lookDuration",0),h(this,"_lastPoiChangedTime",0)}set controlledTarget(e){this.target=e;const t=j.get("MoveRandom");if(t&&this.target){const s=$.getComponent(this.target,t);s&&s.destroy()}}awake(){if(this.avatar=$.getComponentInParent(this.gameObject,fr),this.avatar){const e=$.getComponentInParent(this.gameObject,fr);this._model=new ny(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)&&Ki(this.target,e.position)})}update(){var e;if((!this.context.connection.isConnected||(e=this._model)!=null&&e.hasOwnership)&&(Fr.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Fr.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const t=xt(this._currentTargetObject);Ki(this.target,t),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(t))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const e=Fr.Pois;if(e.length>0){const t=e[Math.floor(Math.random()*e.length)];if(t&&t.obj){if(t.avatar&&t.avatar===this.avatar)return;this._currentTargetObject=t.obj}}}}}class dp extends Ee{constructor(){super(...arguments),h(this,"canGrab",!0)}onPointerClick(e){}}class pp extends Ee{constructor(){super(...arguments),h(this,"isUsed",!0),h(this,"usedBy",null)}}var ca=(i=>(i[i.Average=0]="Average",i[i.Multiply=1]="Multiply",i[i.Minimum=2]="Minimum",i[i.Maximum=3]="Maximum",i))(ca||{}),fb=(i=>(i[i.Discrete=0]="Discrete",i[i.Continuous=1]="Continuous",i))(fb||{}),$i=(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))($i||{}),fp=(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))(fp||{});const vn=function(i,e){return function(t,s,r){OK(t,s,r,i,e)}};function OK(i,e,t,s,r){if(!(!r&&!s&&!i.onValidate)){if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",i,e,t),rs("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,fo.Error);return}if(i.__internalAwake){const n=Symbol(e),o=i.__internalAwake;i.__internalAwake=function(){this[n]===void 0&&(this[n]=this[e],Object.defineProperty(this,e,{set:function(a){var l;if(this[N1]===!0)this[n]=a;else{s?.call(this,a);const c=this[n];this[n]=a,(l=this.onValidate)==null||l.call(this,e,c)}},get:function(){return r?.call(this),this[n]}})),o.call(this)}}}}const LK=function(i){return function(e,t,s){const r=i.prototype,n=Object.getOwnPropertyDescriptor(r,t);if(!(n!=null&&n.value)){console.warn("Can not apply prefix: type does not have method named",t,i);return}const o=n.value,a=e[t];Object.defineProperty(r,t,{value:function(...l){const c=a?.call(this,...l);if(c instanceof Promise){c.then(u=>{if(u!==!1)return o.call(this,...l)});return}if(c!==!1)return o.call(this,...l)}})}};var FK=Object.defineProperty,UK=Object.getOwnPropertyDescriptor,yl=(i,e,t,s)=>{for(var r=s>1?void 0:s?UK(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&FK(e,t,r),r};class NK{constructor(e,t){h(this,"positionChanged",!1),h(this,"rotationChanged",!1),h(this,"position"),h(this,"quaternion"),h(this,"_positionKeys",["x","y","z"]),h(this,"_quaternionKeys",["_x","_y","_z","_w"]),h(this,"mute",!1),h(this,"context"),h(this,"obj"),h(this,"_positionWatch"),h(this,"_rotationWatch"),this.context=t,this.obj=e}get isDirty(){return this.positionChanged||this.rotationChanged}reset(e=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,e){if(this.position)for(const t of this._positionKeys)delete this.position[t];if(this.quaternion)for(const t of this._quaternionKeys)delete this.quaternion[t]}}syncValues(){for(const e of this._positionKeys)this.position[e]=this.obj.position[e];for(const e of this._quaternionKeys)this.quaternion[e]=this.obj.quaternion[e]}applyValues(){if(this.positionChanged&&this.position)for(const e of this._positionKeys){const t=this.position[e];t!==void 0&&(this.obj.position[e]=t)}if(this.rotationChanged&&this.quaternion)for(const e of this._quaternionKeys){const t=this.quaternion[e];t!==void 0&&(this.obj.quaternion[e]=t)}}start(e,t){this.reset(),e&&(this._positionWatch||(this._positionWatch=new hf(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((n,o)=>{var a;if((a=this.context.physics.engine)!=null&&a.isUpdating||this.mute)return;const l=this.position[o];Math.abs(l-n)<1e-5||(this.position[o]=n,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new hf(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((n,o)=>{var a;if((a=this.context.physics.engine)!=null&&a.isUpdating||this.mute)return;const l=this.quaternion[o];Math.abs(l-n)<1e-5||(this.quaternion[o]=n,this.rotationChanged=!0)}));const s=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),r=new Pe;this.obj.matrixWorld.multiplyMatrices=(n,o)=>(r.equals(n)||(this.positionChanged=!0,this.rotationChanged=!0,r.copy(n)),s(n,o))}stop(){var e,t;(e=this._positionWatch)==null||e.revoke(),(t=this._rotationWatch)==null||t.revoke()}}var eE;const tE=(eE=class extends Ee{constructor(){super(...arguments),h(this,"mass",1),h(this,"useGravity",!0),h(this,"constraints",$i.None),h(this,"isKinematic",!1),h(this,"drag",0),h(this,"angularDrag",1),h(this,"detectCollisions",!0),h(this,"sleepThreshold",.01),h(this,"collisionDetectionMode",fb.Discrete),h(this,"_gravityScale",1),h(this,"_propertiesChanged",!1),h(this,"_currentVelocity",new S),h(this,"_smoothedVelocity",new S),h(this,"_smoothedVelocityGetter",new S),h(this,"_lastPosition",new S),h(this,"_watch")}get lockPositionX(){return(this.constraints&$i.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&$i.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&$i.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&$i.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&$i.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&$i.FreezeRotationZ)!==0}set lockPositionX(i){i?this.constraints|=$i.FreezePositionX:this.constraints&=~$i.FreezePositionX}set lockPositionY(i){i?this.constraints|=$i.FreezePositionY:this.constraints&=~$i.FreezePositionY}set lockPositionZ(i){i?this.constraints|=$i.FreezePositionZ:this.constraints&=~$i.FreezePositionZ}set lockRotationX(i){i?this.constraints|=$i.FreezeRotationX:this.constraints&=~$i.FreezeRotationX}set lockRotationY(i){i?this.constraints|=$i.FreezeRotationY:this.constraints&=~$i.FreezeRotationY}set lockRotationZ(i){i?this.constraints|=$i.FreezeRotationZ:this.constraints&=~$i.FreezeRotationZ}set gravityScale(i){this._gravityScale=i}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new NK(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),mn.LateUpdate)}onDisable(){var i,e;(i=this._watch)==null||i.stop(),(e=this.context.physics.engine)==null||e.removeBody(this)}onDestroy(){var i;(i=this.context.physics.engine)==null||i.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(var i,e,t,s;;)this._propertiesChanged&&(this._propertiesChanged=!1,(i=this.context.physics.engine)==null||i.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()):(s=this._watch)==null||s.syncValues(),this.captureVelocity(),yield}teleport(i,e=!0){var t;(t=this._watch)==null||t.reset(!0),e?this.gameObject.position.set(i.x,i.y,i.z):this.setWorldPosition(i.x,i.y,i.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(){var i;(i=this.context.physics.engine)==null||i.resetForces(this,!0)}resetTorques(){var i;(i=this.context.physics.engine)==null||i.resetTorques(this,!0)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var i;(i=this.context.physics.engine)==null||i.wakeup(this)}applyForce(i,e){var t;(t=this.context.physics.engine)==null||t.addForce(this,i,!0)}applyImpulse(i){var e;(e=this.context.physics.engine)==null||e.applyImpulse(this,i,!0)}setForce(i,e,t){var s,r;(s=this.context.physics.engine)==null||s.resetForces(this,!0),(r=this.context.physics.engine)==null||r.addForce(this,{x:i,y:e,z:t},!0)}getVelocity(){var i;const e=(i=this.context.physics.engine)==null?void 0:i.getLinearVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(i,e,t){var s,r;if(i instanceof S){const n=i;(s=this.context.physics.engine)==null||s.setLinearVelocity(this,n,!0);return}e===void 0||t===void 0||(r=this.context.physics.engine)==null||r.setLinearVelocity(this,{x:i,y:e,z:t},!0)}setAngularVelocity(i,e,t){var s,r;if(i instanceof S){const n=i;(s=this.context.physics.engine)==null||s.setAngularVelocity(this,n,!0);return}e===void 0||t===void 0||(r=this.context.physics.engine)==null||r.setAngularVelocity(this,{x:i,y:e,z:t},!0)}getAngularVelocity(){var i;const e=(i=this.context.physics.engine)==null?void 0:i.getAngularVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setTorque(i,e,t){this.setAngularVelocity(i,e,t)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(i=null){}captureVelocity(){const i=xt(this.gameObject);tE.tempPosition.copy(i);const e=i.sub(this._lastPosition);this._lastPosition.copy(tE.tempPosition),this._smoothedVelocity.lerp(e,this.context.time.deltaTime/.1)}},h(eE,"tempPosition",new S),eE);let Ni=tE;yl([vn(),w()],Ni.prototype,"mass",2),yl([vn(),w()],Ni.prototype,"useGravity",2),yl([vn(),w()],Ni.prototype,"constraints",2),yl([vn(),w()],Ni.prototype,"isKinematic",2),yl([vn(),w()],Ni.prototype,"drag",2),yl([vn(),w()],Ni.prototype,"angularDrag",2),yl([vn(),w()],Ni.prototype,"detectCollisions",2),yl([vn(),w()],Ni.prototype,"sleepThreshold",2),yl([vn(),w()],Ni.prototype,"collisionDetectionMode",2);class An{constructor(){h(this,"bb",null),h(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(e,t,s,r){return e.prep(4,12),e.writeFloat32(r),e.writeFloat32(s),e.writeFloat32(t),e.offset()}}class S3{constructor(){h(this,"bb",null),h(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new An).__init(this.bb_pos,this.bb)}rotation(e){return(e||new An).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new An).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,s,r,n,o,a,l,c,u){return e.prep(4,36),e.prep(4,12),e.writeFloat32(u),e.writeFloat32(c),e.writeFloat32(l),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(o),e.writeFloat32(n),e.prep(4,12),e.writeFloat32(r),e.writeFloat32(s),e.writeFloat32(t),e.offset()}}class Hl{constructor(){h(this,"bb",null),h(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new Hl).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+W0),(t||new Hl).__init(e.readInt32(e.position())+e.position(),e)}guid(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){const e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){const t=this.bb.__offset(this.bb_pos,8);return t?(e||new S3).__init(this.bb_pos+t,this.bb):null}dontSave(){const e=this.bb.__offset(this.bb_pos,10);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startSyncedTransformModel(e){e.startObject(4)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addFast(e,t){e.addFieldInt8(1,+t,0)}static addTransform(e,t){e.addFieldStruct(2,t,0)}static addDontSave(e,t){e.addFieldInt8(3,+t,0)}static endSyncedTransformModel(e){return e.endObject()}static finishSyncedTransformModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedTransformModelBuffer(e,t){e.finish(t,void 0,!0)}}const Qc=re("debugsync"),am="STRS";q1(am,Hl.getRootAsSyncedTransformModel);const ha=new gf;function E3(i,e,t=!0){ha.clear();const s=ha.createString(i);Hl.startSyncedTransformModel(ha),Hl.addGuid(ha,s),Hl.addFast(ha,t);const r=e.worldPosition,n=e.worldEuler,o=e.gameObject.scale;Hl.addTransform(ha,S3.createTransform(ha,r.x,r.y,r.z,n.x,n.y,n.z,o.x,o.y,o.z));const a=Hl.endSyncedTransformModel(ha);return ha.finish(a,am),ha.asUint8Array()}class jc extends Ee{constructor(){super(...arguments),h(this,"overridePhysics",!0),h(this,"interpolatePosition",!0),h(this,"interpolateRotation",!0),h(this,"fastMode",!1),h(this,"syncDestroy",!1),h(this,"_model",null),h(this,"_needsUpdate",!0),h(this,"rb",null),h(this,"_wasKinematic",!1),h(this,"_receivedDataBefore",!1),h(this,"_targetPosition"),h(this,"_targetRotation"),h(this,"_receivedFastUpdate",!1),h(this,"_shouldRequestOwnership",!1),h(this,"joinedRoomCallback",null),h(this,"receivedDataCallback",null),h(this,"tempEuler",new vs),h(this,"receivedUpdate",!1),h(this,"lastWorldPos"),h(this,"lastWorldRotation")}requestOwnership(){Qc&&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(){Qc&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new S,this._targetRotation=new Ce,this.lastWorldPos=new S,this.lastWorldRotation=new Ce,this.rb=$.getComponentInChildren(this.gameObject,Ni),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new ny(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(ji.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(am,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Tk(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(ji.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(am,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){Qc&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();const s=e.transform();if(s){on.markDirty(this.gameObject,!0);const r=s.position();r&&(this.interpolatePosition&&((t=this._targetPosition)==null||t.set(r.x(),r.y(),r.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(r.x(),r.y(),r.z()));const n=s.rotation();n&&(this.tempEuler.set(n.x(),n.y(),n.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&VB(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){Qc&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());let e=this.worldPosition,t=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const n=e.distanceTo(this.lastWorldPos),o=t.angleTo(this.lastWorldRotation),a=this._model.hasOwnership||this.fastMode?1e-4:.001;(n>a||o>a)&&(this._model.hasOwnership?this._needsUpdate=!0:(Qc&&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),on.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const n=this._receivedFastUpdate||this.fastMode?.5:.3;let o=!1;if(this.interpolatePosition&&this._targetPosition){const a=this.worldPosition;a.lerp(this._targetPosition,n),this.worldPosition=a,o=!0}if(this.interpolateRotation&&this._targetRotation){const a=this.worldQuaternion;a.slerp(this._targetRotation,n),this.worldQuaternion=a,o=!0}o&&on.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&&(Qc&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new S(0,0,0))>1e3&&(Qc&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0)));const s=10,r=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%s===0||r)){Qc&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this.overridePhysics&&this.rb,this._needsUpdate=!1;const n=E3(this.guid,this,!!r);this.context.connection.sendBinary(n)}}}var Bo={};Bo.d=(i,e)=>{for(var t in e)Bo.o(e,t)&&!Bo.o(i,t)&&Object.defineProperty(i,t,{enumerable:!0,get:e[t]})},Bo.o=(i,e)=>Object.prototype.hasOwnProperty.call(i,e),Bo.r=i=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(i,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(i,"__esModule",{value:!0})};var cs={};Bo.d(cs,{w8:()=>ci,cg:()=>iU,gO:()=>Yv,wb:()=>iE,zV:()=>ru,HS:()=>lm,Ec:()=>su,gF:()=>vf,ol:()=>Jv,pz:()=>j3,tx:()=>po,hj:()=>sE,FV:()=>mm,sV:()=>DF,xv:()=>Kv,mx:()=>N3,gE:()=>z3,ZP:()=>Iee,Vx:()=>sU});var iE={};Bo.r(iE),Bo.d(iE,{get:()=>M3,set:()=>zK});var sE={};Bo.r(sE),Bo.d(sE,{alphaTestTransformer:()=>yb,asPreprocessorValueTransformer:()=>G3,toPreprocessorTriggerTransformer:()=>mE,toUserDataTransformer:()=>KJ,uniformOrUserDataTransformer:()=>$n});const rE={fontFamily:null,fontSize:.05,fontKerning:"normal",fontStyle:"normal",fontWeight:"400",offset:.005,lineHeight:1.2,lineBreak:`- ,.:?!
4179
+ `}function o3(i){return`(${i.r}, ${i.g}, ${i.b})`}function a3(i){return`(${i.x}, ${i.y})`}const l3=class{constructor(i,e,t){h(this,"id"),h(this,"trigger"),h(this,"action"),h(this,"exclusive",!1),this.id="Behavior_"+zS(i)+"_"+l3.global_id++,this.trigger=e,this.action=t}makeExclusive(i){return this.exclusive=i,this}writeTo(i,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 s="";if(Array.isArray(this.trigger)){s="[";for(let r=0;r<this.trigger.length;r++){const n=this.trigger[r];s+="<"+n.id+">",r+1<this.trigger.length&&(s+=", ")}s+="]"}else s=`<${this.trigger.id}>`;if(t.appendLine(`rel triggers = ${s} `),t.appendLine(),Array.isArray(this.trigger))for(const r of this.trigger)r.writeTo(e,t),t.appendLine();else this.trigger.writeTo(e,t);t.appendLine(),this.action.writeTo(e,t),t.closeBlock()}};let Dr=l3;h(Dr,"global_id",0);function QS(i,e){var t,s;let r="";if(Array.isArray(i)){let n="[ ";for(let o=0;o<i.length;o++){let a=i[o];if(typeof a=="string")n+=a;else if(typeof a=="object"){a.isObject3D&&(a=e.findById(a.uuid));const l=(t=a.getPath)==null?void 0:t.call(a);n+=l}o+1<i.length&&(n+=", ")}n+=" ]",r=n}else typeof i=="object"&&(i.isObject3D&&(i=e.findById(i.uuid)),r=(s=i.getPath)==null?void 0:s.call(i));return r=r.replace(e.name,e.name+"/Scenes/Scene"),r}const c3=class{constructor(i,e){h(this,"id"),h(this,"targetId"),h(this,"tokenId"),h(this,"type"),h(this,"distance"),i&&(this.targetId=i),e?this.id=e:this.id="Trigger_"+c3.global_id++}writeTo(i,e){e.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=QS(this.targetId,i)),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 tu=c3;h(tu,"global_id",0);class Zr{static sceneStartTrigger(){const e=new tu;return e.targetId=void 0,e.tokenId="SceneTransition",e.type="enter",e}static tapTrigger(e){const t=new tu(e);return t.tokenId="TapGesture",t}static isTapTrigger(e){return e?.tokenId==="TapGesture"}static proximityToCameraTrigger(e,t){const s=new tu(e);return s.tokenId="ProximityToCamera",s.distance=t,s}}class Bc{constructor(e,t){h(this,"id"),h(this,"actions"),h(this,"loops",0),h(this,"performCount",1),h(this,"type","serial"),this.id=e,this.actions=t}static getId(){return this.global_id++}addAction(e){return this.actions.push(e),this}makeParallel(){return this.type="parallel",this}makeSequence(){return this.type="serial",this}makeLooping(){return this.loops=1,this}makeRepeat(e){return this.performCount=e,this}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),t.beginArray("rel actions");for(const s of this.actions)s&&t.appendLine("<"+s.id+">,");t.closeArray(),t.appendLine(),t.appendLine('token info:id = "Group"'),t.appendLine(`bool loops = ${this.loops} `),t.appendLine(`int performCount = ${this.performCount} `),t.appendLine(`token type = "${this.type}"`),t.appendLine();for(const s of this.actions)s&&(s.writeTo(e,t),t.appendLine());t.closeBlock()}}h(Bc,"global_id",0);var jS=(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))(jS||{}),GS=(i=>(i.Relative="relative",i.Absolute="absolute",i))(GS||{});const HS=class{constructor(i,e){h(this,"id"),h(this,"tokenId"),h(this,"affectedObjects"),h(this,"easeType"),h(this,"motionType"),h(this,"duration"),h(this,"moveDistance"),h(this,"style"),h(this,"type"),h(this,"front"),h(this,"up"),h(this,"start"),h(this,"animationSpeed"),h(this,"reversed"),h(this,"pingPong"),h(this,"xFormTarget"),h(this,"audio"),h(this,"gain"),h(this,"auralMode"),h(this,"multiplePerformOperation"),i&&(this.affectedObjects=i),e?this.id=e:this.id="Action",this.id+="_"+HS.global_id++}clone(){const i=new HS,e=i.id;return Object.assign(i,this),i.id=e,i}writeTo(i,e){e.beginBlock(`def Preliminary_Action "${this.id}"`),this.affectedObjects&&(typeof this.affectedObjects!="string"&&(this.affectedObjects=QS(this.affectedObjects,i)),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=QS(this.xFormTarget,i)),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 Po=HS;h(Po,"global_id",0);let lp=class cf{constructor(e,t,s){h(this,"x",0),h(this,"y",0),h(this,"z",0),this.x=e,this.y=t,this.z=s}static get up(){return new cf(0,1,0)}static get right(){return new cf(1,0,0)}static get forward(){return new cf(0,0,1)}static get back(){return new cf(0,0,-1)}static get zero(){return new cf(0,0,0)}};var h3=(i=>(i.Play="play",i.Pause="pause",i.Stop="stop",i))(h3||{}),VS=(i=>(i.Spatial="spatial",i.NonSpatial="nonSpatial",i.Ambient="ambient",i))(VS||{});class ni{static sequence(...e){return new Bc("group_"+Bc.getId(),e).makeSequence()}static parallel(...e){return new Bc("group_"+Bc.getId(),e).makeParallel()}static fadeAction(e,t,s){const r=new Po(e);return r.tokenId="Visibility",r.type=s?"show":"hide",r.duration=t,r.style="basic",r.motionType="none",r.moveDistance=0,r.easeType="none",r}static startAnimationAction(e,t,s=0,r=1,n=!1,o=!1){const a=new Po(e);if(a.tokenId="StartAnimation",a.start=t,a.duration=s,a.animationSpeed=r,a.reversed=n,a.pingPong=o,n&&(a.start-=s),o){a.pingPong=!1;const l=a.clone();return l.reversed=!n,l.start=a.start,l.reversed&&(l.start-=s),ni.sequence(a,l)}return a}static waitAction(e){const t=new Po;return t.tokenId="Wait",t.duration=e,t}static lookAtCameraAction(e,t=9999999999999,s,r){const n=new Po(e);return n.tokenId="LookAtCamera",n.duration=t,n.front=s??lp.forward,n.up=r??lp.up,n}static emphasize(e,t,s=2,r=1,n="basic"){const o=new Po(e);return o.tokenId="Emphasize",o.duration=t,o.style=n??"basic",o.motionType=jS[s],o.moveDistance=r,o}static transformAction(e,t,s,r,n="inout"){const o=new Po(e);return o.tokenId="Transform",o.duration=s,o.type=r,o.easeType=n,Array.isArray(t)&&console.error("Transform target must not be an array",t),o.xFormTarget=t,o}static playAudioAction(e,t,s="play",r=1,n="spatial"){const o=new Po(e);return o.tokenId="Audio",o.type=s,o.audio=t,o.gain=r,o.auralMode=n,o.multiplePerformOperation="allow",o}}class FY{constructor(e){h(this,"object"),h(this,"model"),this.object=e}get id(){return this.object.uuid}apply(e){if(!this.model&&(this.model=e.findById(this.object.uuid),!this.model)){console.error("could not find model with id "+this.object.uuid);return}this.onApply(e)}}class WS extends FY{constructor(e,t,s,r){super(e),h(this,"matrix"),h(this,"material"),h(this,"geometry"),h(this,"_enableAction"),h(this,"_disableAction"),this.matrix=t,this.material=s,this.geometry=r}onApply(e){var t,s;const r=this.model;if(!r)return;(t=r.parent)!=null&&t.isDynamic||na.createEmptyParent(r);const n=r.clone();this.matrix&&(n.matrix=this.matrix),this.material&&(n.material=this.material),this.geometry&&(n.geometry=this.geometry),(s=r.parent)==null||s.add(n)}enable(){return this._enableAction?this._enableAction:(this._enableAction=ni.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=ni.fadeAction(this.object,0,!1),this._disableAction)}}class qS{constructor(e){h(this,"actions"),h(this,"sortedActions"),this.actions=[...e]}organize(){this.sortedActions={};for(const e of this.actions){const t=e.id;this.sortedActions[t]||(this.sortedActions[t]=[]),this.sortedActions[t].push(e)}}getActions(e){return this.sortedActions||this.organize(),this.sortedActions[e.uuid]}}var UY=Object.defineProperty,NY=Object.getOwnPropertyDescriptor,u3=(i,e,t,s)=>{for(var r=s>1?void 0:s?NY(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&UY(e,t,r),r};class em extends Ee{constructor(){super(...arguments),h(this,"from"),h(this,"to"),h(this,"width",0),h(this,"centered",!0),h(this,"_centerPos")}awake(){this._centerPos=new S}update(){if(!this.from||!this.to)return;const e=xt(this.from).clone(),t=xt(this.to).clone(),s=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),Ki(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(xt(this.to).clone()),this.gameObject.scale.set(this.width,this.width,s)}}u3([w($)],em.prototype,"from",2),u3([w($)],em.prototype,"to",2);var zY=Object.defineProperty,QY=Object.getOwnPropertyDescriptor,tm=(i,e,t,s)=>{for(var r=s>1?void 0:s?QY(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&zY(e,t,r),r};const kc=re("debuganimation");class Jn extends Ee{constructor(){super(...arguments),h(this,"playAutomatically",!0),h(this,"randomStartTime",!0),h(this,"minMaxSpeed"),h(this,"minMaxOffsetNormalized"),h(this,"loop",!0),h(this,"clampWhenFinished",!1),h(this,"_tempAnimationClipBeforeGameObjectExisted",null),h(this,"mixer"),h(this,"_actions",[]),h(this,"_currentActions",[]),h(this,"_handles",[]),h(this,"_didInit",!1)}get clip(){var e;return(e=this.animations)!=null&&e.length?this.animations[0]:null}set clip(e){if(!this.__didAwake){kc&&console.log("Assign clip during serialization",e),this._tempAnimationClipBeforeGameObjectExisted=e;return}e&&(kc&&console.log("Assign clip",e,!!this.gameObject),this.gameObject.animations||(this.gameObject.animations=[]),!this.animations.includes(e)&&(this.animations.length>0?this.animations.splice(0,0,e):this.animations.push(e)))}set clips(e){this.animations=e}set animations(e){kc&&console.log("assign animations",e),this.gameObject.animations=e}get animations(){return this.gameObject.animations}get currentAction(){return this._currentActions[0]}get currentActions(){return this._currentActions}get actions(){return this._actions}set actions(e){this._actions=e}awake(){kc&&console.log(this),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(s=>s.getClip().name===e)}get isPlaying(){for(let e=0;e<this._currentActions.length;e++)if(this._currentActions[e].isRunning())return!0;return!1}play(e=0,t){if(kc&&console.log("PLAY",e),this.init(),!this.mixer){kc&&console.warn("Missing mixer",this);return}e===void 0&&(e=0);let s=e;if(typeof e=="number"){if(e>=this.animations.length){kc&&console.log("No animation at index",e);return}s=this.animations[e]}else typeof e=="string"&&(s=this.animations.find(n=>n.name===e));if(!s){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 n of this.actions)if(n.getClip()===s)return this.internalOnPlay(n,t);if(!(s instanceof Qn)){console.warn("Clip is no AnimationClip",s,"on object: "+this.name);return}const r=this.mixer.clipAction(s);return this.actions.push(r),this.internalOnPlay(r,t)}internalOnPlay(e,t){var s=this.currentAction;if(s===e&&s.isRunning()&&s.time<s.getClip().duration){const a=this.tryFindHandle(e);if(a)return a.getPromise()}const r=t?.exclusive??!0;t!=null&&t.fadeDuration?(r&&s?.fadeOut(t.fadeDuration),e.fadeIn(t.fadeDuration)):r&&s?.stop(),e.reset(),e.enabled=!0,e.time=0,e.timeScale=1;const n=e.getClip();t!=null&&t.minMaxOffsetNormalized&&(e.time=Je.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*n.duration),t!=null&&t.minMaxSpeed&&(e.timeScale=Je.lerp(t.minMaxSpeed.x,t.minMaxSpeed.y,Math.random())),t!=null&&t.clampWhenFinished&&(e.clampWhenFinished=!0),t?.startTime!==void 0&&(e.time=t.startTime),t?.loop!==void 0?e.loop=t.loop?Zw:Rf:e.loop=Rf,e.play(),kc&&console.log("PLAY",e.getClip().name,e);const o=new jY(e,this.mixer,t,a=>{this._handles.splice(this._handles.indexOf(o),1)});return this._handles.push(o),o.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 x0(this.gameObject)))}}tm([w()],Jn.prototype,"playAutomatically",2),tm([w()],Jn.prototype,"randomStartTime",2),tm([w()],Jn.prototype,"loop",2),tm([w()],Jn.prototype,"clampWhenFinished",2),tm([w(Qn)],Jn.prototype,"clips",1);class jY{constructor(e,t,s,r){h(this,"mixer"),h(this,"action"),h(this,"promise",null),h(this,"resolve",null),h(this,"reject",null),h(this,"_options"),h(this,"_resolveCallback",null),h(this,"_rejectCallback",null),h(this,"_loopCallback"),h(this,"_finishedCallback"),h(this,"_resolvedOrRejectedCallback"),this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=r,this._options=s}getPromise(){return this.promise?this.promise:(this.promise=new Promise((e,t)=>{this._resolveCallback=e,this._rejectCallback=t,this.resolve=this.onResolve.bind(this),this.reject=this.onReject.bind(this)}),this._loopCallback=this.onLoop.bind(this),this._finishedCallback=this.onFinished.bind(this),this.mixer.addEventListener("loop",this._loopCallback),this.mixer.addEventListener("finished",this._finishedCallback),this.promise)}_update(){this._options&&this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){var e,t;this.dispose(),(e=this._resolvedOrRejectedCallback)==null||e.call(this,this),(t=this._resolveCallback)==null||t.call(this,this.action)}onReject(e){var t,s;this.dispose(),(t=this._resolvedOrRejectedCallback)==null||t.call(this,this),(s=this._rejectCallback)==null||s.call(this,e)}onLoop(e){}onFinished(e){e.action===this.action&&this.onResolve()}dispose(){this._loopCallback&&this.mixer.removeEventListener("loop",this._loopCallback),this._finishedCallback&&this.mixer.removeEventListener("finished",this._finishedCallback),this._loopCallback=void 0,this._finishedCallback=void 0}}var GY=Object.defineProperty,HY=Object.getOwnPropertyDescriptor,Dc=(i,e,t,s)=>{for(var r=s>1?void 0:s?HY(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&GY(e,t,r),r};class Oc{constructor(){h(this,"time"),h(this,"value"),h(this,"inTangent"),h(this,"inWeight"),h(this,"outTangent"),h(this,"outWeight"),h(this,"weightedMode")}}Dc([w()],Oc.prototype,"time",2),Dc([w()],Oc.prototype,"value",2),Dc([w()],Oc.prototype,"inTangent",2),Dc([w()],Oc.prototype,"inWeight",2),Dc([w()],Oc.prototype,"outTangent",2),Dc([w()],Oc.prototype,"outWeight",2),Dc([w()],Oc.prototype,"weightedMode",2);const d3=class{constructor(){h(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 e=0;e<this.keys.length;e++){const t=this.keys[e];if(t.time<=i)if(e+1<this.keys.length){const s=this.keys[e+1];if(s.time<i)continue;return!isFinite(t.outTangent)||!isFinite(s.inTangent)?t.value:d3.interpolateValue(i,t,s)}else return t.value}return this.keys[this.keys.length-1].value}static interpolateValue(i,e,t){const s=e.time,r=e.value,n=e.outTangent,o=t.time,a=t.value,l=t.inTangent,c=o-s,u=c*c,d=u*c,p=((n+l)*c-2*(a-r))/d,f=(3*(a-r)-(l+2*n)*c)/u,g=n,m=r,v=i-s,A=v*v,b=A*v;return p*b+f*A+g*v+m}};let iu=d3;Dc([w(Oc)],iu.prototype,"keys",2);const cp=re("debugusdzanimation");class ib{constructor(e,t,s){h(this,"ext"),h(this,"root"),h(this,"clip"),this.ext=e,this.root=t,this.clip=s}get start(){return this.ext.getStartTime01(this.root,this.clip)}get duration(){return this.clip.duration}}class sb{constructor(e,t,s,r){h(this,"clip"),h(this,"pos"),h(this,"rot"),h(this,"scale"),h(this,"ext"),h(this,"root"),h(this,"target"),this.ext=e,this.root=t,this.target=s,this.clip=r}get frameRate(){return 60}addTrack(e){e.name.endsWith("position")&&(this.pos=e),e.name.endsWith("quaternion")&&(this.rot=e),e.name.endsWith("scale")&&(this.scale=e)}getFrames(){var e,t,s,r,n,o;return Math.max(((t=(e=this.pos)==null?void 0:e.times)==null?void 0:t.length)??0,((r=(s=this.rot)==null?void 0:s.times)==null?void 0:r.length)??0,((o=(n=this.scale)==null?void 0:n.times)==null?void 0:o.length)??0)}getDuration(){var e,t,s;const r=((e=this.pos)==null?void 0:e.times)??((t=this.rot)==null?void 0:t.times)??((s=this.scale)==null?void 0:s.times);return r?r[r.length-1]:0}getStartTime(e){let t=0;for(let s=0;s<e.length;s++){const r=e[s];if(r===this)return t;t+=r.getDuration()}return t}}class rb{constructor(){h(this,"dict",new Map),h(this,"rootTargetMap",new Map),h(this,"serializers",[])}get extensionName(){return"animation"}getStartTime01(e,t){const s=this.rootTargetMap.get(e);if(!s)return 1/0;let r=-1;for(const n of s){const o=this.dict.get(n);let a=0;if(o!=null&&o.length){for(const l of o){if(l.clip===t)break;a+=l.getDuration()}r=Math.max(r,a)}else console.warn("No animation found on root",e,t,o)}return r}registerAnimation(e,t){if(!t||!e)return null;this.rootTargetMap.has(e)||this.rootTargetMap.set(e,[]);for(const s of t.tracks){const r=s.name.split(".")[2],n=e.getObjectByName(r);if(!n){console.warn("no object found for track",s.name,"using "+e.name+" instead");continue}this.dict.has(n)||this.dict.set(n,[]);const o=this.dict.get(n);if(!o)continue;let a=o.find(c=>c.clip===t);a||(a=new sb(this,e,n,t),o.push(a)),a.addTrack(s);const l=this.rootTargetMap.get(e);l!=null&&l.includes(n)||l==null||l.push(n)}return new ib(this,e,t)}onAfterHierarchy(e){cp&&console.log(this.dict)}onAfterBuildDocument(e){var t,s;for(const r of this.serializers){const n=(t=r.model)==null?void 0:t.parent,o=n?.isDynamic===!0;cp&&console.log(o,(s=r.model)==null?void 0:s.parent),o&&r.registerCallback(n)}}onExportObject(e,t,s){$.foreachComponent(e,n=>{const o=n;typeof o.createAnimation=="function"&&o.createAnimation(this,t,s)},!1);const r=new VY(e,this.dict);this.serializers.push(r),r.registerCallback(t)}}class VY{constructor(e,t){h(this,"object"),h(this,"dict"),h(this,"model"),h(this,"callback"),this.object=e,this.dict=t}registerCallback(e){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),cp&&console.log("REPARENT",e),this.model=e,this.model.addEventListener("serialize",this.callback)}onSerialize(e,t){var s,r,n,o,a,l;if(!this.model)return;cp&&console.log("SERIALIZE",this.model.name,this.object.type);const c=this.object,u=this.dict.get(c);if(!u)return;const d=new Pe,p=new S,f=new Ce,g=new S(1,1,1);e.appendLine("matrix4d xformOp:transform.timeSamples = {"),e.indent++;for(const m of u){let v=(s=m.pos)==null?void 0:s.times,A=(r=m.rot)==null?void 0:r.times,b=(n=m.scale)==null?void 0:n.times,y=[];if(v)for(const C of v)y.push(C);if(A)for(const C of A)y.push(C);if(b)for(const C of b)y.push(C);if(y.sort((C,R)=>C-R),y=[...new Set(y)],!y||y.length===0){console.error("got an animated object but no time values??",c,m);continue}const x=m.getStartTime(u);cp&&e.appendLine(m.clip.name+": start="+x.toFixed(3)+", length="+m.getDuration().toFixed(3)+", frames="+m.getFrames());const _=(o=m.pos)==null?void 0:o.createInterpolant(),M=(a=m.rot)==null?void 0:a.createInterpolant(),P=(l=m.scale)==null?void 0:l.createInterpolant();_||p.set(c.position.x,c.position.y,c.position.z),M||f.set(c.quaternion.x,c.quaternion.y,c.quaternion.z,c.quaternion.w),P||g.set(c.scale.x,c.scale.y,c.scale.z);for(let C=0;C<y.length;C++){const R=y[C];if(_){const z=_.evaluate(R);p.set(z[0],z[1],z[2])}if(M){const z=M.evaluate(R);f.set(z[0],z[1],z[2],z[3])}if(P){const z=P.evaluate(R);g.set(z[0],z[1],z[2])}d.compose(p,f,g);let T=`${(x+R)*m.frameRate}: ${s3(d)},`;cp&&(T="#"+C+" "+T),e.appendLine(T)}}e.indent--,e.appendLine("}")}}class WY{constructor(){h(this,"_context")}get context(){return this._context??Lt.Current}get isStateMachineBehaviour(){return!0}}class nb{constructor(e,t,s,r){h(this,"_name"),h(this,"_nameHash"),h(this,"_normalizedTime"),h(this,"_length"),h(this,"_speed"),this._name=e.name,this._nameHash=e.hash,this._normalizedTime=t,this._length=s,this._speed=r}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 p3(i,e){return{name:"",isLooping:!1,guid:e?.generateUUID()??Cr.generateUUID(),index:-1,clip:new Qn(i,1,[])}}var Lc=(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))(Lc||{}),XS=(i=>(i[i.Float=1]="Float",i[i.Int=3]="Int",i[i.Bool=4]="Bool",i[i.Trigger=9]="Trigger",i))(XS||{});const oa=re("debuganimatorcontroller"),ob=re("debugrootmotion");class Uu{constructor(e){h(this,"normalizedStartOffset",0),h(this,"_speed",1),h(this,"animator"),h(this,"model"),h(this,"_mixer"),h(this,"_activeState"),h(this,"_activeStates",[]),h(this,"rootMotionHandler"),this.model=e,oa&&console.log(this)}play(e,t=-1,s=Number.NEGATIVE_INFINITY,r=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}const n=this.model.layers[t].stateMachine;for(const o of n.states)if(o.name===e||o.hash===e){oa&&console.log("transition to ",o),this.transitionTo(o,r,s);return}console.warn("Could not find "+e+" to play")}reset(){this.setStartTransition()}setBool(e,t){var s,r;const n=typeof e=="string"?"name":"hash";return(r=(s=this.model)==null?void 0:s.parameters)==null?void 0:r.filter(o=>o[n]===e).forEach(o=>o.value=t)}getBool(e){var t,s,r;const n=typeof e=="string"?"name":"hash";return((r=(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.find(o=>o[n]===e))==null?void 0:r.value)??!1}setFloat(e,t){var s,r;const n=typeof e=="string"?"name":"hash";return(r=(s=this.model)==null?void 0:s.parameters)==null?void 0:r.filter(o=>o[n]===e).forEach(o=>o.value=t)}getFloat(e){var t,s,r;const n=typeof e=="string"?"name":"hash";return((r=(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.find(o=>o[n]===e))==null?void 0:r.value)??0}setInteger(e,t){var s,r;const n=typeof e=="string"?"name":"hash";return(r=(s=this.model)==null?void 0:s.parameters)==null?void 0:r.filter(o=>o[n]===e).forEach(o=>o.value=t)}getInteger(e){var t,s,r;const n=typeof e=="string"?"name":"hash";return((r=(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.find(o=>o[n]===e))==null?void 0:r.value)??0}setTrigger(e){var t,s;oa&&console.log("SET TRIGGER",e);const r=typeof e=="string"?"name":"hash";return(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.filter(n=>n[r]===e).forEach(n=>n.value=!0)}resetTrigger(e){var t,s;const r=typeof e=="string"?"name":"hash";return(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.filter(n=>n[r]===e).forEach(n=>n.value=!1)}isInTransition(){return this._activeStates.length>1}setSpeed(e){this._speed=e}FindState(e){return this.findState(e)}findState(e){if(!e)return null;if(Array.isArray(this.model.layers)){for(const t of this.model.layers)for(const s of t.stateMachine.states)if(s.name===e)return s}return null}get context(){var e;return(e=this.animator)==null?void 0:e.context}bind(e){this.animator=e,this._mixer=new x0(this.animator.gameObject),this.createActions(this.animator)}clone(){if(typeof this.model=="string")return console.warn("AnimatorController has not been resolved, can not create model from string",this.model),null;const e=$v(this.model,(t,s,r)=>r==null?!0:!(r.type==="Object3D"||r.isObject3D===!0||qB(r)||r.tracks!==void 0));return console.assert(e!==this.model),new Uu(e)}update(){var e,t;if(!this.animator||(this.evaluateTransitions(),this.updateActiveStates(),!this._activeState))return;const s=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((e=this.rootMotionHandler)==null||e.onBeforeUpdate()),this._mixer.update(s),this.animator.applyRootMotion&&((t=this.rootMotionHandler)==null||t.onAfterUpdate())}updateActiveStates(){for(let e=0;e<this._activeStates.length;e++){const t=this._activeStates[e],s=t.motion;if(!s.action)this._activeStates.splice(e,1),e--;else{const r=s.action;r.getEffectiveWeight()<=0&&!r.isRunning()&&(oa&&console.debug("REMOVE",t.name,r.getEffectiveWeight(),r.isRunning(),r.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(const e of this.model.layers){const t=e.stateMachine;t.defaultState===void 0&&(oa&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",e),t.defaultState=0);const s=t.states[t.defaultState];this.transitionTo(s,0,this.normalizedStartOffset)}}evaluateTransitions(){var e;let t=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;t=!0}const s=this._activeState,r=s.motion.action;for(const o of s.transitions){if(!o.hasExitTime&&o.conditions.length<=0)continue;let a=!0;for(const l of o.conditions)if(!this.evaluateCondition(l)){a=!1;break}if(a){for(const l of o.conditions){const c=this.model.parameters.find(u=>u.name===l.parameter);c?.type===XS.Trigger&&(c.value=!1)}if(r){const l=s.motion.clip.duration,c=l<=0?1:Math.abs(r.time/l);let u=!1;if(o.hasExitTime?r.timeScale>0?u=c>=o.exitTime:r.timeScale<0&&(u=1-c>=o.exitTime):u=!0,u){r.clampWhenFinished=!0,oa&&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}}}let n=!1;if(s.motion.isLooping&&r&&(r.time>=r.getClip().duration?(n=!0,r.reset(),r.time=0,r.play()):r.time<=0&&r.timeScale<0&&(n=!0,r.reset(),r.time=r.getClip().duration,r.play())),!n&&s&&!t&&r&&this.animator&&s.behaviours){const o=r?.getClip().duration,a=r.time/o,l=new nb(this._activeState,a,o,this._speed);for(const c of s.behaviours)c.instance&&((e=c.instance.onStateUpdate)==null||e.call(c.instance,this.animator,l,0))}}getState(e,t){return typeof e=="number"&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState,e===void 0&&(oa&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+t),e=0)),e=this.model.layers[t].stateMachine.states[e]),e}transitionTo(e,t,s){var r,n,o,a,l,c,u,d;if(!this.animator)return;const p=0;if(e=this.getState(e,p),!(e!=null&&e.motion)||!e.motion.clip)return;const f=this._activeState===e;if(f){const A=e.motion;!A.action_loopback&&A.clip&&(this._mixer.uncacheAction(A.clip,this.animator.gameObject),A.action_loopback=this.createAction(A.clip))}if((r=this._activeState)!=null&&r.behaviours&&this._activeState.motion.action){const A=(n=this._activeState)==null?void 0:n.motion.clip.duration,b=this._activeState.motion.action.time/A,y=new nb(this._activeState,b,A,this._speed);for(const x of this._activeState.behaviours)(a=(o=x.instance)==null?void 0:o.onStateExit)==null||a.call(x.instance,this.animator,y,p)}const g=(l=this._activeState)==null?void 0:l.motion.action;g&&g.fadeOut(t),f&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=g);const m=this._activeState;this._activeState=e;const v=(c=e.motion)==null?void 0:c.action;if(v){s=Math.max(0,Math.min(1,s)),v.isRunning()&&v.stop(),v.reset(),v.timeScale=this._speed,e.speed!==void 0&&(v.timeScale*=e.speed),v.enabled=!0;const A=e.motion.clip.duration;if(v.time=s*A,v.timeScale<0&&(v.time=A-v.time),v.clampWhenFinished=!0,v.setLoop(Rf,0),t>0?v.fadeIn(t):v.setEffectiveWeight(1),v.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(v),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){const b=new nb(e,s,A,this._speed);for(const y of this._activeState.behaviours)(d=(u=y.instance)==null?void 0:u.onStateEnter)==null||d.call(y.instance,this.animator,b,p)}}else oa&&(e.__warned_no_motion||(e.__warned_no_motion=!0,console.warn("No action",e.motion,this)));oa&&console.log("TRANSITION FROM "+m?.name+" TO "+e.name,t,g,v,v?.getEffectiveTimeScale(),v?.getEffectiveWeight(),v?.isRunning(),v?.isScheduled(),v?.paused)}createAction(e){var t,s;if(this._mixer.existingAction(e)&&this._mixer.uncacheAction(e,(t=this.animator)==null?void 0:t.gameObject),(s=this.animator)!=null&&s.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new qY(this));const r=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,r,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){const t=this.model.parameters.find(s=>s.name===e.parameter);if(!t)return!1;switch(e.mode){case Lc.If:return t.value===!0;case Lc.IfNot:return t.value===!1;case Lc.Greater:return t.value>e.threshold;case Lc.Less:return t.value<e.threshold;case Lc.Equals:return t.value===e.threshold;case Lc.NotEqual:return t.value!==e.threshold}return!1}createActions(e){var t,s;for(const r of this.model.layers){const n=r.stateMachine;for(let o=0;o<n.states.length;o++){const a=n.states[o];a.transitions||(a.transitions=[]);for(const l of a.transitions)l.conditions||(l.conditions=[]);if(a.motion||(a.motion=p3(a.name)),this.animator&&a.motion.clips){const l=(t=a.motion.clips)==null?void 0:t.find(c=>{var u,d;return c.node.name===((d=(u=this.animator)==null?void 0:u.gameObject)==null?void 0:d.name)});a.motion.clip=l?.clip}if(!a.motion.clip){const l=new Qn(void 0,void 0,[]);a.motion.clip=l}if((s=a.motion)!=null&&s.clip){const l=a.motion.clip,c=this.createAction(l);a.motion.action=c}if(a.behaviours&&Array.isArray(a.behaviours))for(const l of a.behaviours){if(!(l!=null&&l.typeName))continue;const c=j.get(l.typeName),u=new c;u.isStateMachineBehaviour&&(u._context=this.context??void 0,jh(u,l.properties),l.instance=u),oa&&console.log("Created animator controller behaviour",a.name,l.typeName,l.properties,u)}}}}*enumerateActions(){for(const e of this.model.layers){const t=e.stateMachine;for(let s=0;s<t.states.length;s++){const r=t.states[s];r!=null&&r.motion&&(r.motion.action&&(yield r.motion.action),r.motion.action_loopback&&(yield r.motion.action_loopback))}}}}class f3{constructor(e,t){h(this,"track"),h(this,"createdInterpolant"),h(this,"originalEvaluate"),h(this,"customEvaluate"),this.track=e;const s=e,r=s.createInterpolant.bind(e);s.createInterpolant=()=>(s.createInterpolant=r,this.createdInterpolant=r(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=n=>{if(!this.originalEvaluate)return;const o=this.originalEvaluate(n);return t(n,o)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}evaluate(e){this.customEvaluate&&this.customEvaluate(e)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}}const Ms=class{constructor(i,e,t,s,r){if(h(this,"_action"),h(this,"root"),h(this,"clip"),h(this,"positionWrapper",null),h(this,"rotationWrapper",null),h(this,"context"),h(this,"positionChange",new S),h(this,"rotationChange",new Ce),this.context=i,this.root=e,this.clip=t,Ms.firstKeyframeRotation[t.uuid]||(Ms.firstKeyframeRotation[t.uuid]=new Ce),r){const n=r.values;Ms.firstKeyframeRotation[t.uuid].set(n[0],n[1],n[2],n[3])}Ms.spaceRotation[t.uuid]||(Ms.spaceRotation[t.uuid]=new Ce),Ms.effectiveSpaceRotation[t.uuid]||(Ms.effectiveSpaceRotation[t.uuid]=new Ce),Ms.clipOffsetRotation[t.uuid]=new Ce,r&&Ms.clipOffsetRotation[t.uuid].set(r.values[0],r.values[1],r.values[2],r.values[3]).invert(),this.handlePosition(t,s),this.handleRotation(t,r)}set action(i){this._action=i}get action(){return this._action}onStart(i){if(i.getClip()!==this.clip)return;const e=Ms.lastObjRotation[this.root.uuid];if(Ms.spaceRotation[this.clip.uuid].copy(e),ob){const t=new vs().setFromQuaternion(e);console.log("START",this.clip.name,Je.toDegrees(t.y))}}getClipRotationOffset(){return Ms.clipOffsetRotation[this.clip.uuid]}handlePosition(i,e){if(e){const t=this.root;ob&&t.add(new Cd),Ms.lastObjPosition[t.uuid]||(Ms.lastObjPosition[t.uuid]=new S);const s=new S,r=new S;let n=0;this.positionWrapper=new f3(e,(o,a)=>{const l=this.action.getEffectiveWeight();if(ob&&t.position.length()>8&&t.position.set(0,t.position.y,0),o>n){s.set(a[0],a[1],a[2]),s.sub(r),s.multiplyScalar(l),s.applyQuaternion(this.getClipRotationOffset());const c=this.clip.uuid;s.applyQuaternion(Ms.spaceRotation[c]),this.positionChange.copy(s)}return r.fromArray(a),n=o,a[0]=0,a[1]=0,a[2]=0,a})}}handleRotation(i,e){if(e){if(ob){const o=e.values,a=new vs().setFromQuaternion(new Ce(o[0],o[1],o[2],o[3]));console.log(i.name,e.name,"FIRST ROTATION IN TRACK",Je.toDegrees(a.y));const l=e.values.length-4,c=new Ce().set(o[l],o[l+1],o[l+2],o[l+3]),u=new vs().setFromQuaternion(c);console.log(i.name,e.name,"LAST ROTATION IN TRACK",Je.toDegrees(u.y))}const t=this.root;Ms.lastObjRotation[t.uuid]||(Ms.lastObjRotation[t.uuid]=new Ce);let s=0;const r=new Ce,n=new Ce;this.rotationWrapper=new f3(e,(o,a)=>(o>s&&(n.set(a[0],a[1],a[2],a[3]),r.invert(),n.multiply(r),this.rotationChange.copy(n)),r.fromArray(a),s=o,a[0]=0,a[1]=0,a[2]=0,a[3]=1,a))}}onBeforeUpdate(){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(){if(!this.action)return;const i=this.action.getEffectiveWeight();this.positionChange.multiplyScalar(i),this.rotationChange.slerp(Ms.identityQuaternion,1-i)}};let vl=Ms;h(vl,"lastObjPosition",{}),h(vl,"lastObjRotation",{}),h(vl,"firstKeyframeRotation",{}),h(vl,"spaceRotation",{}),h(vl,"effectiveSpaceRotation",{}),h(vl,"clipOffsetRotation",{}),h(vl,"identityQuaternion",new Ce);class qY{constructor(e){h(this,"controller"),h(this,"handler",[]),h(this,"root"),h(this,"summedPosition",new S),h(this,"summedRotation",new Ce),this.controller=e}createClip(e,t,s){this.root=t,t&&"name"in t&&t.name;const r=this.findRootTrack(s,".position"),n=this.findRootTrack(s,".quaternion"),o=new vl(this.controller.context,t,s,r,n);this.handler.push(o);const a=e.clipAction(s);return o.action=a,a}onStart(e){for(const t of this.handler)t.onStart(e)}onBeforeUpdate(){for(const e of this.handler)e.onBeforeUpdate()}onAfterUpdate(){this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(const e of this.handler)e.onAfterUpdate(),this.summedPosition.add(e.positionChange),this.summedRotation.multiply(e.rotationChange);this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation),vl.lastObjRotation[this.root.uuid].copy(this.root.quaternion)}findRootTrack(e,t){const s=e.tracks;if(!s)return null;for(const r of s)if(r.name.endsWith(t))return r;return null}}var XY=Object.defineProperty,YY=Object.getOwnPropertyDescriptor,ab=(i,e,t,s)=>{for(var r=s>1?void 0:s?YY(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&XY(e,t,r),r};const YS=re("debuganimator");class Or extends Ee{constructor(){super(...arguments),h(this,"applyRootMotion",!1),h(this,"hasRootMotion",!1),h(this,"keepAnimatorControllerStateOnDisable",!1),h(this,"speed",1),h(this,"normalizedStartOffset",0),h(this,"_animatorController",null)}set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof Uu?this._animatorController=e:(YS&&console.log("Assign animator controller",e,this),this._animatorController=new Uu(e)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}Play(e,t=-1,s=Number.NEGATIVE_INFINITY,r=0){this.play(e,t,s,r)}play(e,t=-1,s=Number.NEGATIVE_INFINITY,r=0){var n;(n=this.runtimeAnimatorController)==null||n.play(e,t,s,r)}Reset(){this.reset()}reset(){var e;(e=this._animatorController)==null||e.reset()}SetBool(e,t){this.setBool(e,t)}setBool(e,t){var s;(s=this.runtimeAnimatorController)==null||s.setBool(e,t)}GetBool(e){return this.getBool(e)}getBool(e){var t;return((t=this.runtimeAnimatorController)==null?void 0:t.getBool(e))??!1}SetFloat(e,t){this.setFloat(e,t)}setFloat(e,t){var s;(s=this.runtimeAnimatorController)==null||s.setFloat(e,t)}GetFloat(e){return this.getFloat(e)}getFloat(e){var t;return((t=this.runtimeAnimatorController)==null?void 0:t.getFloat(e))??-1}SetInteger(e,t){this.setInteger(e,t)}setInteger(e,t){var s;(s=this.runtimeAnimatorController)==null||s.setInteger(e,t)}GetInteger(e){return this.getInteger(e)}getInteger(e){var t;return((t=this.runtimeAnimatorController)==null?void 0:t.getInteger(e))??-1}SetTrigger(e){this.setTrigger(e)}setTrigger(e){var t;YS&&console.log("SetTrigger",e),(t=this.runtimeAnimatorController)==null||t.setTrigger(e)}ResetTrigger(e){this.resetTrigger(e)}resetTrigger(e){var t;(t=this.runtimeAnimatorController)==null||t.resetTrigger(e)}IsInTransition(){return this.isInTransition()}isInTransition(){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.isInTransition())??!1}SetSpeed(e){return this.setSpeed(e)}setSpeed(e){var t;e!==this.speed&&(this.speed=e,(t=this._animatorController)==null||t.setSpeed(e))}set minMaxSpeed(e){this.speed=Je.lerp(e.x,e.y,Math.random())}set minMaxOffsetNormalized(e){this.normalizedStartOffset=Je.lerp(e.x,e.y,Math.random()),this.runtimeAnimatorController&&(this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset)}awake(){if(YS&&console.log("ANIMATOR",this.name,this),!!this.gameObject&&this.runtimeAnimatorController){const e=this.runtimeAnimatorController.clone();e?(console.assert(this.runtimeAnimatorController!==e),this.runtimeAnimatorController=e,console.assert(this.runtimeAnimatorController===e),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.setSpeed(this.speed),this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset):console.warn("Could not clone animator controller",this.runtimeAnimatorController)}}onDisable(){var e;this.keepAnimatorControllerStateOnDisable||(e=this._animatorController)==null||e.reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}}ab([w()],Or.prototype,"applyRootMotion",2),ab([w()],Or.prototype,"hasRootMotion",2),ab([w()],Or.prototype,"keepAnimatorControllerStateOnDisable",2),ab([w()],Or.prototype,"runtimeAnimatorController",1);class KY extends Xi{constructor(e,t=1,s=16,r=2){const n=new mt,o=s+r*2,a=new Float32Array((o*3+3)*3);n.setAttribute("position",new tt(a,3));const l=new qi({color:65280}),c=new qi({color:16776960});super(n,[c,l]),this.audio=e,this.range=t,this.divisionsInnerAngle=s,this.divisionsOuterAngle=r,this.type="PositionalAudioHelper",this.update()}update(){const e=this.audio,t=this.range,s=this.divisionsInnerAngle,r=this.divisionsOuterAngle,n=Cr.degToRad(e.panner.coneInnerAngle),o=Cr.degToRad(e.panner.coneOuterAngle),a=n/2,l=o/2;let c=0,u=0,d,p;const f=this.geometry,g=f.attributes.position;f.clearGroups();function m(v,A,b,y){const x=(A-v)/b;for(g.setXYZ(c,0,0,0),u++,d=v;d<A;d+=x)p=c+u,g.setXYZ(p,Math.sin(d)*t,0,Math.cos(d)*t),g.setXYZ(p+1,Math.sin(Math.min(d+x,A))*t,0,Math.cos(Math.min(d+x,A))*t),g.setXYZ(p+2,0,0,0),u+=3;f.addGroup(c,u,y),c+=u,u=0}m(-l,-a,r,0),m(-a,a,s,1),m(a,l,r,0),g.needsUpdate=!0,n===o&&(this.material[0].visible=!1)}dispose(){this.geometry.dispose(),this.material[0].dispose(),this.material[1].dispose()}}var JY=Object.defineProperty,ZY=Object.getOwnPropertyDescriptor,Fc=(i,e,t,s)=>{for(var r=s>1?void 0:s?ZY(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&JY(e,t,r),r};const pr=re("debugaudio");var im;const Ds=(im=class extends Ee{constructor(){super(...arguments),h(this,"clip",""),h(this,"playOnAwake",!1),h(this,"_spatialBlend",0),h(this,"_minDistance",1),h(this,"_maxDistance",100),h(this,"_volume",1),h(this,"rollOffMode",0),h(this,"playInBackground",!0),h(this,"_loop",!1),h(this,"sound",null),h(this,"helper",null),h(this,"wasPlaying",!1),h(this,"audioLoader",null),h(this,"shouldPlay",!1),h(this,"_lastClipStartedLoading",null),h(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||dh())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":pr&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,Ds._userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&Ds._userInteractionRegistered&&this.wasPlaying&&this.play();break}}),h(this,"onApplicationMuteChanged",()=>{var i,e;this.context.application.muted?(i=this.sound)==null||i.setVolume(0):(e=this.sound)==null||e.setVolume(this.volume)}),h(this,"lerp",(i,e,t)=>i*(1-t)+e*t),h(this,"_lastContextTime",0),h(this,"_hasEnded",!0),h(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return Ds._didCallBeginWaitForUserInteraction||(Ds._didCallBeginWaitForUserInteraction=!0,Ds._beginWaitForUserInteraction()),Ds._userInteractionRegistered}static registerWaitForAllowAudio(i){if(i!==null){if(this._userInteractionRegistered){i();return}this.callbacks.indexOf(i)===-1&&this.callbacks.push(i),Ds._didCallBeginWaitForUserInteraction||(Ds._didCallBeginWaitForUserInteraction=!0,Ds._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(i=null){if(this._userInteractionRegistered){i&&i();return}i!==null&&this.registerWaitForAllowAudio(i);const e=(()=>{if(e!=null&&!Ds._userInteractionRegistered){Ds._userInteractionRegistered=!0,pr&&console.log("\u{1F50A} registered interaction, can play audio now"),document.removeEventListener("pointerdown",e),document.removeEventListener("click",e),document.removeEventListener("dragstart",e),document.removeEventListener("touchstart",e);for(const t of this.callbacks)t();this.callbacks.length=0}}).bind(this);document.addEventListener("pointerdown",e),document.addEventListener("click",e),document.addEventListener("dragstart",e),document.addEventListener("touchstart",e)}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(i){this._loop=i,this.sound&&this.sound.setLoop(i)}get spatialBlend(){return this._spatialBlend}set spatialBlend(i){i!==this._spatialBlend&&(this._spatialBlend=i,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(i){this._minDistance!==i&&(this._minDistance=i,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(i){this._maxDistance!==i&&(this._maxDistance=i,this._needUpdateSpatialDistanceSettings=!0)}get volume(){return this._volume}set volume(i){this._volume=i,this.sound&&!this.context.application.muted&&(pr&&console.log(this.name,"audio set volume",i),this.sound.setVolume(i))}get Sound(){if(!this.sound&&Ds._userInteractionRegistered){const i=$.getComponent(this.context.mainCamera,Ep)??$.findObjectOfType(Ep,this.context);i!=null&&i.listener&&(this.sound=new hB(i.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}awake(){this.audioLoader=new A0,this.playOnAwake&&(this.shouldPlay=!0)}onEnable(){Ds._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Ds._beginWaitForUserInteraction(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.loadAndPlay(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(Py.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(Py.MuteChanged,this.onApplicationMuteChanged),this.stop()}onLoaded(i){pr&&console.log("audio buffer loaded"),Ds.registerWaitForAllowAudio(()=>{pr&&console.log("finished loading",i);const e=this.Sound;if(!e){console.warn("Failed getting sound",this.name);return}e.isPlaying&&e.stop(),e.setBuffer(i),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(),pr&&console.log(this.name,this.shouldPlay,Ds.userInteractionRegistered,this),this.shouldPlay&&Ds._userInteractionRegistered&&this.play()})}applySpatialDistanceSettings(){const i=this.sound;if(!i)return;this._needUpdateSpatialDistanceSettings=!1;const e=this.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(pr&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+e),i.setRefDistance(e),i.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:i.setDistanceModel("exponential");break;case 1:i.setDistanceModel("linear");break}this.spatialBlend>0?pr&&!this.helper&&(this.helper=new KY(i,i.getRefDistance()),i.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(i){if(i&&(this.clip=i),this.clip&&(pr&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new A0),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){pr&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,pr&&console.log("load audio",this.clip),this.audioLoader.load(this.clip,this.onLoaded.bind(this),()=>{},console.error)}}play(i=void 0){var e;if(!this.audioLoader||!this.sound||i&&i!==this.clip){this.loadAndPlay(i);return}if(this.shouldPlay=!0,this._hasEnded=!1,pr&&console.log("play",(e=this.sound)==null?void 0:e.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const t=this.context.application.muted;t&&this.sound.setVolume(0),this.sound.play(t?.1:0)}}pause(){var i;pr&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=(i=this.sound)==null?void 0:i.context.currentTime,this.sound.pause())}stop(){var i;pr&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=(i=this.sound)==null?void 0:i.context.currentTime,pr&&console.log(this._lastContextTime),this.sound.stop())}get isPlaying(){var i;return((i=this.sound)==null?void 0:i.isPlaying)??!1}set isPlaying(i){}get time(){var i,e;return(i=this.sound)!=null&&i.source?((e=this.sound.source)==null?void 0:e.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(i){if(this.sound){if(i===this.sound.offset)return;const e=this.isPlaying;this.stop(),this.sound.offset=i,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,pr&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},h(im,"_didCallBeginWaitForUserInteraction",!1),h(im,"callbacks",[]),h(im,"_userInteractionRegistered",!1),im);let as=Ds;Fc([w(URL)],as.prototype,"clip",2),Fc([w()],as.prototype,"playOnAwake",2),Fc([w()],as.prototype,"loop",1),Fc([w()],as.prototype,"spatialBlend",1),Fc([w()],as.prototype,"minDistance",1),Fc([w()],as.prototype,"maxDistance",1),Fc([w()],as.prototype,"volume",1),Fc([w()],as.prototype,"rollOffMode",2);var $Y=Object.defineProperty,eK=Object.getOwnPropertyDescriptor,tK=(i,e,t,s)=>{for(var r=s>1?void 0:s?eK(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&$Y(e,t,r),r};class sm extends Ee{constructor(){super(...arguments),h(this,"constraintActive",!0),h(this,"locked",!1),h(this,"sources",[])}}tK([w(Me)],sm.prototype,"sources",2);const g3={type:"change"},KS={type:"start"},m3={type:"end"};let iK=class extends bs{constructor(i,e){super(),this.object=i,this.domElement=e,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new S,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:ph.ROTATE,MIDDLE:ph.DOLLY,RIGHT:ph.PAN},this.touches={ONE:fh.ROTATE,TWO:fh.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this.getPolarAngle=function(){return o.phi},this.getAzimuthalAngle=function(){return o.theta},this.getDistance=function(){return this.object.position.distanceTo(this.target)},this.listenToKeyEvents=function(Q){Q.addEventListener("keydown",si),this._domElementKeyEvents=Q},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(g3),t.update(),r=s.NONE},this.update=function(){const Q=new S,K=new Ce().setFromUnitVectors(i.up,new S(0,1,0)),Ve=K.clone().invert(),qe=new S,Qe=new Ce,ge=2*Math.PI;return function(){const at=t.object.getWorldPosition(i.position);Q.copy(at).sub(t.target),Q.applyQuaternion(K),o.setFromVector3(Q),t.autoRotate&&r===s.NONE&&R(P()),t.enableDamping?(o.theta+=a.theta*t.dampingFactor,o.phi+=a.phi*t.dampingFactor):(o.theta+=a.theta,o.phi+=a.phi);let It=t.minAzimuthAngle,E=t.maxAzimuthAngle;return isFinite(It)&&isFinite(E)&&(It<-Math.PI?It+=ge:It>Math.PI&&(It-=ge),E<-Math.PI?E+=ge:E>Math.PI&&(E-=ge),It<=E?o.theta=Math.max(It,Math.min(E,o.theta)):o.theta=o.theta>(It+E)/2?Math.max(It,o.theta):Math.min(E,o.theta)),o.phi=Math.max(t.minPolarAngle,Math.min(t.maxPolarAngle,o.phi)),o.makeSafe(),t.enableDamping?c=Cr.lerp(c,l,t.dampingFactor):c=l,o.radius*=c,o.radius=Math.max(t.minDistance,Math.min(t.maxDistance,o.radius)),t.enableDamping===!0?t.target.addScaledVector(u,t.dampingFactor):t.target.add(u),Q.setFromSpherical(o),Q.applyQuaternion(Ve),at.copy(t.target).add(Q),t.object.parent?t.object.parent.worldToLocal(at):t.object.position.copy(at),t.object.lookAt(t.target),t.enableDamping===!0?(a.theta*=1-t.dampingFactor,a.phi*=1-t.dampingFactor,u.multiplyScalar(1-t.dampingFactor)):(a.set(0,0,0),u.set(0,0,0)),l=1,d||qe.distanceToSquared(t.object.position)>n||8*(1-Qe.dot(t.object.quaternion))>n?(t.dispatchEvent(g3),qe.copy(t.object.position),Qe.copy(t.object.quaternion),d=!1,!0):!1}}(),this.dispose=function(){t.domElement.removeEventListener("contextmenu",le),t.domElement.removeEventListener("pointerdown",Ne),t.domElement.removeEventListener("pointercancel",me),t.domElement.removeEventListener("wheel",kt),t.domElement.removeEventListener("pointermove",Be),t.domElement.removeEventListener("pointerup",ct),t._domElementKeyEvents!==null&&t._domElementKeyEvents.removeEventListener("keydown",si)};const t=this,s={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let r=s.NONE;const n=1e-6,o=new S1,a=new S1;let l=1,c=1;const u=new S;let d=!1;const p=new W,f=new W,g=new W,m=new W,v=new W,A=new W,b=new W,y=new W,x=new W,_=[],M={};function P(){return 2*Math.PI/60/60*t.autoRotateSpeed}function C(){return Math.pow(.95,t.zoomSpeed)}function R(Q){a.theta-=Q}function T(Q){a.phi-=Q}const z=function(){const Q=new S;return function(K,Ve){Q.setFromMatrixColumn(Ve,0),Q.multiplyScalar(-K),u.add(Q)}}(),G=function(){const Q=new S;return function(K,Ve){t.screenSpacePanning===!0?Q.setFromMatrixColumn(Ve,1):(Q.setFromMatrixColumn(Ve,0),Q.crossVectors(t.object.up,Q)),Q.multiplyScalar(K),u.add(Q)}}(),N=function(){const Q=new S,K=new S;return function(Ve,qe){const Qe=t.domElement;if(t.object.isPerspectiveCamera){t.object.getWorldPosition(K),Q.copy(K).sub(t.target);let ge=Q.length();ge*=Math.tan(t.object.fov/2*Math.PI/180),z(2*Ve*ge/Qe.clientHeight,t.object.matrixWorld),G(2*qe*ge/Qe.clientHeight,t.object.matrixWorld)}else t.object.isOrthographicCamera?(z(Ve*(t.object.right-t.object.left)/t.object.zoom/Qe.clientWidth,t.object.matrixWorld),G(qe*(t.object.top-t.object.bottom)/t.object.zoom/Qe.clientHeight,t.object.matrixWorld)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),t.enablePan=!1)}}();function F(Q){t.object.isPerspectiveCamera?l/=Q:t.object.isOrthographicCamera?(t.object.zoom=Math.max(t.minZoom,Math.min(t.maxZoom,t.object.zoom*Q)),t.object.updateProjectionMatrix(),d=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),t.enableZoom=!1)}function X(Q){t.object.isPerspectiveCamera?l*=Q:t.object.isOrthographicCamera?(t.object.zoom=Math.max(t.minZoom,Math.min(t.maxZoom,t.object.zoom/Q)),t.object.updateProjectionMatrix(),d=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),t.enableZoom=!1)}function te(Q){p.set(Q.clientX,Q.clientY)}function ne(Q){b.set(Q.clientX,Q.clientY)}function Z(Q){m.set(Q.clientX,Q.clientY)}function fe(Q){f.set(Q.clientX,Q.clientY),g.subVectors(f,p).multiplyScalar(t.rotateSpeed);const K=t.domElement;R(2*Math.PI*g.x/K.clientHeight),T(2*Math.PI*g.y/K.clientHeight),p.copy(f),t.update()}function ae(Q){y.set(Q.clientX,Q.clientY),x.subVectors(y,b),x.y>0?F(C()):x.y<0&&X(C()),b.copy(y),t.update()}function Le(Q){v.set(Q.clientX,Q.clientY),A.subVectors(v,m).multiplyScalar(t.panSpeed),N(A.x,A.y),m.copy(v),t.update()}function Se(Q){Q.deltaY<0?X(C()):Q.deltaY>0&&F(C()),t.update()}function ie(Q){let K=!1;switch(Q.code){case t.keys.UP:Q.ctrlKey||Q.metaKey||Q.shiftKey?T(2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):N(0,t.keyPanSpeed),K=!0;break;case t.keys.BOTTOM:Q.ctrlKey||Q.metaKey||Q.shiftKey?T(-2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):N(0,-t.keyPanSpeed),K=!0;break;case t.keys.LEFT:Q.ctrlKey||Q.metaKey||Q.shiftKey?R(2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):N(t.keyPanSpeed,0),K=!0;break;case t.keys.RIGHT:Q.ctrlKey||Q.metaKey||Q.shiftKey?R(-2*Math.PI*t.rotateSpeed/t.domElement.clientHeight):N(-t.keyPanSpeed,0),K=!0;break}K&&(Q.preventDefault(),t.update())}function ce(){if(_.length===1)p.set(_[0].pageX,_[0].pageY);else{const Q=.5*(_[0].pageX+_[1].pageX),K=.5*(_[0].pageY+_[1].pageY);p.set(Q,K)}}function Re(){if(_.length===1)m.set(_[0].pageX,_[0].pageY);else{const Q=.5*(_[0].pageX+_[1].pageX),K=.5*(_[0].pageY+_[1].pageY);m.set(Q,K)}}function J(){const Q=_[0].pageX-_[1].pageX,K=_[0].pageY-_[1].pageY,Ve=Math.sqrt(Q*Q+K*K);b.set(0,Ve)}function je(){t.enableZoom&&J(),t.enablePan&&Re()}function ze(){t.enableZoom&&J(),t.enableRotate&&ce()}function ke(Q){if(_.length==1)f.set(Q.pageX,Q.pageY);else{const Ve=rt(Q),qe=.5*(Q.pageX+Ve.x),Qe=.5*(Q.pageY+Ve.y);f.set(qe,Qe)}g.subVectors(f,p).multiplyScalar(t.rotateSpeed);const K=t.domElement;R(2*Math.PI*g.x/K.clientHeight),T(2*Math.PI*g.y/K.clientHeight),p.copy(f)}function Ae(Q){if(_.length===1)v.set(Q.pageX,Q.pageY);else{const K=rt(Q),Ve=.5*(Q.pageX+K.x),qe=.5*(Q.pageY+K.y);v.set(Ve,qe)}A.subVectors(v,m).multiplyScalar(t.panSpeed),N(A.x,A.y),m.copy(v)}function de(Q){const K=rt(Q),Ve=Q.pageX-K.x,qe=Q.pageY-K.y,Qe=Math.sqrt(Ve*Ve+qe*qe);y.set(0,Qe),x.set(0,Math.pow(y.y/b.y,t.zoomSpeed)),F(x.y),b.copy(y)}function ye(Q){t.enableZoom&&de(Q),t.enablePan&&Ae(Q)}function pe(Q){t.enableZoom&&de(Q),t.enableRotate&&ke(Q)}function Ne(Q){t.enabled!==!1&&(_.length===0&&(t.domElement.addEventListener("pointermove",Be),t.domElement.addEventListener("pointerup",ct)),Te(Q),Q.pointerType==="touch"?U(Q):ht(Q))}function Be(Q){t.enabled!==!1&&(Q.pointerType==="touch"?D(Q):ut(Q))}function ct(Q){De(Q),_.length===0&&(t.domElement.removeEventListener("pointermove",Be),t.domElement.removeEventListener("pointerup",ct)),t.dispatchEvent(m3),r=s.NONE}function me(Q){De(Q)}function ht(Q){let K;switch(Q.button){case 0:K=t.mouseButtons.LEFT;break;case 1:K=t.mouseButtons.MIDDLE;break;case 2:K=t.mouseButtons.RIGHT;break;default:K=-1}switch(K){case ph.DOLLY:if(t.enableZoom===!1)return;ne(Q),r=s.DOLLY;break;case ph.ROTATE:if(Q.ctrlKey||Q.metaKey||Q.shiftKey){if(t.enablePan===!1)return;Z(Q),r=s.PAN}else{if(t.enableRotate===!1)return;te(Q),r=s.ROTATE}break;case ph.PAN:if(Q.ctrlKey||Q.metaKey||Q.shiftKey){if(t.enableRotate===!1)return;te(Q),r=s.ROTATE}else{if(t.enablePan===!1)return;Z(Q),r=s.PAN}break;default:r=s.NONE}r!==s.NONE&&t.dispatchEvent(KS)}function ut(Q){switch(r){case s.ROTATE:if(t.enableRotate===!1)return;fe(Q);break;case s.DOLLY:if(t.enableZoom===!1)return;ae(Q);break;case s.PAN:if(t.enablePan===!1)return;Le(Q);break}}function kt(Q){t.enabled===!1||t.enableZoom===!1||r!==s.NONE||(Q.preventDefault(),t.dispatchEvent(KS),Se(Q),t.dispatchEvent(m3))}function si(Q){t.enabled===!1||t.enablePan===!1||ie(Q)}function U(Q){switch(Ge(Q),_.length){case 1:switch(t.touches.ONE){case fh.ROTATE:if(t.enableRotate===!1)return;ce(),r=s.TOUCH_ROTATE;break;case fh.PAN:if(t.enablePan===!1)return;Re(),r=s.TOUCH_PAN;break;default:r=s.NONE}break;case 2:switch(t.touches.TWO){case fh.DOLLY_PAN:if(t.enableZoom===!1&&t.enablePan===!1)return;je(),r=s.TOUCH_DOLLY_PAN;break;case fh.DOLLY_ROTATE:if(t.enableZoom===!1&&t.enableRotate===!1)return;ze(),r=s.TOUCH_DOLLY_ROTATE;break;default:r=s.NONE}break;default:r=s.NONE}r!==s.NONE&&t.dispatchEvent(KS)}function D(Q){switch(Ge(Q),r){case s.TOUCH_ROTATE:if(t.enableRotate===!1)return;ke(Q),t.update();break;case s.TOUCH_PAN:if(t.enablePan===!1)return;Ae(Q),t.update();break;case s.TOUCH_DOLLY_PAN:if(t.enableZoom===!1&&t.enablePan===!1)return;ye(Q),t.update();break;case s.TOUCH_DOLLY_ROTATE:if(t.enableZoom===!1&&t.enableRotate===!1)return;pe(Q),t.update();break;default:r=s.NONE}}function le(Q){t.enabled!==!1&&Q.preventDefault()}function Te(Q){_.push(Q)}function De(Q){delete M[Q.pointerId];for(let K=0;K<_.length;K++)if(_[K].pointerId==Q.pointerId){_.splice(K,1);return}}function Ge(Q){let K=M[Q.pointerId];K===void 0&&(K=new W,M[Q.pointerId]=K),K.set(Q.pageX,Q.pageY)}function rt(Q){const K=Q.pointerId===_[0].pointerId?_[1]:_[0];return M[K.pointerId]}t.domElement.addEventListener("contextmenu",le),t.domElement.addEventListener("pointerdown",Ne),t.domElement.addEventListener("pointercancel",me),t.domElement.addEventListener("wheel",kt,{passive:!1}),this.update()}};class sK{static createButton(e,t={},s){const r=document.createElement("button");let n=!1;function o(){if(t.optionalFeatures=t.optionalFeatures||[],t.domOverlay===void 0){var u=document.createElement("div");u.style.display="none",document.body.appendChild(u);var d=document.createElementNS("http://www.w3.org/2000/svg","svg");d.setAttribute("width",38),d.setAttribute("height",38),d.style.position="absolute",d.style.right="20px",d.style.top="20px",d.addEventListener("click",function(){f.end()}),u.appendChild(d);var p=document.createElementNS("http://www.w3.org/2000/svg","path");p.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),p.setAttribute("stroke","#fff"),p.setAttribute("stroke-width",2),d.appendChild(p),t.optionalFeatures.push("dom-overlay"),t.domOverlay={root:u},n=!0}let f=null,g=null;async function m(A){var b;const y=/WebXRViewer\//i.test(navigator.userAgent),x=t.domOverlay.root;y&&((b=t.domOverlay)!=null&&b.root?(g=x.parentNode,g&&(console.log("Reparent DOM Overlay to body",x,x.style.display),x.style.display="",x.style.visibility="",document.body.appendChild(x))):console.warn("WebXRViewer: No DOM Overlay found")),A.addEventListener("end",v),await e.xr.setSession(A),r.textContent="STOP AR",n&&(t.domOverlay.root.style.display=""),f=A}function v(){f.removeEventListener("end",v),r.textContent="START AR";const A=t.domOverlay.root;g&&g.appendChild(A),n&&(A.style.display="none"),f=null}r.style.display="",r.style.cursor="pointer",r.style.left="calc(50% - 50px)",r.style.width="100px",r.textContent="START AR",r.onmouseenter=function(){r.style.opacity="1.0"},r.onmouseleave=function(){r.style.opacity="0.5"},r.onclick=function(){f===null?(s?.call(this,t),navigator.xr.requestSession("immersive-ar",t).then(m)):f.end()}}function a(){r.disabled=!0,r.style.display="",r.style.cursor="auto",r.style.left="calc(50% - 75px)",r.style.width="150px",r.onmouseenter=null,r.onmouseleave=null,r.onclick=null}function l(){a(),r.textContent="AR NOT SUPPORTED"}function c(u){u.style.position="absolute",u.style.bottom="20px",u.style.padding="12px 6px",u.style.border="1px solid #fff",u.style.borderRadius="4px",u.style.background="rgba(0,0,0,0.1)",u.style.color="#fff",u.style.font="normal 13px sans-serif",u.style.textAlign="center",u.style.opacity="0.5",u.style.outline="none",u.style.zIndex="999"}if("xr"in navigator)return r.id="ARButton",r.style.display="none",c(r),navigator.xr.isSessionSupported("immersive-ar").then(function(u){u?o():l()}).catch(l),r;{const u=document.createElement("a");return window.isSecureContext===!1?(u.href=document.location.href.replace(/^http:/,"https:"),u.innerHTML="WEBXR NEEDS HTTPS"):(u.href="https://immersiveweb.dev/",u.innerHTML="WEBXR NOT AVAILABLE"),u.style.left="calc(50% - 90px)",u.style.width="180px",u.style.textDecoration="none",c(u),u}}}const JS=class{static createButton(i,e){const t=document.createElement("button");function s(){let a=null;async function l(u){u.addEventListener("end",c),await i.xr.setSession(u),t.textContent="EXIT VR",a=u}function c(){a.removeEventListener("end",c),t.textContent="ENTER VR",a=null}t.style.display="",t.style.cursor="pointer",t.style.left="calc(50% - 50px)",t.style.width="100px",t.textContent="ENTER VR",t.onmouseenter=function(){t.style.opacity="1.0"},t.onmouseleave=function(){t.style.opacity="0.5"},t.onclick=function(){if(a===null){const u={optionalFeatures:e.optionalFeatures};navigator.xr.requestSession("immersive-vr",u).then(l)}else a.end()}}function r(){t.disabled=!0,t.style.display="",t.style.cursor="auto",t.style.left="calc(50% - 75px)",t.style.width="150px",t.onmouseenter=null,t.onmouseleave=null,t.onclick=null}function n(){r(),t.textContent="VR NOT SUPPORTED"}function o(a){a.style.position="absolute",a.style.bottom="20px",a.style.padding="12px 6px",a.style.border="1px solid #fff",a.style.borderRadius="4px",a.style.background="rgba(0,0,0,0.1)",a.style.color="#fff",a.style.font="normal 13px sans-serif",a.style.textAlign="center",a.style.opacity="0.5",a.style.outline="none",a.style.zIndex="999"}if("xr"in navigator)return t.id="VRButton",t.style.display="none",o(t),navigator.xr.isSessionSupported("immersive-vr").then(function(a){a?s():n(),JS.xrSessionIsGranted&&(console.log("XR session is granted - will enter immersive web now"),t.click())}),t;{const a=document.createElement("a");return window.isSecureContext===!1?(a.href=document.location.href.replace(/^http:/,"https:"),a.innerHTML="WEBXR NEEDS HTTPS"):(a.href="https://immersiveweb.dev/",a.innerHTML="WEBXR NOT AVAILABLE"),a.style.left="calc(50% - 90px)",a.style.width="180px",a.style.textDecoration="none",o(a),a}}static registerSessionGrantedListener(){if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent))return;navigator.xr.addEventListener("sessiongranted",()=>{JS.xrSessionIsGranted=!0})}}};let ZS=JS;h(ZS,"xrSessionIsGranted",!1),ZS.registerSessionGrantedListener();const lb="noVoip",$r=re("debugvoip"),rK=re("voip");class nK{constructor(e){h(this,"id"),this.id=e}}class oK{constructor(e,t,s,r){h(this,"peer"),h(this,"voip"),h(this,"userId"),h(this,"peerId"),h(this,"call",null),h(this,"callErrorListener",null),h(this,"stream",null),this.voip=e,this.peer=t,this.userId=s,this.peerId=r}close(){var e;$r&&console.log("close voip call"),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.open&&this.call.close(),(e=this.stream)==null||e.getTracks().forEach(function(t){t.stop()})}updateMute(e){var t;if(!this.stream)return;const s=(t=this.stream)==null?void 0:t.getAudioTracks();for(const r of s)r.enabled=!e}async startVoipCall(){if(!await Gl.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}$r&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),$r&&console.log(this.stream),this.call=this.peer.call(this.peerId,this.stream,{metadata:{userId:this.userId}}),this.call.on("error",e=>{console.error(e)}),this.call.on("stream",e=>{$r&&console.log("received stream from remote again",e)}),this.peer.on("close",this.onCallClose.bind(this)),this.callErrorListener=e=>{var t;e.message.includes(this.peerId)?(console.log("Could not connect to "+this.peerId),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.close(),(t=this.stream)==null||t.getTracks().forEach(function(s){s.stop()}),this.stream=null):console.error(e)},this.peer.on("error",this.callErrorListener)}onCallClose(e){$r&&console.log("call closed",e)}}class aK{constructor(e,t,s){h(this,"voip"),h(this,"call"),h(this,"audio",null),h(this,"stream",null),h(this,"obj"),h(this,"analyzer",null),h(this,"waitingForStart",!1),h(this,"closed",!1),h(this,"audioElement",null),this.voip=e,this.obj=t,this.call=s}get currentStream(){return this.stream}get currentAudio(){return this.audio}get currentAnalyzer(){return this.analyzer}openAudioStream(e){const t=e.getAudioTracks();for(const s of t)if(s.kind==="audio"&&s.readyState==="live"){this.open(s);return}console.warn("failed finding valid audio stream to begin call")}open(e){console.assert(e.kind==="audio","invalid track kind, expected audio but received "+e.kind),!this.waitingForStart&&(this.waitingForStart=!0,as.userInteractionRegistered||$r&&console.log("Incoming call, waiting for user interaction before opening audio"),as.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){$r&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);const t=new x1;this.audio=new b0(t),this.audio.setVolume(this.voip.muteInput?0:1),this.audio.setMediaStreamSource(this.stream);const s=document.createElement("audio");this.audioElement=s,s.style.display="none",document.body.appendChild(s),s.srcObject=this.stream,s.sinkId!==void 0&&navigator.mediaDevices.enumerateDevices().then(r=>{if(s){console.log(r);for(const n of r)if(n.label==="Speakerphone"){s.sinkId=n.deviceId;break}}}),$r&&console.log("call is setup, you should hear something now"),this.analyzer=new uB(this.audio,32)}}))}close(){var e,t,s;this.closed=!0,(e=this.call)!=null&&e.open&&this.call.close(),(t=this.audio)==null||t.disconnect(),(s=this.stream)==null||s.getTracks().forEach(r=>{r.stop()}),this.stream=null,this.audioElement&&this.audioElement.remove()}}class Gl extends Ee{constructor(){super(...arguments),h(this,"requireParam",!1),h(this,"peer",null),h(this,"model",null),h(this,"connections",{}),h(this,"currentIncomingCalls",{}),h(this,"_inputMuted",!1),h(this,"_outputMuted",!1)}set muteInput(e){var t;if(e===this._inputMuted||(this._inputMuted=e,!this.currentIncomingCalls))return;const s=this._inputMuted?0:1;for(const r in this.currentIncomingCalls){const n=this.currentIncomingCalls[r];(t=n?.currentAudio)==null||t.setVolume(s)}}get muteInput(){return this._inputMuted}set muteOutput(e){if(e!==this._outputMuted&&(this._outputMuted=e,!!this.connections))for(const t in this.connections){const s=this.connections[t];s?.updateMute(e)}}get muteOutput(){return this._outputMuted}getFrequency(e){if(e===null){for(const s in this.currentIncomingCalls){const r=this.currentIncomingCalls[s];if(r&&r.currentAnalyzer)return r.currentAnalyzer.getAverageFrequency()}return null}const t=this.currentIncomingCalls[e];return t&&t.currentAnalyzer?t.currentAnalyzer.getAverageFrequency():null}awake(){if(re(lb)){console.log("VOIP is disabled by url parameter: "+lb);return}if(this.requireParam&&!rK){console.debug("VOIP must be enabled explicitly by url parameter");return}if(wf()&&Da()){console.log("VOIP is currently not supported on Safari iOS");return}this.peer=new ry,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,this.context.connection.beginListen(ji.JoinedRoom,e=>{navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}),this.context.connection.beginListen("peer-update-id",e=>{if(e.id!==this.context.connection.connectionId){const t=this.connections[e.id];if(t&&t.close(),this.peer&&this.context.connection.connectionId){const s=new oK(this,this.peer,this.context.connection.connectionId,e.peerId);this.connections[e.id]=s,s.startVoipCall()}}}),this.context.connection.beginListen(ji.UserLeftRoom,e=>{const{userId:t}=e,s=this.connections[t];this.connections[t]=null,s&&s.close();const r=this.currentIncomingCalls[t];$r&&console.log("UserLeftRoom",e,t,r),r&&(r.close(),this.currentIncomingCalls[t]=null)}),this.peer.on("open",this.onOpenPeerConnection.bind(this))}onEnable(){}onDisable(){console.log("TODO: close all");for(const e in this.currentIncomingCalls)try{const t=this.currentIncomingCalls[e];t?.close();const s=this.connections[e];s?.close()}catch(t){console.error(t)}}async onOpenPeerConnection(e){$r&&console.log("Peer connection established and received id"),this.model=new nK(e),this.context.connection.send("peer-update-id",this.model,Xr.OnRoomJoin),this.peer&&(this.peer.on("call",this.onReceiveCall.bind(this)),this.peer.on("connection",function(t){$r&&console.log("CONNECTION",t),t.on("data",function(s){$r&&console.log("Received",s)})}))}async onReceiveCall(e){const{metadata:t}=e;console.assert(t.userId);const{userId:s}=t,r=this.currentIncomingCalls[s];if(r&&r.close(),$r&&console.log("received call"),await Gl.HasMicrophonePermissions()){const n=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(n)}else e.answer(null);this.currentIncomingCalls[s]=new aK(this,this.gameObject,e),e.on("stream",n=>{var o;$r&&console.log("receive caller stream, will setup audio now"),(o=this.currentIncomingCalls[s])==null||o.openAudioStream(n)}),e.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}}var lK=Object.defineProperty,cK=Object.getOwnPropertyDescriptor,v3=(i,e,t,s)=>{for(var r=s>1?void 0:s?cK(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&lK(e,t,r),r};class Uc extends Ee{constructor(){super(...arguments),h(this,"webAR",null),h(this,"invertForward",!1),h(this,"_initalMatrix",new Pe),h(this,"_selectStartFn",this.onSelectStart.bind(this)),h(this,"_selectEndFn",this.onSelectEnd.bind(this)),h(this,"_arScale",5),h(this,"_rig",null),h(this,"_startPose",null),h(this,"_placementPose",null),h(this,"_isTouching",!1),h(this,"_rigStartPose",null),h(this,"_gotFirstHitTestResult",!1)}get rig(){var e;return(e=this.webAR)==null?void 0:e.webxr.Rig}get arScale(){return this._arScale}set arScale(e){e!==this._arScale&&(this._arScale=e,this.setScale(e))}start(){const e=$.findObjectOfType(_t);e&&(e.Rig.updateMatrix(),this._initalMatrix.copy(e.Rig.matrix))}onBegin(e){var t;this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose=this.gameObject.matrix.clone(),this._rigStartPose=(t=this.rig)==null?void 0:t.matrix.clone(),this._gotFirstHitTestResult=!1,e.addEventListener("selectstart",this._selectStartFn),e.addEventListener("selectend",this._selectEndFn),this.gameObject.visible=!1,this.rig&&(this.rig.matrixAutoUpdate=!0,this._initalMatrix.decompose(this.rig.position,this.rig.quaternion,this.rig.scale)),this.dispatchEvent(new CustomEvent("onBeginSession"))}onUpdate(e,t,s){if(s&&!this._placementPose&&(this._gotFirstHitTestResult||(this._gotFirstHitTestResult=!0,this.dispatchEvent(new CustomEvent("canPlaceSession",{detail:{pose:s}}))),this._isTouching)){const r=new Pe().fromArray(s.transform.matrix).invert();return this.dispatchEvent(new CustomEvent("placedSession",{detail:{pose:s,poseMatrix:r}})),this.webAR&&this.webAR.setReticleActive(!1),this.placeAt(e,r),!0}return!1}placeAt(e,t){this._placementPose||(this._placementPose=new Pe),this._placementPose.copy(t);const s=this.gameObject.matrixWorld.clone().invert();if(this._placementPose.premultiply(s),e){if(this.invertForward){const r=new Pe().makeRotationY(Math.PI);this._placementPose.premultiply(r)}this._rig=e,this.setScale(this.arScale)}else this._rig=null;this.gameObject.visible=!0}onEnd(e,t){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose&&this.gameObject.matrix.copy(this._startPose),e&&(e.matrixAutoUpdate=!0,this._rigStartPose&&this._rigStartPose.decompose(e.position,e.quaternion,e.scale)),on.markDirty(this.gameObject,!0),setTimeout(()=>{this.gameObject.matrixAutoUpdate=!0,this.gameObject.visible=!0},100)}onSelectStart(){this._isTouching=!0}onSelectEnd(){this._isTouching=!1}setScale(e){const t=this._rig;!t||!this._placementPose||(this._rigStartPose||(this._rigStartPose=t.matrix.clone()),t.matrixAutoUpdate=!1,t.matrix.multiplyMatrices(new Pe().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld(),console.log("Place",t.position))}}v3([w()],Uc.prototype,"invertForward",2),v3([w()],Uc.prototype,"arScale",1);const hK="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/";class uK{constructor(e,t,s,r,n=null){this.controller=t,this.handModel=e,this.bones=[],n===null&&(n=new zd,n.setPath(s||hK)),n.load(`${r}.glb`,o=>{const a=o.scene.children[0];this.handModel.add(a),a.layers.mask=this.handModel.layers.mask;const l=a.getObjectByProperty("type","SkinnedMesh");l.frustumCulled=!1,l.castShadow=!0,l.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(c=>{const u=a.getObjectByName(c);u!==void 0?u.jointName=c:console.warn(`Couldn't find ${c} in ${r} hand mesh`),this.bones.push(u)})})}updateMesh(){const e=this.controller.joints;for(let t=0;t<this.bones.length;t++){const s=this.bones[t];if(s){const r=e[s.jointName];if(r.visible){const n=r.position;s.position.copy(n),s.quaternion.copy(r.quaternion)}}}}}const dK=.01,pK="index-finger-tip";class fK extends Me{constructor(e,t=null){super(),this.controller=e,this.motionController=null,this.envMap=null,this.loader=t,this.mesh=null,e.addEventListener("connected",s=>{const r=s.data;r.hand&&!this.motionController&&(this.xrInputSource=r,this.motionController=new uK(this,e,this.path,r.handedness,this.loader))}),e.addEventListener("disconnected",()=>{this.clear(),this.motionController=null})}updateMatrixWorld(e){super.updateMatrixWorld(e),this.motionController&&this.motionController.updateMesh()}getPointerPosition(){const e=this.controller.joints[pK];return e?e.position:null}intersectBoxObject(e){const t=this.getPointerPosition();if(t){const s=new Ao(t,dK),r=new or().setFromObject(e);return s.intersectsBox(r)}else return!1}checkButton(e){this.intersectBoxObject(e)?e.onPress():e.onClear(),e.isPressed()&&e.whilePressed()}}const gK=.05,A3=.02,cb=.01,y3=.02,b3=1,hp=.4,mK=.002,rm=.01,hb=.003,x3=.035,Ai=16,Zn=12,$S=110,vK=new S(0,1,0),AK=new S(0,0,1),yK=.02,bK=1.5;class xK extends Me{constructor(e,t){super(),this.hand=e,this.controller=t,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,e.addEventListener("connected",s=>{const r=s.data;r.hand&&(this.visible=!0,this.xrInputSource=r,this.pointerObject===null&&this.createPointer())})}_drawVerticesRing(e,t,s){const r=t.clone();for(let n=0;n<Ai;n++){r.applyAxisAngle(AK,Math.PI*2/Ai);const o=s*Ai+n;e[3*o]=r.x,e[3*o+1]=r.y,e[3*o+2]=r.z}}_updatePointerVertices(e){const t=this.pointerGeometry.attributes.position.array,s=new S(mK,0,-1*(x3-e));this._drawVerticesRing(t,s,0);const r=new S(Math.sin(Math.PI*$S/180)*e,Math.cos(Math.PI*$S/180)*e,0);for(let c=0;c<Zn;c++)this._drawVerticesRing(t,r,c+1),r.applyAxisAngle(vK,Math.PI*$S/180/(Zn*-2));const n=Ai*(1+Zn),o=Ai*(1+Zn)+1,a=new S(0,0,-1*(x3-e));t[n*3]=a.x,t[n*3+1]=a.y,t[n*3+2]=a.z;const l=new S(0,0,e);t[o*3]=l.x,t[o*3+1]=l.y,t[o*3+2]=l.z,this.pointerGeometry.setAttribute("position",new $e(t,3))}createPointer(){let e,t;const s=new Array(((Zn+1)*Ai+2)*3).fill(0),r=[];for(this.pointerGeometry=new mt,this.pointerGeometry.setAttribute("position",new $e(s,3)),this._updatePointerVertices(rm),e=0;e<Zn;e++){for(t=0;t<Ai-1;t++)r.push(e*Ai+t,e*Ai+t+1,(e+1)*Ai+t),r.push(e*Ai+t+1,(e+1)*Ai+t+1,(e+1)*Ai+t);r.push((e+1)*Ai-1,e*Ai,(e+2)*Ai-1),r.push(e*Ai,(e+1)*Ai,(e+2)*Ai-1)}const n=Ai*(1+Zn),o=Ai*(1+Zn)+1;for(e=0;e<Ai-1;e++)r.push(n,e+1,e),r.push(o,e+Ai*Zn,e+Ai*Zn+1);r.push(n,0,Ai-1),r.push(o,Ai*(Zn+1)-1,Ai*Zn);const a=new pi;a.transparent=!0,a.opacity=hp,this.pointerGeometry.setIndex(r),this.pointerMesh=new ve(this.pointerGeometry,a),this.pointerMesh.position.set(0,0,-1*rm),this.pointerObject=new Me,this.pointerObject.add(this.pointerMesh),this.raycaster=new _d;const l=new Bn(yK,10,10),c=new pi;c.transparent=!0,c.opacity=hp,this.cursorObject=new ve(l,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 e=this.pointerObject.matrixWorld,t=new Pe;t.identity().extractRotation(e),this.raycaster.ray.origin.setFromMatrixPosition(e),this.raycaster.ray.direction.set(0,0,-1).applyMatrix4(t)}}_updatePointer(){this.pointerObject.visible=this.controller.visible;const e=this.hand.joints["index-finger-tip"],t=this.hand.joints["thumb-tip"],s=e.position.distanceTo(t.position),r=e.position.clone().add(t.position).multiplyScalar(.5);this.pointerObject.position.copy(r),this.pointerObject.quaternion.copy(this.controller.quaternion),this.pinched=s<=A3;const n=(s-cb)/(gK-cb),o=(s-cb)/(A3-cb);if(n>1)this._updatePointerVertices(rm),this.pointerMesh.position.set(0,0,-1*rm),this.pointerMesh.material.opacity=hp;else if(n>0){const a=(rm-hb)*n+hb;this._updatePointerVertices(a),o<1?(this.pointerMesh.position.set(0,0,-1*a-(1-o)*y3),this.pointerMesh.material.opacity=hp+(1-o)*(b3-hp)):(this.pointerMesh.position.set(0,0,-1*a),this.pointerMesh.material.opacity=hp)}else this._updatePointerVertices(hb),this.pointerMesh.position.set(0,0,-1*hb-y3),this.pointerMesh.material.opacity=b3;this.cursorObject.material.opacity=this.pointerMesh.material.opacity}updateMatrixWorld(e){super.updateMatrixWorld(e),this.pointerGeometry&&(this._updatePointer(),this._updateRaycaster())}isPinched(){return this.pinched}setAttached(e){this.attached=e}isAttached(){return this.attached}intersectObject(e,t=!0){if(this.raycaster)return this.raycaster.intersectObject(e,t)}intersectObjects(e,t=!0){if(this.raycaster)return this.raycaster.intersectObjects(e,t)}checkIntersections(e,t=!1){if(this.raycaster&&!this.attached){const s=this.raycaster.intersectObjects(e,t),r=new S(0,0,-1);if(s.length>0){const n=s[0].distance;this.cursorObject.position.copy(r.multiplyScalar(n))}else this.cursorObject.position.copy(r.multiplyScalar(bK))}}setCursor(e){const t=new S(0,0,-1);this.raycaster&&!this.attached&&this.cursorObject.position.copy(t.multiplyScalar(e))}}const Gi={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 w3(i){const e=await fetch(i);if(e.ok)return e.json();throw new Error(e.statusText)}async function wK(i){if(!i)throw new Error("No basePath supplied");return await w3(`${i}/profilesList.json`)}async function _K(i,e,t=null,s=!0){if(!i)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No basePath supplied");const r=await wK(e);let n;if(i.profiles.some(l=>{const c=r[l];return c&&(n={profileId:l,profilePath:`${e}/${c.path}`,deprecated:!!c.deprecated}),!!n}),!n){if(!t)throw new Error("No matching profile name found");const l=r[t];if(!l)throw new Error(`No matching profile name found and default profile "${t}" missing.`);n={profileId:t,profilePath:`${e}/${l.path}`,deprecated:!!l.deprecated}}const o=await w3(n.profilePath);let a;if(s){let l;if(i.handedness==="any"?l=o.layouts[Object.keys(o.layouts)[0]]:l=o.layouts[i.handedness],!l)throw new Error(`No matching handedness, ${i.handedness}, in profile ${n.profileId}`);l.assetPath&&(a=n.profilePath.replace("profile.json",l.assetPath))}return{profile:o,assetPath:a}}const CK={xAxis:0,yAxis:0,button:0,state:Gi.ComponentState.DEFAULT};function SK(i=0,e=0){let t=i,s=e;if(Math.sqrt(i*i+e*e)>1){const r=Math.atan2(e,i);t=Math.cos(r),s=Math.sin(r)}return{normalizedXAxis:t*.5+.5,normalizedYAxis:s*.5+.5}}class EK{constructor(e){this.componentProperty=e.componentProperty,this.states=e.states,this.valueNodeName=e.valueNodeName,this.valueNodeProperty=e.valueNodeProperty,this.valueNodeProperty===Gi.VisualResponseProperty.TRANSFORM&&(this.minNodeName=e.minNodeName,this.maxNodeName=e.maxNodeName),this.value=0,this.updateFromComponent(CK)}updateFromComponent({xAxis:e,yAxis:t,button:s,state:r}){const{normalizedXAxis:n,normalizedYAxis:o}=SK(e,t);switch(this.componentProperty){case Gi.ComponentProperty.X_AXIS:this.value=this.states.includes(r)?n:.5;break;case Gi.ComponentProperty.Y_AXIS:this.value=this.states.includes(r)?o:.5;break;case Gi.ComponentProperty.BUTTON:this.value=this.states.includes(r)?s:0;break;case Gi.ComponentProperty.STATE:this.valueNodeProperty===Gi.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(r):this.value=this.states.includes(r)?1:0;break;default:throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}}class MK{constructor(e,t){if(!e||!t||!t.visualResponses||!t.gamepadIndices||Object.keys(t.gamepadIndices).length===0)throw new Error("Invalid arguments supplied");this.id=e,this.type=t.type,this.rootNodeName=t.rootNodeName,this.touchPointNodeName=t.touchPointNodeName,this.visualResponses={},Object.keys(t.visualResponses).forEach(s=>{const r=new EK(t.visualResponses[s]);this.visualResponses[s]=r}),this.gamepadIndices=Object.assign({},t.gamepadIndices),this.values={state:Gi.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(e){if(this.values.state=Gi.ComponentState.DEFAULT,this.gamepadIndices.button!==void 0&&e.buttons.length>this.gamepadIndices.button){const t=e.buttons[this.gamepadIndices.button];this.values.button=t.value,this.values.button=this.values.button<0?0:this.values.button,this.values.button=this.values.button>1?1:this.values.button,t.pressed||this.values.button===1?this.values.state=Gi.ComponentState.PRESSED:(t.touched||this.values.button>Gi.ButtonTouchThreshold)&&(this.values.state=Gi.ComponentState.TOUCHED)}this.gamepadIndices.xAxis!==void 0&&e.axes.length>this.gamepadIndices.xAxis&&(this.values.xAxis=e.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===Gi.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>Gi.AxisTouchThreshold&&(this.values.state=Gi.ComponentState.TOUCHED)),this.gamepadIndices.yAxis!==void 0&&e.axes.length>this.gamepadIndices.yAxis&&(this.values.yAxis=e.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===Gi.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>Gi.AxisTouchThreshold&&(this.values.state=Gi.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(t=>{t.updateFromComponent(this.values)})}}class IK{constructor(e,t,s){if(!e)throw new Error("No xrInputSource supplied");if(!t)throw new Error("No profile supplied");this.xrInputSource=e,this.assetUrl=s,this.id=t.profileId,this.layoutDescription=t.layouts[e.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(r=>{const n=this.layoutDescription.components[r];this.components[r]=new MK(r,n)}),this.updateFromGamepad()}get gripSpace(){return this.xrInputSource.gripSpace}get targetRaySpace(){return this.xrInputSource.targetRaySpace}get data(){const e=[];return Object.values(this.components).forEach(t=>{e.push(t.data)}),e}updateFromGamepad(){Object.values(this.components).forEach(e=>{e.updateFromGamepad(this.xrInputSource.gamepad)})}}const TK="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",RK="generic-trigger";class PK extends Me{constructor(){super(),this.motionController=null,this.envMap=null}setEnvironmentMap(e){return this.envMap==e?this:(this.envMap=e,this.traverse(t=>{t.isMesh&&(t.material.envMap=this.envMap,t.material.needsUpdate=!0)}),this)}updateMatrixWorld(e){super.updateMatrixWorld(e),this.motionController&&(this.motionController.updateFromGamepad(),Object.values(this.motionController.components).forEach(t=>{Object.values(t.visualResponses).forEach(s=>{const{valueNode:r,minNode:n,maxNode:o,value:a,valueNodeProperty:l}=s;r&&(l===Gi.VisualResponseProperty.VISIBILITY?r.visible=a:l===Gi.VisualResponseProperty.TRANSFORM&&(r.quaternion.slerpQuaternions(n.quaternion,o.quaternion,a),r.position.lerpVectors(n.position,o.position,a)))})}))}}function BK(i,e){Object.values(i.components).forEach(t=>{const{type:s,touchPointNodeName:r,visualResponses:n}=t;if(s===Gi.ComponentType.TOUCHPAD)if(t.touchPointNode=e.getObjectByName(r),t.touchPointNode){const o=new Bn(.001),a=new pi({color:255}),l=new ve(o,a);t.touchPointNode.add(l)}else console.warn(`Could not find touch dot, ${t.touchPointNodeName}, in touchpad component ${t.id}`);Object.values(n).forEach(o=>{const{valueNodeName:a,minNodeName:l,maxNodeName:c,valueNodeProperty:u}=o;if(u===Gi.VisualResponseProperty.TRANSFORM){if(o.minNode=e.getObjectByName(l),o.maxNode=e.getObjectByName(c),!o.minNode){console.warn(`Could not find ${l} in the model`);return}if(!o.maxNode){console.warn(`Could not find ${c} in the model`);return}}o.valueNode=e.getObjectByName(a),o.valueNode||console.warn(`Could not find ${a} in the model`)})})}function _3(i,e){BK(i.motionController,e),i.envMap&&e.traverse(t=>{t.isMesh&&(t.material.envMap=i.envMap,t.material.needsUpdate=!0)}),i.layers.mask!=0&&e.traverse(t=>{t.layers.mask=i.layers.mask}),i.add(e)}class kK{constructor(e=null){this.gltfLoader=e,this.path=TK,this._assetCache={},this.gltfLoader||(this.gltfLoader=new zd)}createControllerModel(e){const t=new PK;let s=null;return e.addEventListener("connected",r=>{const n=r.data;n.targetRayMode!=="tracked-pointer"||!n.gamepad||_K(n,this.path,RK).then(({profile:o,assetPath:a})=>{t.motionController=new IK(n,o,a);const l=this._assetCache[t.motionController.assetUrl];if(l)s=l.scene.clone(),_3(t,s);else{if(!this.gltfLoader)throw new Error("GLTFLoader not set.");this.gltfLoader.setPath(""),this.gltfLoader.load(t.motionController.assetUrl,c=>{this._assetCache[t.motionController.assetUrl]=c,s=c.scene.clone(),_3(t,s)},null,()=>{throw new Error(`Asset ${t.motionController.assetUrl} missing or malformed.`)})}}).catch(o=>{console.warn(o)})}),e.addEventListener("disconnected",()=>{t.motionController=null,t.remove(s),s=null}),t}}const nm=re("debugavatar");class ub{constructor(e,t,s,r){h(this,"root"),h(this,"head"),h(this,"leftHand"),h(this,"rigthHand");var n;this.root=e,this.head=t,this.leftHand=s,this.rigthHand=r,(n=this.root)==null||n.traverse(o=>o.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class db{constructor(){h(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let s=null;if(typeof t=="string"){if(s=await this.loadAvatar(e,t),!s){const n=new Jo;s=$.instantiate(zu(t,e.scene),n)}}else s=t;if(!s)return null;const r=this.findAvatar(s);return r.isValid?(nm&&console.log("[Custom Avatar] valid config",t,nm?r:""),r):(console.warn("[Custom Avatar] config isn't valid",t,nm?r:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(nm&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const r=await fetch("./"+t);let n=null;if(r.ok){const a=await r.blob();a&&(n=await a.arrayBuffer())}if(!n&&(n=await DC(t,t,0,"no url here go away",!0),!n))return null;const o=await Eo().parseSync(e,n,null,0);return o?.scene??null}const s=new zd;return zg(s,e),new Promise((r,n)=>{const o=this.avatarRegistryUrl+"/"+t;s.load(o,async a=>{await Eo().createBuiltinComponents(e,o,a,null,void 0),r(a.scene)},a=>{nm&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),r(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let s=t;s.children.length==1&&(s=e.children[0]);let r=this.findAvatarPart(s,["head"]);const n=this.findAvatarPart(s,["left","hand"]),o=this.findAvatarPart(s,["right","hand"]);if(!r){r=t;const a=new S;new or().setFromObject(r).getSize(a);const l=Math.max(a.x,a.y,a.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+l+" meters! Should be < 0.3m"),l>.3&&r.scale.multiplyScalar(1/l*.3)}return new ub(t,r,n,o)}findAvatarPart(e,t){const s=e.name.toLowerCase();let r=!0;for(const n of t){if(!r)break;s.indexOf(n)===-1&&(r=!1)}if(r)return e;if(e.children)for(const n of e.children){const o=this.findAvatarPart(n,t);if(o)return o}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}const up=re("debugflags");var ls=(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))(ls||{});const C3=class{constructor(){h(this,"Mask",17)}Has(i){return(this.Mask&i)!==0}Set(i){up&&console.warn("Set XR flag state to",i),this.Mask=i,Lr.Apply()}Enable(i){this.Mask|=i,Lr.Apply()}Disable(i){this.Mask&=~i,Lr.Apply()}Toggle(i){this.Mask^=i,Lr.Apply()}EnableAll(){this.Mask=-1,Lr.Apply()}DisableAll(){this.Mask=0,Lr.Apply()}};let aa=C3;h(aa,"Global",new C3);const Al=class extends Ee{constructor(){super(...arguments),h(this,"visibleIn")}static Apply(){for(const i of this.registry)i.UpdateVisible(aa.Global)}awake(){Al.registry.push(this)}onEnable(){Al.firstApply?this.UpdateVisible(aa.Global):(Al.firstApply=!0,Al.Apply())}onDestroy(){const i=Al.registry.indexOf(this);i>=0&&Al.registry.splice(i,1)}get isOn(){return this.gameObject.visible}UpdateVisible(i=null){let e;const t=i;t&&typeof t=="number"&&(console.assert(typeof t=="number","XRFlag.UpdateVisible: state must be a number",t),up&&console.log(t),Al.buffer.Mask=t,i=Al.buffer);const s=i;if(s?(up&&console.warn(this.name,"use passed in mask",s.Mask,this.visibleIn),e=s.Has(this.visibleIn)):(up&&console.log(this.name,"use global mask"),aa.Global.Has(this.visibleIn)),e!==void 0)if(e)up&&console.log(this.name,"is visible",this.gameObject.uuid),$.setActive(this.gameObject,!0);else{if(up&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}};let Lr=Al;h(Lr,"registry",[]),h(Lr,"firstApply"),h(Lr,"buffer",new aa);const Nc=re("debugavatar"),la=class extends Ee{constructor(){super(...arguments),h(this,"connectionId"),h(this,"avatar")}static getAvatar(i){return i>=0&&i<la.instances.length?la.instances[i]:null}static onAvatarMarkerCreated(i){return la._onNewAvatarMarkerAdded.push(i),i}static onAvatarMarkerDestroyed(i){return la._onAvatarMarkerDestroyed.push(i),i}awake(){la.instances.push(this),Nc&&console.log(this);for(const i of la._onNewAvatarMarkerAdded)i({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){la.instances.splice(la.instances.indexOf(this),1);for(const i of la._onAvatarMarkerDestroyed)i({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}setVisible(i){this.avatar&&("setVisible"in this.avatar?this.avatar.setVisible(i):$.setActive(this.avatar,i))}};let fr=la;h(fr,"instances",[]),h(fr,"_onNewAvatarMarkerAdded",[]),h(fr,"_onAvatarMarkerDestroyed",[]);const pb=class{constructor(i,e,t){h(this,"_isVisible",!0),h(this,"guid"),h(this,"root",null),h(this,"head",null),h(this,"handLeft",null),h(this,"handRight",null),h(this,"lastUpdate",-1),h(this,"isLocalAvatar",!1),h(this,"flags",null),h(this,"headScale",new S(1,1,1)),h(this,"handLeftScale",new S(1,1,1)),h(this,"handRightScale",new S(1,1,1)),h(this,"webxr"),h(this,"lastAvatarId",null),h(this,"hasAvatarOverride",!1),h(this,"context"),h(this,"avatarMarker",null),h(this,"_headTarget",new Me),h(this,"_handLeftTarget",new Me),h(this,"_handRightTarget",new Me),h(this,"_canInterpolate",!1),this.context=i,this.guid=e,this.webxr=t,this.setupCustomAvatar(this.webxr.defaultAvatar)}setVisible(i){this._isVisible=i,this.updateVisibility()}get isWebXRAvatar(){return!0}updateFlags(){if(!this.flags)return;let i=this.isLocalAvatar?ls.FirstPerson:ls.ThirdPerson;this.context.isInVR?i|=ls.VR:this.context.isInAR?i|=ls.AR:i|=ls.Browser;for(const e of this.flags)e.gameObject.visible=!0,e.UpdateVisible(i)}async setAvatarOverride(i){return this.hasAvatarOverride=i!==null,this.hasAvatarOverride&&this.lastAvatarId!==i&&(this.lastAvatarId=i,i!=null&&i.length>0)?await this.setupCustomAvatar(i):null}tryUpdate(i,e){if(i.guid===this.guid&&(this.lastAvatarId!==i.avatarId&&i.avatarId&&i.avatarId.length>0&&(this.lastAvatarId=i.avatarId,this.setupCustomAvatar(i.avatarId)),this.lastUpdate=i.time,this.head)){const t=this.webxr.IsInAR?$o.Handheld:$o.Headset;let s=this.head;this.context.players.setPlayerView(i.guid,s,t),on.markDirty(this.head),this._canInterpolate=!0;const r=this.isLocalAvatar?this.head:this._headTarget;if(r.position.set(i.position.x,i.position.y,i.position.z),r.quaternion.set(i.rotation.x,i.rotation.y,i.rotation.z,i.rotation.w),r.scale.set(i.scale,i.scale,i.scale),r.scale.multiply(this.headScale),this.handLeft){const n=this.isLocalAvatar?this.handLeft:this._handLeftTarget;n.position.set(i.posLeftHand.x,i.posLeftHand.y,i.posLeftHand.z),n.quaternion.set(i.rotLeftHand._x,i.rotLeftHand._y,i.rotLeftHand._z,i.rotLeftHand._w),n.quaternion.multiply(pb.invertRotation),n.scale.set(i.scale,i.scale,i.scale),n.scale.multiply(this.handLeftScale),on.markDirty(this.handLeft)}if(this.handRight){const n=this.isLocalAvatar?this.handRight:this._handRightTarget;n.position.set(i.posRightHand.x,i.posRightHand.y,i.posRightHand.z),n.quaternion.set(i.rotRightHand._x,i.rotRightHand._y,i.rotRightHand._z,i.rotRightHand._w),n.quaternion.multiply(pb.invertRotation),n.scale.set(i.scale,i.scale,i.scale),n.scale.multiply(this.handRightScale),on.markDirty(this.handRight)}}}update(){if(this.isLocalAvatar||!this._canInterpolate)return;const i=this.context.time.deltaTime/.1;this.head&&(this.head.position.lerp(this._headTarget.position,i),this.head.quaternion.slerp(this._headTarget.quaternion,i),this.head.scale.lerp(this._headTarget.scale,i)),this.handLeft&&this._handLeftTarget&&(this.handLeft.position.lerp(this._handLeftTarget.position,i),this.handLeft.quaternion.slerp(this._handLeftTarget.quaternion,i),this.handLeft.scale.lerp(this._handLeftTarget.scale,i)),this.handRight&&this._handRightTarget&&(this.handRight.position.lerp(this._handRightTarget.position,i),this.handRight.quaternion.slerp(this._handRightTarget.quaternion,i),this.handRight.scale.lerp(this._handRightTarget.scale,i))}destroy(){var i,e;Nc&&console.log("Destroy avatar",this.guid),(i=this.root)==null||i.removeFromParent(),(e=this.avatarMarker)==null||e.destroy(),this.lastAvatarId=null,this.head&&Fr.Remove(this.context,this.head)}updateVisibility(){const i=this.root;i&&$.setActive(i,this._isVisible)}async setupCustomAvatar(i){var e,t,s;if(Nc&&console.log("LOAD",i,this),!i||typeof i=="string"&&i.length<=0)return!1;this.head&&Fr.Remove(this.context,this.head);const r=i;if(r?.loadAssetAsync!==void 0){await r.loadAssetAsync();const o=r.asset;$.setActive(o,!1),i=$.instantiate(o),$.setActive(i,!0)}Nc&&console.log(i);const n=await pb.loader.getOrCreateNewAvatarInstance(this.context,i);if(Nc&&console.log(n,n?.isValid,this.lastAvatarId,i),n!=null&&n.isValid){if(this.root=n.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=$.addNewComponent(this.root,fr),this.avatarMarker.connectionId=this.guid,this.avatarMarker.avatar=this,this.head&&this.head!==n.head&&((e=this.head)==null||e.removeFromParent()),this.head=n.head,this.headScale.copy(this.head.scale),this.head&&!this.isLocalAvatar&&Fr.Add(this.context,this.head,this.avatarMarker),n.leftHand&&((t=this.handLeft)==null||t.removeFromParent()),this.handLeft=n.leftHand??this.handLeft,this.handLeft?this.handLeftScale.copy(this.handLeft.scale):this.handLeftScale.set(1,1,1),n.rigthHand&&((s=this.handRight)==null||s.removeFromParent()),this.handRight=n.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(...$.getComponentsInChildren(this.root,Lr)),this.flags.length<=0&&this.head){const o=$.addNewComponent(this.head,Lr);o.visibleIn=ls.ThirdPerson|ls.VR,this.flags.push(o),Nc&&console.log("Added flag to head: "+o.visibleIn,this.head.name)}return Nc&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return Nc&&console.warn("build avatar failed"),!1}};let zc=pb;h(zc,"loader",new db),h(zc,"invertRotation",new Ce().setFromAxisAngle(new S(0,1,0),Math.PI));class Fr{static Add(e,t,s=null){if(t){for(const r of this.Pois)if(r.obj===t)return;this.Pois.push({obj:t,avatar:s}),this.LastChangeTime=e.time.time}}static Remove(e,t){var s;if(t){for(const r of this.Pois)if(r.obj===t){this.Pois.splice(this.Pois.indexOf(r),1),this.LastChangeTime=e?.time.time??((s=Lt.Current)==null?void 0:s.time.time);return}}}}h(Fr,"Pois",[]),h(Fr,"LastChangeTime",0);class DK{constructor(){h(this,"guid"),h(this,"position",new S)}}class om extends Ee{constructor(){super(...arguments),h(this,"target",null),h(this,"avatar",null),h(this,"_model",null),h(this,"_targetModel",new DK),h(this,"_currentTargetObject",null),h(this,"_lastUpdateTime",0),h(this,"_lookDuration",0),h(this,"_lastPoiChangedTime",0)}set controlledTarget(e){this.target=e;const t=j.get("MoveRandom");if(t&&this.target){const s=$.getComponent(this.target,t);s&&s.destroy()}}awake(){if(this.avatar=$.getComponentInParent(this.gameObject,fr),this.avatar){const e=$.getComponentInParent(this.gameObject,fr);this._model=new ny(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)&&Ki(this.target,e.position)})}update(){var e;if((!this.context.connection.isConnected||(e=this._model)!=null&&e.hasOwnership)&&(Fr.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Fr.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const t=xt(this._currentTargetObject);Ki(this.target,t),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(t))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const e=Fr.Pois;if(e.length>0){const t=e[Math.floor(Math.random()*e.length)];if(t&&t.obj){if(t.avatar&&t.avatar===this.avatar)return;this._currentTargetObject=t.obj}}}}}class dp extends Ee{constructor(){super(...arguments),h(this,"canGrab",!0)}onPointerClick(e){}}class pp extends Ee{constructor(){super(...arguments),h(this,"isUsed",!0),h(this,"usedBy",null)}}var ca=(i=>(i[i.Average=0]="Average",i[i.Multiply=1]="Multiply",i[i.Minimum=2]="Minimum",i[i.Maximum=3]="Maximum",i))(ca||{}),fb=(i=>(i[i.Discrete=0]="Discrete",i[i.Continuous=1]="Continuous",i))(fb||{}),$i=(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))($i||{}),fp=(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))(fp||{});const vn=function(i,e){return function(t,s,r){OK(t,s,r,i,e)}};function OK(i,e,t,s,r){if(!(!r&&!s&&!i.onValidate)){if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",i,e,t),rs("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,fo.Error);return}if(i.__internalAwake){const n=Symbol(e),o=i.__internalAwake;i.__internalAwake=function(){this[n]===void 0&&(this[n]=this[e],Object.defineProperty(this,e,{set:function(a){var l;if(this[N1]===!0)this[n]=a;else{s?.call(this,a);const c=this[n];this[n]=a,(l=this.onValidate)==null||l.call(this,e,c)}},get:function(){return r?.call(this),this[n]}})),o.call(this)}}}}const LK=function(i){return function(e,t,s){const r=i.prototype,n=Object.getOwnPropertyDescriptor(r,t);if(!(n!=null&&n.value)){console.warn("Can not apply prefix: type does not have method named",t,i);return}const o=n.value,a=e[t];Object.defineProperty(r,t,{value:function(...l){const c=a?.call(this,...l);if(c instanceof Promise){c.then(u=>{if(u!==!1)return o.call(this,...l)});return}if(c!==!1)return o.call(this,...l)}})}};var FK=Object.defineProperty,UK=Object.getOwnPropertyDescriptor,yl=(i,e,t,s)=>{for(var r=s>1?void 0:s?UK(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&FK(e,t,r),r};class NK{constructor(e,t){h(this,"positionChanged",!1),h(this,"rotationChanged",!1),h(this,"position"),h(this,"quaternion"),h(this,"_positionKeys",["x","y","z"]),h(this,"_quaternionKeys",["_x","_y","_z","_w"]),h(this,"mute",!1),h(this,"context"),h(this,"obj"),h(this,"_positionWatch"),h(this,"_rotationWatch"),this.context=t,this.obj=e}get isDirty(){return this.positionChanged||this.rotationChanged}reset(e=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,e){if(this.position)for(const t of this._positionKeys)delete this.position[t];if(this.quaternion)for(const t of this._quaternionKeys)delete this.quaternion[t]}}syncValues(){for(const e of this._positionKeys)this.position[e]=this.obj.position[e];for(const e of this._quaternionKeys)this.quaternion[e]=this.obj.quaternion[e]}applyValues(){if(this.positionChanged&&this.position)for(const e of this._positionKeys){const t=this.position[e];t!==void 0&&(this.obj.position[e]=t)}if(this.rotationChanged&&this.quaternion)for(const e of this._quaternionKeys){const t=this.quaternion[e];t!==void 0&&(this.obj.quaternion[e]=t)}}start(e,t){this.reset(),e&&(this._positionWatch||(this._positionWatch=new hf(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((n,o)=>{var a;if((a=this.context.physics.engine)!=null&&a.isUpdating||this.mute)return;const l=this.position[o];Math.abs(l-n)<1e-5||(this.position[o]=n,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new hf(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((n,o)=>{var a;if((a=this.context.physics.engine)!=null&&a.isUpdating||this.mute)return;const l=this.quaternion[o];Math.abs(l-n)<1e-5||(this.quaternion[o]=n,this.rotationChanged=!0)}));const s=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),r=new Pe;this.obj.matrixWorld.multiplyMatrices=(n,o)=>(r.equals(n)||(this.positionChanged=!0,this.rotationChanged=!0,r.copy(n)),s(n,o))}stop(){var e,t;(e=this._positionWatch)==null||e.revoke(),(t=this._rotationWatch)==null||t.revoke()}}var eE;const tE=(eE=class extends Ee{constructor(){super(...arguments),h(this,"mass",1),h(this,"useGravity",!0),h(this,"constraints",$i.None),h(this,"isKinematic",!1),h(this,"drag",0),h(this,"angularDrag",1),h(this,"detectCollisions",!0),h(this,"sleepThreshold",.01),h(this,"collisionDetectionMode",fb.Discrete),h(this,"_gravityScale",1),h(this,"_propertiesChanged",!1),h(this,"_currentVelocity",new S),h(this,"_smoothedVelocity",new S),h(this,"_smoothedVelocityGetter",new S),h(this,"_lastPosition",new S),h(this,"_watch")}get lockPositionX(){return(this.constraints&$i.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&$i.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&$i.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&$i.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&$i.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&$i.FreezeRotationZ)!==0}set lockPositionX(i){i?this.constraints|=$i.FreezePositionX:this.constraints&=~$i.FreezePositionX}set lockPositionY(i){i?this.constraints|=$i.FreezePositionY:this.constraints&=~$i.FreezePositionY}set lockPositionZ(i){i?this.constraints|=$i.FreezePositionZ:this.constraints&=~$i.FreezePositionZ}set lockRotationX(i){i?this.constraints|=$i.FreezeRotationX:this.constraints&=~$i.FreezeRotationX}set lockRotationY(i){i?this.constraints|=$i.FreezeRotationY:this.constraints&=~$i.FreezeRotationY}set lockRotationZ(i){i?this.constraints|=$i.FreezeRotationZ:this.constraints&=~$i.FreezeRotationZ}set gravityScale(i){this._gravityScale=i}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new NK(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),mn.LateUpdate)}onDisable(){var i,e;(i=this._watch)==null||i.stop(),(e=this.context.physics.engine)==null||e.removeBody(this)}onDestroy(){var i;(i=this.context.physics.engine)==null||i.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(var i,e,t,s;;)this._propertiesChanged&&(this._propertiesChanged=!1,(i=this.context.physics.engine)==null||i.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()):(s=this._watch)==null||s.syncValues(),this.captureVelocity(),yield}teleport(i,e=!0){var t;(t=this._watch)==null||t.reset(!0),e?this.gameObject.position.set(i.x,i.y,i.z):this.setWorldPosition(i.x,i.y,i.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(){var i;(i=this.context.physics.engine)==null||i.resetForces(this,!0)}resetTorques(){var i;(i=this.context.physics.engine)==null||i.resetTorques(this,!0)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var i;(i=this.context.physics.engine)==null||i.wakeup(this)}applyForce(i,e){var t;(t=this.context.physics.engine)==null||t.addForce(this,i,!0)}applyImpulse(i){var e;(e=this.context.physics.engine)==null||e.applyImpulse(this,i,!0)}setForce(i,e,t){var s,r;(s=this.context.physics.engine)==null||s.resetForces(this,!0),(r=this.context.physics.engine)==null||r.addForce(this,{x:i,y:e,z:t},!0)}getVelocity(){var i;const e=(i=this.context.physics.engine)==null?void 0:i.getLinearVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(i,e,t){var s,r;if(i instanceof S){const n=i;(s=this.context.physics.engine)==null||s.setLinearVelocity(this,n,!0);return}e===void 0||t===void 0||(r=this.context.physics.engine)==null||r.setLinearVelocity(this,{x:i,y:e,z:t},!0)}setAngularVelocity(i,e,t){var s,r;if(i instanceof S){const n=i;(s=this.context.physics.engine)==null||s.setAngularVelocity(this,n,!0);return}e===void 0||t===void 0||(r=this.context.physics.engine)==null||r.setAngularVelocity(this,{x:i,y:e,z:t},!0)}getAngularVelocity(){var i;const e=(i=this.context.physics.engine)==null?void 0:i.getAngularVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setTorque(i,e,t){this.setAngularVelocity(i,e,t)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(i=null){}captureVelocity(){const i=xt(this.gameObject);tE.tempPosition.copy(i);const e=i.sub(this._lastPosition);this._lastPosition.copy(tE.tempPosition),this._smoothedVelocity.lerp(e,this.context.time.deltaTime/.1)}},h(eE,"tempPosition",new S),eE);let Ni=tE;yl([vn(),w()],Ni.prototype,"mass",2),yl([vn(),w()],Ni.prototype,"useGravity",2),yl([vn(),w()],Ni.prototype,"constraints",2),yl([vn(),w()],Ni.prototype,"isKinematic",2),yl([vn(),w()],Ni.prototype,"drag",2),yl([vn(),w()],Ni.prototype,"angularDrag",2),yl([vn(),w()],Ni.prototype,"detectCollisions",2),yl([vn(),w()],Ni.prototype,"sleepThreshold",2),yl([vn(),w()],Ni.prototype,"collisionDetectionMode",2);class An{constructor(){h(this,"bb",null),h(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(e,t,s,r){return e.prep(4,12),e.writeFloat32(r),e.writeFloat32(s),e.writeFloat32(t),e.offset()}}class S3{constructor(){h(this,"bb",null),h(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new An).__init(this.bb_pos,this.bb)}rotation(e){return(e||new An).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new An).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,s,r,n,o,a,l,c,u){return e.prep(4,36),e.prep(4,12),e.writeFloat32(u),e.writeFloat32(c),e.writeFloat32(l),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(o),e.writeFloat32(n),e.prep(4,12),e.writeFloat32(r),e.writeFloat32(s),e.writeFloat32(t),e.offset()}}class Hl{constructor(){h(this,"bb",null),h(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new Hl).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+W0),(t||new Hl).__init(e.readInt32(e.position())+e.position(),e)}guid(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){const e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){const t=this.bb.__offset(this.bb_pos,8);return t?(e||new S3).__init(this.bb_pos+t,this.bb):null}dontSave(){const e=this.bb.__offset(this.bb_pos,10);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startSyncedTransformModel(e){e.startObject(4)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addFast(e,t){e.addFieldInt8(1,+t,0)}static addTransform(e,t){e.addFieldStruct(2,t,0)}static addDontSave(e,t){e.addFieldInt8(3,+t,0)}static endSyncedTransformModel(e){return e.endObject()}static finishSyncedTransformModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedTransformModelBuffer(e,t){e.finish(t,void 0,!0)}}const Qc=re("debugsync"),am="STRS";q1(am,Hl.getRootAsSyncedTransformModel);const ha=new gf;function E3(i,e,t=!0){ha.clear();const s=ha.createString(i);Hl.startSyncedTransformModel(ha),Hl.addGuid(ha,s),Hl.addFast(ha,t);const r=e.worldPosition,n=e.worldEuler,o=e.gameObject.scale;Hl.addTransform(ha,S3.createTransform(ha,r.x,r.y,r.z,n.x,n.y,n.z,o.x,o.y,o.z));const a=Hl.endSyncedTransformModel(ha);return ha.finish(a,am),ha.asUint8Array()}class jc extends Ee{constructor(){super(...arguments),h(this,"overridePhysics",!0),h(this,"interpolatePosition",!0),h(this,"interpolateRotation",!0),h(this,"fastMode",!1),h(this,"syncDestroy",!1),h(this,"_model",null),h(this,"_needsUpdate",!0),h(this,"rb",null),h(this,"_wasKinematic",!1),h(this,"_receivedDataBefore",!1),h(this,"_targetPosition"),h(this,"_targetRotation"),h(this,"_receivedFastUpdate",!1),h(this,"_shouldRequestOwnership",!1),h(this,"joinedRoomCallback",null),h(this,"receivedDataCallback",null),h(this,"tempEuler",new vs),h(this,"receivedUpdate",!1),h(this,"lastWorldPos"),h(this,"lastWorldRotation")}requestOwnership(){Qc&&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(){Qc&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new S,this._targetRotation=new Ce,this.lastWorldPos=new S,this.lastWorldRotation=new Ce,this.rb=$.getComponentInChildren(this.gameObject,Ni),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new ny(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(ji.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(am,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Tk(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(ji.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(am,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){Qc&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();const s=e.transform();if(s){on.markDirty(this.gameObject,!0);const r=s.position();r&&(this.interpolatePosition&&((t=this._targetPosition)==null||t.set(r.x(),r.y(),r.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(r.x(),r.y(),r.z()));const n=s.rotation();n&&(this.tempEuler.set(n.x(),n.y(),n.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&VB(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){Qc&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());let e=this.worldPosition,t=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const n=e.distanceTo(this.lastWorldPos),o=t.angleTo(this.lastWorldRotation),a=this._model.hasOwnership||this.fastMode?1e-4:.001;(n>a||o>a)&&(this._model.hasOwnership?this._needsUpdate=!0:(Qc&&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),on.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const n=this._receivedFastUpdate||this.fastMode?.5:.3;let o=!1;if(this.interpolatePosition&&this._targetPosition){const a=this.worldPosition;a.lerp(this._targetPosition,n),this.worldPosition=a,o=!0}if(this.interpolateRotation&&this._targetRotation){const a=this.worldQuaternion;a.slerp(this._targetRotation,n),this.worldQuaternion=a,o=!0}o&&on.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&&(Qc&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new S(0,0,0))>1e3&&(Qc&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0)));const s=10,r=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%s===0||r)){Qc&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this.overridePhysics&&this.rb,this._needsUpdate=!1;const n=E3(this.guid,this,!!r);this.context.connection.sendBinary(n)}}}var Bo={};Bo.d=(i,e)=>{for(var t in e)Bo.o(e,t)&&!Bo.o(i,t)&&Object.defineProperty(i,t,{enumerable:!0,get:e[t]})},Bo.o=(i,e)=>Object.prototype.hasOwnProperty.call(i,e),Bo.r=i=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(i,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(i,"__esModule",{value:!0})};var cs={};Bo.d(cs,{w8:()=>ci,cg:()=>iU,gO:()=>Yv,wb:()=>iE,zV:()=>ru,HS:()=>lm,Ec:()=>su,gF:()=>vf,ol:()=>Jv,pz:()=>j3,tx:()=>po,hj:()=>sE,FV:()=>mm,sV:()=>DF,xv:()=>Kv,mx:()=>N3,gE:()=>z3,ZP:()=>Iee,Vx:()=>sU});var iE={};Bo.r(iE),Bo.d(iE,{get:()=>M3,set:()=>zK});var sE={};Bo.r(sE),Bo.d(sE,{alphaTestTransformer:()=>yb,asPreprocessorValueTransformer:()=>G3,toPreprocessorTriggerTransformer:()=>mE,toUserDataTransformer:()=>KJ,uniformOrUserDataTransformer:()=>$n});const rE={fontFamily:null,fontSize:.05,fontKerning:"normal",fontStyle:"normal",fontWeight:"400",offset:.005,lineHeight:1.2,lineBreak:`- ,.:?!
4180
4180
  `,whiteSpace:"pre-line",flexDirection:"column",justifyContent:"start",alignItems:"start",backgroundImage:null,textAlign:"left",boxSizing:"content-box",position:"static",color:16777215,fontColor:16777215,fontOpacity:1,opacity:1,fontPXRange:4,fontSupersampling:!0,fontSmooth:"antialiased",borderRadius:0,borderWidth:0,borderColor:"black",borderOpacity:1,backgroundSize:"cover",backgroundColor:0,backgroundOpacity:0,overflow:"visible",letterSpacing:0,invertAlpha:!1,segments:1},zK=function(i){for(const e in i)rE[e]=i[e]},M3=function(i){return Object.prototype.hasOwnProperty.call(rE,i)||console.warn(`ThreeMeshUI::DefaultValues is trying to retrieve non-existing property '${i}'`),rE[i]};class ci{constructor(e,t=null,s=!0){this._id=e,this._value=t,this._needsUpdate=!0,this._needsProcess=!1,this._needsRender=!1,this._isPrimitive=s}get id(){return this._id}get value(){return this._value}set value(e){this.isValid(e)&&this._value!==e&&(this._value=e,this._needsUpdate=!0)}update(e,t){this.output(t)}output(e){}_outputValue(e){e[this._id]=this._value}process(e){}render(e){}getInheritedInput(e){if(this._value!=="inherit")return this._value;const t=e._parent._value;return t&&t[`_${this._id}`]?t[`_${this._id}`].getInheritedInput(t):this.getDefaultValue()}getDefaultValue(){return M3(this._id)}isValid(e){return!0}emptyStrategyLogic(){throw new Error(`ThreeMeshUI::${this.constructor.name} has empty strategy. Update has not been processed.`)}requestUpdate(){this._needsUpdate=!0}requestProcess(){this._needsProcess=!1}requestRender(){this._needsRender=!1}}class QK extends ci{constructor(){super("renderOrder","auto",!0),this.output=this._outputValue,this._actualValue=0}set value(e){this.isValid(e)&&(this._value=e,this._needsUpdate=!0)}update(e,t){if(this._value!=="auto")this._actualValue=this._value;else{const s=e._parent._value;if(s!==null){const r=s._renderOrder._actualValue,n=1+s._children._uis.indexOf(e);this._actualValue=r+n}}for(const s of e._children._uis)s._renderOrder._value==="auto"&&(s._renderOrder._needsUpdate=!0);this._outputValue(t)}_outputValue(e){e[this._id]=this._actualValue}get value(){return this._value}}class su extends ci{constructor(e,t=null,s=!0){super(e,t,s),this.output=this._outputValue,this._notInheritedValue=null}update(e,t){this._notInheritedValue=this._value,this._notInheritedValue==="inherit"&&(this._notInheritedValue=this.getInheritedInput(e)),this.propagate(e),this._outputValue(t)}propagate(e){for(const t of e._children._uis){const s=t[`_${this._id}`];s!==void 0&&s._value==="inherit"&&(t[`_${this._id}`]._needsUpdate=!0)}}_outputValue(e){e[this._id]=this._notInheritedValue}set value(e){this.isValid(e)&&this._value!==e&&(this._value=e,this._needsUpdate=!0)}get value(){return this._value==="inherit"?this._notInheritedValue:this._value}}class jK extends su{constructor(){super("offset","inherit",!1)}update(e,t){super.update(e,t),e._parent._value!==null&&(e.position.z=this._notInheritedValue)}}class GK extends su{constructor(){super("fontSmooth","inherit",!0),this._needsUpdate=!1,this.isValid=VK,this.output=this._outputValue}}const HK=["inherit","none","antialiased"];function VK(i){return HK.indexOf(i)===-1?(console.warn(`.fontSmoothing value '${i}' is not valid. Aborted`),!1):!0}var WK=i=>{var e={};return Bo.d(e,i),e};const Ke=WK({BackSide:()=>As,BufferAttribute:()=>tt,BufferGeometry:()=>mt,Color:()=>be,DoubleSide:()=>bi,EventDispatcher:()=>bs,FileLoader:()=>Cs,FrontSide:()=>wr,LinearFilter:()=>Pt,Mesh:()=>ve,Object3D:()=>Me,Plane:()=>Fn,PlaneGeometry:()=>Ns,ShaderMaterial:()=>Bt,Texture:()=>Ft,TextureLoader:()=>uc,Vector2:()=>W,Vector3:()=>S,Vector4:()=>st});class Ti extends ci{constructor(e,t,s=!0){super(e,"unset",s),this._input="inherit",this._allowsInherit=!0,this._inheritedInput=void 0,this._inline=void 0}update(e,t){this._allowsInherit||(this._inheritedInput=this.getInheritedInput(e)),this.computeOutputValue(e);for(const s of e._children._uis){const r=s[`_${this._id}`];(r._input?r._input:r._value)==="inherit"&&(s[`_${this._id}`]._needsUpdate=!0)}this.output(t)}computeOutputValue(e){this._value=this._input}_computeFromInherited(e){this._value=this._inheritedInput}set value(e){console.warn(".(style) sub-property cannot be directly set. It must comes from inline or computed setter.")}set inline(e){this.isValidValue(e)&&e!==this._inline&&(this._input=this._inline=e,this._needsUpdate=!0)}get inline(){return this._inline}isValidValue(e){return!0}getInheritedInput(e){if(this._input!=="inherit")return this._input;const t=e._parent._value;return t?t[`_${this._id}`].getInheritedInput(t):this.getDefaultValue()}}class gb extends Ti{constructor(e,t){super(e,t,!1),this._input=new Ke.Vector4(0,0,0,0),this._inline=null,this._value=new Ke.Vector4(0,0,0,0)}get value(){return this._value}computeOutputValue(e){this._vector4ValueSetter(this._value,this._input)}set inline(e){this._vector4ValueSetter(this._input,e),!this._input.equals(this._value)&&(this._needsUpdate=!0)}set top(e){this._input.x!==e&&(this._input.x=e,this._needsUpdate=!0)}get top(){return this._input.x}set right(e){this._input.y!==e&&(this._input.y=e,this._needsUpdate=!0)}get right(){return this._input.y}set bottom(e){this._input.z!==e&&(this._input.z=e,this._needsUpdate=!0)}get bottom(){return this._input.z}set left(e){this._input.w!==e&&(this._input.w=e,this._needsUpdate=!0)}get left(){return this._input.w}dispose(){this._computed=null,this._inline=null,this._input=null,this._output=null}_vector4ValueSetter(e,t){if(t instanceof Ke.Vector4){e.copy(t);return}if((typeof t=="string"||t instanceof String)&&(t=t.split(" ")),Array.isArray(t))switch(t=t.map(s=>parseFloat(s)),t.length){case 1:e.setScalar(t[0]);return;case 2:e.x=e.z=t[0],e.y=e.w=t[1];return;case 3:e.x=t[0],e.y=t[1],e.z=t[2];return;case 4:e.x=t[0],e.y=t[1],e.z=t[2],e.w=t[3];return;default:console.error("StyleVector4Property::set() Four Dimension property had more than four values");return}isNaN(t)||e.setScalar(t)}}class qK extends gb{constructor(){super("padding",new Ke.Vector4(0,0,0,0))}computeOutputValue(e){super.computeOutputValue(e),e._bounds._needsUpdate=!0,e._bounds._needsRender=!0,e._layouter._needsProcess=!0,e._renderer._needsRender=!0,e._parent._value&&(e._parent._value._layouter._needsProcess=!0)}}class XK extends gb{constructor(){super("margin",new Ke.Vector4(0,0,0,0))}computeOutputValue(e){super.computeOutputValue(e),e._renderer._needsRender=!0,e._parent._value&&(e._parent._value._flexDirection._needsProcess=!0)}}const I3=function(i,e,t){i[e]=t},YK=function(i,e,t){t!==null&&(i[e]=t)};class mb{constructor(e){this._definition=e}set definition(e){this._definition=e}mediate(e,t,s,r=null){for(const n in this._definition){const o=this._definition[n];if(s[n]!==void 0){const a=o.t?o.t:I3;a(t,o.m,s[n]),r&&a(r,o.m,s[n])}}}static mediate(e,t,s,r,n=null){if(t)for(const o in r){const a=r[o];if(s[o]!==void 0){const l=a.t?a.t:I3;l(t,a.m,s[o]),n&&l(n,a.m,s[o])}}}}class KK extends ci{constructor(){super("parent",null,!1)}update(e,t){e.parent&&e.parent.isUI?this._value=e.parent:this._value=null}set value(e){console.warn("ParentProperty is readonly")}get value(){return this._value}find(e){return this._value?e(this._value)?this._value:this._value._parent.find(e):null}dispose(){this._value=null}}const nE=function(i,e,t=6){return i.toFixed(t)===e.toFixed(t)};class T3 extends ci{constructor(e,t){super(e,t,!0),this.output=this._outputValue}set value(e){this.isValid(e)&&(nE(this._value,e)||(this._value=e,this._needsUpdate=!0))}get value(){return this._value}}class R3 extends su{constructor(e){super(e,"inherit",!0),this.isValid=ZK}}const JK=[Ke.FrontSide,Ke.BackSide,Ke.DoubleSide];function ZK(i){return JK.indexOf(i)===-1?(console.warn(`SideProperty value '${i}' is not valid. Abort`),!1):!0}class $K extends Ke.EventDispatcher{constructor(e,t){super(),this._isReady=!1,this._weight=e,this._style=t,this._size=42,this._lineHeight=42,this._lineBase=42,this._font=null}get typographic(){return this._font}get isReady(){return this._isReady}get weight(){return this._weight}get style(){return this._style}get texture(){return this._texture}set fontMaterial(e){throw Error(`FontVariant('${this.id}')::fontMaterial - is abstract.`)}get fontMaterial(){throw Error(`FontVariant('${this.id}')::fontMaterial - is abstract.`)}get id(){return`${this._name}(w:${this.weight},s:${this.style})`}getTypographicGlyph(e){let t=this._chars[e];if(t)return t;if(e.match(/\s/))return this._chars[" "];const s=this._getFallbackCharacter(e);if(s&&(t=this._chars[s],t))return t;throw Error(`FontVariant('${this.id}')::getTypographicGlyph() - character('${e}') and/or fallback character were not found in provided msdf charset.`)}_getFallbackCharacter(e){throw new Error(`FontVariant(${typeof this})::_getFallbackCharacter() is abstract and should therefore be overridden.`)}getGeometricGlyph(e,t){throw new Error(`FontVariant(${typeof this})::getGeometryCharacter() is abstract and should therefore be overridden.`)}getKerningAmount(e){return this._kernings[e]?this._kernings[e]:0}adjustTypographicGlyphs(e){for(const t in e){const s=this.getTypographicGlyph(t),r=e[t];for(const n in r)s["_"+n]=e[t][n]}}_checkReadiness(){this._readyCondition()&&tJ(this)}_alterElementProperties(e){throw new Error(`FontVariant(${typeof this})::_alterElementProperties() is abstract and should therefore be overridden.`)}_readyCondition(){throw new Error(`FontVariant(${typeof this})::_readyCondition() is abstract and should therefore be overridden.`)}}const eJ={type:"ready"};function tJ(i){i._isReady=!0,i.dispatchEvent(eJ)}const lm=$K;class iJ extends ci{constructor(e=null){super("font",e,!1),this._needsUpdate=!1,this._fontVariant=null,this._handleFontReadyClosure=null,this.isValid=sJ}output(e){e[this._id]=this._fontVariant}update(e,t){if(this._fontVariant&&!this._fontVariant.isReady&&this._fontVariant.removeEventListener("ready",this._handleFontReadyClosure),this._value&&this._value instanceof lm)this._fontVariant=this._value;else{const s=e._fontFamily._value;s&&(this._fontVariant=s.getVariant(e._fontWeight._value,e._fontStyle._value))}this._fontVariant&&(this._fontVariant._alterElementProperties(e),this._handleFontReadyClosure=rJ(e,this),this._fontVariant.isReady?this._handleFontReadyClosure():this._fontVariant.addEventListener("ready",this._handleFontReadyClosure),(!e._fontMaterial._defaultMaterial||!(e._fontMaterial._defaultMaterial instanceof this._fontVariant.fontMaterial))&&(e._fontMaterial._defaultMaterial=new this._fontVariant.fontMaterial,e._fontMaterial._needsUpdate=!0))}set value(e){this.isValid(e)&&this._value!==e&&(this._value=e,this._needsUpdate=!0)}get value(){return this._value}get fontVariant(){return this._fontVariant}dispose(){this._handleFontReadyClosure&&(this._fontVariant.removeEventListener("ready",this._handleFontReadyClosure),this._handleFontReadyClosure=null),this._value=null,this._fontVariant=null}}function sJ(i){return i instanceof lm?!0:(console.warn(`.font value '${i}' is not valid. It requires a FontVariant instance. Aborted`),!1)}function rJ(i,e){return function(){e._needsUpdate=!0,i._glyphs._needsProcess=!0,e._fontVariant.removeEventListener("ready",e._handleFontReadyClosure),e._handleFontReadyClosure=null}}class nJ extends Ti{constructor(e){super("display",e),this._value="flex",this._allowsInherit=!1,this._needsUpdate=!1,this.isValidValue=aJ}computeOutputValue(e){e._visible._value=this._output!=="none"}}const oJ=["none","flex"];function aJ(i){return oJ.indexOf(i)===-1?(console.warn(`(.style) display value '${i}' is not valid. Aborted`),!1):!0}class lJ extends Ti{constructor(e){super("boxSizing",e),this._allowsInherit=!1,this.isValidValue=hJ}computeOutputValue(e){this._value=this._inheritedInput,e._bounds._needsUpdate=!0}}const cJ=["border-box","content-box"];function hJ(i){return cJ.indexOf(i)===-1?(console.warn(`(.style) boxSizing value '${i}' is not valid. Aborted`),!1):!0}class cm extends Ti{constructor(e,t){super(e,t,!1),this._value=new Ke.Color,this.output=this._outputValue}computeOutputValue(e){this._input!=="inherit"&&this._value.set(this._input)}set inline(e){this._input=this._inline=e,this._needsUpdate=!0}}class oE extends Ti{constructor(e,t){super(e,t,!0),this.isValidValue=uJ,this._allowsInherit=!1,this._input=t,this._value=t,this.output=this._outputValue,this.computeOutputValue=this._computeFromInherited}_outputValue(e){e[this._id]=this._inheritedInput}}function uJ(i){return i<0&&i>1?(console.warn(`(.style) styleFactorProperty('${this.id}') value '${i}' is not valid)`),!1):!0}class dJ extends Ti{constructor(e){super("backgroundImage",e,!0),this._input=null,this._allowsInherit=!1,this._textureSize=new Ke.Vector2(1,1),this.isValidValue=pJ}get value(){return this._value}output(e){e[this._id]=this._value,e.tSize=this._textureSize}computeOutputValue(e){if(this._value=this._inheritedInput,this._value instanceof Ke.Texture&&!this._value.image){console.warn("ThreeMeshUI - .backgroundImage :: Please provide preloaded texture in order to have accurate sizing.");return}this._needsProcess=!0}process(e){this._value?this._textureSize.set(this._value.image.width,this._value.image.height):this._textureSize.set(1,1)}}function pJ(i){return!0}class fJ extends Ti{constructor(e){super("backgroundSize",e,!0),this.isValidValue=mJ,this.output=this._outputValue}}const gJ=["cover","contain","stretch"];function mJ(i){return gJ.indexOf(i)===-1?(console.warn(`(.style) backgroundSize value '${i}' is not valid. Aborted`),!1):!0}class vJ extends Ti{constructor(e){super("overflow",e,!0),this.isValidValue=yJ,this._clippingPlanes=null,this._renderStrategy=this._emptyRender}update(e,t){this._inline!==void 0&&this._inline!=="unset"?this._input=this._inline:this._computed!==void 0&&(this._input=this._computed),this._allowsInherit||(this._inheritedInput=this.getInheritedInput(e)),this.computeOutputValue(e);for(const s of e._children._uis)s._overflow._needsUpdate=!0;this.output(t)}output(e){e.clippingPlanes=this._clippingPlanes}computeOutputValue(e){super.computeOutputValue(e),this._value==="hidden"?this._renderStrategy=this._propagateRender:(this._renderStrategy=this._emptyRender,this._clippingPlanes=null);const t=e._parent._value;if(t!==null){const s=t._overflow;if((s._value==="hidden"||s._clippingPlanes!==null)&&!this._clippingPlanes){this._clippingPlanes=[new Ke.Plane(new Ke.Vector3(0,-1,0),1),new Ke.Plane(new Ke.Vector3(-1,0,0),1),new Ke.Plane(new Ke.Vector3(0,1,0),1),new Ke.Plane(new Ke.Vector3(1,0,0),1)];for(let r=0;r<this._clippingPlanes.length;r++)this._clippingPlanes[r].parent=t;s._clippingPlanes!==null&&this._clippingPlanes.push(...s._clippingPlanes),this._renderStrategy=this._hiddenRender,this._needsRender=!0}else(s._value==="visible"||s._clippingPlanes===null)&&this._clippingPlanes!==null&&(this._clippingPlanes=null,this._renderStrategy=this._emptyRender,this._needsRender=!0)}}render(e){this._renderStrategy(e)}_emptyRender(e){}_hiddenRender(e){const t=e._parent._value,s=t._bounds._offsetHeight,r=t._bounds._offsetWidth,n=t._padding._value,o=t._borderWidth._value;for(let a=0;a<4&&a<this._clippingPlanes.length;a++){const l=this._clippingPlanes[a];switch(a%4){case 0:l.constant=s/2-(n.x+o.x);break;case 1:l.constant=r/2-(n.y+o.y);break;case 2:l.constant=s/2-(n.z+o.z);break;case 3:l.constant=r/2-(n.w+o.w);break}l.applyMatrix4(t.matrixWorld)}for(let a=0;a<e._children._uis.length;a++){const l=e._children._uis[a];l._overflow._needsRender=!0}}_propagateRender(e){for(let t=0;t<e._children._uis.length;t++){const s=e._children._uis[t];s._overflow._needsRender=!0}}}const AJ=["visible","hidden"];function yJ(i){return AJ.indexOf(i)===-1?(console.warn(`(.style) overflow value '${i}' is not valid. Aborted`),!1):!0}const gp="rem",P3="em",vb="%",bJ=[gp,P3,vb],B3=function(i){return bJ.indexOf(i)===-1?gp:i};class xJ extends gb{constructor(e){super("borderRadius",e),this._valueUV=this._value.clone(),this._input=new Ke.Vector4(0,0,0,0),this._mediation=!0,this._cornerTL=new Ke.Vector2(0,1),this._cornerTR=new Ke.Vector2(1,1),this._cornerBR=new Ke.Vector2(1,0),this._cornerBL=new Ke.Vector2(0,0);const t=new Ab(this._valueUV,["x","y"]),s=new Ab(this._valueUV,["z","w"]),r=new Ab(this._valueUV,["x","w"]),n=new Ab(this._valueUV,["y","z"]);t.complementaryMediation=s,s.complementaryMediation=t,r.complementaryMediation=n,n.complementaryMediation=r,this._sideMediators=[t,s,r,n],this._units=gp}set units(e){this._units=B3(e),this._needsProcess=!0}get units(){return this._units}set mediation(e){e!==this._mediation&&(this._mediation=e,this._needsUpdate=!0)}get mediation(){return this._mediation}output(e){e.cornerTL=this._cornerTL,e.cornerTR=this._cornerTR,e.cornerBR=this._cornerBR,e.cornerBL=this._cornerBL}computeOutputValue(e){this._vector4ValueSetter(this._value,this._input),this._needsProcess=!0}process(e){this._needsRender=!0}render(e){this._valueUV.copy(this._value);const t=e._bounds._offsetWidth,s=e._bounds._offsetHeight;if(this._units===vb&&this._valueUV.divideScalar(100),this._units===gp&&this._valueUV.divideScalar(Math.min(t,s)),this._mediation)do this._sideMediators.forEach(o=>o.computeValue()),this._sideMediators.sort((o,a)=>o.value<a.value?1:-1),this._sideMediators[0].value>1&&this._sideMediators[0].mediate();while(this._sideMediators[0].value>1);let r=t>s?s/t:1,n=t<s?t/s:1;this._units===vb&&(r=n=1),this._cornerTL.x=this._valueUV.x*r,this._cornerTL.y=1-this._valueUV.x*n,this._cornerTR.x=1-this._valueUV.y*r,this._cornerTR.y=1-this._valueUV.y*n,this._cornerBR.x=1-this._valueUV.z*r,this._cornerBR.y=this._valueUV.z*n,this._cornerBL.x=this._valueUV.w*r,this._cornerBL.y=this._valueUV.w*n}dispose(){for(const e of this._sideMediators)e.dispose();this._sideMediators=null,this._cornerTL=null,this._cornerTR=null,this._cornerBR=null,this._cornerBL=null,super.dispose()}set topLeft(e){this._input.x!==e&&(this._input.x=e,this._needsUpdate=!0)}get topLeft(){return this._input.x}set topRight(e){this._input.y!==e&&(this._input.y=e,this._needsUpdate=!0)}get topRight(){return this._input.y}set bottomRight(e){this._input.z!==e&&(this._input.z=e,this._needsUpdate=!0)}get bottomRight(){return this._input.z}set bottomLeft(e){this._input.w!==e&&(this._input.w=e,this._needsUpdate=!0)}get bottomLeft(){return this._input.w}set top(e){this._input.x===e&&this._input.y===e||(this._input.x=this._input.y=e,this._needsUpdate=!0)}get top(){return(this._input.x+this._input.y)/2}set right(e){this._input.y===e&&this._input.z===e||(this._input.y=this._input.z=e,this._needsUpdate=!0)}get right(){return(this._input.y+this._input.z)/2}set bottom(e){this._input.z===e&&this._input.w===e||(this._input.z=this._input.w=e,this._needsUpdate=!0)}get bottom(){return(this._input.z+this._input.w)/2}set left(e){this._input.w===e&&this._input.x===e||(this._input.w=this._input.x=e,this._needsUpdate=!0)}get left(){return(this._input.w+this._input.x)/2}}class Ab{constructor(e,t){this._borderRadiuses=e,this._sideProperties=t,this._complementaryMediation=null,this._value=0}get value(){return this._value}set complementaryMediation(e){this._complementaryMediation=e}computeValue(){let e=0;for(const t of this._sideProperties)e+=this._borderRadiuses[t];this._value=e}mediate(e=!0){if(!(this._value<1)){for(const t of this._sideProperties)this._borderRadiuses[t]/=this._value;e&&this._complementaryMediation.mediate(!1)}}dispose(){this._complementaryMediation=null,this._borderRadiuses=null}}class wJ extends gb{constructor(e){super("borderWidth",e,!1),this._valueUV=this._value.clone(),this.output=this._outputValue,this._units=gp}set units(e){this._units=B3(e),this._needsUpdate=!0}get units(){return this._units}computeOutputValue(e){this._vector4ValueSetter(this._value,this._input),this._needsProcess=!0,e._bounds._needsUpdate=!0,e._layouter._needsUpdate=!0}_outputValue(e){e[this._id]=this._valueUV}process(e){this._needsRender=!0,e._borderRadius._needsRender=!0}render(e){this._valueUV.copy(this._value);const t=e._bounds._offsetWidth,s=e._bounds._offsetHeight;if(this._units===vb&&(console.log("Percent"),console.log(this._valueUV)),this._units===gp)t!==0&&(this._valueUV.w/=t,this._valueUV.y/=t),s!==0&&(this._valueUV.x/=s,this._valueUV.z/=s);else if(this._units===P3){if(t!==0){const r=t>s?s/t:1;this._valueUV.y*=r,this._valueUV.w*=r}if(s!==0){const r=t<s?t/s:1;this._valueUV.x*=r,this._valueUV.z*=r}}}}class _J extends ci{constructor(e,t=!0){super("visible",t,!0),this._needsUpdate=!1}update(e,t){e.visible=this._value,e._parent._value&&(e._parent._value._children._needsUpdate=!0)}set value(e){this.isValid(e)&&this._value!==e&&(this._value=e,this._needsUpdate=!0)}get value(){return this._value}}class k3 extends cm{constructor(e){super("backgroundColor",e,!1),this._input="transparent",this._allowsInherit=!1}computeOutputValue(e){e._backgroundMesh.visible=!(this._input==="none"||this._input==="transparent"),this._input==="inherit"?this._value.set(this.getInheritedInput(e)):this._input==="transparent"||this._input==="none"||this._value.set(this._input)}}class bl extends ci{constructor(e="untitled"){super(e,void 0,!1)}update(e,t){}output(e){}}class CJ extends ci{constructor(){super("inlineJustificator",null,!1),this._value=null}update(e,t){}process(e){const t=e._bounds._innerHeight,s=e._layouter._value,r=Math.abs(s.height);let n=(()=>{switch(e._alignItems._value){case"inherit":case"start":return t/2;case"end":return r-t/2;case"stretch":case"center":return r/2}})();const o=e._padding._value,a=e._borderWidth._value;n+=(-o.x+o.z)/2+(-a.x+a.z)/2,s.forEach(l=>{l.y+=n,l.forEach(c=>{c.offsetY+=n})})}}const SJ=["start","center","end","stretch"],EJ=function(i){return SJ.indexOf(i)===-1?(console.warn(`(.style) alignItems value '${i}' is not valid. Aborted`),!1):!0};class aE extends Ti{constructor(){super("alignItems","inherit",!0),this.isValidValue=EJ}}class lE extends Ti{constructor(){super("textAlign","inherit",!0),this.isValidValue=IJ}}const MJ=["left","right","center","justify","justify-left","justify-right","justify-center"],IJ=function(i){return MJ.indexOf(i)===-1?(console.warn(`(.style) textAlign value '${i}' is not valid. Aborted`),!1):!0};class cE extends Ti{constructor(){super("flexDirection","inherit",!0),this.isValid=RJ}}const TJ=["row","row-reverse","column","column-reverse"];function RJ(i){return TJ.indexOf(i)===-1?(console.warn(`(.style) flexDirection value '${i}' is not valid. Aborted`),!1):!0}class hE extends Ti{constructor(){super("justifyContent","inherit",!0),this.isValidValue=BJ}}const PJ=["start","center","end","space-between","space-around","space-evenly"];function BJ(i){return PJ.indexOf(i)===-1?(console.warn(`(.style) justifyContent value '${i}' is not valid. Aborted`),!1):!0}class kJ extends Ti{constructor(){super("order",0,!0),this._value=0,this._input=0,this._allowsInherit=!1}computeOutputValue(e){this._value=this._inheritedInput,e._parent._value&&(e._parent._value._children._needsProcess=!0)}}class D3 extends Ti{constructor(){super("position","static",!0),this._allowsInherit=!1,this._value="static",this._needsUpdate=!1,this.computeOutputValue=this._computeFromInherited,this.isValidValue=OJ}_computeFromInherited(e){super._computeFromInherited(e),e._parent._value&&(e._parent._value._children._needsProcess=!0)}}const DJ=["static","absolute"];function OJ(i){return DJ.indexOf(i)===-1?(console.warn(`(.style) position value '${i}' is not valid. Aborted`),!1):!0}class O3 extends Ti{constructor(e,t=null){super(e,t,!0),this._input="auto",this._auto=!0,this._relative=!1,this._updateRequired=!0}set inline(e){this.isValidValue(e)&&e!==this._inline&&(this._inline=e,this._input!==this._inline&&this._parseInput())}get inline(){return this._inline}_parseInput(){let e=!0;if(this._inline!==void 0&&this._inline!=="unset"?this._input=this._inline:this._computed!==void 0?(this._computed===this._input&&(e=!1),this._input=this._computed):e=this._input==="inherit",e){if(this._auto=!this._input||this._input==="auto",this._auto)this._relative=!1;else if((typeof this._input=="string"||this._input instanceof String)&&this._input.endsWith("%")){this._relative=!0,this._value=0;const t=parseFloat(this._input.replace("%","").trim());isNaN(t)||(this._value=t/100)}else this._relative=!1,this._value=this._input;this._needsUpdate=this._updateRequired=e}}update(e,t){if(this._updateRequired){this._updateRequired=!1,this._allowsInherit||(this._inheritedInput=this.getInheritedInput(e)),this.computeOutputValue(e);for(const s of e._children._uis)s[`_${this._id}`]._needsUpdate=!0;this.output(t),e._parent._value&&(e._parent._value._layouter._needsProcess=!0)}}computeOutputValue(e){e._bounds._needsUpdate=!0,e._renderer._needsRender=!0}getInheritedInput(e){if(this._input!=="inherit"&&!this._auto)return this._input;const t=e._parent._value;return t?t[`_${this._id}`].getInheritedInput(t):this.getDefaultValue()}getDefaultValue(){return 0}get value(){return this._value}}class LJ extends O3{constructor(){super("width")}}class FJ extends O3{constructor(){super("height")}computeOutputValue(e){super.computeOutputValue(e)}}class L3 extends bl{constructor(){super("textContent"),this._needsUpdate=!1}set value(e){}process(e){let t="";for(let s=0;s<e.children.length;s++){const r=e.children[s];r.isUI&&(t+=r.textContent)}this._value=t}}class F3 extends Ti{constructor(e){super("fontStyle",e,!0),this.isValidValue=NJ}}const UJ=["normal","italic"];function NJ(i){return UJ.indexOf(i)===-1?(console.warn(`(.style) fontStyle value '${i}' is not valid. Aborted`),!1):!0}class U3 extends Ti{constructor(){super("fontWeight","inherit",!0),this.isValid=QJ}}const zJ=["100","200","300","400","500","600","700","800","900","light","normal","bold","bolder"];function QJ(i){return zJ.indexOf(i.toString())===-1?(console.warn(`(.style) fontWeight value '${i}' is not valid. Aborted`),!1):!0}class N3{constructor(){this._size=42,this._lineHeight=42,this._lineBase=38,this._name="-",this._charset=""}get size(){return this._size}get lineHeight(){return this._lineHeight}get lineBase(){return this._lineBase}get name(){return this._name}get charset(){return this._charset}}class jJ extends N3{constructor(e){super(),this._size=e.info.size,this._lineHeight=e.common.lineHeight,this._lineBase=e.common.base,this._name=e.info.face,this._textureWidth=e.common.scaleW,this._textureHeight=e.common.scaleH,this._charset=e.chars.map(t=>t.char).join("")}get textureWidth(){return this._textureWidth}get textureHeight(){return this._textureHeight}}class z3{constructor(e){this._char="",this._width=1,this._heigth=1,this._xadvance=1,this._xoffset=0,this._yoffset=0,this._font=e}get font(){return this._font}get char(){return this._char}get width(){return this._width}get height(){return this._heigth}get xadvance(){return this._xadvance}get xoffset(){return this._xoffset}get yoffset(){return this._yoffset}set yoffset(e){this._yoffset=e}clone(e){throw new Error("Abstract... Need to be implemented")}asInlineGlyph(){throw new Error("Abstract... Need to be implemented")}}class Q3{constructor(){this._offsetX=0,this._offsetY=0,this._lineBreak=null,this._kerning=0,this._fontFactor=1,this._fontSize=0,this._cumulativeWidth=0,this._paddingLeft=0,this._paddingRight=0,this._marginLeft=0,this._marginRight=0}resetOffsets(){this._offsetX=this._offsetY=0,this._cumulativeWidth=0}get xadvance(){return 0}get xoffset(){return 0}get yoffset(){return 0}get width(){return 0}get height(){return 0}set lineBreak(e){this._lineBreak=e}get lineBreak(){return this._lineBreak}get anchor(){return 0}get kerning(){return this._kerning*this._fontFactor}set kerning(e){this._kerning=e}get fontSize(){return this._fontSize}set fontSize(e){this._fontSize=e}get lineHeight(){return 0}get offsetX(){return this._offsetX}set offsetX(e){this._offsetX=e}get offsetY(){return this._offsetY}set offsetY(e){this._offsetY=e}get cumulativeWidth(){return this._cumulativeWidth}set cumulativeWidth(e){this._cumulativeWidth=e}get marginLeft(){return this._marginLeft}set marginLeft(e){this._marginLeft=e}get marginRight(){return this._marginRight}set marginRight(e){this._marginRight=e}get paddingLeft(){return this._paddingLeft}set paddingLeft(e){this._paddingLeft=e}get paddingRight(){return this._paddingRight}set paddingRight(e){this._paddingRight=e}get lineBase(){return 0}set fontFactor(e){this._fontFactor=e}get fontFactor(){return this._fontFactor}}class j3 extends Q3{constructor(e){super(),this._typographic=e}get typographic(){return this._typographic}get xadvance(){return this._typographic.xadvance*this._fontFactor}get xoffset(){return this._typographic.xoffset*this._fontFactor}get yoffset(){return this._typographic.yoffset*this._fontFactor}get width(){return this._typographic.width*this._fontFactor}get height(){return this._typographic.height*this._fontFactor}get char(){return this._typographic.char}get anchor(){return this.yoffset}get lineHeight(){return this._typographic.font.lineHeight*this._fontFactor}get lineBase(){return this._typographic.font.lineBase*this._fontFactor}}class GJ extends j3{constructor(e){super(e)}get uv(){return this.typographic.uv}}class rw extends z3{constructor(e,t){super(e),this._char=t.char,this._width=t.width,this._heigth=t.height,this._xadvance=t.xadvance?t.xadvance:this._width,this._xoffset=t.xoffset?t.xoffset:0,this._yoffset=t.yoffset?t.yoffset:0,this._uv=t.uv?t.uv:null,isNaN(t.x)||(this._uv={left:t.x/e.textureWidth,right:(t.x+t.width)/e.textureWidth,top:1-(t.y+t.height)/e.textureHeight,bottom:1-t.y/e.textureHeight})}get uv(){return this._uv}clone(e){return new rw(this._font,{char:e,width:this._width,height:this._heigth,xadvance:this._xadvance,xoffset:this._xoffset,yoffset:this._yoffset,uv:null})}asInlineGlyph(){return new GJ(this)}}class HJ extends Ke.PlaneGeometry{constructor(e,t){let s=1,r=1;const n=e.typographic.font.size,o=t._segments.value;s=Math.ceil(e.typographic.width/n*o),r=Math.ceil(e.typographic.height/n*o),super(e.width,e.height,s,r),e.uv?(this._mapUVs(e),this._transformGeometry(e)):(this._nullifyUVs(),this.scale(0,0,1),this.translate(0,e.fontSize/2,0)),this.name="GlyphGeometry"}_mapUVs(e){const t=e.uv.right-e.uv.left,s=e.uv.bottom-e.uv.top,r=this.getAttribute("uv").array.slice(),n=[];for(let o=0;o<r.length;o+=2){const a=r[o],l=r[o+1];n.push(e.uv.left+t*a),n.push(e.uv.top+s*l)}this.setAttribute("uvG",new Ke.BufferAttribute(new Float32Array(n),2))}_nullifyUVs(){const e=[],t=this.getAttribute("uv").array.length;for(let s=0;s<t;s++)e.push(0);this.setAttribute("uvG",new Ke.BufferAttribute(new Float32Array(e),2))}_transformGeometry(e){this.translate(e.width/2,-e.height/2,0)}}const VJ=`
4181
4181
  attribute vec2 uvG;
4182
4182
  varying vec2 vUvG;
@@ -5435,7 +5435,7 @@ void main() {
5435
5435
  // be blended onto the scene.
5436
5436
  gl_FragColor = vec4(direct, max);
5437
5437
  return;
5438
- `)}}}applyShadowMaterial(){var e;const t=$.getComponent(this.gameObject,Ii);if(t)if(((e=t.sharedMaterial)==null?void 0:e.type)!=="ShadowMaterial"){const s=new a1;s.color=this.shadowColor,s.opacity=this.shadowColor.alpha,this.applyMaterialOptions(s),t.sharedMaterial=s}else{const s=t.sharedMaterial;s.color=this.shadowColor,s.opacity=this.shadowColor.alpha,this.applyMaterialOptions(s)}}applyOccluderMaterial(){const e=$.getComponent(this.gameObject,Ii);if(e){const t=e.sharedMaterial;t.depthWrite=!0,t.stencilWrite=!0,t.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}}NN([w()],pv.prototype,"mode",2),NN([w(vi)],pv.prototype,"shadowColor",2);var mne=Object.defineProperty,vne=Object.getOwnPropertyDescriptor,Dx=(i,e,t,s)=>{for(var r=s>1?void 0:s?vne(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&mne(e,t,r),r},dI;const zN=(dI=class extends Ee{constructor(){super(...arguments),h(this,"target",null),h(this,"followFactor",.1),h(this,"rotateFactor",.1),h(this,"positionAxes",fp.All),h(this,"flipForward",!1),h(this,"_firstUpdate",!0)}onBeforeRender(){this.updateNow(!1)}updateNow(i){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const e=xt(this.target),t=this._firstUpdate||i?1:Je.clamp01(this.context.time.deltaTime*this.followFactor),s=this.worldPosition;this.positionAxes&fp.X&&(s.x=Je.lerp(s.x,e.x,t)),this.positionAxes&fp.Y&&(s.y=Je.lerp(s.y,e.y,t)),this.positionAxes&fp.Z&&(s.z=Je.lerp(s.z,e.z,t)),this.worldPosition=s}if(this.rotateFactor>0){const e=Ss(this.target);this.flipForward&&e.premultiply(zN._invertForward);const t=this._firstUpdate||i?1:Je.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(e,t)}this._firstUpdate=!1}}},h(dI,"_invertForward",new Ce().setFromAxisAngle(new S(0,1,0),Math.PI)),dI);let nh=zN;Dx([w(Me)],nh.prototype,"target",2),Dx([w()],nh.prototype,"followFactor",2),Dx([w()],nh.prototype,"rotateFactor",2),Dx([w()],nh.prototype,"positionAxes",2);class Ane extends ve{constructor(e){const t=new yne(e),s=new Ns(t.image.width*.001,t.image.height*.001),r=new pi({map:t,toneMapped:!1,transparent:!0});super(s,r);function n(o){r.map.dispatchDOMEvent(o)}this.addEventListener("mousedown",n),this.addEventListener("mousemove",n),this.addEventListener("mouseup",n),this.addEventListener("click",n),this.dispose=function(){s.dispose(),r.dispose(),r.map.dispose(),pI.delete(e),this.removeEventListener("mousedown",n),this.removeEventListener("mousemove",n),this.removeEventListener("mouseup",n),this.removeEventListener("click",n)}}}class yne extends SP{constructor(e){super(QN(e)),this.dom=e,this.anisotropy=16,this.encoding=yt,this.minFilter=Pt,this.magFilter=Pt;const t=new MutationObserver(()=>{this.scheduleUpdate||(this.scheduleUpdate=setTimeout(()=>this.update(),16))}),s={attributes:!0,childList:!0,subtree:!0,characterData:!0};t.observe(e,s),this.observer=t}dispatchDOMEvent(e){e.data&&bne(this.dom,e.type,e.data.x,e.data.y)}update(){this.image=QN(this.dom),this.needsUpdate=!0,this.scheduleUpdate=null}dispose(){this.observer&&this.observer.disconnect(),this.scheduleUpdate=clearTimeout(this.scheduleUpdate),super.dispose()}}const pI=new WeakMap;function QN(i){const e=document.createRange(),t=new be;function s(p){const f=[];let g=!1;function m(){if(g&&(g=!1,p.restore()),f.length===0)return;let v=-1/0,A=-1/0,b=1/0,y=1/0;for(let x=0;x<f.length;x++){const _=f[x];v=Math.max(v,_.x),A=Math.max(A,_.y),b=Math.min(b,_.x+_.width),y=Math.min(y,_.y+_.height)}p.save(),p.beginPath(),p.rect(v,A,b-v,y-A),p.clip(),g=!0}return{add:function(v){f.push(v),m()},remove:function(){f.pop(),m()}}}function r(p,f,g,m){m!==""&&(p.textTransform==="uppercase"&&(m=m.toUpperCase()),u.font=p.fontWeight+" "+p.fontSize+" "+p.fontFamily,u.textBaseline="top",u.fillStyle=p.color,u.fillText(m,f,g+parseFloat(p.fontSize)*.1))}function n(p,f,g,m,v){g<2*v&&(v=g/2),m<2*v&&(v=m/2),u.beginPath(),u.moveTo(p+v,f),u.arcTo(p+g,f,p+g,f+m,v),u.arcTo(p+g,f+m,p,f+m,v),u.arcTo(p,f+m,p,f,v),u.arcTo(p,f,p+g,f,v),u.closePath()}function o(p,f,g,m,v,A){const b=p[f+"Width"],y=p[f+"Style"],x=p[f+"Color"];b!=="0px"&&y!=="none"&&x!=="transparent"&&x!=="rgba(0, 0, 0, 0)"&&(u.strokeStyle=x,u.lineWidth=parseFloat(b),u.beginPath(),u.moveTo(g,m),u.lineTo(g+v,m+A),u.stroke())}function a(p,f){let g=0,m=0,v=0,A=0;if(p.nodeType===Node.TEXT_NODE){e.selectNode(p);const y=e.getBoundingClientRect();g=y.left-l.left-.5,m=y.top-l.top-.5,v=y.width,A=y.height,r(f,g,m,p.nodeValue.trim())}else{if(p.nodeType===Node.COMMENT_NODE)return;if(p instanceof HTMLCanvasElement){if(p.style.display==="none")return;u.save();const y=window.devicePixelRatio;u.scale(1/y,1/y),u.drawImage(p,0,0),u.restore()}else{if(p.style.display==="none")return;const y=p.getBoundingClientRect();g=y.left-l.left-.5,m=y.top-l.top-.5,v=y.width,A=y.height,f=window.getComputedStyle(p),n(g,m,v,A,parseFloat(f.borderRadius));const x=f.backgroundColor;x!=="transparent"&&x!=="rgba(0, 0, 0, 0)"&&(u.fillStyle=x,u.fill());const _=["borderTop","borderLeft","borderBottom","borderRight"];let M=!0,P=null;for(const C of _){if(P!==null&&(M=f[C+"Width"]===f[P+"Width"]&&f[C+"Color"]===f[P+"Color"]&&f[C+"Style"]===f[P+"Style"]),M===!1)break;P=C}if(M===!0){const C=parseFloat(f.borderTopWidth);f.borderTopWidth!=="0px"&&f.borderTopStyle!=="none"&&f.borderTopColor!=="transparent"&&f.borderTopColor!=="rgba(0, 0, 0, 0)"&&(u.strokeStyle=f.borderTopColor,u.lineWidth=C,u.stroke())}else o(f,"borderTop",g,m,v,0),o(f,"borderLeft",g,m,0,A),o(f,"borderBottom",g,m+A,v,0),o(f,"borderRight",g+v,m,0,A);if(p instanceof HTMLInputElement){let C=f.accentColor;(C===void 0||C==="auto")&&(C=f.color),t.set(C);const R=Math.sqrt(.299*t.r**2+.587*t.g**2+.114*t.b**2)<.5?"white":"#111111";if(p.type==="radio"&&(n(g,m,v,A,A),u.fillStyle="white",u.strokeStyle=C,u.lineWidth=1,u.fill(),u.stroke(),p.checked&&(n(g+2,m+2,v-4,A-4,A),u.fillStyle=C,u.strokeStyle=R,u.lineWidth=2,u.fill(),u.stroke())),p.type==="checkbox"&&(n(g,m,v,A,2),u.fillStyle=p.checked?C:"white",u.strokeStyle=p.checked?R:C,u.lineWidth=1,u.stroke(),u.fill(),p.checked)){const T=u.textAlign;u.textAlign="center";const z={color:R,fontFamily:f.fontFamily,fontSize:A+"px",fontWeight:"bold"};r(z,g+v/2,m,"\u2714"),u.textAlign=T}if(p.type==="range"){const[T,z,G]=["min","max","value"].map(F=>parseFloat(p[F])),N=(G-T)/(z-T)*(v-A);n(g,m+A/4,v,A/2,A/4),u.fillStyle=R,u.strokeStyle=C,u.lineWidth=1,u.fill(),u.stroke(),n(g,m+A/4,N+A/2,A/2,A/4),u.fillStyle=C,u.fill(),n(g+N,m,A,A,A/2),u.fillStyle=C,u.fill()}(p.type==="color"||p.type==="text"||p.type==="number")&&(d.add({x:g,y:m,width:v,height:A}),r(f,g+parseInt(f.paddingLeft),m+parseInt(f.paddingTop),p.value),d.remove())}}}const b=f.overflow==="auto"||f.overflow==="hidden";b&&d.add({x:g,y:m,width:v,height:A});for(let y=0;y<p.childNodes.length;y++)a(p.childNodes[y],f);b&&d.remove()}const l=i.getBoundingClientRect();let c=pI.get(i);c===void 0&&(c=document.createElement("canvas"),c.width=l.width,c.height=l.height,pI.set(i,c));const u=c.getContext("2d"),d=new s(u);return a(i),c}function bne(i,e,t,s){const r={clientX:t*i.offsetWidth+i.offsetLeft,clientY:s*i.offsetHeight+i.offsetTop,view:i.ownerDocument.defaultView};window.dispatchEvent(new MouseEvent(e,r));const n=i.getBoundingClientRect();t=t*n.width+n.left,s=s*n.height+n.top;function o(a){if(a.nodeType!==Node.TEXT_NODE&&a.nodeType!==Node.COMMENT_NODE){const l=a.getBoundingClientRect();if(t>l.left&&t<l.right&&s>l.top&&s<l.bottom&&(a.dispatchEvent(new MouseEvent(e,r)),a instanceof HTMLInputElement&&a.type==="range"&&(e==="mousedown"||e==="click"))){const[c,u]=["min","max"].map(f=>parseFloat(a[f])),d=l.width,p=(t-l.x)/d;a.value=c+(u-c)*p,a.dispatchEvent(new InputEvent("input",{bubbles:!0}))}for(let c=0;c<a.childNodes.length;c++)o(a.childNodes[c])}}o(i)}const Ox=new W,$p={type:"",data:Ox};class xne extends Un{constructor(e,t){super();const s=this,r=new _d,n=new Pe,o=e.domElement;function a(p){p.stopPropagation();const f=e.domElement.getBoundingClientRect();Ox.x=(p.clientX-f.left)/f.width*2-1,Ox.y=-(p.clientY-f.top)/f.height*2+1,r.setFromCamera(Ox,t);const g=r.intersectObjects(s.children,!1);if(g.length>0){const m=g[0],v=m.object,A=m.uv;$p.type=p.type,$p.data.set(A.x,1-A.y),v.dispatchEvent($p)}}o.addEventListener("pointerdown",a),o.addEventListener("pointerup",a),o.addEventListener("pointermove",a),o.addEventListener("mousedown",a),o.addEventListener("mouseup",a),o.addEventListener("mousemove",a),o.addEventListener("click",a);const l={move:"mousemove",select:"click",selectstart:"mousedown",selectend:"mouseup"};function c(p){const f=p.target;n.identity().extractRotation(f.matrixWorld),r.ray.origin.setFromMatrixPosition(f.matrixWorld),r.ray.direction.set(0,0,-1).applyMatrix4(n);const g=r.intersectObjects(s.children,!1);if(g.length>0){const m=g[0],v=m.object,A=m.uv;$p.type=l[p.type],$p.data.set(A.x,1-A.y),v.dispatchEvent($p)}}const u=e.xr.getController(0);u.addEventListener("move",c),u.addEventListener("select",c),u.addEventListener("selectstart",c),u.addEventListener("selectend",c);const d=e.xr.getController(1);d.addEventListener("move",c),d.addEventListener("select",c),d.addEventListener("selectstart",c),d.addEventListener("selectend",c)}}class fI extends Ee{constructor(){super(...arguments),h(this,"id",null),h(this,"keepAspect",!1)}start(){if(!this.id||!this.context.mainCamera)return;const e=document.getElementById(this.id);if(!e){console.warn('Could not find element with id "'+this.id+'"');return}e.style.display="block",e.style.visibility="hidden";const t=new xne(this.context.renderer,this.context.mainCamera);this.gameObject.add(t);const s=new Ane(e);t.add(s),s.visible=!1,console.log(s);const r=s.material;r.transparent=!0,setTimeout(()=>{s.visible=!0;const n=O0(this.gameObject).clone();L0(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const o=new or;o.setFromObject(t),this.setWorldRotation(n.x,n.y,n.z);const a=o.max.x-o.min.x,l=o.max.y-o.min.y;if(this.keepAspect){const u=a/l;a>l?s.scale.set(1/a,1/l/u,1):s.scale.set(1/a*u,1/l,1)}else s.scale.set(1/a,1/l,1);const c=this.gameObject.scale;s.scale.multiply(c)},1)}}var wne=Object.defineProperty,_ne=Object.getOwnPropertyDescriptor,fv=(i,e,t,s)=>{for(var r=s>1?void 0:s?_ne(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&wne(e,t,r),r};const gv=re("debugspatialtrigger"),jN=new On,GN=new On;function Cne(i,e){return jN.mask=i,GN.mask=e,jN.test(GN)}class xa extends Ee{constructor(){super(...arguments),h(this,"triggerMask",0),h(this,"onEnter"),h(this,"onStay"),h(this,"onExit"),h(this,"currentIntersected",[]),h(this,"lastIntersected",[])}start(){gv&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const e of mv.triggers)Cne(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){const t=this.lastIntersected[e];this.currentIntersected.indexOf(t)<0&&(this.onExitTrigger(t),this.lastIntersected.splice(e,1))}for(const e of this.currentIntersected)this.lastIntersected.indexOf(e)<0&&this.onEnterTrigger(e),this.onStayTrigger(e);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}onEnterTrigger(e){var t;gv&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),(t=this.onEnter)==null||t.invoke(this,e)}onExitTrigger(e){var t;gv&&console.log("EXIT TRIGGER",this.name,e.name,this,e),e.raiseOnExitEvent(this),(t=this.onExit)==null||t.invoke(this,e)}onStayTrigger(e){var t;e.raiseOnStayEvent(this),(t=this.onStay)==null||t.invoke(this,e)}}fv([w()],xa.prototype,"triggerMask",2),fv([w(Jr)],xa.prototype,"onEnter",2),fv([w(Jr)],xa.prototype,"onStay",2),fv([w(Jr)],xa.prototype,"onExit",2);var gI;const Lx=(gI=class extends Ee{constructor(){super(...arguments),h(this,"triggerMask"),h(this,"boxHelper")}start(){gv&&console.log(this.name,this.triggerMask,this)}onEnable(){var i;Lx.triggers.push(this),this.boxHelper||(this.boxHelper=$.addNewComponent(this.gameObject,ra),(i=this.boxHelper)==null||i.showHelper(null,gv))}onDisable(){Lx.triggers.splice(Lx.triggers.indexOf(this),1)}test(i){return this.boxHelper?this.boxHelper.isInBox(i)??!1:!1}raiseOnEnterEvent(i){$.foreachComponent(this.gameObject,e=>{e!==i&&e instanceof xa&&e.onEnterTrigger(this)},!1)}raiseOnStayEvent(i){$.foreachComponent(this.gameObject,e=>{e!==i&&e instanceof xa&&e.onStayTrigger(this)},!1)}raiseOnExitEvent(i){$.foreachComponent(this.gameObject,e=>{e!==i&&e instanceof xa&&e.onExitTrigger(this)},!1)}},h(gI,"triggers",[]),gI);let mv=Lx;fv([w()],mv.prototype,"triggerMask",2);var Sne=Object.defineProperty,Ene=Object.getOwnPropertyDescriptor,Mne=(i,e,t,s)=>{for(var r=s>1?void 0:s?Ene(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Sne(e,t,r),r};const In=re("debugspectator");class Fx extends Ee{constructor(){super(...arguments),h(this,"cam",null),h(this,"useKeys",!0),h(this,"_mode",0),h(this,"orbit",null),h(this,"_handler"),h(this,"eventSub_WebXRRequestStartEvent",null),h(this,"eventSub_WebXRStartEvent",null),h(this,"eventSub_WebXREndEvent",null),h(this,"_debug"),h(this,"_networking")}get mode(){return this._mode}set mode(e){this._mode=e}get isSpectating(){var e;return((e=this._handler)==null?void 0:e.currentTarget)!==void 0}isSpectatingUser(e){var t;return((t=this.target)==null?void 0:t.userId)===e}isFollowedBy(e){var t;return(t=this.followers)==null?void 0:t.includes(e)}get followers(){return this._networking.followers}stopSpectating(){if(this.context.isInXR){this.followSelf();return}this.target=void 0}get localId(){return this.context.connection.connectionId??"local"}set target(e){var t;if(this._handler){const s=(t=this._handler.currentTarget)==null?void 0:t.userId,r=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&r?.currentObject===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),$.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,s)):this._handler.currentTarget!==e&&(this._handler.set(e),$.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,s))}}get target(){var e;return(e=this._handler)==null?void 0:e.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){var e,t;return this.isSpectating&&((e=this.target)==null?void 0:e.currentObject)===((t=this.context.players.getPlayerView(this.localId))==null?void 0:t.currentObject)}awake(){if(this._debug=new Rne(this.context,this),this._networking=new kne(this.context,this),this._networking.awake(),$.setActive(this.gameObject,!1),this.cam=$.getComponent(this.gameObject,Pi),!this.cam){console.error("Spectator camera needs camera component",this);return}!this._handler&&this.cam&&(this._handler=new Ine(this.context,this.cam,this)),this.eventSub_WebXRRequestStartEvent=this.onXRSessionRequestStart.bind(this),this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),_t.addEventListener(xi.RequestVRSession,this.eventSub_WebXRRequestStartEvent),_t.addEventListener(xi.XRStarted,this.eventSub_WebXRStartEvent),_t.addEventListener(xi.XRStopped,this.eventSub_WebXREndEvent),this.orbit=$.getComponent(this.context.mainCamera,Tl)}onDestroy(){var e;this.stopSpectating(),_t.removeEventListener(xi.RequestVRSession,this.eventSub_WebXRStartEvent),_t.removeEventListener(xi.XRStarted,this.eventSub_WebXRStartEvent),_t.removeEventListener(xi.XRStopped,this.eventSub_WebXREndEvent),(e=this._handler)==null||e.destroy(),this._networking.destroy()}isSupportedPlatform(){const e=window.navigator.userAgent,t=/Windows|MacOS/.test(e),s=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return t&&!s}onXRSessionRequestStart(e){this.isSupportedPlatform()&&$.setActive(this.gameObject,!0)}onXRSessionStart(e){this.isSupportedPlatform()&&(In&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onXRSessionEnded(e){var t,s;this.context.removeCamera(this.cam),$.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),(t=this._handler)==null||t.set(void 0),(s=this._handler)==null||s.disable(),this.isSpectatingSelf&&this.stopSpectating()}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),this.target||(this.context.players.setPlayerView(this.localId,this.context.mainCamera,$o.Headset),this.target=this.context.players.getPlayerView(this.localId)),In&&console.log("Follow self",this.target)}onAfterRender(){var e,t,s;if(!this.cam)return;const r=this.context.renderer,n=r.xr.enabled;if(!r.xr.isPresenting&&!((e=this._handler)!=null&&e.currentTarget))return;(t=this._handler)==null||t.update(this._mode);const o=r.getRenderTarget();let a=null;if(!o){if(!r.state.bindFramebuffer||!r.state.bindXRFramebuffer)return;a=r._framebuffer,r.state.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const l=this.context.mainCameraComponent;if(l){const d=l.backgroundColor;d&&r.setClearColor(d,d.alpha),this.cam.backgroundColor=d,this.cam.clearFlags=l.clearFlags,this.cam.nearClipPlane=l.nearClipPlane,this.cam.farClipPlane=l.farClipPlane}else r.setClearColor(new be(1,1,1));r.setRenderTarget(null),r.xr.enabled=!1;const c=(s=this.cam)==null?void 0:s.cam;this.context.updateAspect(c);const u=r.xr.isPresenting;r.xr.isPresenting=!1,r.setSize(this.context.domWidth,this.context.domHeight),r.render(this.context.scene,c),r.xr.isPresenting=u,r.xr.enabled=n,o?r.setRenderTarget(o):r.state.bindXRFramebuffer(a),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const e=this._mode===0;for(const t of fr.instances)if(t.avatar&&"isLocalAvatar"in t.avatar){let s=ls.All;this.isSpectatingSelf&&(s=e&&t.avatar.isLocalAvatar?ls.FirstPerson:ls.ThirdPerson);const r=t.avatar.flags;if(!r)continue;for(const n of r)n.UpdateVisible(s)}}resetAvatarFlags(){var e;for(const t of fr.instances)if(t.avatar&&"flags"in t.avatar){const s=t.avatar.flags;if(!s)continue;for(const r of s)(e=t.avatar)!=null&&e.isLocalAvatar?r.UpdateVisible(ls.FirstPerson):r.UpdateVisible(ls.ThirdPerson)}}}Mne([w()],Fx.prototype,"useKeys",2);class Ine{constructor(e,t,s){h(this,"context"),h(this,"cam"),h(this,"spectator"),h(this,"follow"),h(this,"target"),h(this,"view"),h(this,"currentObject"),this.context=e,this.cam=t,this.spectator=s}get currentTarget(){return this.view}set(e){const t=e?.currentObject;if(!t){this.spectator.stopSpectating();return}t!==this.currentObject&&(this.currentObject=t,this.view=e,this.follow||(this.follow=$.addNewComponent(this.cam.gameObject,nh)),this.target||(this.target=new Me),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,In&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){In&&console.log("STOP FOLLOW",this.currentObject),this.view=void 0,this.currentObject=void 0,this.context.removeCamera(this.cam),this.follow&&(this.follow.enabled=!1)}destroy(){var e;(e=this.target)==null||e.removeFromParent(),this.follow&&$.destroy(this.follow)}update(e){var t,s,r,n,o,a;if(((t=this.currentTarget)==null?void 0:t.isConnected)===!1||((s=this.currentTarget)==null?void 0:s.removed)===!0){In&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&((r=this.currentTarget)==null?void 0:r.currentObject)!==this.currentObject&&(In&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const l=this.context.mainCamera;l&&(this.cam.cam.near!==l.near||this.cam.cam.far!==l.far)&&(this.cam.cam.near=l.near,this.cam.cam.far=l.far,this.cam.cam.updateProjectionMatrix());const c=(n=this.follow)==null?void 0:n.target;if(!(!c||!this.follow)){switch(e){case 0:((o=this.view)==null?void 0:o.viewDevice)!==$o.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),c.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,c.position.set(0,.5,1.5);break}this.follow.flipForward=!1,((a=this.view)==null?void 0:a.viewDevice)!==$o.Browser?c.quaternion.copy(Tne):c.quaternion.identity()}}}const Tne=new Ce().setFromAxisAngle(new S(0,1,0),Math.PI);class Rne{constructor(e,t){h(this,"context"),h(this,"spectator"),this.context=e,this.spectator=t,console.log("Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),this.context.domElement.addEventListener("keydown",r=>{!this.spectator.useKeys||r.key==="Escape"&&this.spectator.stopSpectating()});let s=0;this.context.input.addEventListener(Xo.PointerDown,r=>{s=this.context.time.time}),this.context.input.addEventListener(Xo.PointerUp,r=>{const n=this.context.time.time-s;n>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&n<.3&&this.trySelectObject()})}trySelectObject(){const e=new _o;e.setMask(16777215);const t=this.context.physics.raycast(e);if(In&&console.log(...t),t!=null&&t.length)for(const s of t){if(s.distance<.2)continue;const r=s.object,n=$.getComponentInParent(r,fr),o=n?.connectionId;if(o){const a=this.context.players.getPlayerView(o);this.spectator.target=a,In&&console.log("spectate",o,n);break}}}}class Pne{constructor(e,t,s){h(this,"guid"),h(this,"dontSave",!0),h(this,"targetUserId"),h(this,"stoppedFollowing"),this.guid=e,this.targetUserId=t,this.stoppedFollowing=s}}class Bne{constructor(e,t){h(this,"guid"),h(this,"userId"),this.guid=e.guid,this.userId=t}}class kne{constructor(e,t){h(this,"followers",[]),h(this,"context"),h(this,"spectator"),h(this,"_followerEventMethod"),h(this,"_requestFollowMethod"),h(this,"_joinedRoomMethod"),h(this,"_lastRequestFollowUser"),h(this,"_enforceFollowInterval"),this.context=e,this.spectator=t,this._followerEventMethod=this.onFollowerEvent.bind(this),this._requestFollowMethod=this.onRequestFollowEvent.bind(this),this._joinedRoomMethod=this.onUserJoinedRoom.bind(this)}awake(){this.context.connection.beginListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.beginListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.beginListen(ji.JoinedRoom,this._joinedRoomMethod),this.context.domElement.addEventListener("keydown",e=>{this.spectator.useKeys&&(e.key==="f"?this.onRequestFollowMe():e.key==="Escape"&&this.onRequestFollowMe(!0))})}destroy(){this.context.connection.stopListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.stopListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.stopListen(ji.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(e,t){if(In&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",e,t),this.context.connection.connectionId){const s=e?.userId===void 0,r=s?t:e?.userId,n=new Pne(this.context.connection.connectionId,r,s);this.context.connection.send("spectator-follower-changed",n)}}onRequestFollowMe(e=!1){if(In&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const t=e?void 0:this.context.connection.connectionId,s=new Bne(this.spectator,t);this.context.connection.send("spectator-request-follow",s)}}onUserJoinedRoom(){re("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){const t=e.targetUserId,s=e.guid;if(In&&console.log(e),t===this.context.connection.connectionId)if(e.stoppedFollowing){const r=this.followers.indexOf(s);r!==-1&&(this.followers.splice(r,1),this.removeDisconnectedFollowers(),console.log(s,"unfollows you",this.followers.length))}else this.followers.includes(s)||(this.followers.push(s),this.removeDisconnectedFollowers(),console.log(s,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let e=this.followers.length-1;e>=0;e--){const t=this.followers[e];this.context.connection.userIsInRoom(t)===!1&&this.followers.splice(e,1)}}onRequestFollowEvent(e){if(this._lastRequestFollowUser=e,e.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(e.userId===void 0)this.spectator.stopSpectating();else{const t=this.context.players.getPlayerView(e.userId);if(t)this.spectator.target=t;else return In&&console.warn("Could not find view",e.userId),this.enforceFollow(),!1}return!0}enforceFollow(){this._enforceFollowInterval||(this._enforceFollowInterval=setInterval(()=>{this._lastRequestFollowUser===void 0||this._lastRequestFollowUser.userId&&this.spectator.isFollowedBy(this._lastRequestFollowUser.userId)?(clearInterval(this._enforceFollowInterval),this._enforceFollowInterval=void 0):(In&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}var Dne=Object.defineProperty,One=Object.getOwnPropertyDescriptor,jr=(i,e,t,s)=>{for(var r=s>1?void 0:s?One(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Dne(e,t,r),r};const mI=re("debugspriterenderer"),Lne=re("wireframe"),vI=class{static getOrCreateGeometry(i){if(i._geometry)return i._geometry;if(i.guid&&vI.cache[i.guid])return mI&&console.log("Take cached geometry for sprite",i.guid),vI.cache[i.guid];const e=new mt;i._geometry=e;const t=new Float32Array(i.triangles.length*3),s=new Float32Array(i.triangles.length*2);for(let r=0;r<i.triangles.length;r+=1){const n=i.triangles[r];t[r*3]=-i.vertices[n].x,t[r*3+1]=i.vertices[n].y,t[r*3+2]=0;const o=i.uv[n];s[r*2]=o.x,s[r*2+1]=1-o.y}return e.setAttribute("position",new tt(t,3)),e.setAttribute("uv",new tt(s,2)),i.guid&&(this.cache[i.guid]=e),mI&&console.log("Built sprite geometry",i,e),e}};let AI=vI;h(AI,"cache",{});class Nl{constructor(){h(this,"guid"),h(this,"texture"),h(this,"triangles"),h(this,"uv"),h(this,"vertices"),h(this,"_geometry")}}jr([w()],Nl.prototype,"guid",2),jr([w(Ft)],Nl.prototype,"texture",2),jr([ip()],Nl.prototype,"triangles",2),jr([ip()],Nl.prototype,"uv",2),jr([ip()],Nl.prototype,"vertices",2);const yI=Symbol("spriteOwner");class vv{constructor(){h(this,"sprites")}}jr([w(Nl)],vv.prototype,"sprites",2);class ef{constructor(){h(this,"spriteSheet"),h(this,"index",0)}update(){if(!this.spriteSheet)return;const e=this.index;if(e<0||e>=this.spriteSheet.sprites.length)return;const t=this.spriteSheet.sprites[e];let s=t?.texture;s&&(s.encoding=yt,s.minFilter==Wt&&s.magFilter==Wt&&(s.anisotropy=1),s.needsUpdate=!0)}}jr([w(vv)],ef.prototype,"spriteSheet",2),jr([w()],ef.prototype,"index",2);class wa extends Ee{constructor(){super(...arguments),h(this,"drawMode",0),h(this,"size",{x:1,y:1}),h(this,"color"),h(this,"sharedMaterial"),h(this,"_spriteSheet"),h(this,"_currentSprite"),h(this,"transparent",!0),h(this,"cutoutThreshold",0),h(this,"castShadows",!1)}get sprite(){return this._spriteSheet}set sprite(e){if(e!==this._spriteSheet)if(typeof e=="number"){const t=Math.floor(e);t===e&&(this.spriteIndex=t);return}else this._spriteSheet=e,this.updateSprite()}set spriteIndex(e){this._spriteSheet&&(this._spriteSheet.index=e,this.updateSprite())}get spriteIndex(){var e;return((e=this._spriteSheet)==null?void 0:e.index)??0}get spriteFrames(){var e,t;return((t=(e=this._spriteSheet)==null?void 0:e.spriteSheet)==null?void 0:t.sprites.length)??0}awake(){this._currentSprite=void 0,mI&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(){var e,t,s;if(!this.__didAwake||!((t=(e=this.sprite)==null?void 0:e.spriteSheet)!=null&&t.sprites))return;const r=this.sprite.spriteSheet.sprites[this.spriteIndex];if(this._currentSprite)this._currentSprite.geometry=AI.getOrCreateGeometry(r),this._currentSprite.material.map=r.texture;else{const n=new pi({color:16777215,side:bi});if(!n)return;if(Lne&&(n.wireframe=!0),this.color&&(n.color||(n.color=new be),n.color.copy(this.color),n.opacity=this.color.alpha),n.transparent=!0,r.texture&&!n.wireframe){let o=r.texture;o[yI]!==void 0&&o[yI]!==this&&this.spriteFrames>1&&(o=r.texture=o.clone()),o[yI]=this,n.map=o}this.sharedMaterial=n,this._currentSprite=new ve(AI.getOrCreateGeometry(r),n)}this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite)),this._currentSprite&&this._currentSprite.layers.set(this.layer),this.sharedMaterial&&(this.sharedMaterial.alphaTest=this.cutoutThreshold,this.sharedMaterial.transparent=this.transparent),this._currentSprite.castShadow=this.castShadows,(s=this._spriteSheet)==null||s.update()}}jr([w()],wa.prototype,"drawMode",2),jr([w(vi)],wa.prototype,"color",2),jr([w(Tt)],wa.prototype,"sharedMaterial",2),jr([w(ef)],wa.prototype,"sprite",1),jr([w()],wa.prototype,"transparent",2),jr([w()],wa.prototype,"cutoutThreshold",2),jr([w()],wa.prototype,"castShadows",2);class Pa{constructor(){h(this,"bb",null),h(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedCameraModel(e,t){return(t||new Pa).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+W0),(t||new Pa).__init(e.readInt32(e.position())+e.position(),e)}userId(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}guid(e){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}dontSave(){const e=this.bb.__offset(this.bb_pos,8);return e?!!this.bb.readInt8(this.bb_pos+e):!1}pos(e){const t=this.bb.__offset(this.bb_pos,10);return t?(e||new An).__init(this.bb_pos+t,this.bb):null}rot(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new An).__init(this.bb_pos+t,this.bb):null}static startSyncedCameraModel(e){e.startObject(5)}static addUserId(e,t){e.addFieldOffset(0,t,0)}static addGuid(e,t){e.addFieldOffset(1,t,0)}static addDontSave(e,t){e.addFieldInt8(2,+t,0)}static addPos(e,t){e.addFieldStruct(3,t,0)}static addRot(e,t){e.addFieldStruct(4,t,0)}static endSyncedCameraModel(e){return e.endObject()}static finishSyncedCameraModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedCameraModelBuffer(e,t){e.finish(t,void 0,!0)}}var Fne=Object.defineProperty,Une=Object.getOwnPropertyDescriptor,Nne=(i,e,t,s)=>{for(var r=s>1?void 0:s?Une(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Fne(e,t,r),r};const Ux="SCAM";q1(Ux,Pa.getRootAsSyncedCameraModel);const Tn=new gf;class zne{constructor(e,t){h(this,"userId"),h(this,"guid"),this.guid=t,this.userId=e}send(e,t){if(e){Tn.clear();const s=Tn.createString(this.guid),r=Tn.createString(this.userId);Pa.startSyncedCameraModel(Tn),Pa.addGuid(Tn,s),Pa.addUserId(Tn,r);const n=xt(e),o=O0(e);Pa.addPos(Tn,An.createVec3(Tn,n.x,n.y,n.z)),Pa.addRot(Tn,An.createVec3(Tn,o.x,o.y,o.z));const a=Pa.endSyncedCameraModel(Tn);Tn.finish(a,Ux),t.sendBinary(Tn.asUint8Array())}}}var bI;const xI=(bI=class extends Ee{constructor(){super(...arguments),h(this,"cameraPrefab",null),h(this,"_lastWorldPosition"),h(this,"_lastWorldQuaternion"),h(this,"_model",null),h(this,"_needsUpdate",!0),h(this,"_lastUpdateTime",0),h(this,"remoteCams",{}),h(this,"userToCamMap",{}),h(this,"_camTimeoutInSeconds",10),h(this,"_receiveCallback",null)}getCameraObject(i){const e=this.userToCamMap[i];return e?this.remoteCams[e].obj:null}async awake(){this._lastWorldPosition=this.worldPosition.clone(),this._lastWorldQuaternion=this.worldQuaternion.clone(),this.cameraPrefab&&("uri"in this.cameraPrefab&&(this.cameraPrefab=await this.cameraPrefab.instantiate(this.gameObject)),this.cameraPrefab&&"isObject3D"in this.cameraPrefab&&(this.cameraPrefab.visible=!1))}onEnable(){this._receiveCallback=this.context.connection.beginListenBinary(Ux,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(Ux,this._receiveCallback)}update(){for(const s in this.remoteCams){const r=this.remoteCams[s],n=this.context.time.realtimeSinceStartup-r.lastUpdate;if(!r||n>this._camTimeoutInSeconds){console.log("Remote cam timeout",r,n),r!=null&&r.obj&&$.destroy(r.obj),delete this.remoteCams[s],r&&delete this.userToCamMap[r.userId],xI.instances.push(r),this.context.players.removePlayerView(r.userId,$o.Browser);continue}}if(_t.IsInWebXR)return;const i=this.context.mainCamera;if(i===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new zne(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const e=xt(i),t=Ss(i);(e.distanceTo(this._lastWorldPosition)>.001||t.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(e),this._lastWorldQuaternion.copy(t),!((!this._needsUpdate||this.context.time.frameCount%2!==0)&&!(this.context.time.realtimeSinceStartup-this._lastUpdateTime>this._camTimeoutInSeconds*.5))&&(this._lastUpdateTime=this.context.time.realtimeSinceStartup,this._needsUpdate=!1,this._model.send(i,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,i,$o.Browser))}onReceivedRemoteCameraInfoBin(i){const e=i.guid();if(!e)return;const t=i.userId();if(!t||!this.context.connection.userIsInRoom(t)||!this.cameraPrefab)return;let s=this.remoteCams[e];if(!s)if("isObject3D"in this.cameraPrefab){const a=new Jo;a.context=this.context;const l=$.instantiate(this.cameraPrefab,a);s=this.remoteCams[e]={obj:l,lastUpdate:this.context.time.realtimeSinceStartup,userId:t},s.obj.visible=!0,this.gameObject.add(l),this.userToCamMap[t]=e,xI.instances.push(s);const c=$.getOrAddComponent(l,fr);c.connectionId=t,c.avatar=l}else return;const r=s.obj;this.context.players.setPlayerView(t,r,$o.Browser),s.lastUpdate=this.context.time.realtimeSinceStartup,on.markDirty(r);const n=i.pos();n&&Sd(r,n.x(),n.y(),n.z());const o=i.rot();o&&L0(r,o.x(),o.y(),o.z())}},h(bI,"instances",[]),bI);let Nx=xI;Nne([w([Me,dr])],Nx.prototype,"cameraPrefab",2);var Qne=Object.defineProperty,jne=Object.getOwnPropertyDescriptor,Av=(i,e,t,s)=>{for(var r=s>1?void 0:s?jne(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Qne(e,t,r),r};const wI="view",_I=re("debugsyncedroom");class oh extends Ee{constructor(){super(...arguments),h(this,"roomName"),h(this,"urlParameterName","room"),h(this,"joinRandomRoom",!0),h(this,"requireRoomParameter",!1),h(this,"autoRejoin",!0),h(this,"_roomPrefix"),h(this,"_lastPingTime",0),h(this,"_lastRoomTime",-1)}get RoomPrefix(){return this._roomPrefix}awake(){_I&&console.log("Room",this.roomName,this.urlParameterName,this.joinRandomRoom,this.requireRoomParameter,this.autoRejoin),this._roomPrefix===void 0&&(this._roomPrefix=this.roomName,this.roomName="")}onEnable(){const e=re(wI);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}(this.joinRandomRoom||re(this.urlParameterName))&&this.tryJoinRoom()}onDisable(){this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}tryJoinRandomRoom(){this.setRandomRoomUrlParameter(),this.tryJoinRoom()}tryJoinRoom(e=0){e===void 0&&(e=0);let t=!1;if(this.urlParameterName){const s=re(this.urlParameterName);if(s&&typeof s=="string"){t=!0;const r=hT(s);this.roomName=r}else if(this.joinRandomRoom&&(console.log("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),e<1))return this.tryJoinRoom(e+1)}else this.joinRandomRoom&&(this.roomName===null||this.roomName===void 0||this.roomName.length<=0)&&(console.log("generate room name"),this.roomName=this.generateRoomName());return this.requireRoomParameter&&!t?(_I&&console.log('No required room parameter "'+this.urlParameterName+'" in url - will not connect to networking backend.'),!1):(this.context.connection.isConnected||this.context.connection.connect(),_I&&console.log("Join "+this.roomName),this._roomPrefix&&(this.roomName=this._roomPrefix+this.roomName),this.context.connection.joinRoom(this.roomName),!0)}update(){this.context.connection.isConnected&&(this.context.time.time-this._lastPingTime>3&&(this._lastPingTime=this.context.time.time,this.context.connection.sendPing()),this.context.connection.isInRoom&&(this._lastRoomTime=this.context.time.time)),this._lastRoomTime>0&&this.context.time.time-this._lastRoomTime>.3&&(this._lastRoomTime=-1,this.autoRejoin?(console.log("Disconnected from networking backend - attempt reconnecting now"),this.tryJoinRoom()):console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you)"))}get currentRoomName(){return re(wI)||re(this.urlParameterName)}setRandomRoomUrlParameter(){const e=yf(),t=this.generateRoomName();re(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),mw(t,e)}generateRoomName(){return cT()+"_"+oT(100,999)}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){const e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(wI,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}}Av([w()],oh.prototype,"roomName",2),Av([w()],oh.prototype,"urlParameterName",2),Av([w()],oh.prototype,"joinRandomRoom",2),Av([w()],oh.prototype,"requireRoomParameter",2),Av([w()],oh.prototype,"autoRejoin",2);function Gne(){const i=re("testwindowcount")||0;i&&i>0&&Hne(i)}function Hne(i){if(re("testwindow"))return null;const e=new URL(window.location.href);bf(e.searchParams,lb,1),bf(e.searchParams,"testwindow",1);const t=e.toString(),s=[];window.onbeforeunload=()=>{for(const l of s)l.close()};const r=.05,n=128;let o=0,a=0;for(let l=0;l<i;l++){o*n+n*.01>=window.innerWidth&&(a+=1,o=0);const c=o*(n*(1+r))+window.screenLeft,u=a*(n*(1+r))+window.screenTop+90+60*a;o+=1;const d=window.open(t,"test window "+l,`popup=yes width=${n} height=${n} top=${u} left=${c}`);if(!d){console.warn("Failed to open window");continue}s.push(d),d.onload=()=>{d.onbeforeunload=()=>{for(let p=0;p<s.length;p++){const f=s[p];f!==d&&f.close()}s.length=0}}}return s}class CI extends Ee{awake(){Gne()}}class SI extends Ee{constructor(){super(...arguments),h(this,"transformsPerFrame",10),h(this,"interval",0),h(this,"useFlatbuffers",!0),h(this,"builder",null),h(this,"models",null)}awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(am,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new HN(this.context.connection.connectionId+"_simulatedTransform_"+e,this))}}update(){if(this.context.connection.isConnected){if(this.useFlatbuffers){if(!this.context.connection.connectionId||this.context.time.frameCount%this.interval!==0)return;this.builder===null&&(this.builder=new gf(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const s=E3(this.context.connection.connectionId,this);this.context.connection.sendBinary(s)}}else if(this.models)for(let e=0;e<this.models.length;e++){const t=this.models[e];t.dontSave=!0,t.update(this,null),this.context.connection.send("TestSimulateUserData-"+e,t)}}}}class HN{constructor(e,t){h(this,"guid"),h(this,"fast",!1),h(this,"position"),h(this,"rotation"),h(this,"velocity"),h(this,"dontSave"),this.guid=e,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(t,null)}isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}update(e,t){const s=e.worldPosition;this.position.x=s.x,this.position.y=s.y,this.position.z=s.z;const r=e.worldQuaternion;if(this.rotation.x=r.x,this.rotation.y=r.y,this.rotation.z=r.z,this.rotation.w=r.w,this.fast=!1,t){const n=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=n.x,this.velocity.y=n.y,this.velocity.z=n.z}}}h(HN,"temp",new S);var Vne=Object.defineProperty,Wne=Object.getOwnPropertyDescriptor,tf=(i,e,t,s)=>{for(var r=s>1?void 0:s?Wne(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Vne(e,t,r),r};class _a extends gr{constructor(){super(...arguments),h(this,"offset"),h(this,"rotation"),h(this,"focusArea"),h(this,"feather"),h(this,"kernelSize"),h(this,"resolutionScale")}get typeName(){return"TiltShiftEffect"}init(){this.offset.defaultValue=0,this.rotation.defaultValue=0,this.focusArea.defaultValue=.4,this.feather.defaultValue=.3,this.kernelSize.defaultValue=ll.MEDIUM,this.resolutionScale.defaultValue=1/window.devicePixelRatio}onCreateEffect(){console.log(this);const e=new W7({kernelSize:ll.VERY_LARGE});return this.offset.onValueChanged=t=>e.offset=t,this.rotation.onValueChanged=t=>e.rotation=t,this.focusArea.onValueChanged=t=>e.focusArea=t,this.feather.onValueChanged=t=>e.feather=t,this.kernelSize.onValueChanged=t=>e.blurPass.kernelSize=t,this.resolutionScale.onValueChanged=t=>e.resolution.scale=t/window.devicePixelRatio,e}}tf([w(Et)],_a.prototype,"offset",2),tf([w(Et)],_a.prototype,"rotation",2),tf([w(Et)],_a.prototype,"focusArea",2),tf([w(Et)],_a.prototype,"feather",2),tf([w(Et)],_a.prototype,"kernelSize",2),tf([w(Et)],_a.prototype,"resolutionScale",2),oo("TiltShiftEffect",_a);var qne=Object.defineProperty,Xne=Object.getOwnPropertyDescriptor,Yne=(i,e,t,s)=>{for(var r=s>1?void 0:s?Xne(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&qne(e,t,r),r};class yv extends gr{constructor(){super(...arguments),h(this,"mode")}get typeName(){return"ToneMapping"}get isToneMapping(){return!0}init(){this.mode.defaultValue=_r}apply(){this.mode.onValueChanged=this._apply.bind(this),this._apply(this.mode.value)}unapply(){this.context.renderer.toneMapping=_r}_apply(e){switch(e){case 0:this.context.renderer.toneMapping=Ef;break;case 1:this.context.renderer.toneMapping=kw;break;case 2:this.context.renderer.toneMapping=Dw;break}}}Yne([w(Et)],yv.prototype,"mode",2),oo("Tonemapping",yv);const Pu=new _d,nn=new S,ah=new S,ki=new Ce,VN={X:new S(1,0,0),Y:new S(0,1,0),Z:new S(0,0,1)},EI={type:"change"},WN={type:"mouseDown"},qN={type:"mouseUp",mode:null},XN={type:"objectChange"};class Kne extends Me{constructor(e,t){super(),t===void 0&&(console.warn('THREE.TransformControls: The second parameter "domElement" is now mandatory.'),t=document),this.isTransformControls=!0,this.visible=!1,this.domElement=t,this.domElement.style.touchAction="none";const s=new ioe;this._gizmo=s,this.add(s);const r=new soe;this._plane=r,this.add(r);const n=this;function o(b,y){let x=y;Object.defineProperty(n,b,{get:function(){return x!==void 0?x:y},set:function(_){x!==_&&(x=_,r[b]=_,s[b]=_,n.dispatchEvent({type:b+"-changed",value:_}),n.dispatchEvent(EI))}}),n[b]=y,r[b]=y,s[b]=y}o("camera",e),o("object",void 0),o("enabled",!0),o("axis",null),o("mode","translate"),o("translationSnap",null),o("rotationSnap",null),o("scaleSnap",null),o("space","world"),o("size",1),o("dragging",!1),o("showX",!0),o("showY",!0),o("showZ",!0);const a=new S,l=new S,c=new Ce,u=new Ce,d=new S,p=new Ce,f=new S,g=new S,m=new S,v=0,A=new S;o("worldPosition",a),o("worldPositionStart",l),o("worldQuaternion",c),o("worldQuaternionStart",u),o("cameraPosition",d),o("cameraQuaternion",p),o("pointStart",f),o("pointEnd",g),o("rotationAxis",m),o("rotationAngle",v),o("eye",A),this._offset=new S,this._startNorm=new S,this._endNorm=new S,this._cameraScale=new S,this._parentPosition=new S,this._parentQuaternion=new Ce,this._parentQuaternionInv=new Ce,this._parentScale=new S,this._worldScaleStart=new S,this._worldQuaternionInv=new Ce,this._worldScale=new S,this._positionStart=new S,this._quaternionStart=new Ce,this._scaleStart=new S,this._getPointer=Jne.bind(this),this._onPointerDown=$ne.bind(this),this._onPointerHover=Zne.bind(this),this._onPointerMove=eoe.bind(this),this._onPointerUp=toe.bind(this),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointermove",this._onPointerHover),this.domElement.addEventListener("pointerup",this._onPointerUp)}updateMatrixWorld(){this.object!==void 0&&(this.object.updateMatrixWorld(),this.object.parent===null?console.error("TransformControls: The attached 3D object must be a part of the scene graph."):this.object.parent.matrixWorld.decompose(this._parentPosition,this._parentQuaternion,this._parentScale),this.object.matrixWorld.decompose(this.worldPosition,this.worldQuaternion,this._worldScale),this._parentQuaternionInv.copy(this._parentQuaternion).invert(),this._worldQuaternionInv.copy(this.worldQuaternion).invert()),this.camera.updateMatrixWorld(),this.camera.matrixWorld.decompose(this.cameraPosition,this.cameraQuaternion,this._cameraScale),this.camera.isOrthographicCamera?this.camera.getWorldDirection(this.eye).negate():this.eye.copy(this.cameraPosition).sub(this.worldPosition).normalize(),super.updateMatrixWorld(this)}pointerHover(e){if(this.object===void 0||this.dragging===!0)return;Pu.setFromCamera(e,this.camera);const t=MI(this._gizmo.picker[this.mode],Pu);t?this.axis=t.object.name:this.axis=null}pointerDown(e){if(!(this.object===void 0||this.dragging===!0||e.button!==0)&&this.axis!==null){Pu.setFromCamera(e,this.camera);const t=MI(this._plane,Pu,!0);t&&(this.object.updateMatrixWorld(),this.object.parent.updateMatrixWorld(),this._positionStart.copy(this.object.position),this._quaternionStart.copy(this.object.quaternion),this._scaleStart.copy(this.object.scale),this.object.matrixWorld.decompose(this.worldPositionStart,this.worldQuaternionStart,this._worldScaleStart),this.pointStart.copy(t.point).sub(this.worldPositionStart)),this.dragging=!0,WN.mode=this.mode,this.dispatchEvent(WN)}}pointerMove(e){const t=this.axis,s=this.mode,r=this.object;let n=this.space;if(s==="scale"?n="local":(t==="E"||t==="XYZE"||t==="XYZ")&&(n="world"),r===void 0||t===null||this.dragging===!1||e.button!==-1)return;Pu.setFromCamera(e,this.camera);const o=MI(this._plane,Pu,!0);if(o){if(this.pointEnd.copy(o.point).sub(this.worldPositionStart),s==="translate")this._offset.copy(this.pointEnd).sub(this.pointStart),n==="local"&&t!=="XYZ"&&this._offset.applyQuaternion(this._worldQuaternionInv),t.indexOf("X")===-1&&(this._offset.x=0),t.indexOf("Y")===-1&&(this._offset.y=0),t.indexOf("Z")===-1&&(this._offset.z=0),n==="local"&&t!=="XYZ"?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),r.position.copy(this._offset).add(this._positionStart),this.translationSnap&&(n==="local"&&(r.position.applyQuaternion(ki.copy(this._quaternionStart).invert()),t.search("X")!==-1&&(r.position.x=Math.round(r.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(r.position.y=Math.round(r.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(r.position.z=Math.round(r.position.z/this.translationSnap)*this.translationSnap),r.position.applyQuaternion(this._quaternionStart)),n==="world"&&(r.parent&&r.position.add(nn.setFromMatrixPosition(r.parent.matrixWorld)),t.search("X")!==-1&&(r.position.x=Math.round(r.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(r.position.y=Math.round(r.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(r.position.z=Math.round(r.position.z/this.translationSnap)*this.translationSnap),r.parent&&r.position.sub(nn.setFromMatrixPosition(r.parent.matrixWorld))));else if(s==="scale"){if(t.search("XYZ")!==-1){let a=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(a*=-1),ah.set(a,a,a)}else nn.copy(this.pointStart),ah.copy(this.pointEnd),nn.applyQuaternion(this._worldQuaternionInv),ah.applyQuaternion(this._worldQuaternionInv),ah.divide(nn),t.search("X")===-1&&(ah.x=1),t.search("Y")===-1&&(ah.y=1),t.search("Z")===-1&&(ah.z=1);r.scale.copy(this._scaleStart).multiply(ah),this.scaleSnap&&(t.search("X")!==-1&&(r.scale.x=Math.round(r.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Y")!==-1&&(r.scale.y=Math.round(r.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Z")!==-1&&(r.scale.z=Math.round(r.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(s==="rotate"){this._offset.copy(this.pointEnd).sub(this.pointStart);const a=20/this.worldPosition.distanceTo(nn.setFromMatrixPosition(this.camera.matrixWorld));t==="E"?(this.rotationAxis.copy(this.eye),this.rotationAngle=this.pointEnd.angleTo(this.pointStart),this._startNorm.copy(this.pointStart).normalize(),this._endNorm.copy(this.pointEnd).normalize(),this.rotationAngle*=this._endNorm.cross(this._startNorm).dot(this.eye)<0?1:-1):t==="XYZE"?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(nn.copy(this.rotationAxis).cross(this.eye))*a):(t==="X"||t==="Y"||t==="Z")&&(this.rotationAxis.copy(VN[t]),nn.copy(VN[t]),n==="local"&&nn.applyQuaternion(this.worldQuaternion),this.rotationAngle=this._offset.dot(nn.cross(this.eye).normalize())*a),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),n==="local"&&t!=="E"&&t!=="XYZE"?(r.quaternion.copy(this._quaternionStart),r.quaternion.multiply(ki.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),r.quaternion.copy(ki.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),r.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(EI),this.dispatchEvent(XN)}}pointerUp(e){e.button===0&&(this.dragging&&this.axis!==null&&(qN.mode=this.mode,this.dispatchEvent(qN)),this.dragging=!1,this.axis=null)}dispose(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerHover),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.traverse(function(e){e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()})}attach(e){return this.object=e,this.visible=!0,this}detach(){return this.object=void 0,this.visible=!1,this.axis=null,this}reset(){this.enabled&&this.dragging&&(this.object.position.copy(this._positionStart),this.object.quaternion.copy(this._quaternionStart),this.object.scale.copy(this._scaleStart),this.dispatchEvent(EI),this.dispatchEvent(XN),this.pointStart.copy(this.pointEnd))}getRaycaster(){return Pu}getMode(){return this.mode}setMode(e){this.mode=e}setTranslationSnap(e){this.translationSnap=e}setRotationSnap(e){this.rotationSnap=e}setScaleSnap(e){this.scaleSnap=e}setSize(e){this.size=e}setSpace(e){this.space=e}}function Jne(i){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:i.button};{const e=this.domElement.getBoundingClientRect();return{x:(i.clientX-e.left)/e.width*2-1,y:-(i.clientY-e.top)/e.height*2+1,button:i.button}}}function Zne(i){if(this.enabled)switch(i.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(i));break}}function $ne(i){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(i.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(i)),this.pointerDown(this._getPointer(i)))}function eoe(i){this.enabled&&this.pointerMove(this._getPointer(i))}function toe(i){this.enabled&&(this.domElement.releasePointerCapture(i.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(i)))}function MI(i,e,t){const s=e.intersectObject(i,!0);for(let r=0;r<s.length;r++)if(s[r].object.visible||t)return s[r];return!1}const zx=new vs,yi=new S(0,1,0),YN=new S(0,0,0),KN=new Pe,Qx=new Ce,jx=new Ce,Ca=new S,JN=new Pe,bv=new S(1,0,0),Bu=new S(0,1,0),xv=new S(0,0,1),Gx=new S,wv=new S,_v=new S;class ioe extends Me{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const e=new pi({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),t=new qi({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),s=e.clone();s.opacity=.15;const r=t.clone();r.opacity=.5;const n=e.clone();n.color.setHex(16711680);const o=e.clone();o.color.setHex(65280);const a=e.clone();a.color.setHex(255);const l=e.clone();l.color.setHex(16711680),l.opacity=.5;const c=e.clone();c.color.setHex(65280),c.opacity=.5;const u=e.clone();u.color.setHex(255),u.opacity=.5;const d=e.clone();d.opacity=.25;const p=e.clone();p.color.setHex(16776960),p.opacity=.25,e.clone().color.setHex(16776960);const f=e.clone();f.color.setHex(7895160);const g=new Hi(0,.04,.1,12);g.translate(0,.05,0);const m=new ui(.08,.08,.08);m.translate(0,.04,0);const v=new mt;v.setAttribute("position",new $e([0,0,0,1,0,0],3));const A=new Hi(.0075,.0075,.5,3);A.translate(0,.25,0);function b(F,X){const te=new Ta(F,.0075,3,64,X*Math.PI*2);return te.rotateY(Math.PI/2),te.rotateX(Math.PI/2),te}function y(){const F=new mt;return F.setAttribute("position",new $e([0,0,0,1,1,1],3)),F}const x={X:[[new ve(g,n),[.5,0,0],[0,0,-Math.PI/2]],[new ve(g,n),[-.5,0,0],[0,0,Math.PI/2]],[new ve(A,n),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new ve(g,o),[0,.5,0]],[new ve(g,o),[0,-.5,0],[Math.PI,0,0]],[new ve(A,o)]],Z:[[new ve(g,a),[0,0,.5],[Math.PI/2,0,0]],[new ve(g,a),[0,0,-.5],[-Math.PI/2,0,0]],[new ve(A,a),null,[Math.PI/2,0,0]]],XYZ:[[new ve(new Ia(.1,0),d.clone()),[0,0,0]]],XY:[[new ve(new ui(.15,.15,.01),u.clone()),[.15,.15,0]]],YZ:[[new ve(new ui(.15,.15,.01),l.clone()),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new ve(new ui(.15,.15,.01),c.clone()),[.15,0,.15],[-Math.PI/2,0,0]]]},_={X:[[new ve(new Hi(.2,0,.6,4),s),[.3,0,0],[0,0,-Math.PI/2]],[new ve(new Hi(.2,0,.6,4),s),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new ve(new Hi(.2,0,.6,4),s),[0,.3,0]],[new ve(new Hi(.2,0,.6,4),s),[0,-.3,0],[0,0,Math.PI]]],Z:[[new ve(new Hi(.2,0,.6,4),s),[0,0,.3],[Math.PI/2,0,0]],[new ve(new Hi(.2,0,.6,4),s),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new ve(new Ia(.2,0),s)]],XY:[[new ve(new ui(.2,.2,.01),s),[.15,.15,0]]],YZ:[[new ve(new ui(.2,.2,.01),s),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new ve(new ui(.2,.2,.01),s),[.15,0,.15],[-Math.PI/2,0,0]]]},M={START:[[new ve(new Ia(.01,2),r),null,null,null,"helper"]],END:[[new ve(new Ia(.01,2),r),null,null,null,"helper"]],DELTA:[[new Xi(y(),r),null,null,null,"helper"]],X:[[new Xi(v,r.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new Xi(v,r.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new Xi(v,r.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},P={XYZE:[[new ve(b(.5,1),f),null,[0,Math.PI/2,0]]],X:[[new ve(b(.5,.5),n)]],Y:[[new ve(b(.5,.5),o),null,[0,0,-Math.PI/2]]],Z:[[new ve(b(.5,.5),a),null,[0,Math.PI/2,0]]],E:[[new ve(b(.75,1),p),null,[0,Math.PI/2,0]]]},C={AXIS:[[new Xi(v,r.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},R={XYZE:[[new ve(new Bn(.25,10,8),s)]],X:[[new ve(new Ta(.5,.1,4,24),s),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new ve(new Ta(.5,.1,4,24),s),[0,0,0],[Math.PI/2,0,0]]],Z:[[new ve(new Ta(.5,.1,4,24),s),[0,0,0],[0,0,-Math.PI/2]]],E:[[new ve(new Ta(.75,.1,2,24),s)]]},T={X:[[new ve(m,n),[.5,0,0],[0,0,-Math.PI/2]],[new ve(A,n),[0,0,0],[0,0,-Math.PI/2]],[new ve(m,n),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new ve(m,o),[0,.5,0]],[new ve(A,o)],[new ve(m,o),[0,-.5,0],[0,0,Math.PI]]],Z:[[new ve(m,a),[0,0,.5],[Math.PI/2,0,0]],[new ve(A,a),[0,0,0],[Math.PI/2,0,0]],[new ve(m,a),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new ve(new ui(.15,.15,.01),u),[.15,.15,0]]],YZ:[[new ve(new ui(.15,.15,.01),l),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new ve(new ui(.15,.15,.01),c),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new ve(new ui(.1,.1,.1),d.clone())]]},z={X:[[new ve(new Hi(.2,0,.6,4),s),[.3,0,0],[0,0,-Math.PI/2]],[new ve(new Hi(.2,0,.6,4),s),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new ve(new Hi(.2,0,.6,4),s),[0,.3,0]],[new ve(new Hi(.2,0,.6,4),s),[0,-.3,0],[0,0,Math.PI]]],Z:[[new ve(new Hi(.2,0,.6,4),s),[0,0,.3],[Math.PI/2,0,0]],[new ve(new Hi(.2,0,.6,4),s),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new ve(new ui(.2,.2,.01),s),[.15,.15,0]]],YZ:[[new ve(new ui(.2,.2,.01),s),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new ve(new ui(.2,.2,.01),s),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new ve(new ui(.2,.2,.2),s),[0,0,0]]]},G={X:[[new Xi(v,r.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new Xi(v,r.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new Xi(v,r.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function N(F){const X=new Me;for(const te in F)for(let ne=F[te].length;ne--;){const Z=F[te][ne][0].clone(),fe=F[te][ne][1],ae=F[te][ne][2],Le=F[te][ne][3],Se=F[te][ne][4];Z.name=te,Z.tag=Se,fe&&Z.position.set(fe[0],fe[1],fe[2]),ae&&Z.rotation.set(ae[0],ae[1],ae[2]),Le&&Z.scale.set(Le[0],Le[1],Le[2]),Z.updateMatrix();const ie=Z.geometry.clone();ie.applyMatrix4(Z.matrix),Z.geometry=ie,Z.renderOrder=1/0,Z.position.set(0,0,0),Z.rotation.set(0,0,0),Z.scale.set(1,1,1),X.add(Z)}return X}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=N(x)),this.add(this.gizmo.rotate=N(P)),this.add(this.gizmo.scale=N(T)),this.add(this.picker.translate=N(_)),this.add(this.picker.rotate=N(R)),this.add(this.picker.scale=N(z)),this.add(this.helper.translate=N(M)),this.add(this.helper.rotate=N(C)),this.add(this.helper.scale=N(G)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}updateMatrixWorld(e){const t=(this.mode==="scale"?"local":this.space)==="local"?this.worldQuaternion:jx;this.gizmo.translate.visible=this.mode==="translate",this.gizmo.rotate.visible=this.mode==="rotate",this.gizmo.scale.visible=this.mode==="scale",this.helper.translate.visible=this.mode==="translate",this.helper.rotate.visible=this.mode==="rotate",this.helper.scale.visible=this.mode==="scale";let s=[];s=s.concat(this.picker[this.mode].children),s=s.concat(this.gizmo[this.mode].children),s=s.concat(this.helper[this.mode].children);for(let r=0;r<s.length;r++){const n=s[r];n.visible=!0,n.rotation.set(0,0,0),n.position.copy(this.worldPosition);let o;if(this.camera.isOrthographicCamera?o=(this.camera.top-this.camera.bottom)/this.camera.zoom:o=this.worldPosition.distanceTo(this.cameraPosition)*Math.min(1.9*Math.tan(Math.PI*this.camera.fov/360)/this.camera.zoom,7),n.scale.set(1,1,1).multiplyScalar(o*this.size/4),n.tag==="helper"){n.visible=!1,n.name==="AXIS"?(n.position.copy(this.worldPositionStart),n.visible=!!this.axis,this.axis==="X"&&(ki.setFromEuler(zx.set(0,0,0)),n.quaternion.copy(t).multiply(ki),Math.abs(yi.copy(bv).applyQuaternion(t).dot(this.eye))>.9&&(n.visible=!1)),this.axis==="Y"&&(ki.setFromEuler(zx.set(0,0,Math.PI/2)),n.quaternion.copy(t).multiply(ki),Math.abs(yi.copy(Bu).applyQuaternion(t).dot(this.eye))>.9&&(n.visible=!1)),this.axis==="Z"&&(ki.setFromEuler(zx.set(0,Math.PI/2,0)),n.quaternion.copy(t).multiply(ki),Math.abs(yi.copy(xv).applyQuaternion(t).dot(this.eye))>.9&&(n.visible=!1)),this.axis==="XYZE"&&(ki.setFromEuler(zx.set(0,Math.PI/2,0)),yi.copy(this.rotationAxis),n.quaternion.setFromRotationMatrix(KN.lookAt(YN,yi,Bu)),n.quaternion.multiply(ki),n.visible=this.dragging),this.axis==="E"&&(n.visible=!1)):n.name==="START"?(n.position.copy(this.worldPositionStart),n.visible=this.dragging):n.name==="END"?(n.position.copy(this.worldPosition),n.visible=this.dragging):n.name==="DELTA"?(n.position.copy(this.worldPositionStart),n.quaternion.copy(this.worldQuaternionStart),nn.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),nn.applyQuaternion(this.worldQuaternionStart.clone().invert()),n.scale.copy(nn),n.visible=this.dragging):(n.quaternion.copy(t),this.dragging?n.position.copy(this.worldPositionStart):n.position.copy(this.worldPosition),this.axis&&(n.visible=this.axis.search(n.name)!==-1));continue}n.quaternion.copy(t),this.mode==="translate"||this.mode==="scale"?(n.name==="X"&&Math.abs(yi.copy(bv).applyQuaternion(t).dot(this.eye))>.99&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1),n.name==="Y"&&Math.abs(yi.copy(Bu).applyQuaternion(t).dot(this.eye))>.99&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1),n.name==="Z"&&Math.abs(yi.copy(xv).applyQuaternion(t).dot(this.eye))>.99&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1),n.name==="XY"&&Math.abs(yi.copy(xv).applyQuaternion(t).dot(this.eye))<.2&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1),n.name==="YZ"&&Math.abs(yi.copy(bv).applyQuaternion(t).dot(this.eye))<.2&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1),n.name==="XZ"&&Math.abs(yi.copy(Bu).applyQuaternion(t).dot(this.eye))<.2&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1)):this.mode==="rotate"&&(Qx.copy(t),yi.copy(this.eye).applyQuaternion(ki.copy(t).invert()),n.name.search("E")!==-1&&n.quaternion.setFromRotationMatrix(KN.lookAt(this.eye,YN,Bu)),n.name==="X"&&(ki.setFromAxisAngle(bv,Math.atan2(-yi.y,yi.z)),ki.multiplyQuaternions(Qx,ki),n.quaternion.copy(ki)),n.name==="Y"&&(ki.setFromAxisAngle(Bu,Math.atan2(yi.x,yi.z)),ki.multiplyQuaternions(Qx,ki),n.quaternion.copy(ki)),n.name==="Z"&&(ki.setFromAxisAngle(xv,Math.atan2(yi.y,yi.x)),ki.multiplyQuaternions(Qx,ki),n.quaternion.copy(ki))),n.visible=n.visible&&(n.name.indexOf("X")===-1||this.showX),n.visible=n.visible&&(n.name.indexOf("Y")===-1||this.showY),n.visible=n.visible&&(n.name.indexOf("Z")===-1||this.showZ),n.visible=n.visible&&(n.name.indexOf("E")===-1||this.showX&&this.showY&&this.showZ),n.material._color=n.material._color||n.material.color.clone(),n.material._opacity=n.material._opacity||n.material.opacity,n.material.color.copy(n.material._color),n.material.opacity=n.material._opacity,this.enabled&&this.axis&&(n.name===this.axis||this.axis.split("").some(function(a){return n.name===a}))&&(n.material.color.setHex(16776960),n.material.opacity=1)}super.updateMatrixWorld(e)}}class soe extends ve{constructor(){super(new Ns(1e5,1e5,2,2),new pi({visible:!1,wireframe:!0,side:bi,transparent:!0,opacity:.1,toneMapped:!1})),this.isTransformControlsPlane=!0,this.type="TransformControlsPlane"}updateMatrixWorld(e){let t=this.space;switch(this.position.copy(this.worldPosition),this.mode==="scale"&&(t="local"),Gx.copy(bv).applyQuaternion(t==="local"?this.worldQuaternion:jx),wv.copy(Bu).applyQuaternion(t==="local"?this.worldQuaternion:jx),_v.copy(xv).applyQuaternion(t==="local"?this.worldQuaternion:jx),yi.copy(wv),this.mode){case"translate":case"scale":switch(this.axis){case"X":yi.copy(this.eye).cross(Gx),Ca.copy(Gx).cross(yi);break;case"Y":yi.copy(this.eye).cross(wv),Ca.copy(wv).cross(yi);break;case"Z":yi.copy(this.eye).cross(_v),Ca.copy(_v).cross(yi);break;case"XY":Ca.copy(_v);break;case"YZ":Ca.copy(Gx);break;case"XZ":yi.copy(_v),Ca.copy(wv);break;case"XYZ":case"E":Ca.set(0,0,0);break}break;case"rotate":default:Ca.set(0,0,0)}Ca.length()===0?this.quaternion.copy(this.cameraQuaternion):(JN.lookAt(nn.set(0,0,0),Ca,yi),this.quaternion.setFromRotationMatrix(JN)),super.updateMatrixWorld(e)}}var roe=Object.defineProperty,noe=Object.getOwnPropertyDescriptor,Hx=(i,e,t,s)=>{for(var r=s>1?void 0:s?noe(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&roe(e,t,r),r};class ku extends Ee{constructor(){super(...arguments),h(this,"isGizmo",!1),h(this,"translationSnap",1),h(this,"rotationSnapAngle",15),h(this,"scaleSnap",.25),h(this,"control"),h(this,"orbit"),h(this,"changeEventListener"),h(this,"windowKeyDownListener"),h(this,"windowKeyUpListener")}onEnable(){var e;this.isGizmo&&!og||this.context.mainCamera&&(this.control||(this.control=new Kne(this.context.mainCamera,this.context.domElement),this.control.visible=!0,this.control.enabled=!0,this.control.getRaycaster().layers.set(2),this.control.size=1,this.control.traverse(t=>{const s=t;if(s.layers.set(2),s){const r=s.material;r&&(r.opacity=.3)}}),this.orbit=$.getComponentInParent(this.context.mainCamera,Tl)??void 0),this.control&&(this.context.scene.add(this.control),this.control.attach(this.gameObject),this.changeEventListener=this.onControlChangedEvent.bind(this),(e=this.control)==null||e.addEventListener("dragging-changed",this.changeEventListener),this.addWindowEvents()))}onDisable(){var e,t;(e=this.control)==null||e.removeFromParent(),this.changeEventListener&&((t=this.control)==null||t.removeEventListener("dragging-changed",this.changeEventListener)),this.removeWindowEvents()}enableSnapping(){this.control&&(this.control.setTranslationSnap(this.translationSnap),this.control.setRotationSnap(Cr.degToRad(this.rotationSnapAngle)),this.control.setScaleSnap(this.scaleSnap))}disableSnapping(){this.control&&(this.control.setTranslationSnap(null),this.control.setRotationSnap(null),this.control.setScaleSnap(null))}onControlChangedEvent(e){const t=this.orbit;if(t&&(t.enabled=!e.value),e.value){const s=$.getComponentInParent(this.gameObject,jc);s&&s.requestOwnership()}}addWindowEvents(){const e=this.control;e&&(this.windowKeyDownListener||(this.windowKeyDownListener=t=>{if(this.enabled)switch(t.keyCode){case 81:e.setSpace(e.space==="local"?"world":"local");break;case 16:this.enableSnapping();break;case 87:e.setMode("translate");break;case 69:e.setMode("rotate");break;case 82:e.setMode("scale");break;case 187:case 107:e.setSize(e.size+.1);break;case 189:case 109:e.setSize(Math.max(e.size-.1,.1));break;case 88:e.showX=!e.showX;break;case 89:e.showY=!e.showY;break;case 90:e.showZ=!e.showZ;break;case 32:e.enabled=!e.enabled;break}}),this.windowKeyUpListener||(this.windowKeyUpListener=t=>{if(this.enabled)switch(t.keyCode){case 16:this.disableSnapping();break}}),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener))}removeWindowEvents(){window.removeEventListener("keydown",this.windowKeyDownListener),window.removeEventListener("keyup",this.windowKeyUpListener)}}Hx([w()],ku.prototype,"isGizmo",2),Hx([w()],ku.prototype,"translationSnap",2),Hx([w()],ku.prototype,"rotationSnapAngle",2),Hx([w()],ku.prototype,"scaleSnap",2);var ooe=Object.defineProperty,aoe=Object.getOwnPropertyDescriptor,II=(i,e,t,s)=>{for(var r=s>1?void 0:s?aoe(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&ooe(e,t,r),r};class Du extends gr{constructor(){super(...arguments),h(this,"color"),h(this,"intensity"),h(this,"center")}get typeName(){return"Vignette"}init(){this.color.defaultValue={r:0,g:0,b:0,a:1},this.intensity.defaultValue=0,this.center.defaultValue={x:.5,y:.5}}onCreateEffect(){const e=new PD;return this.intensity.onValueChanged=t=>{e.offset=t,this.updateDarkness(e)},this.color.onValueChanged=t=>{this.updateDarkness(e)},e}updateDarkness(e){const t=this.intensity.value;e.darkness=t}}II([w(Et)],Du.prototype,"color",2),II([w(Et)],Du.prototype,"intensity",2),II([w(Et)],Du.prototype,"center",2),oo("Vignette",Du);var loe=Object.defineProperty,coe=Object.getOwnPropertyDescriptor,hoe=(i,e,t,s)=>{for(var r=s>1?void 0:s?coe(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&loe(e,t,r),r};const TI=re("debugpost");class Vx extends Ee{constructor(){super(...arguments),h(this,"sharedProfile"),h(this,"_postprocessing"),h(this,"_effects",[]),h(this,"_lastApplyTime"),h(this,"_rapidApplyCount",0),h(this,"_isDirty",!1),h(this,"_modificationQueue"),h(this,"_recreateId",-1)}markDirty(){this._isDirty=!0}awake(){var e;(e=this.sharedProfile)==null||e.init(),TI&&(console.log(this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",t=>{t.key==="p"&&(console.log("Toggle volume: "+this.name,!this.enabled),this.enabled=!this.enabled)}))}onDisable(){var e;(e=this._postprocessing)==null||e.unapply()}onBeforeRender(){if(!this.context.isInXR){if(this.context.composer&&!(this.context.composer instanceof IC))return;this.context.mainCamera&&(!this._postprocessing||!this._postprocessing.isActive||this._isDirty)&&this.apply(),this.context.composer&&(this.context.composer.setRenderer(this.context.renderer),this.context.composer.setMainScene(this.context.scene),this.context.mainCamera&&this.context.composer.setMainCamera(this.context.mainCamera))}}onDestroy(){var e;(e=this._postprocessing)==null||e.dispose()}apply(){var e,t;TI&&console.log("Apply PostProcessing",this,(e=this.context.mainCamera)==null?void 0:e.name),lr()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("Detected rapid post processing modifications - this might be a bug",this)),this._lastApplyTime=Date.now()),this._isDirty=!1,this.unapply(),this._effects.length=0,(t=this.sharedProfile)!=null&&t.components&&this._effects.push(...this.sharedProfile.components);const s=this.gameObject.getComponentsInChildren(gr);if(TI&&s!=null&&s.length&&console.log("Additional",s),s)for(const r of s)r.active&&this._effects.push(r);this._effects.length>0&&(this._postprocessing||(this._postprocessing=new Tx(this.context)),this._postprocessing.apply(this._effects),this._applyPostQueue())}unapply(){var e;(e=this._postprocessing)==null||e.unapply()}_applyPostQueue(){if(this._modificationQueue){for(const e of this._modificationQueue.values())this.onEditorModification(e);this._modificationQueue.clear()}}onEditorModification(e){var t,s;if(e.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(e.propertyName,e),!0;if(!((t=this._effects)!=null&&t.length))return;const r=e.propertyName.split(".");if(r.length===3||r.length===4){const n=r[1],o=r[2];for(const a of this._effects)if(((s=a.typeName)==null?void 0:s.toLowerCase())===n.toLowerCase()){if(o==="active"){a.active=e.value,this.scheduleRecreate();return}if(!Wx.has(n)){const l=new Array;Wx.set(n,l);const c=Object.keys(a);for(const u of c)a[u]instanceof Et&&l.push(u)}if(Wx.has(n)){const l=o.toLowerCase(),c=Wx.get(n);for(const u of c)if(u.toLowerCase()===l){const d=a[u];d instanceof Et&&(r.length===4&&r[3]==="active"?(d.overrideState=e.value,this.scheduleRecreate()):d&&d.value!==void 0&&(d.value=e.value));return}}console.warn("Unknown modification",o);return}}return!0}return!1}scheduleRecreate(){const e=++this._recreateId;setTimeout(()=>{e===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}hoe([ip(Dm)],Vx.prototype,"sharedProfile",2);const Wx=new Map;var uoe=Object.defineProperty,doe=Object.getOwnPropertyDescriptor,poe=(i,e,t,s)=>{for(var r=s>1?void 0:s?doe(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&uoe(e,t,r),r};class qx extends Ee{constructor(){super(...arguments),h(this,"backgroundTint",new vi(1,1,1,1)),h(this,"_preRender"),h(this,"backgroundPlane"),h(this,"threeTexture"),h(this,"forceTextureInitialization",function(){const e=new pi,t=new Ns,s=new Vr;s.add(new ve(t,e));const r=new Eh;return function(n,o){e.map=o,n.render(s,r)}}())}awake(){_t.OptionalFeatures_AR.push("camera-access")}get background(){return this.backgroundPlane}onEnable(){this._preRender=this.preRender.bind(this),this.context.pre_render_callbacks.push(this._preRender),this.backgroundPlane&&(this.gameObject.add(this.backgroundPlane),this.backgroundPlane.visible=!1)}onDisable(){this.context.pre_render_callbacks=this.context.pre_render_callbacks.filter(e=>e!==this._preRender),this.backgroundPlane&&this.gameObject.remove(this.backgroundPlane)}preRender(){if(!this||!this.gameObject)return;const e=this.context.renderer.xr.getFrame();e&&(!this.threeTexture&&this.context.renderer&&(this.threeTexture=new Ft,this.forceTextureInitialization(this.context.renderer,this.threeTexture)),this.backgroundPlane===void 0&&(this.backgroundPlane=goe(this.backgroundTint),this.gameObject.add(this.backgroundPlane)),this.updateFromFrame(e))}onBeforeRender(e){this.updateFromFrame(e)}updateFromFrame(e){if(!e)return;const t=e.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(t){for(const s of t.views)if("camera"in s&&s.camera){let r=this.context.renderer.xr.getBinding();if(r||(r=new XRWebGLBinding(e.session,this.context.renderer.getContext())),r){let n=null;if("getCameraImage"in r){n=r.getCameraImage(s.camera);const o=this.context.renderer.properties.get(this.threeTexture);o.__webglTexture=n,this.backgroundPlane&&(this.backgroundPlane.setTexture(this.threeTexture),this.backgroundPlane.visible=!0)}}}}}}poe([w()],qx.prototype,"backgroundTint",2);let foe=`
5438
+ `)}}}applyShadowMaterial(){var e;const t=$.getComponent(this.gameObject,Ii);if(t)if(((e=t.sharedMaterial)==null?void 0:e.type)!=="ShadowMaterial"){const s=new a1;s.color=this.shadowColor,s.opacity=this.shadowColor.alpha,this.applyMaterialOptions(s),t.sharedMaterial=s}else{const s=t.sharedMaterial;s.color=this.shadowColor,s.opacity=this.shadowColor.alpha,this.applyMaterialOptions(s)}}applyOccluderMaterial(){const e=$.getComponent(this.gameObject,Ii);if(e){const t=e.sharedMaterial;t.depthWrite=!0,t.stencilWrite=!0,t.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}}NN([w()],pv.prototype,"mode",2),NN([w(vi)],pv.prototype,"shadowColor",2);var mne=Object.defineProperty,vne=Object.getOwnPropertyDescriptor,Dx=(i,e,t,s)=>{for(var r=s>1?void 0:s?vne(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&mne(e,t,r),r},dI;const zN=(dI=class extends Ee{constructor(){super(...arguments),h(this,"target",null),h(this,"followFactor",.1),h(this,"rotateFactor",.1),h(this,"positionAxes",fp.All),h(this,"flipForward",!1),h(this,"_firstUpdate",!0)}onBeforeRender(){this.updateNow(!1)}updateNow(i){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const e=xt(this.target),t=this._firstUpdate||i?1:Je.clamp01(this.context.time.deltaTime*this.followFactor),s=this.worldPosition;this.positionAxes&fp.X&&(s.x=Je.lerp(s.x,e.x,t)),this.positionAxes&fp.Y&&(s.y=Je.lerp(s.y,e.y,t)),this.positionAxes&fp.Z&&(s.z=Je.lerp(s.z,e.z,t)),this.worldPosition=s}if(this.rotateFactor>0){const e=Ss(this.target);this.flipForward&&e.premultiply(zN._invertForward);const t=this._firstUpdate||i?1:Je.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(e,t)}this._firstUpdate=!1}}},h(dI,"_invertForward",new Ce().setFromAxisAngle(new S(0,1,0),Math.PI)),dI);let nh=zN;Dx([w(Me)],nh.prototype,"target",2),Dx([w()],nh.prototype,"followFactor",2),Dx([w()],nh.prototype,"rotateFactor",2),Dx([w()],nh.prototype,"positionAxes",2);class Ane extends ve{constructor(e){const t=new yne(e),s=new Ns(t.image.width*.001,t.image.height*.001),r=new pi({map:t,toneMapped:!1,transparent:!0});super(s,r);function n(o){r.map.dispatchDOMEvent(o)}this.addEventListener("mousedown",n),this.addEventListener("mousemove",n),this.addEventListener("mouseup",n),this.addEventListener("click",n),this.dispose=function(){s.dispose(),r.dispose(),r.map.dispose(),pI.delete(e),this.removeEventListener("mousedown",n),this.removeEventListener("mousemove",n),this.removeEventListener("mouseup",n),this.removeEventListener("click",n)}}}class yne extends SP{constructor(e){super(QN(e)),this.dom=e,this.anisotropy=16,this.encoding=yt,this.minFilter=Pt,this.magFilter=Pt;const t=new MutationObserver(()=>{this.scheduleUpdate||(this.scheduleUpdate=setTimeout(()=>this.update(),16))}),s={attributes:!0,childList:!0,subtree:!0,characterData:!0};t.observe(e,s),this.observer=t}dispatchDOMEvent(e){e.data&&bne(this.dom,e.type,e.data.x,e.data.y)}update(){this.image=QN(this.dom),this.needsUpdate=!0,this.scheduleUpdate=null}dispose(){this.observer&&this.observer.disconnect(),this.scheduleUpdate=clearTimeout(this.scheduleUpdate),super.dispose()}}const pI=new WeakMap;function QN(i){const e=document.createRange(),t=new be;function s(p){const f=[];let g=!1;function m(){if(g&&(g=!1,p.restore()),f.length===0)return;let v=-1/0,A=-1/0,b=1/0,y=1/0;for(let x=0;x<f.length;x++){const _=f[x];v=Math.max(v,_.x),A=Math.max(A,_.y),b=Math.min(b,_.x+_.width),y=Math.min(y,_.y+_.height)}p.save(),p.beginPath(),p.rect(v,A,b-v,y-A),p.clip(),g=!0}return{add:function(v){f.push(v),m()},remove:function(){f.pop(),m()}}}function r(p,f,g,m){m!==""&&(p.textTransform==="uppercase"&&(m=m.toUpperCase()),u.font=p.fontWeight+" "+p.fontSize+" "+p.fontFamily,u.textBaseline="top",u.fillStyle=p.color,u.fillText(m,f,g+parseFloat(p.fontSize)*.1))}function n(p,f,g,m,v){g<2*v&&(v=g/2),m<2*v&&(v=m/2),u.beginPath(),u.moveTo(p+v,f),u.arcTo(p+g,f,p+g,f+m,v),u.arcTo(p+g,f+m,p,f+m,v),u.arcTo(p,f+m,p,f,v),u.arcTo(p,f,p+g,f,v),u.closePath()}function o(p,f,g,m,v,A){const b=p[f+"Width"],y=p[f+"Style"],x=p[f+"Color"];b!=="0px"&&y!=="none"&&x!=="transparent"&&x!=="rgba(0, 0, 0, 0)"&&(u.strokeStyle=x,u.lineWidth=parseFloat(b),u.beginPath(),u.moveTo(g,m),u.lineTo(g+v,m+A),u.stroke())}function a(p,f){let g=0,m=0,v=0,A=0;if(p.nodeType===Node.TEXT_NODE){e.selectNode(p);const y=e.getBoundingClientRect();g=y.left-l.left-.5,m=y.top-l.top-.5,v=y.width,A=y.height,r(f,g,m,p.nodeValue.trim())}else{if(p.nodeType===Node.COMMENT_NODE)return;if(p instanceof HTMLCanvasElement){if(p.style.display==="none")return;u.save();const y=window.devicePixelRatio;u.scale(1/y,1/y),u.drawImage(p,0,0),u.restore()}else{if(p.style.display==="none")return;const y=p.getBoundingClientRect();g=y.left-l.left-.5,m=y.top-l.top-.5,v=y.width,A=y.height,f=window.getComputedStyle(p),n(g,m,v,A,parseFloat(f.borderRadius));const x=f.backgroundColor;x!=="transparent"&&x!=="rgba(0, 0, 0, 0)"&&(u.fillStyle=x,u.fill());const _=["borderTop","borderLeft","borderBottom","borderRight"];let M=!0,P=null;for(const C of _){if(P!==null&&(M=f[C+"Width"]===f[P+"Width"]&&f[C+"Color"]===f[P+"Color"]&&f[C+"Style"]===f[P+"Style"]),M===!1)break;P=C}if(M===!0){const C=parseFloat(f.borderTopWidth);f.borderTopWidth!=="0px"&&f.borderTopStyle!=="none"&&f.borderTopColor!=="transparent"&&f.borderTopColor!=="rgba(0, 0, 0, 0)"&&(u.strokeStyle=f.borderTopColor,u.lineWidth=C,u.stroke())}else o(f,"borderTop",g,m,v,0),o(f,"borderLeft",g,m,0,A),o(f,"borderBottom",g,m+A,v,0),o(f,"borderRight",g+v,m,0,A);if(p instanceof HTMLInputElement){let C=f.accentColor;(C===void 0||C==="auto")&&(C=f.color),t.set(C);const R=Math.sqrt(.299*t.r**2+.587*t.g**2+.114*t.b**2)<.5?"white":"#111111";if(p.type==="radio"&&(n(g,m,v,A,A),u.fillStyle="white",u.strokeStyle=C,u.lineWidth=1,u.fill(),u.stroke(),p.checked&&(n(g+2,m+2,v-4,A-4,A),u.fillStyle=C,u.strokeStyle=R,u.lineWidth=2,u.fill(),u.stroke())),p.type==="checkbox"&&(n(g,m,v,A,2),u.fillStyle=p.checked?C:"white",u.strokeStyle=p.checked?R:C,u.lineWidth=1,u.stroke(),u.fill(),p.checked)){const T=u.textAlign;u.textAlign="center";const z={color:R,fontFamily:f.fontFamily,fontSize:A+"px",fontWeight:"bold"};r(z,g+v/2,m,"\u2714"),u.textAlign=T}if(p.type==="range"){const[T,z,G]=["min","max","value"].map(F=>parseFloat(p[F])),N=(G-T)/(z-T)*(v-A);n(g,m+A/4,v,A/2,A/4),u.fillStyle=R,u.strokeStyle=C,u.lineWidth=1,u.fill(),u.stroke(),n(g,m+A/4,N+A/2,A/2,A/4),u.fillStyle=C,u.fill(),n(g+N,m,A,A,A/2),u.fillStyle=C,u.fill()}(p.type==="color"||p.type==="text"||p.type==="number")&&(d.add({x:g,y:m,width:v,height:A}),r(f,g+parseInt(f.paddingLeft),m+parseInt(f.paddingTop),p.value),d.remove())}}}const b=f.overflow==="auto"||f.overflow==="hidden";b&&d.add({x:g,y:m,width:v,height:A});for(let y=0;y<p.childNodes.length;y++)a(p.childNodes[y],f);b&&d.remove()}const l=i.getBoundingClientRect();let c=pI.get(i);c===void 0&&(c=document.createElement("canvas"),c.width=l.width,c.height=l.height,pI.set(i,c));const u=c.getContext("2d"),d=new s(u);return a(i),c}function bne(i,e,t,s){const r={clientX:t*i.offsetWidth+i.offsetLeft,clientY:s*i.offsetHeight+i.offsetTop,view:i.ownerDocument.defaultView};window.dispatchEvent(new MouseEvent(e,r));const n=i.getBoundingClientRect();t=t*n.width+n.left,s=s*n.height+n.top;function o(a){if(a.nodeType!==Node.TEXT_NODE&&a.nodeType!==Node.COMMENT_NODE){const l=a.getBoundingClientRect();if(t>l.left&&t<l.right&&s>l.top&&s<l.bottom&&(a.dispatchEvent(new MouseEvent(e,r)),a instanceof HTMLInputElement&&a.type==="range"&&(e==="mousedown"||e==="click"))){const[c,u]=["min","max"].map(f=>parseFloat(a[f])),d=l.width,p=(t-l.x)/d;a.value=c+(u-c)*p,a.dispatchEvent(new InputEvent("input",{bubbles:!0}))}for(let c=0;c<a.childNodes.length;c++)o(a.childNodes[c])}}o(i)}const Ox=new W,$p={type:"",data:Ox};class xne extends Un{constructor(e,t){super();const s=this,r=new _d,n=new Pe,o=e.domElement;function a(p){p.stopPropagation();const f=e.domElement.getBoundingClientRect();Ox.x=(p.clientX-f.left)/f.width*2-1,Ox.y=-(p.clientY-f.top)/f.height*2+1,r.setFromCamera(Ox,t);const g=r.intersectObjects(s.children,!1);if(g.length>0){const m=g[0],v=m.object,A=m.uv;$p.type=p.type,$p.data.set(A.x,1-A.y),v.dispatchEvent($p)}}o.addEventListener("pointerdown",a),o.addEventListener("pointerup",a),o.addEventListener("pointermove",a),o.addEventListener("mousedown",a),o.addEventListener("mouseup",a),o.addEventListener("mousemove",a),o.addEventListener("click",a);const l={move:"mousemove",select:"click",selectstart:"mousedown",selectend:"mouseup"};function c(p){const f=p.target;n.identity().extractRotation(f.matrixWorld),r.ray.origin.setFromMatrixPosition(f.matrixWorld),r.ray.direction.set(0,0,-1).applyMatrix4(n);const g=r.intersectObjects(s.children,!1);if(g.length>0){const m=g[0],v=m.object,A=m.uv;$p.type=l[p.type],$p.data.set(A.x,1-A.y),v.dispatchEvent($p)}}const u=e.xr.getController(0);u.addEventListener("move",c),u.addEventListener("select",c),u.addEventListener("selectstart",c),u.addEventListener("selectend",c);const d=e.xr.getController(1);d.addEventListener("move",c),d.addEventListener("select",c),d.addEventListener("selectstart",c),d.addEventListener("selectend",c)}}class fI extends Ee{constructor(){super(...arguments),h(this,"id",null),h(this,"keepAspect",!1)}start(){if(!this.id||!this.context.mainCamera)return;const e=document.getElementById(this.id);if(!e){console.warn('Could not find element with id "'+this.id+'"');return}e.style.display="block",e.style.visibility="hidden";const t=new xne(this.context.renderer,this.context.mainCamera);this.gameObject.add(t);const s=new Ane(e);t.add(s),s.visible=!1,console.log(s);const r=s.material;r.transparent=!0,setTimeout(()=>{s.visible=!0;const n=O0(this.gameObject).clone();L0(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const o=new or;o.setFromObject(t),this.setWorldRotation(n.x,n.y,n.z);const a=o.max.x-o.min.x,l=o.max.y-o.min.y;if(this.keepAspect){const u=a/l;a>l?s.scale.set(1/a,1/l/u,1):s.scale.set(1/a*u,1/l,1)}else s.scale.set(1/a,1/l,1);const c=this.gameObject.scale;s.scale.multiply(c)},1)}}var wne=Object.defineProperty,_ne=Object.getOwnPropertyDescriptor,fv=(i,e,t,s)=>{for(var r=s>1?void 0:s?_ne(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&wne(e,t,r),r};const gv=re("debugspatialtrigger"),jN=new On,GN=new On;function Cne(i,e){return jN.mask=i,GN.mask=e,jN.test(GN)}class xa extends Ee{constructor(){super(...arguments),h(this,"triggerMask",0),h(this,"onEnter"),h(this,"onStay"),h(this,"onExit"),h(this,"currentIntersected",[]),h(this,"lastIntersected",[])}start(){gv&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const e of mv.triggers)Cne(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){const t=this.lastIntersected[e];this.currentIntersected.indexOf(t)<0&&(this.onExitTrigger(t),this.lastIntersected.splice(e,1))}for(const e of this.currentIntersected)this.lastIntersected.indexOf(e)<0&&this.onEnterTrigger(e),this.onStayTrigger(e);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}onEnterTrigger(e){var t;gv&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),(t=this.onEnter)==null||t.invoke(this,e)}onExitTrigger(e){var t;gv&&console.log("EXIT TRIGGER",this.name,e.name,this,e),e.raiseOnExitEvent(this),(t=this.onExit)==null||t.invoke(this,e)}onStayTrigger(e){var t;e.raiseOnStayEvent(this),(t=this.onStay)==null||t.invoke(this,e)}}fv([w()],xa.prototype,"triggerMask",2),fv([w(Jr)],xa.prototype,"onEnter",2),fv([w(Jr)],xa.prototype,"onStay",2),fv([w(Jr)],xa.prototype,"onExit",2);var gI;const Lx=(gI=class extends Ee{constructor(){super(...arguments),h(this,"triggerMask"),h(this,"boxHelper")}start(){gv&&console.log(this.name,this.triggerMask,this)}onEnable(){var i;Lx.triggers.push(this),this.boxHelper||(this.boxHelper=$.addNewComponent(this.gameObject,ra),(i=this.boxHelper)==null||i.showHelper(null,gv))}onDisable(){Lx.triggers.splice(Lx.triggers.indexOf(this),1)}test(i){return this.boxHelper?this.boxHelper.isInBox(i)??!1:!1}raiseOnEnterEvent(i){$.foreachComponent(this.gameObject,e=>{e!==i&&e instanceof xa&&e.onEnterTrigger(this)},!1)}raiseOnStayEvent(i){$.foreachComponent(this.gameObject,e=>{e!==i&&e instanceof xa&&e.onStayTrigger(this)},!1)}raiseOnExitEvent(i){$.foreachComponent(this.gameObject,e=>{e!==i&&e instanceof xa&&e.onExitTrigger(this)},!1)}},h(gI,"triggers",[]),gI);let mv=Lx;fv([w()],mv.prototype,"triggerMask",2);var Sne=Object.defineProperty,Ene=Object.getOwnPropertyDescriptor,Mne=(i,e,t,s)=>{for(var r=s>1?void 0:s?Ene(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Sne(e,t,r),r};const In=re("debugspectator");class Fx extends Ee{constructor(){super(...arguments),h(this,"cam",null),h(this,"useKeys",!0),h(this,"_mode",0),h(this,"orbit",null),h(this,"_handler"),h(this,"eventSub_WebXRRequestStartEvent",null),h(this,"eventSub_WebXRStartEvent",null),h(this,"eventSub_WebXREndEvent",null),h(this,"_debug"),h(this,"_networking")}get mode(){return this._mode}set mode(e){this._mode=e}get isSpectating(){var e;return((e=this._handler)==null?void 0:e.currentTarget)!==void 0}isSpectatingUser(e){var t;return((t=this.target)==null?void 0:t.userId)===e}isFollowedBy(e){var t;return(t=this.followers)==null?void 0:t.includes(e)}get followers(){return this._networking.followers}stopSpectating(){if(this.context.isInXR){this.followSelf();return}this.target=void 0}get localId(){return this.context.connection.connectionId??"local"}set target(e){var t;if(this._handler){const s=(t=this._handler.currentTarget)==null?void 0:t.userId,r=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&r?.currentObject===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),$.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,s)):this._handler.currentTarget!==e&&(this._handler.set(e),$.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,s))}}get target(){var e;return(e=this._handler)==null?void 0:e.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){var e,t;return this.isSpectating&&((e=this.target)==null?void 0:e.currentObject)===((t=this.context.players.getPlayerView(this.localId))==null?void 0:t.currentObject)}awake(){if(this._debug=new Rne(this.context,this),this._networking=new kne(this.context,this),this._networking.awake(),$.setActive(this.gameObject,!1),this.cam=$.getComponent(this.gameObject,Pi),!this.cam){console.error("Spectator camera needs camera component",this);return}!this._handler&&this.cam&&(this._handler=new Ine(this.context,this.cam,this)),this.eventSub_WebXRRequestStartEvent=this.onXRSessionRequestStart.bind(this),this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),_t.addEventListener(xi.RequestVRSession,this.eventSub_WebXRRequestStartEvent),_t.addEventListener(xi.XRStarted,this.eventSub_WebXRStartEvent),_t.addEventListener(xi.XRStopped,this.eventSub_WebXREndEvent),this.orbit=$.getComponent(this.context.mainCamera,Tl)}onDestroy(){var e,t;this.stopSpectating(),_t.removeEventListener(xi.RequestVRSession,this.eventSub_WebXRStartEvent),_t.removeEventListener(xi.XRStarted,this.eventSub_WebXRStartEvent),_t.removeEventListener(xi.XRStopped,this.eventSub_WebXREndEvent),(e=this._handler)==null||e.destroy(),(t=this._networking)==null||t.destroy()}isSupportedPlatform(){const e=window.navigator.userAgent,t=/Windows|MacOS/.test(e),s=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return t&&!s}onXRSessionRequestStart(e){this.isSupportedPlatform()&&$.setActive(this.gameObject,!0)}onXRSessionStart(e){this.isSupportedPlatform()&&(In&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onXRSessionEnded(e){var t,s;this.context.removeCamera(this.cam),$.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),(t=this._handler)==null||t.set(void 0),(s=this._handler)==null||s.disable(),this.isSpectatingSelf&&this.stopSpectating()}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),this.target||(this.context.players.setPlayerView(this.localId,this.context.mainCamera,$o.Headset),this.target=this.context.players.getPlayerView(this.localId)),In&&console.log("Follow self",this.target)}onAfterRender(){var e,t,s;if(!this.cam)return;const r=this.context.renderer,n=r.xr.enabled;if(!r.xr.isPresenting&&!((e=this._handler)!=null&&e.currentTarget))return;(t=this._handler)==null||t.update(this._mode);const o=r.getRenderTarget();let a=null;if(!o){if(!r.state.bindFramebuffer||!r.state.bindXRFramebuffer)return;a=r._framebuffer,r.state.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const l=this.context.mainCameraComponent;if(l){const d=l.backgroundColor;d&&r.setClearColor(d,d.alpha),this.cam.backgroundColor=d,this.cam.clearFlags=l.clearFlags,this.cam.nearClipPlane=l.nearClipPlane,this.cam.farClipPlane=l.farClipPlane}else r.setClearColor(new be(1,1,1));r.setRenderTarget(null),r.xr.enabled=!1;const c=(s=this.cam)==null?void 0:s.cam;this.context.updateAspect(c);const u=r.xr.isPresenting;r.xr.isPresenting=!1,r.setSize(this.context.domWidth,this.context.domHeight),r.render(this.context.scene,c),r.xr.isPresenting=u,r.xr.enabled=n,o?r.setRenderTarget(o):r.state.bindXRFramebuffer(a),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const e=this._mode===0;for(const t of fr.instances)if(t.avatar&&"isLocalAvatar"in t.avatar){let s=ls.All;this.isSpectatingSelf&&(s=e&&t.avatar.isLocalAvatar?ls.FirstPerson:ls.ThirdPerson);const r=t.avatar.flags;if(!r)continue;for(const n of r)n.UpdateVisible(s)}}resetAvatarFlags(){var e;for(const t of fr.instances)if(t.avatar&&"flags"in t.avatar){const s=t.avatar.flags;if(!s)continue;for(const r of s)(e=t.avatar)!=null&&e.isLocalAvatar?r.UpdateVisible(ls.FirstPerson):r.UpdateVisible(ls.ThirdPerson)}}}Mne([w()],Fx.prototype,"useKeys",2);class Ine{constructor(e,t,s){h(this,"context"),h(this,"cam"),h(this,"spectator"),h(this,"follow"),h(this,"target"),h(this,"view"),h(this,"currentObject"),this.context=e,this.cam=t,this.spectator=s}get currentTarget(){return this.view}set(e){const t=e?.currentObject;if(!t){this.spectator.stopSpectating();return}t!==this.currentObject&&(this.currentObject=t,this.view=e,this.follow||(this.follow=$.addNewComponent(this.cam.gameObject,nh)),this.target||(this.target=new Me),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,In&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){In&&console.log("STOP FOLLOW",this.currentObject),this.view=void 0,this.currentObject=void 0,this.context.removeCamera(this.cam),this.follow&&(this.follow.enabled=!1)}destroy(){var e;(e=this.target)==null||e.removeFromParent(),this.follow&&$.destroy(this.follow)}update(e){var t,s,r,n,o,a;if(((t=this.currentTarget)==null?void 0:t.isConnected)===!1||((s=this.currentTarget)==null?void 0:s.removed)===!0){In&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&((r=this.currentTarget)==null?void 0:r.currentObject)!==this.currentObject&&(In&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const l=this.context.mainCamera;l&&(this.cam.cam.near!==l.near||this.cam.cam.far!==l.far)&&(this.cam.cam.near=l.near,this.cam.cam.far=l.far,this.cam.cam.updateProjectionMatrix());const c=(n=this.follow)==null?void 0:n.target;if(!(!c||!this.follow)){switch(e){case 0:((o=this.view)==null?void 0:o.viewDevice)!==$o.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),c.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,c.position.set(0,.5,1.5);break}this.follow.flipForward=!1,((a=this.view)==null?void 0:a.viewDevice)!==$o.Browser?c.quaternion.copy(Tne):c.quaternion.identity()}}}const Tne=new Ce().setFromAxisAngle(new S(0,1,0),Math.PI);class Rne{constructor(e,t){h(this,"context"),h(this,"spectator"),this.context=e,this.spectator=t,console.log("Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),this.context.domElement.addEventListener("keydown",r=>{!this.spectator.useKeys||r.key==="Escape"&&this.spectator.stopSpectating()});let s=0;this.context.input.addEventListener(Xo.PointerDown,r=>{s=this.context.time.time}),this.context.input.addEventListener(Xo.PointerUp,r=>{const n=this.context.time.time-s;n>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&n<.3&&this.trySelectObject()})}trySelectObject(){const e=new _o;e.setMask(16777215);const t=this.context.physics.raycast(e);if(In&&console.log(...t),t!=null&&t.length)for(const s of t){if(s.distance<.2)continue;const r=s.object,n=$.getComponentInParent(r,fr),o=n?.connectionId;if(o){const a=this.context.players.getPlayerView(o);this.spectator.target=a,In&&console.log("spectate",o,n);break}}}}class Pne{constructor(e,t,s){h(this,"guid"),h(this,"dontSave",!0),h(this,"targetUserId"),h(this,"stoppedFollowing"),this.guid=e,this.targetUserId=t,this.stoppedFollowing=s}}class Bne{constructor(e,t){h(this,"guid"),h(this,"userId"),this.guid=e.guid,this.userId=t}}class kne{constructor(e,t){h(this,"followers",[]),h(this,"context"),h(this,"spectator"),h(this,"_followerEventMethod"),h(this,"_requestFollowMethod"),h(this,"_joinedRoomMethod"),h(this,"_lastRequestFollowUser"),h(this,"_enforceFollowInterval"),this.context=e,this.spectator=t,this._followerEventMethod=this.onFollowerEvent.bind(this),this._requestFollowMethod=this.onRequestFollowEvent.bind(this),this._joinedRoomMethod=this.onUserJoinedRoom.bind(this)}awake(){this.context.connection.beginListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.beginListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.beginListen(ji.JoinedRoom,this._joinedRoomMethod),this.context.domElement.addEventListener("keydown",e=>{this.spectator.useKeys&&(e.key==="f"?this.onRequestFollowMe():e.key==="Escape"&&this.onRequestFollowMe(!0))})}destroy(){this.context.connection.stopListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.stopListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.stopListen(ji.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(e,t){if(In&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",e,t),this.context.connection.connectionId){const s=e?.userId===void 0,r=s?t:e?.userId,n=new Pne(this.context.connection.connectionId,r,s);this.context.connection.send("spectator-follower-changed",n)}}onRequestFollowMe(e=!1){if(In&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const t=e?void 0:this.context.connection.connectionId,s=new Bne(this.spectator,t);this.context.connection.send("spectator-request-follow",s)}}onUserJoinedRoom(){re("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){const t=e.targetUserId,s=e.guid;if(In&&console.log(e),t===this.context.connection.connectionId)if(e.stoppedFollowing){const r=this.followers.indexOf(s);r!==-1&&(this.followers.splice(r,1),this.removeDisconnectedFollowers(),console.log(s,"unfollows you",this.followers.length))}else this.followers.includes(s)||(this.followers.push(s),this.removeDisconnectedFollowers(),console.log(s,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let e=this.followers.length-1;e>=0;e--){const t=this.followers[e];this.context.connection.userIsInRoom(t)===!1&&this.followers.splice(e,1)}}onRequestFollowEvent(e){if(this._lastRequestFollowUser=e,e.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(e.userId===void 0)this.spectator.stopSpectating();else{const t=this.context.players.getPlayerView(e.userId);if(t)this.spectator.target=t;else return In&&console.warn("Could not find view",e.userId),this.enforceFollow(),!1}return!0}enforceFollow(){this._enforceFollowInterval||(this._enforceFollowInterval=setInterval(()=>{this._lastRequestFollowUser===void 0||this._lastRequestFollowUser.userId&&this.spectator.isFollowedBy(this._lastRequestFollowUser.userId)?(clearInterval(this._enforceFollowInterval),this._enforceFollowInterval=void 0):(In&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}var Dne=Object.defineProperty,One=Object.getOwnPropertyDescriptor,jr=(i,e,t,s)=>{for(var r=s>1?void 0:s?One(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Dne(e,t,r),r};const mI=re("debugspriterenderer"),Lne=re("wireframe"),vI=class{static getOrCreateGeometry(i){if(i._geometry)return i._geometry;if(i.guid&&vI.cache[i.guid])return mI&&console.log("Take cached geometry for sprite",i.guid),vI.cache[i.guid];const e=new mt;i._geometry=e;const t=new Float32Array(i.triangles.length*3),s=new Float32Array(i.triangles.length*2);for(let r=0;r<i.triangles.length;r+=1){const n=i.triangles[r];t[r*3]=-i.vertices[n].x,t[r*3+1]=i.vertices[n].y,t[r*3+2]=0;const o=i.uv[n];s[r*2]=o.x,s[r*2+1]=1-o.y}return e.setAttribute("position",new tt(t,3)),e.setAttribute("uv",new tt(s,2)),i.guid&&(this.cache[i.guid]=e),mI&&console.log("Built sprite geometry",i,e),e}};let AI=vI;h(AI,"cache",{});class Nl{constructor(){h(this,"guid"),h(this,"texture"),h(this,"triangles"),h(this,"uv"),h(this,"vertices"),h(this,"_geometry")}}jr([w()],Nl.prototype,"guid",2),jr([w(Ft)],Nl.prototype,"texture",2),jr([ip()],Nl.prototype,"triangles",2),jr([ip()],Nl.prototype,"uv",2),jr([ip()],Nl.prototype,"vertices",2);const yI=Symbol("spriteOwner");class vv{constructor(){h(this,"sprites")}}jr([w(Nl)],vv.prototype,"sprites",2);class ef{constructor(){h(this,"spriteSheet"),h(this,"index",0)}update(){if(!this.spriteSheet)return;const e=this.index;if(e<0||e>=this.spriteSheet.sprites.length)return;const t=this.spriteSheet.sprites[e];let s=t?.texture;s&&(s.encoding=yt,s.minFilter==Wt&&s.magFilter==Wt&&(s.anisotropy=1),s.needsUpdate=!0)}}jr([w(vv)],ef.prototype,"spriteSheet",2),jr([w()],ef.prototype,"index",2);class wa extends Ee{constructor(){super(...arguments),h(this,"drawMode",0),h(this,"size",{x:1,y:1}),h(this,"color"),h(this,"sharedMaterial"),h(this,"_spriteSheet"),h(this,"_currentSprite"),h(this,"transparent",!0),h(this,"cutoutThreshold",0),h(this,"castShadows",!1)}get sprite(){return this._spriteSheet}set sprite(e){if(e!==this._spriteSheet)if(typeof e=="number"){const t=Math.floor(e);t===e&&(this.spriteIndex=t);return}else this._spriteSheet=e,this.updateSprite()}set spriteIndex(e){this._spriteSheet&&(this._spriteSheet.index=e,this.updateSprite())}get spriteIndex(){var e;return((e=this._spriteSheet)==null?void 0:e.index)??0}get spriteFrames(){var e,t;return((t=(e=this._spriteSheet)==null?void 0:e.spriteSheet)==null?void 0:t.sprites.length)??0}awake(){this._currentSprite=void 0,mI&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(){var e,t,s;if(!this.__didAwake||!((t=(e=this.sprite)==null?void 0:e.spriteSheet)!=null&&t.sprites))return;const r=this.sprite.spriteSheet.sprites[this.spriteIndex];if(this._currentSprite)this._currentSprite.geometry=AI.getOrCreateGeometry(r),this._currentSprite.material.map=r.texture;else{const n=new pi({color:16777215,side:bi});if(!n)return;if(Lne&&(n.wireframe=!0),this.color&&(n.color||(n.color=new be),n.color.copy(this.color),n.opacity=this.color.alpha),n.transparent=!0,r.texture&&!n.wireframe){let o=r.texture;o[yI]!==void 0&&o[yI]!==this&&this.spriteFrames>1&&(o=r.texture=o.clone()),o[yI]=this,n.map=o}this.sharedMaterial=n,this._currentSprite=new ve(AI.getOrCreateGeometry(r),n)}this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite)),this._currentSprite&&this._currentSprite.layers.set(this.layer),this.sharedMaterial&&(this.sharedMaterial.alphaTest=this.cutoutThreshold,this.sharedMaterial.transparent=this.transparent),this._currentSprite.castShadow=this.castShadows,(s=this._spriteSheet)==null||s.update()}}jr([w()],wa.prototype,"drawMode",2),jr([w(vi)],wa.prototype,"color",2),jr([w(Tt)],wa.prototype,"sharedMaterial",2),jr([w(ef)],wa.prototype,"sprite",1),jr([w()],wa.prototype,"transparent",2),jr([w()],wa.prototype,"cutoutThreshold",2),jr([w()],wa.prototype,"castShadows",2);class Pa{constructor(){h(this,"bb",null),h(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedCameraModel(e,t){return(t||new Pa).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+W0),(t||new Pa).__init(e.readInt32(e.position())+e.position(),e)}userId(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}guid(e){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}dontSave(){const e=this.bb.__offset(this.bb_pos,8);return e?!!this.bb.readInt8(this.bb_pos+e):!1}pos(e){const t=this.bb.__offset(this.bb_pos,10);return t?(e||new An).__init(this.bb_pos+t,this.bb):null}rot(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new An).__init(this.bb_pos+t,this.bb):null}static startSyncedCameraModel(e){e.startObject(5)}static addUserId(e,t){e.addFieldOffset(0,t,0)}static addGuid(e,t){e.addFieldOffset(1,t,0)}static addDontSave(e,t){e.addFieldInt8(2,+t,0)}static addPos(e,t){e.addFieldStruct(3,t,0)}static addRot(e,t){e.addFieldStruct(4,t,0)}static endSyncedCameraModel(e){return e.endObject()}static finishSyncedCameraModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedCameraModelBuffer(e,t){e.finish(t,void 0,!0)}}var Fne=Object.defineProperty,Une=Object.getOwnPropertyDescriptor,Nne=(i,e,t,s)=>{for(var r=s>1?void 0:s?Une(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Fne(e,t,r),r};const Ux="SCAM";q1(Ux,Pa.getRootAsSyncedCameraModel);const Tn=new gf;class zne{constructor(e,t){h(this,"userId"),h(this,"guid"),this.guid=t,this.userId=e}send(e,t){if(e){Tn.clear();const s=Tn.createString(this.guid),r=Tn.createString(this.userId);Pa.startSyncedCameraModel(Tn),Pa.addGuid(Tn,s),Pa.addUserId(Tn,r);const n=xt(e),o=O0(e);Pa.addPos(Tn,An.createVec3(Tn,n.x,n.y,n.z)),Pa.addRot(Tn,An.createVec3(Tn,o.x,o.y,o.z));const a=Pa.endSyncedCameraModel(Tn);Tn.finish(a,Ux),t.sendBinary(Tn.asUint8Array())}}}var bI;const xI=(bI=class extends Ee{constructor(){super(...arguments),h(this,"cameraPrefab",null),h(this,"_lastWorldPosition"),h(this,"_lastWorldQuaternion"),h(this,"_model",null),h(this,"_needsUpdate",!0),h(this,"_lastUpdateTime",0),h(this,"remoteCams",{}),h(this,"userToCamMap",{}),h(this,"_camTimeoutInSeconds",10),h(this,"_receiveCallback",null)}getCameraObject(i){const e=this.userToCamMap[i];return e?this.remoteCams[e].obj:null}async awake(){this._lastWorldPosition=this.worldPosition.clone(),this._lastWorldQuaternion=this.worldQuaternion.clone(),this.cameraPrefab&&("uri"in this.cameraPrefab&&(this.cameraPrefab=await this.cameraPrefab.instantiate(this.gameObject)),this.cameraPrefab&&"isObject3D"in this.cameraPrefab&&(this.cameraPrefab.visible=!1))}onEnable(){this._receiveCallback=this.context.connection.beginListenBinary(Ux,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(Ux,this._receiveCallback)}update(){for(const s in this.remoteCams){const r=this.remoteCams[s],n=this.context.time.realtimeSinceStartup-r.lastUpdate;if(!r||n>this._camTimeoutInSeconds){console.log("Remote cam timeout",r,n),r!=null&&r.obj&&$.destroy(r.obj),delete this.remoteCams[s],r&&delete this.userToCamMap[r.userId],xI.instances.push(r),this.context.players.removePlayerView(r.userId,$o.Browser);continue}}if(_t.IsInWebXR)return;const i=this.context.mainCamera;if(i===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new zne(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const e=xt(i),t=Ss(i);(e.distanceTo(this._lastWorldPosition)>.001||t.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(e),this._lastWorldQuaternion.copy(t),!((!this._needsUpdate||this.context.time.frameCount%2!==0)&&!(this.context.time.realtimeSinceStartup-this._lastUpdateTime>this._camTimeoutInSeconds*.5))&&(this._lastUpdateTime=this.context.time.realtimeSinceStartup,this._needsUpdate=!1,this._model.send(i,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,i,$o.Browser))}onReceivedRemoteCameraInfoBin(i){const e=i.guid();if(!e)return;const t=i.userId();if(!t||!this.context.connection.userIsInRoom(t)||!this.cameraPrefab)return;let s=this.remoteCams[e];if(!s)if("isObject3D"in this.cameraPrefab){const a=new Jo;a.context=this.context;const l=$.instantiate(this.cameraPrefab,a);s=this.remoteCams[e]={obj:l,lastUpdate:this.context.time.realtimeSinceStartup,userId:t},s.obj.visible=!0,this.gameObject.add(l),this.userToCamMap[t]=e,xI.instances.push(s);const c=$.getOrAddComponent(l,fr);c.connectionId=t,c.avatar=l}else return;const r=s.obj;this.context.players.setPlayerView(t,r,$o.Browser),s.lastUpdate=this.context.time.realtimeSinceStartup,on.markDirty(r);const n=i.pos();n&&Sd(r,n.x(),n.y(),n.z());const o=i.rot();o&&L0(r,o.x(),o.y(),o.z())}},h(bI,"instances",[]),bI);let Nx=xI;Nne([w([Me,dr])],Nx.prototype,"cameraPrefab",2);var Qne=Object.defineProperty,jne=Object.getOwnPropertyDescriptor,Av=(i,e,t,s)=>{for(var r=s>1?void 0:s?jne(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Qne(e,t,r),r};const wI="view",_I=re("debugsyncedroom");class oh extends Ee{constructor(){super(...arguments),h(this,"roomName"),h(this,"urlParameterName","room"),h(this,"joinRandomRoom",!0),h(this,"requireRoomParameter",!1),h(this,"autoRejoin",!0),h(this,"_roomPrefix"),h(this,"_lastPingTime",0),h(this,"_lastRoomTime",-1)}get RoomPrefix(){return this._roomPrefix}awake(){_I&&console.log("Room",this.roomName,this.urlParameterName,this.joinRandomRoom,this.requireRoomParameter,this.autoRejoin),this._roomPrefix===void 0&&(this._roomPrefix=this.roomName,this.roomName="")}onEnable(){const e=re(wI);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}(this.joinRandomRoom||re(this.urlParameterName))&&this.tryJoinRoom()}onDisable(){this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}tryJoinRandomRoom(){this.setRandomRoomUrlParameter(),this.tryJoinRoom()}tryJoinRoom(e=0){e===void 0&&(e=0);let t=!1;if(this.urlParameterName){const s=re(this.urlParameterName);if(s&&typeof s=="string"){t=!0;const r=hT(s);this.roomName=r}else if(this.joinRandomRoom&&(console.log("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),e<1))return this.tryJoinRoom(e+1)}else this.joinRandomRoom&&(this.roomName===null||this.roomName===void 0||this.roomName.length<=0)&&(console.log("generate room name"),this.roomName=this.generateRoomName());return this.requireRoomParameter&&!t?(_I&&console.log('No required room parameter "'+this.urlParameterName+'" in url - will not connect to networking backend.'),!1):(this.context.connection.isConnected||this.context.connection.connect(),_I&&console.log("Join "+this.roomName),this._roomPrefix&&(this.roomName=this._roomPrefix+this.roomName),this.context.connection.joinRoom(this.roomName),!0)}update(){this.context.connection.isConnected&&(this.context.time.time-this._lastPingTime>3&&(this._lastPingTime=this.context.time.time,this.context.connection.sendPing()),this.context.connection.isInRoom&&(this._lastRoomTime=this.context.time.time)),this._lastRoomTime>0&&this.context.time.time-this._lastRoomTime>.3&&(this._lastRoomTime=-1,this.autoRejoin?(console.log("Disconnected from networking backend - attempt reconnecting now"),this.tryJoinRoom()):console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you)"))}get currentRoomName(){return re(wI)||re(this.urlParameterName)}setRandomRoomUrlParameter(){const e=yf(),t=this.generateRoomName();re(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),mw(t,e)}generateRoomName(){return cT()+"_"+oT(100,999)}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){const e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(wI,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}}Av([w()],oh.prototype,"roomName",2),Av([w()],oh.prototype,"urlParameterName",2),Av([w()],oh.prototype,"joinRandomRoom",2),Av([w()],oh.prototype,"requireRoomParameter",2),Av([w()],oh.prototype,"autoRejoin",2);function Gne(){const i=re("testwindowcount")||0;i&&i>0&&Hne(i)}function Hne(i){if(re("testwindow"))return null;const e=new URL(window.location.href);bf(e.searchParams,lb,1),bf(e.searchParams,"testwindow",1);const t=e.toString(),s=[];window.onbeforeunload=()=>{for(const l of s)l.close()};const r=.05,n=128;let o=0,a=0;for(let l=0;l<i;l++){o*n+n*.01>=window.innerWidth&&(a+=1,o=0);const c=o*(n*(1+r))+window.screenLeft,u=a*(n*(1+r))+window.screenTop+90+60*a;o+=1;const d=window.open(t,"test window "+l,`popup=yes width=${n} height=${n} top=${u} left=${c}`);if(!d){console.warn("Failed to open window");continue}s.push(d),d.onload=()=>{d.onbeforeunload=()=>{for(let p=0;p<s.length;p++){const f=s[p];f!==d&&f.close()}s.length=0}}}return s}class CI extends Ee{awake(){Gne()}}class SI extends Ee{constructor(){super(...arguments),h(this,"transformsPerFrame",10),h(this,"interval",0),h(this,"useFlatbuffers",!0),h(this,"builder",null),h(this,"models",null)}awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(am,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new HN(this.context.connection.connectionId+"_simulatedTransform_"+e,this))}}update(){if(this.context.connection.isConnected){if(this.useFlatbuffers){if(!this.context.connection.connectionId||this.context.time.frameCount%this.interval!==0)return;this.builder===null&&(this.builder=new gf(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const s=E3(this.context.connection.connectionId,this);this.context.connection.sendBinary(s)}}else if(this.models)for(let e=0;e<this.models.length;e++){const t=this.models[e];t.dontSave=!0,t.update(this,null),this.context.connection.send("TestSimulateUserData-"+e,t)}}}}class HN{constructor(e,t){h(this,"guid"),h(this,"fast",!1),h(this,"position"),h(this,"rotation"),h(this,"velocity"),h(this,"dontSave"),this.guid=e,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(t,null)}isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}update(e,t){const s=e.worldPosition;this.position.x=s.x,this.position.y=s.y,this.position.z=s.z;const r=e.worldQuaternion;if(this.rotation.x=r.x,this.rotation.y=r.y,this.rotation.z=r.z,this.rotation.w=r.w,this.fast=!1,t){const n=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=n.x,this.velocity.y=n.y,this.velocity.z=n.z}}}h(HN,"temp",new S);var Vne=Object.defineProperty,Wne=Object.getOwnPropertyDescriptor,tf=(i,e,t,s)=>{for(var r=s>1?void 0:s?Wne(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Vne(e,t,r),r};class _a extends gr{constructor(){super(...arguments),h(this,"offset"),h(this,"rotation"),h(this,"focusArea"),h(this,"feather"),h(this,"kernelSize"),h(this,"resolutionScale")}get typeName(){return"TiltShiftEffect"}init(){this.offset.defaultValue=0,this.rotation.defaultValue=0,this.focusArea.defaultValue=.4,this.feather.defaultValue=.3,this.kernelSize.defaultValue=ll.MEDIUM,this.resolutionScale.defaultValue=1/window.devicePixelRatio}onCreateEffect(){console.log(this);const e=new W7({kernelSize:ll.VERY_LARGE});return this.offset.onValueChanged=t=>e.offset=t,this.rotation.onValueChanged=t=>e.rotation=t,this.focusArea.onValueChanged=t=>e.focusArea=t,this.feather.onValueChanged=t=>e.feather=t,this.kernelSize.onValueChanged=t=>e.blurPass.kernelSize=t,this.resolutionScale.onValueChanged=t=>e.resolution.scale=t/window.devicePixelRatio,e}}tf([w(Et)],_a.prototype,"offset",2),tf([w(Et)],_a.prototype,"rotation",2),tf([w(Et)],_a.prototype,"focusArea",2),tf([w(Et)],_a.prototype,"feather",2),tf([w(Et)],_a.prototype,"kernelSize",2),tf([w(Et)],_a.prototype,"resolutionScale",2),oo("TiltShiftEffect",_a);var qne=Object.defineProperty,Xne=Object.getOwnPropertyDescriptor,Yne=(i,e,t,s)=>{for(var r=s>1?void 0:s?Xne(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&qne(e,t,r),r};class yv extends gr{constructor(){super(...arguments),h(this,"mode")}get typeName(){return"ToneMapping"}get isToneMapping(){return!0}init(){this.mode.defaultValue=_r}apply(){this.mode.onValueChanged=this._apply.bind(this),this._apply(this.mode.value)}unapply(){this.context.renderer.toneMapping=_r}_apply(e){switch(e){case 0:this.context.renderer.toneMapping=Ef;break;case 1:this.context.renderer.toneMapping=kw;break;case 2:this.context.renderer.toneMapping=Dw;break}}}Yne([w(Et)],yv.prototype,"mode",2),oo("Tonemapping",yv);const Pu=new _d,nn=new S,ah=new S,ki=new Ce,VN={X:new S(1,0,0),Y:new S(0,1,0),Z:new S(0,0,1)},EI={type:"change"},WN={type:"mouseDown"},qN={type:"mouseUp",mode:null},XN={type:"objectChange"};class Kne extends Me{constructor(e,t){super(),t===void 0&&(console.warn('THREE.TransformControls: The second parameter "domElement" is now mandatory.'),t=document),this.isTransformControls=!0,this.visible=!1,this.domElement=t,this.domElement.style.touchAction="none";const s=new ioe;this._gizmo=s,this.add(s);const r=new soe;this._plane=r,this.add(r);const n=this;function o(b,y){let x=y;Object.defineProperty(n,b,{get:function(){return x!==void 0?x:y},set:function(_){x!==_&&(x=_,r[b]=_,s[b]=_,n.dispatchEvent({type:b+"-changed",value:_}),n.dispatchEvent(EI))}}),n[b]=y,r[b]=y,s[b]=y}o("camera",e),o("object",void 0),o("enabled",!0),o("axis",null),o("mode","translate"),o("translationSnap",null),o("rotationSnap",null),o("scaleSnap",null),o("space","world"),o("size",1),o("dragging",!1),o("showX",!0),o("showY",!0),o("showZ",!0);const a=new S,l=new S,c=new Ce,u=new Ce,d=new S,p=new Ce,f=new S,g=new S,m=new S,v=0,A=new S;o("worldPosition",a),o("worldPositionStart",l),o("worldQuaternion",c),o("worldQuaternionStart",u),o("cameraPosition",d),o("cameraQuaternion",p),o("pointStart",f),o("pointEnd",g),o("rotationAxis",m),o("rotationAngle",v),o("eye",A),this._offset=new S,this._startNorm=new S,this._endNorm=new S,this._cameraScale=new S,this._parentPosition=new S,this._parentQuaternion=new Ce,this._parentQuaternionInv=new Ce,this._parentScale=new S,this._worldScaleStart=new S,this._worldQuaternionInv=new Ce,this._worldScale=new S,this._positionStart=new S,this._quaternionStart=new Ce,this._scaleStart=new S,this._getPointer=Jne.bind(this),this._onPointerDown=$ne.bind(this),this._onPointerHover=Zne.bind(this),this._onPointerMove=eoe.bind(this),this._onPointerUp=toe.bind(this),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointermove",this._onPointerHover),this.domElement.addEventListener("pointerup",this._onPointerUp)}updateMatrixWorld(){this.object!==void 0&&(this.object.updateMatrixWorld(),this.object.parent===null?console.error("TransformControls: The attached 3D object must be a part of the scene graph."):this.object.parent.matrixWorld.decompose(this._parentPosition,this._parentQuaternion,this._parentScale),this.object.matrixWorld.decompose(this.worldPosition,this.worldQuaternion,this._worldScale),this._parentQuaternionInv.copy(this._parentQuaternion).invert(),this._worldQuaternionInv.copy(this.worldQuaternion).invert()),this.camera.updateMatrixWorld(),this.camera.matrixWorld.decompose(this.cameraPosition,this.cameraQuaternion,this._cameraScale),this.camera.isOrthographicCamera?this.camera.getWorldDirection(this.eye).negate():this.eye.copy(this.cameraPosition).sub(this.worldPosition).normalize(),super.updateMatrixWorld(this)}pointerHover(e){if(this.object===void 0||this.dragging===!0)return;Pu.setFromCamera(e,this.camera);const t=MI(this._gizmo.picker[this.mode],Pu);t?this.axis=t.object.name:this.axis=null}pointerDown(e){if(!(this.object===void 0||this.dragging===!0||e.button!==0)&&this.axis!==null){Pu.setFromCamera(e,this.camera);const t=MI(this._plane,Pu,!0);t&&(this.object.updateMatrixWorld(),this.object.parent.updateMatrixWorld(),this._positionStart.copy(this.object.position),this._quaternionStart.copy(this.object.quaternion),this._scaleStart.copy(this.object.scale),this.object.matrixWorld.decompose(this.worldPositionStart,this.worldQuaternionStart,this._worldScaleStart),this.pointStart.copy(t.point).sub(this.worldPositionStart)),this.dragging=!0,WN.mode=this.mode,this.dispatchEvent(WN)}}pointerMove(e){const t=this.axis,s=this.mode,r=this.object;let n=this.space;if(s==="scale"?n="local":(t==="E"||t==="XYZE"||t==="XYZ")&&(n="world"),r===void 0||t===null||this.dragging===!1||e.button!==-1)return;Pu.setFromCamera(e,this.camera);const o=MI(this._plane,Pu,!0);if(o){if(this.pointEnd.copy(o.point).sub(this.worldPositionStart),s==="translate")this._offset.copy(this.pointEnd).sub(this.pointStart),n==="local"&&t!=="XYZ"&&this._offset.applyQuaternion(this._worldQuaternionInv),t.indexOf("X")===-1&&(this._offset.x=0),t.indexOf("Y")===-1&&(this._offset.y=0),t.indexOf("Z")===-1&&(this._offset.z=0),n==="local"&&t!=="XYZ"?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),r.position.copy(this._offset).add(this._positionStart),this.translationSnap&&(n==="local"&&(r.position.applyQuaternion(ki.copy(this._quaternionStart).invert()),t.search("X")!==-1&&(r.position.x=Math.round(r.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(r.position.y=Math.round(r.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(r.position.z=Math.round(r.position.z/this.translationSnap)*this.translationSnap),r.position.applyQuaternion(this._quaternionStart)),n==="world"&&(r.parent&&r.position.add(nn.setFromMatrixPosition(r.parent.matrixWorld)),t.search("X")!==-1&&(r.position.x=Math.round(r.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(r.position.y=Math.round(r.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(r.position.z=Math.round(r.position.z/this.translationSnap)*this.translationSnap),r.parent&&r.position.sub(nn.setFromMatrixPosition(r.parent.matrixWorld))));else if(s==="scale"){if(t.search("XYZ")!==-1){let a=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(a*=-1),ah.set(a,a,a)}else nn.copy(this.pointStart),ah.copy(this.pointEnd),nn.applyQuaternion(this._worldQuaternionInv),ah.applyQuaternion(this._worldQuaternionInv),ah.divide(nn),t.search("X")===-1&&(ah.x=1),t.search("Y")===-1&&(ah.y=1),t.search("Z")===-1&&(ah.z=1);r.scale.copy(this._scaleStart).multiply(ah),this.scaleSnap&&(t.search("X")!==-1&&(r.scale.x=Math.round(r.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Y")!==-1&&(r.scale.y=Math.round(r.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Z")!==-1&&(r.scale.z=Math.round(r.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(s==="rotate"){this._offset.copy(this.pointEnd).sub(this.pointStart);const a=20/this.worldPosition.distanceTo(nn.setFromMatrixPosition(this.camera.matrixWorld));t==="E"?(this.rotationAxis.copy(this.eye),this.rotationAngle=this.pointEnd.angleTo(this.pointStart),this._startNorm.copy(this.pointStart).normalize(),this._endNorm.copy(this.pointEnd).normalize(),this.rotationAngle*=this._endNorm.cross(this._startNorm).dot(this.eye)<0?1:-1):t==="XYZE"?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(nn.copy(this.rotationAxis).cross(this.eye))*a):(t==="X"||t==="Y"||t==="Z")&&(this.rotationAxis.copy(VN[t]),nn.copy(VN[t]),n==="local"&&nn.applyQuaternion(this.worldQuaternion),this.rotationAngle=this._offset.dot(nn.cross(this.eye).normalize())*a),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),n==="local"&&t!=="E"&&t!=="XYZE"?(r.quaternion.copy(this._quaternionStart),r.quaternion.multiply(ki.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),r.quaternion.copy(ki.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),r.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(EI),this.dispatchEvent(XN)}}pointerUp(e){e.button===0&&(this.dragging&&this.axis!==null&&(qN.mode=this.mode,this.dispatchEvent(qN)),this.dragging=!1,this.axis=null)}dispose(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerHover),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.traverse(function(e){e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()})}attach(e){return this.object=e,this.visible=!0,this}detach(){return this.object=void 0,this.visible=!1,this.axis=null,this}reset(){this.enabled&&this.dragging&&(this.object.position.copy(this._positionStart),this.object.quaternion.copy(this._quaternionStart),this.object.scale.copy(this._scaleStart),this.dispatchEvent(EI),this.dispatchEvent(XN),this.pointStart.copy(this.pointEnd))}getRaycaster(){return Pu}getMode(){return this.mode}setMode(e){this.mode=e}setTranslationSnap(e){this.translationSnap=e}setRotationSnap(e){this.rotationSnap=e}setScaleSnap(e){this.scaleSnap=e}setSize(e){this.size=e}setSpace(e){this.space=e}}function Jne(i){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:i.button};{const e=this.domElement.getBoundingClientRect();return{x:(i.clientX-e.left)/e.width*2-1,y:-(i.clientY-e.top)/e.height*2+1,button:i.button}}}function Zne(i){if(this.enabled)switch(i.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(i));break}}function $ne(i){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(i.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(i)),this.pointerDown(this._getPointer(i)))}function eoe(i){this.enabled&&this.pointerMove(this._getPointer(i))}function toe(i){this.enabled&&(this.domElement.releasePointerCapture(i.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(i)))}function MI(i,e,t){const s=e.intersectObject(i,!0);for(let r=0;r<s.length;r++)if(s[r].object.visible||t)return s[r];return!1}const zx=new vs,yi=new S(0,1,0),YN=new S(0,0,0),KN=new Pe,Qx=new Ce,jx=new Ce,Ca=new S,JN=new Pe,bv=new S(1,0,0),Bu=new S(0,1,0),xv=new S(0,0,1),Gx=new S,wv=new S,_v=new S;class ioe extends Me{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const e=new pi({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),t=new qi({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),s=e.clone();s.opacity=.15;const r=t.clone();r.opacity=.5;const n=e.clone();n.color.setHex(16711680);const o=e.clone();o.color.setHex(65280);const a=e.clone();a.color.setHex(255);const l=e.clone();l.color.setHex(16711680),l.opacity=.5;const c=e.clone();c.color.setHex(65280),c.opacity=.5;const u=e.clone();u.color.setHex(255),u.opacity=.5;const d=e.clone();d.opacity=.25;const p=e.clone();p.color.setHex(16776960),p.opacity=.25,e.clone().color.setHex(16776960);const f=e.clone();f.color.setHex(7895160);const g=new Hi(0,.04,.1,12);g.translate(0,.05,0);const m=new ui(.08,.08,.08);m.translate(0,.04,0);const v=new mt;v.setAttribute("position",new $e([0,0,0,1,0,0],3));const A=new Hi(.0075,.0075,.5,3);A.translate(0,.25,0);function b(F,X){const te=new Ta(F,.0075,3,64,X*Math.PI*2);return te.rotateY(Math.PI/2),te.rotateX(Math.PI/2),te}function y(){const F=new mt;return F.setAttribute("position",new $e([0,0,0,1,1,1],3)),F}const x={X:[[new ve(g,n),[.5,0,0],[0,0,-Math.PI/2]],[new ve(g,n),[-.5,0,0],[0,0,Math.PI/2]],[new ve(A,n),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new ve(g,o),[0,.5,0]],[new ve(g,o),[0,-.5,0],[Math.PI,0,0]],[new ve(A,o)]],Z:[[new ve(g,a),[0,0,.5],[Math.PI/2,0,0]],[new ve(g,a),[0,0,-.5],[-Math.PI/2,0,0]],[new ve(A,a),null,[Math.PI/2,0,0]]],XYZ:[[new ve(new Ia(.1,0),d.clone()),[0,0,0]]],XY:[[new ve(new ui(.15,.15,.01),u.clone()),[.15,.15,0]]],YZ:[[new ve(new ui(.15,.15,.01),l.clone()),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new ve(new ui(.15,.15,.01),c.clone()),[.15,0,.15],[-Math.PI/2,0,0]]]},_={X:[[new ve(new Hi(.2,0,.6,4),s),[.3,0,0],[0,0,-Math.PI/2]],[new ve(new Hi(.2,0,.6,4),s),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new ve(new Hi(.2,0,.6,4),s),[0,.3,0]],[new ve(new Hi(.2,0,.6,4),s),[0,-.3,0],[0,0,Math.PI]]],Z:[[new ve(new Hi(.2,0,.6,4),s),[0,0,.3],[Math.PI/2,0,0]],[new ve(new Hi(.2,0,.6,4),s),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new ve(new Ia(.2,0),s)]],XY:[[new ve(new ui(.2,.2,.01),s),[.15,.15,0]]],YZ:[[new ve(new ui(.2,.2,.01),s),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new ve(new ui(.2,.2,.01),s),[.15,0,.15],[-Math.PI/2,0,0]]]},M={START:[[new ve(new Ia(.01,2),r),null,null,null,"helper"]],END:[[new ve(new Ia(.01,2),r),null,null,null,"helper"]],DELTA:[[new Xi(y(),r),null,null,null,"helper"]],X:[[new Xi(v,r.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new Xi(v,r.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new Xi(v,r.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},P={XYZE:[[new ve(b(.5,1),f),null,[0,Math.PI/2,0]]],X:[[new ve(b(.5,.5),n)]],Y:[[new ve(b(.5,.5),o),null,[0,0,-Math.PI/2]]],Z:[[new ve(b(.5,.5),a),null,[0,Math.PI/2,0]]],E:[[new ve(b(.75,1),p),null,[0,Math.PI/2,0]]]},C={AXIS:[[new Xi(v,r.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},R={XYZE:[[new ve(new Bn(.25,10,8),s)]],X:[[new ve(new Ta(.5,.1,4,24),s),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new ve(new Ta(.5,.1,4,24),s),[0,0,0],[Math.PI/2,0,0]]],Z:[[new ve(new Ta(.5,.1,4,24),s),[0,0,0],[0,0,-Math.PI/2]]],E:[[new ve(new Ta(.75,.1,2,24),s)]]},T={X:[[new ve(m,n),[.5,0,0],[0,0,-Math.PI/2]],[new ve(A,n),[0,0,0],[0,0,-Math.PI/2]],[new ve(m,n),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new ve(m,o),[0,.5,0]],[new ve(A,o)],[new ve(m,o),[0,-.5,0],[0,0,Math.PI]]],Z:[[new ve(m,a),[0,0,.5],[Math.PI/2,0,0]],[new ve(A,a),[0,0,0],[Math.PI/2,0,0]],[new ve(m,a),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new ve(new ui(.15,.15,.01),u),[.15,.15,0]]],YZ:[[new ve(new ui(.15,.15,.01),l),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new ve(new ui(.15,.15,.01),c),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new ve(new ui(.1,.1,.1),d.clone())]]},z={X:[[new ve(new Hi(.2,0,.6,4),s),[.3,0,0],[0,0,-Math.PI/2]],[new ve(new Hi(.2,0,.6,4),s),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new ve(new Hi(.2,0,.6,4),s),[0,.3,0]],[new ve(new Hi(.2,0,.6,4),s),[0,-.3,0],[0,0,Math.PI]]],Z:[[new ve(new Hi(.2,0,.6,4),s),[0,0,.3],[Math.PI/2,0,0]],[new ve(new Hi(.2,0,.6,4),s),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new ve(new ui(.2,.2,.01),s),[.15,.15,0]]],YZ:[[new ve(new ui(.2,.2,.01),s),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new ve(new ui(.2,.2,.01),s),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new ve(new ui(.2,.2,.2),s),[0,0,0]]]},G={X:[[new Xi(v,r.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new Xi(v,r.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new Xi(v,r.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function N(F){const X=new Me;for(const te in F)for(let ne=F[te].length;ne--;){const Z=F[te][ne][0].clone(),fe=F[te][ne][1],ae=F[te][ne][2],Le=F[te][ne][3],Se=F[te][ne][4];Z.name=te,Z.tag=Se,fe&&Z.position.set(fe[0],fe[1],fe[2]),ae&&Z.rotation.set(ae[0],ae[1],ae[2]),Le&&Z.scale.set(Le[0],Le[1],Le[2]),Z.updateMatrix();const ie=Z.geometry.clone();ie.applyMatrix4(Z.matrix),Z.geometry=ie,Z.renderOrder=1/0,Z.position.set(0,0,0),Z.rotation.set(0,0,0),Z.scale.set(1,1,1),X.add(Z)}return X}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=N(x)),this.add(this.gizmo.rotate=N(P)),this.add(this.gizmo.scale=N(T)),this.add(this.picker.translate=N(_)),this.add(this.picker.rotate=N(R)),this.add(this.picker.scale=N(z)),this.add(this.helper.translate=N(M)),this.add(this.helper.rotate=N(C)),this.add(this.helper.scale=N(G)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}updateMatrixWorld(e){const t=(this.mode==="scale"?"local":this.space)==="local"?this.worldQuaternion:jx;this.gizmo.translate.visible=this.mode==="translate",this.gizmo.rotate.visible=this.mode==="rotate",this.gizmo.scale.visible=this.mode==="scale",this.helper.translate.visible=this.mode==="translate",this.helper.rotate.visible=this.mode==="rotate",this.helper.scale.visible=this.mode==="scale";let s=[];s=s.concat(this.picker[this.mode].children),s=s.concat(this.gizmo[this.mode].children),s=s.concat(this.helper[this.mode].children);for(let r=0;r<s.length;r++){const n=s[r];n.visible=!0,n.rotation.set(0,0,0),n.position.copy(this.worldPosition);let o;if(this.camera.isOrthographicCamera?o=(this.camera.top-this.camera.bottom)/this.camera.zoom:o=this.worldPosition.distanceTo(this.cameraPosition)*Math.min(1.9*Math.tan(Math.PI*this.camera.fov/360)/this.camera.zoom,7),n.scale.set(1,1,1).multiplyScalar(o*this.size/4),n.tag==="helper"){n.visible=!1,n.name==="AXIS"?(n.position.copy(this.worldPositionStart),n.visible=!!this.axis,this.axis==="X"&&(ki.setFromEuler(zx.set(0,0,0)),n.quaternion.copy(t).multiply(ki),Math.abs(yi.copy(bv).applyQuaternion(t).dot(this.eye))>.9&&(n.visible=!1)),this.axis==="Y"&&(ki.setFromEuler(zx.set(0,0,Math.PI/2)),n.quaternion.copy(t).multiply(ki),Math.abs(yi.copy(Bu).applyQuaternion(t).dot(this.eye))>.9&&(n.visible=!1)),this.axis==="Z"&&(ki.setFromEuler(zx.set(0,Math.PI/2,0)),n.quaternion.copy(t).multiply(ki),Math.abs(yi.copy(xv).applyQuaternion(t).dot(this.eye))>.9&&(n.visible=!1)),this.axis==="XYZE"&&(ki.setFromEuler(zx.set(0,Math.PI/2,0)),yi.copy(this.rotationAxis),n.quaternion.setFromRotationMatrix(KN.lookAt(YN,yi,Bu)),n.quaternion.multiply(ki),n.visible=this.dragging),this.axis==="E"&&(n.visible=!1)):n.name==="START"?(n.position.copy(this.worldPositionStart),n.visible=this.dragging):n.name==="END"?(n.position.copy(this.worldPosition),n.visible=this.dragging):n.name==="DELTA"?(n.position.copy(this.worldPositionStart),n.quaternion.copy(this.worldQuaternionStart),nn.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),nn.applyQuaternion(this.worldQuaternionStart.clone().invert()),n.scale.copy(nn),n.visible=this.dragging):(n.quaternion.copy(t),this.dragging?n.position.copy(this.worldPositionStart):n.position.copy(this.worldPosition),this.axis&&(n.visible=this.axis.search(n.name)!==-1));continue}n.quaternion.copy(t),this.mode==="translate"||this.mode==="scale"?(n.name==="X"&&Math.abs(yi.copy(bv).applyQuaternion(t).dot(this.eye))>.99&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1),n.name==="Y"&&Math.abs(yi.copy(Bu).applyQuaternion(t).dot(this.eye))>.99&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1),n.name==="Z"&&Math.abs(yi.copy(xv).applyQuaternion(t).dot(this.eye))>.99&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1),n.name==="XY"&&Math.abs(yi.copy(xv).applyQuaternion(t).dot(this.eye))<.2&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1),n.name==="YZ"&&Math.abs(yi.copy(bv).applyQuaternion(t).dot(this.eye))<.2&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1),n.name==="XZ"&&Math.abs(yi.copy(Bu).applyQuaternion(t).dot(this.eye))<.2&&(n.scale.set(1e-10,1e-10,1e-10),n.visible=!1)):this.mode==="rotate"&&(Qx.copy(t),yi.copy(this.eye).applyQuaternion(ki.copy(t).invert()),n.name.search("E")!==-1&&n.quaternion.setFromRotationMatrix(KN.lookAt(this.eye,YN,Bu)),n.name==="X"&&(ki.setFromAxisAngle(bv,Math.atan2(-yi.y,yi.z)),ki.multiplyQuaternions(Qx,ki),n.quaternion.copy(ki)),n.name==="Y"&&(ki.setFromAxisAngle(Bu,Math.atan2(yi.x,yi.z)),ki.multiplyQuaternions(Qx,ki),n.quaternion.copy(ki)),n.name==="Z"&&(ki.setFromAxisAngle(xv,Math.atan2(yi.y,yi.x)),ki.multiplyQuaternions(Qx,ki),n.quaternion.copy(ki))),n.visible=n.visible&&(n.name.indexOf("X")===-1||this.showX),n.visible=n.visible&&(n.name.indexOf("Y")===-1||this.showY),n.visible=n.visible&&(n.name.indexOf("Z")===-1||this.showZ),n.visible=n.visible&&(n.name.indexOf("E")===-1||this.showX&&this.showY&&this.showZ),n.material._color=n.material._color||n.material.color.clone(),n.material._opacity=n.material._opacity||n.material.opacity,n.material.color.copy(n.material._color),n.material.opacity=n.material._opacity,this.enabled&&this.axis&&(n.name===this.axis||this.axis.split("").some(function(a){return n.name===a}))&&(n.material.color.setHex(16776960),n.material.opacity=1)}super.updateMatrixWorld(e)}}class soe extends ve{constructor(){super(new Ns(1e5,1e5,2,2),new pi({visible:!1,wireframe:!0,side:bi,transparent:!0,opacity:.1,toneMapped:!1})),this.isTransformControlsPlane=!0,this.type="TransformControlsPlane"}updateMatrixWorld(e){let t=this.space;switch(this.position.copy(this.worldPosition),this.mode==="scale"&&(t="local"),Gx.copy(bv).applyQuaternion(t==="local"?this.worldQuaternion:jx),wv.copy(Bu).applyQuaternion(t==="local"?this.worldQuaternion:jx),_v.copy(xv).applyQuaternion(t==="local"?this.worldQuaternion:jx),yi.copy(wv),this.mode){case"translate":case"scale":switch(this.axis){case"X":yi.copy(this.eye).cross(Gx),Ca.copy(Gx).cross(yi);break;case"Y":yi.copy(this.eye).cross(wv),Ca.copy(wv).cross(yi);break;case"Z":yi.copy(this.eye).cross(_v),Ca.copy(_v).cross(yi);break;case"XY":Ca.copy(_v);break;case"YZ":Ca.copy(Gx);break;case"XZ":yi.copy(_v),Ca.copy(wv);break;case"XYZ":case"E":Ca.set(0,0,0);break}break;case"rotate":default:Ca.set(0,0,0)}Ca.length()===0?this.quaternion.copy(this.cameraQuaternion):(JN.lookAt(nn.set(0,0,0),Ca,yi),this.quaternion.setFromRotationMatrix(JN)),super.updateMatrixWorld(e)}}var roe=Object.defineProperty,noe=Object.getOwnPropertyDescriptor,Hx=(i,e,t,s)=>{for(var r=s>1?void 0:s?noe(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&roe(e,t,r),r};class ku extends Ee{constructor(){super(...arguments),h(this,"isGizmo",!1),h(this,"translationSnap",1),h(this,"rotationSnapAngle",15),h(this,"scaleSnap",.25),h(this,"control"),h(this,"orbit"),h(this,"changeEventListener"),h(this,"windowKeyDownListener"),h(this,"windowKeyUpListener")}onEnable(){var e;this.isGizmo&&!og||this.context.mainCamera&&(this.control||(this.control=new Kne(this.context.mainCamera,this.context.domElement),this.control.visible=!0,this.control.enabled=!0,this.control.getRaycaster().layers.set(2),this.control.size=1,this.control.traverse(t=>{const s=t;if(s.layers.set(2),s){const r=s.material;r&&(r.opacity=.3)}}),this.orbit=$.getComponentInParent(this.context.mainCamera,Tl)??void 0),this.control&&(this.context.scene.add(this.control),this.control.attach(this.gameObject),this.changeEventListener=this.onControlChangedEvent.bind(this),(e=this.control)==null||e.addEventListener("dragging-changed",this.changeEventListener),this.addWindowEvents()))}onDisable(){var e,t;(e=this.control)==null||e.removeFromParent(),this.changeEventListener&&((t=this.control)==null||t.removeEventListener("dragging-changed",this.changeEventListener)),this.removeWindowEvents()}enableSnapping(){this.control&&(this.control.setTranslationSnap(this.translationSnap),this.control.setRotationSnap(Cr.degToRad(this.rotationSnapAngle)),this.control.setScaleSnap(this.scaleSnap))}disableSnapping(){this.control&&(this.control.setTranslationSnap(null),this.control.setRotationSnap(null),this.control.setScaleSnap(null))}onControlChangedEvent(e){const t=this.orbit;if(t&&(t.enabled=!e.value),e.value){const s=$.getComponentInParent(this.gameObject,jc);s&&s.requestOwnership()}}addWindowEvents(){const e=this.control;e&&(this.windowKeyDownListener||(this.windowKeyDownListener=t=>{if(this.enabled)switch(t.keyCode){case 81:e.setSpace(e.space==="local"?"world":"local");break;case 16:this.enableSnapping();break;case 87:e.setMode("translate");break;case 69:e.setMode("rotate");break;case 82:e.setMode("scale");break;case 187:case 107:e.setSize(e.size+.1);break;case 189:case 109:e.setSize(Math.max(e.size-.1,.1));break;case 88:e.showX=!e.showX;break;case 89:e.showY=!e.showY;break;case 90:e.showZ=!e.showZ;break;case 32:e.enabled=!e.enabled;break}}),this.windowKeyUpListener||(this.windowKeyUpListener=t=>{if(this.enabled)switch(t.keyCode){case 16:this.disableSnapping();break}}),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener))}removeWindowEvents(){window.removeEventListener("keydown",this.windowKeyDownListener),window.removeEventListener("keyup",this.windowKeyUpListener)}}Hx([w()],ku.prototype,"isGizmo",2),Hx([w()],ku.prototype,"translationSnap",2),Hx([w()],ku.prototype,"rotationSnapAngle",2),Hx([w()],ku.prototype,"scaleSnap",2);var ooe=Object.defineProperty,aoe=Object.getOwnPropertyDescriptor,II=(i,e,t,s)=>{for(var r=s>1?void 0:s?aoe(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&ooe(e,t,r),r};class Du extends gr{constructor(){super(...arguments),h(this,"color"),h(this,"intensity"),h(this,"center")}get typeName(){return"Vignette"}init(){this.color.defaultValue={r:0,g:0,b:0,a:1},this.intensity.defaultValue=0,this.center.defaultValue={x:.5,y:.5}}onCreateEffect(){const e=new PD;return this.intensity.onValueChanged=t=>{e.offset=t,this.updateDarkness(e)},this.color.onValueChanged=t=>{this.updateDarkness(e)},e}updateDarkness(e){const t=this.intensity.value;e.darkness=t}}II([w(Et)],Du.prototype,"color",2),II([w(Et)],Du.prototype,"intensity",2),II([w(Et)],Du.prototype,"center",2),oo("Vignette",Du);var loe=Object.defineProperty,coe=Object.getOwnPropertyDescriptor,hoe=(i,e,t,s)=>{for(var r=s>1?void 0:s?coe(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&loe(e,t,r),r};const TI=re("debugpost");class Vx extends Ee{constructor(){super(...arguments),h(this,"sharedProfile"),h(this,"_postprocessing"),h(this,"_effects",[]),h(this,"_lastApplyTime"),h(this,"_rapidApplyCount",0),h(this,"_isDirty",!1),h(this,"_modificationQueue"),h(this,"_recreateId",-1)}markDirty(){this._isDirty=!0}awake(){var e;(e=this.sharedProfile)==null||e.init(),TI&&(console.log(this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",t=>{t.key==="p"&&(console.log("Toggle volume: "+this.name,!this.enabled),this.enabled=!this.enabled)}))}onDisable(){var e;(e=this._postprocessing)==null||e.unapply()}onBeforeRender(){if(!this.context.isInXR){if(this.context.composer&&!(this.context.composer instanceof IC))return;this.context.mainCamera&&(!this._postprocessing||!this._postprocessing.isActive||this._isDirty)&&this.apply(),this.context.composer&&(this.context.composer.setRenderer(this.context.renderer),this.context.composer.setMainScene(this.context.scene),this.context.mainCamera&&this.context.composer.setMainCamera(this.context.mainCamera))}}onDestroy(){var e;(e=this._postprocessing)==null||e.dispose()}apply(){var e,t;TI&&console.log("Apply PostProcessing",this,(e=this.context.mainCamera)==null?void 0:e.name),lr()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("Detected rapid post processing modifications - this might be a bug",this)),this._lastApplyTime=Date.now()),this._isDirty=!1,this.unapply(),this._effects.length=0,(t=this.sharedProfile)!=null&&t.components&&this._effects.push(...this.sharedProfile.components);const s=this.gameObject.getComponentsInChildren(gr);if(TI&&s!=null&&s.length&&console.log("Additional",s),s)for(const r of s)r.active&&this._effects.push(r);this._effects.length>0&&(this._postprocessing||(this._postprocessing=new Tx(this.context)),this._postprocessing.apply(this._effects),this._applyPostQueue())}unapply(){var e;(e=this._postprocessing)==null||e.unapply()}_applyPostQueue(){if(this._modificationQueue){for(const e of this._modificationQueue.values())this.onEditorModification(e);this._modificationQueue.clear()}}onEditorModification(e){var t,s;if(e.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(e.propertyName,e),!0;if(!((t=this._effects)!=null&&t.length))return;const r=e.propertyName.split(".");if(r.length===3||r.length===4){const n=r[1],o=r[2];for(const a of this._effects)if(((s=a.typeName)==null?void 0:s.toLowerCase())===n.toLowerCase()){if(o==="active"){a.active=e.value,this.scheduleRecreate();return}if(!Wx.has(n)){const l=new Array;Wx.set(n,l);const c=Object.keys(a);for(const u of c)a[u]instanceof Et&&l.push(u)}if(Wx.has(n)){const l=o.toLowerCase(),c=Wx.get(n);for(const u of c)if(u.toLowerCase()===l){const d=a[u];d instanceof Et&&(r.length===4&&r[3]==="active"?(d.overrideState=e.value,this.scheduleRecreate()):d&&d.value!==void 0&&(d.value=e.value));return}}console.warn("Unknown modification",o);return}}return!0}return!1}scheduleRecreate(){const e=++this._recreateId;setTimeout(()=>{e===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}hoe([ip(Dm)],Vx.prototype,"sharedProfile",2);const Wx=new Map;var uoe=Object.defineProperty,doe=Object.getOwnPropertyDescriptor,poe=(i,e,t,s)=>{for(var r=s>1?void 0:s?doe(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&uoe(e,t,r),r};class qx extends Ee{constructor(){super(...arguments),h(this,"backgroundTint",new vi(1,1,1,1)),h(this,"_preRender"),h(this,"backgroundPlane"),h(this,"threeTexture"),h(this,"forceTextureInitialization",function(){const e=new pi,t=new Ns,s=new Vr;s.add(new ve(t,e));const r=new Eh;return function(n,o){e.map=o,n.render(s,r)}}())}awake(){_t.OptionalFeatures_AR.push("camera-access")}get background(){return this.backgroundPlane}onEnable(){this._preRender=this.preRender.bind(this),this.context.pre_render_callbacks.push(this._preRender),this.backgroundPlane&&(this.gameObject.add(this.backgroundPlane),this.backgroundPlane.visible=!1)}onDisable(){this.context.pre_render_callbacks=this.context.pre_render_callbacks.filter(e=>e!==this._preRender),this.backgroundPlane&&this.gameObject.remove(this.backgroundPlane)}preRender(){if(!this||!this.gameObject)return;const e=this.context.renderer.xr.getFrame();e&&(!this.threeTexture&&this.context.renderer&&(this.threeTexture=new Ft,this.forceTextureInitialization(this.context.renderer,this.threeTexture)),this.backgroundPlane===void 0&&(this.backgroundPlane=goe(this.backgroundTint),this.gameObject.add(this.backgroundPlane)),this.updateFromFrame(e))}onBeforeRender(e){this.updateFromFrame(e)}updateFromFrame(e){if(!e)return;const t=e.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(t){for(const s of t.views)if("camera"in s&&s.camera){let r=this.context.renderer.xr.getBinding();if(r||(r=new XRWebGLBinding(e.session,this.context.renderer.getContext())),r){let n=null;if("getCameraImage"in r){n=r.getCameraImage(s.camera);const o=this.context.renderer.properties.get(this.threeTexture);o.__webglTexture=n,this.backgroundPlane&&(this.backgroundPlane.setTexture(this.threeTexture),this.backgroundPlane.visible=!0)}}}}}}poe([w()],qx.prototype,"backgroundTint",2);let foe=`
5439
5439
  uniform sampler2D t2D;
5440
5440
 
5441
5441
  varying vec2 vUv;