@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.
- package/CHANGELOG.md +4 -1
- package/dist/needle-engine.js +3 -3
- package/dist/needle-engine.light.js +3 -3
- package/dist/needle-engine.light.min.js +2 -2
- package/dist/needle-engine.light.umd.cjs +2 -2
- package/dist/needle-engine.min.js +2 -2
- package/dist/needle-engine.umd.cjs +2 -2
- package/lib/engine-components/SpectatorCamera.js +1 -1
- package/lib/engine-components/SpectatorCamera.js.map +1 -1
- package/package.json +1 -1
- package/src/engine-components/SpectatorCamera.ts +1 -1
|
@@ -4176,7 +4176,7 @@ ${r.join(`
|
|
|
4176
4176
|
`)}
|
|
4177
4177
|
|
|
4178
4178
|
}
|
|
4179
|
-
`}function DB(n){return`(${n.r}, ${n.g}, ${n.b})`}function kB(n){return`(${n.x}, ${n.y})`}const pT=class{constructor(e,t,i){h(this,"id");h(this,"trigger");h(this,"action");h(this,"exclusive",!1);this.id="Behavior_"+TI(e)+"_"+pT.global_id++,this.trigger=t,this.action=i}makeExclusive(e){return this.exclusive=e,this}writeTo(e,t,i){if(!this.trigger||!this.action)return;i.beginBlock(`def Preliminary_Behavior "${this.id}"`),i.appendLine(`rel actions = <${this.action.id}>`),i.appendLine(`uniform bool exclusive = ${this.exclusive}`);let s="";if(Array.isArray(this.trigger)){s="[";for(let r=0;r<this.trigger.length;r++){const o=this.trigger[r];s+="<"+o.id+">",r+1<this.trigger.length&&(s+=", ")}s+="]"}else s=`<${this.trigger.id}>`;if(i.appendLine(`rel triggers = ${s} `),i.appendLine(),Array.isArray(this.trigger))for(const r of this.trigger)r.writeTo(t,i),i.appendLine();else this.trigger.writeTo(t,i);i.appendLine(),this.action.writeTo(t,i),i.closeBlock()}};let ls=pT;h(ls,"global_id",0);function aE(n,e){var i,s;let t="";if(Array.isArray(n)){let r="[ ";for(let o=0;o<n.length;o++){let a=n[o];if(typeof a=="string")r+=a;else if(typeof a=="object"){a.isObject3D&&(a=e.findById(a.uuid));const l=(i=a.getPath)==null?void 0:i.call(a);r+=l}o+1<n.length&&(r+=", ")}r+=" ]",t=r}else typeof n=="object"&&(n.isObject3D&&(n=e.findById(n.uuid)),t=(s=n.getPath)==null?void 0:s.call(n));return t=t.replace(e.name,e.name+"/Scenes/Scene"),t}const gT=class{constructor(e,t){h(this,"id");h(this,"targetId");h(this,"tokenId");h(this,"type");h(this,"distance");e&&(this.targetId=e),t?this.id=t:this.id="Trigger_"+gT.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=aE(this.targetId,e)),t.appendLine("rel affectedObjects = "+this.targetId)),this.tokenId&&t.appendLine(`token info:id = "${this.tokenId}"`),this.type&&t.appendLine(`token type = "${this.type}"`),typeof this.distance=="number"&&t.appendLine(`double distance = ${this.distance}`),t.closeBlock()}};let kl=gT;h(kl,"global_id",0);class dr{static sceneStartTrigger(){const e=new kl;return e.targetId=void 0,e.tokenId="SceneTransition",e.type="enter",e}static tapTrigger(e){const t=new kl(e);return t.tokenId="TapGesture",t}static isTapTrigger(e){return(e==null?void 0:e.tokenId)==="TapGesture"}static proximityToCameraTrigger(e,t){const i=new kl(e);return i.tokenId="ProximityToCamera",i.distance=t,i}}class zc{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 i of this.actions)i&&t.appendLine("<"+i.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 i of this.actions)i&&(i.writeTo(e,t),t.appendLine());t.closeBlock()}}h(zc,"global_id",0);var PI=(n=>(n[n.pop=0]="pop",n[n.blink=1]="blink",n[n.bounce=2]="bounce",n[n.flip=3]="flip",n[n.float=4]="float",n[n.jiggle=5]="jiggle",n[n.pulse=6]="pulse",n[n.spin=7]="spin",n))(PI||{}),lE=(n=>(n.Relative="relative",n.Absolute="absolute",n))(lE||{});const Db=class{constructor(e,t){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");e&&(this.affectedObjects=e),t?this.id=t:this.id="Action",this.id+="_"+Db.global_id++}clone(){const e=new Db,t=e.id;return Object.assign(e,this),e.id=t,e}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),this.affectedObjects&&(typeof this.affectedObjects!="string"&&(this.affectedObjects=aE(this.affectedObjects,e)),t.appendLine("rel affectedObjects = "+this.affectedObjects)),typeof this.duration=="number"&&t.appendLine(`double duration = ${this.duration} `),this.easeType&&t.appendLine(`token easeType = "${this.easeType}"`),this.tokenId&&t.appendLine(`token info:id = "${this.tokenId}"`),this.motionType&&t.appendLine(`token motionType = "${this.motionType}"`),typeof this.moveDistance=="number"&&t.appendLine(`double moveDistance = ${this.moveDistance} `),this.style&&t.appendLine(`token style = "${this.style}"`),this.type&&t.appendLine(`token type = "${this.type}"`),this.front&&t.appendLine(`vector3d front = (${this.front.x}, ${this.front.y}, ${this.front.z})`),this.up&&t.appendLine(`vector3d upVector = (${this.up.x}, ${this.up.y}, ${this.up.z})`),typeof this.start=="number"&&t.appendLine(`double start = ${this.start} `),typeof this.animationSpeed=="number"&&t.appendLine(`double animationSpeed = ${this.animationSpeed} `),typeof this.reversed=="boolean"&&t.appendLine(`bool reversed = ${this.reversed}`),typeof this.pingPong=="boolean"&&t.appendLine(`bool reverses = ${this.pingPong}`),this.xFormTarget&&(typeof this.xFormTarget!="string"&&(this.xFormTarget=aE(this.xFormTarget,e)),t.appendLine(`rel xformTarget = ${this.xFormTarget}`)),typeof this.audio=="string"&&t.appendLine(`asset audio = @${this.audio}@`),typeof this.gain=="number"&&t.appendLine(`double gain = ${this.gain}`),typeof this.auralMode=="string"&&t.appendLine(`token auralMode = "${this.auralMode}"`),typeof this.multiplePerformOperation=="string"&&t.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),t.closeBlock()}};let Pr=Db;h(Pr,"global_id",0);let Xd=class Fd{constructor(e,t,i){h(this,"x",0);h(this,"y",0);h(this,"z",0);this.x=e,this.y=t,this.z=i}static get up(){return new Fd(0,1,0)}static get right(){return new Fd(1,0,0)}static get forward(){return new Fd(0,0,1)}static get back(){return new Fd(0,0,-1)}static get zero(){return new Fd(0,0,0)}};var oU=(n=>(n.Play="play",n.Pause="pause",n.Stop="stop",n))(oU||{}),cE=(n=>(n.Spatial="spatial",n.NonSpatial="nonSpatial",n.Ambient="ambient",n))(cE||{});class ai{static sequence(...e){return new zc("group_"+zc.getId(),e).makeSequence()}static parallel(...e){return new zc("group_"+zc.getId(),e).makeParallel()}static fadeAction(e,t,i){const s=new Pr(e);return s.tokenId="Visibility",s.type=i?"show":"hide",s.duration=t,s.style="basic",s.motionType="none",s.moveDistance=0,s.easeType="none",s}static startAnimationAction(e,t,i=0,s=1,r=!1,o=!1){const a=new Pr(e);if(a.tokenId="StartAnimation",a.start=t,a.duration=i,a.animationSpeed=s,a.reversed=r,a.pingPong=o,r&&(a.start-=i),o){a.pingPong=!1;const l=a.clone();return l.reversed=!r,l.start=a.start,l.reversed&&(l.start-=i),ai.sequence(a,l)}return a}static waitAction(e){const t=new Pr;return t.tokenId="Wait",t.duration=e,t}static lookAtCameraAction(e,t=9999999999999,i,s){const r=new Pr(e);return r.tokenId="LookAtCamera",r.duration=t,r.front=i??Xd.forward,r.up=s??Xd.up,r}static emphasize(e,t,i=2,s=1,r="basic"){const o=new Pr(e);return o.tokenId="Emphasize",o.duration=t,o.style=r??"basic",o.motionType=PI[i],o.moveDistance=s,o}static transformAction(e,t,i,s,r="inout"){const o=new Pr(e);return o.tokenId="Transform",o.duration=i,o.type=s,o.easeType=r,Array.isArray(t)&&console.error("Transform target must not be an array",t),o.xFormTarget=t,o}static playAudioAction(e,t,i="play",s=1,r="spatial"){const o=new Pr(e);return o.tokenId="Audio",o.type=i,o.audio=t,o.gain=s,o.auralMode=r,o.multiplePerformOperation="allow",o}}class QY{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 RI extends QY{constructor(t,i,s,r){super(t);h(this,"matrix");h(this,"material");h(this,"geometry");h(this,"_enableAction");h(this,"_disableAction");this.matrix=i,this.material=s,this.geometry=r}onApply(t){var r,o;const i=this.model;if(!i)return;(r=i.parent)!=null&&r.isDynamic||go.createEmptyParent(i);const s=i.clone();this.matrix&&(s.matrix=this.matrix),this.material&&(s.material=this.material),this.geometry&&(s.geometry=this.geometry),(o=i.parent)==null||o.add(s)}enable(){return this._enableAction?this._enableAction:(this._enableAction=ai.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=ai.fadeAction(this.object,0,!1),this._disableAction)}}class BI{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 HY=Object.defineProperty,VY=Object.getOwnPropertyDescriptor,aU=(n,e,t,i)=>{for(var s=i>1?void 0:i?VY(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&HY(e,t,s),s};class LA extends Ce{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 t=wt(this.from).clone(),i=wt(this.to).clone(),s=t.distanceTo(i);this._centerPos.copy(t),this._centerPos.add(i),this._centerPos.multiplyScalar(.5),hn(this.gameObject,this.centered?this._centerPos:t),this.gameObject.lookAt(wt(this.to).clone()),this.gameObject.scale.set(this.width,this.width,s)}}aU([x(Z)],LA.prototype,"from",2);aU([x(Z)],LA.prototype,"to",2);var WY=Object.defineProperty,jY=Object.getOwnPropertyDescriptor,FA=(n,e,t,i)=>{for(var s=i>1?void 0:i?jY(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&WY(e,t,s),s};const Ec=oe("debuganimation");class Eo extends Ce{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 t;return(t=this.animations)!=null&&t.length?this.animations[0]:null}set clip(t){if(!this.__didAwake){Ec&&console.log("Assign clip during serialization",t),this._tempAnimationClipBeforeGameObjectExisted=t;return}t&&(Ec&&console.log("Assign clip",t,!!this.gameObject),this.gameObject.animations||(this.gameObject.animations=[]),!this.animations.includes(t)&&(this.animations.length>0?this.animations.splice(0,0,t):this.animations.push(t)))}set clips(t){this.animations=t}set animations(t){Ec&&console.log("assign animations",t),this.gameObject.animations=t}get animations(){return this.gameObject.animations}get currentAction(){return this._currentActions[0]}get currentActions(){return this._currentActions}get actions(){return this._actions}set actions(t){this._actions=t}awake(){Ec&&console.log(this),this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.playAutomatically&&this.init()}onEnable(){var t;if(this.playAutomatically&&((t=this.animations)==null?void 0:t.length)>0&&this.currentActions.length<=0){const i=Math.floor(Math.random()*this.actions.length);this.play(i)}}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(t){var i;return(i=this.actions)==null?void 0:i.find(s=>s.getClip().name===t)}get isPlaying(){for(let t=0;t<this._currentActions.length;t++)if(this._currentActions[t].isRunning())return!0;return!1}play(t=0,i){if(Ec&&console.log("PLAY",t),this.init(),!this.mixer){Ec&&console.warn("Missing mixer",this);return}t===void 0&&(t=0);let s=t;if(typeof t=="number"){if(t>=this.animations.length){Ec&&console.log("No animation at index",t);return}s=this.animations[t]}else typeof t=="string"&&(s=this.animations.find(o=>o.name===t));if(!s){console.error("Could not find clip",t);return}i||(i={}),i.minMaxOffsetNormalized||(i.minMaxOffsetNormalized=this.minMaxOffsetNormalized),i.minMaxSpeed||(i.minMaxSpeed=this.minMaxSpeed),i.loop===void 0&&(i.loop=this.loop),i.clampWhenFinished===void 0&&(i.clampWhenFinished=this.clampWhenFinished);for(const o of this.actions)if(o.getClip()===s)return this.internalOnPlay(o,i);if(!(s instanceof wo)){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,i)}internalOnPlay(t,i){var s=this.currentAction;if(s===t&&s.isRunning()&&s.time<s.getClip().duration){const l=this.tryFindHandle(t);if(l)return l.getPromise()}const r=(i==null?void 0:i.exclusive)??!0;i!=null&&i.fadeDuration?(r&&(s==null||s.fadeOut(i.fadeDuration)),t.fadeIn(i.fadeDuration)):r&&(s==null||s.stop()),t.reset(),t.enabled=!0,t.time=0,t.timeScale=1;const o=t.getClip();i!=null&&i.minMaxOffsetNormalized&&(t.time=$e.lerp(i.minMaxOffsetNormalized.x,i.minMaxOffsetNormalized.y,Math.random())*o.duration),i!=null&&i.minMaxSpeed&&(t.timeScale=$e.lerp(i.minMaxSpeed.x,i.minMaxSpeed.y,Math.random())),i!=null&&i.clampWhenFinished&&(t.clampWhenFinished=!0),(i==null?void 0:i.startTime)!==void 0&&(t.time=i.startTime),(i==null?void 0:i.loop)!==void 0?t.loop=i.loop?JE:mm:t.loop=mm,t.play(),Ec&&console.log("PLAY",t.getClip().name,t);const a=new qY(t,this.mixer,i,l=>{this._handles.splice(this._handles.indexOf(a),1)});return this._handles.push(a),a.getPromise()}tryFindHandle(t){for(const i of this._handles)if(i.action===t)return i}init(){this._didInit||(this._didInit=!0,this.gameObject&&(this.actions=[],this.mixer=new h_(this.gameObject)))}}FA([x()],Eo.prototype,"playAutomatically",2);FA([x()],Eo.prototype,"randomStartTime",2);FA([x()],Eo.prototype,"loop",2);FA([x()],Eo.prototype,"clampWhenFinished",2);FA([x(wo)],Eo.prototype,"clips",1);class qY{constructor(e,t,i,s){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=s,this._options=i}getPromise(){return this.promise?this.promise:(this.promise=new Promise((e,t)=>{this._resolveCallback=e,this._rejectCallback=t,this.resolve=this.onResolve.bind(this),this.reject=this.onReject.bind(this)}),this._loopCallback=this.onLoop.bind(this),this._finishedCallback=this.onFinished.bind(this),this.mixer.addEventListener("loop",this._loopCallback),this.mixer.addEventListener("finished",this._finishedCallback),this.promise)}_update(){this._options&&this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){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,i;this.dispose(),(t=this._resolvedOrRejectedCallback)==null||t.call(this,this),(i=this._rejectCallback)==null||i.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 XY=Object.defineProperty,YY=Object.getOwnPropertyDescriptor,uh=(n,e,t,i)=>{for(var s=i>1?void 0:i?YY(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&XY(e,t,s),s};class dh{constructor(){h(this,"time");h(this,"value");h(this,"inTangent");h(this,"inWeight");h(this,"outTangent");h(this,"outWeight");h(this,"weightedMode")}}uh([x()],dh.prototype,"time",2);uh([x()],dh.prototype,"value",2);uh([x()],dh.prototype,"inTangent",2);uh([x()],dh.prototype,"inWeight",2);uh([x()],dh.prototype,"outTangent",2);uh([x()],dh.prototype,"outWeight",2);uh([x()],dh.prototype,"weightedMode",2);const lU=class{constructor(){h(this,"keys")}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(n){if(!this.keys||this.keys.length==0)return 0;if(this.keys[0].time>=n)return this.keys[0].value;for(let e=0;e<this.keys.length;e++){const t=this.keys[e];if(t.time<=n)if(e+1<this.keys.length){const s=this.keys[e+1];if(s.time<n)continue;return!isFinite(t.outTangent)||!isFinite(s.inTangent)?t.value:lU.interpolateValue(n,t,s)}else return t.value}return this.keys[this.keys.length-1].value}static interpolateValue(n,e,t){const i=e.time,s=e.value,r=e.outTangent,o=t.time,a=t.value,l=t.inTangent,c=o-i,u=c*c,d=u*c,f=((r+l)*c-2*(a-s))/d,p=(3*(a-s)-(l+2*r)*c)/u,g=r,m=s,A=n-i,v=A*A,b=v*A;return f*b+p*v+g*A+m}};let ku=lU;uh([x(dh)],ku.prototype,"keys",2);const Yd=oe("debugusdzanimation");class F_{constructor(e,t,i){h(this,"ext");h(this,"root");h(this,"clip");this.ext=e,this.root=t,this.clip=i}get start(){return this.ext.getStartTime01(this.root,this.clip)}get duration(){return this.clip.duration}}class U_{constructor(e,t,i,s){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=i,this.clip=s}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,i,s,r,o;return Math.max(((t=(e=this.pos)==null?void 0:e.times)==null?void 0:t.length)??0,((s=(i=this.rot)==null?void 0:i.times)==null?void 0:s.length)??0,((o=(r=this.scale)==null?void 0:r.times)==null?void 0:o.length)??0)}getDuration(){var t,i,s;const e=((t=this.pos)==null?void 0:t.times)??((i=this.rot)==null?void 0:i.times)??((s=this.scale)==null?void 0:s.times);return e?e[e.length-1]:0}getStartTime(e){let t=0;for(let i=0;i<e.length;i++){const s=e[i];if(s===this)return t;t+=s.getDuration()}return t}}class N_{constructor(){h(this,"dict",new Map);h(this,"rootTargetMap",new Map);h(this,"serializers",[])}get extensionName(){return"animation"}getStartTime01(e,t){const i=this.rootTargetMap.get(e);if(!i)return 1/0;let s=-1;for(const r of i){const o=this.dict.get(r);let a=0;if(o!=null&&o.length){for(const l of o){if(l.clip===t)break;a+=l.getDuration()}s=Math.max(s,a)}else console.warn("No animation found on root",e,t,o)}return s}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],o=e.getObjectByName(r);if(!o){console.warn("no object found for track",s.name,"using "+e.name+" instead");continue}this.dict.has(o)||this.dict.set(o,[]);const a=this.dict.get(o);if(!a)continue;let l=a.find(u=>u.clip===t);l||(l=new U_(this,e,o,t),a.push(l)),l.addTrack(s);const c=this.rootTargetMap.get(e);c!=null&&c.includes(o)||c==null||c.push(o)}return new F_(this,e,t)}onAfterHierarchy(e){Yd&&console.log(this.dict)}onAfterBuildDocument(e){var t,i;for(const s of this.serializers){const r=(t=s.model)==null?void 0:t.parent,o=(r==null?void 0:r.isDynamic)===!0;Yd&&console.log(o,(i=s.model)==null?void 0:i.parent),o&&s.registerCallback(r)}}onExportObject(e,t,i){Z.foreachComponent(e,r=>{const o=r;typeof o.createAnimation=="function"&&o.createAnimation(this,t,i)},!1);const s=new KY(e,this.dict);this.serializers.push(s),s.registerCallback(t)}}class KY{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)),Yd&&console.log("REPARENT",e),this.model=e,this.model.addEventListener("serialize",this.callback)}onSerialize(e,t){var c,u,d,f,p,g;if(!this.model)return;Yd&&console.log("SERIALIZE",this.model.name,this.object.type);const i=this.object,s=this.dict.get(i);if(!s)return;const r=new Pe,o=new S,a=new xe,l=new S(1,1,1);e.appendLine("matrix4d xformOp:transform.timeSamples = {"),e.indent++;for(const m of s){let A=(c=m.pos)==null?void 0:c.times,v=(u=m.rot)==null?void 0:u.times,b=(d=m.scale)==null?void 0:d.times,y=[];if(A)for(const w of A)y.push(w);if(v)for(const w of v)y.push(w);if(b)for(const w of b)y.push(w);if(y.sort((w,M)=>w-M),y=[...new Set(y)],!y||y.length===0){console.error("got an animated object but no time values??",i,m);continue}const _=m.getStartTime(s);Yd&&e.appendLine(m.clip.name+": start="+_.toFixed(3)+", length="+m.getDuration().toFixed(3)+", frames="+m.getFrames());const C=(f=m.pos)==null?void 0:f.createInterpolant(),E=(p=m.rot)==null?void 0:p.createInterpolant(),T=(g=m.scale)==null?void 0:g.createInterpolant();C||o.set(i.position.x,i.position.y,i.position.z),E||a.set(i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w),T||l.set(i.scale.x,i.scale.y,i.scale.z);for(let w=0;w<y.length;w++){const M=y[w];if(C){const k=C.evaluate(M);o.set(k[0],k[1],k[2])}if(E){const k=E.evaluate(M);a.set(k[0],k[1],k[2],k[3])}if(T){const k=T.evaluate(M);l.set(k[0],k[1],k[2])}r.compose(o,a,l);let P=`${(_+M)*m.frameRate}: ${rU(r)},`;Yd&&(P="#"+w+" "+P),e.appendLine(P)}}e.indent--,e.appendLine("}")}}class JY{constructor(){h(this,"_context")}get context(){return this._context??kt.Current}get isStateMachineBehaviour(){return!0}}class w0{constructor(e,t,i,s){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=i,this._speed=s}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 cU(n,e){return{name:"",isLooping:!1,guid:(e==null?void 0:e.generateUUID())??Hs.generateUUID(),index:-1,clip:new wo(n,1,[])}}var Dc=(n=>(n[n.If=1]="If",n[n.IfNot=2]="IfNot",n[n.Greater=3]="Greater",n[n.Less=4]="Less",n[n.Equals=6]="Equals",n[n.NotEqual=7]="NotEqual",n))(Dc||{}),DI=(n=>(n[n.Float=1]="Float",n[n.Int=3]="Int",n[n.Bool=4]="Bool",n[n.Trigger=9]="Trigger",n))(DI||{});const aa=oe("debuganimatorcontroller"),xy=oe("debugrootmotion");class wu{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,aa&&console.log(this)}play(e,t=-1,i=Number.NEGATIVE_INFINITY,s=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}const o=this.model.layers[t].stateMachine;for(const a of o.states)if(a.name===e||a.hash===e){aa&&console.log("transition to ",a),this.transitionTo(a,s,i);return}console.warn("Could not find "+e+" to play")}reset(){this.setStartTransition()}setBool(e,t){var s,r;const i=typeof e=="string"?"name":"hash";return(r=(s=this.model)==null?void 0:s.parameters)==null?void 0:r.filter(o=>o[i]===e).forEach(o=>o.value=t)}getBool(e){var i,s,r;const t=typeof e=="string"?"name":"hash";return((r=(s=(i=this.model)==null?void 0:i.parameters)==null?void 0:s.find(o=>o[t]===e))==null?void 0:r.value)??!1}setFloat(e,t){var s,r;const i=typeof e=="string"?"name":"hash";return(r=(s=this.model)==null?void 0:s.parameters)==null?void 0:r.filter(o=>o[i]===e).forEach(o=>o.value=t)}getFloat(e){var i,s,r;const t=typeof e=="string"?"name":"hash";return((r=(s=(i=this.model)==null?void 0:i.parameters)==null?void 0:s.find(o=>o[t]===e))==null?void 0:r.value)??0}setInteger(e,t){var s,r;const i=typeof e=="string"?"name":"hash";return(r=(s=this.model)==null?void 0:s.parameters)==null?void 0:r.filter(o=>o[i]===e).forEach(o=>o.value=t)}getInteger(e){var i,s,r;const t=typeof e=="string"?"name":"hash";return((r=(s=(i=this.model)==null?void 0:i.parameters)==null?void 0:s.find(o=>o[t]===e))==null?void 0:r.value)??0}setTrigger(e){var i,s;aa&&console.log("SET TRIGGER",e);const t=typeof e=="string"?"name":"hash";return(s=(i=this.model)==null?void 0:i.parameters)==null?void 0:s.filter(r=>r[t]===e).forEach(r=>r.value=!0)}resetTrigger(e){var i,s;const t=typeof e=="string"?"name":"hash";return(s=(i=this.model)==null?void 0:i.parameters)==null?void 0:s.filter(r=>r[t]===e).forEach(r=>r.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 i of t.stateMachine.states)if(i.name===e)return i}return null}get context(){var e;return(e=this.animator)==null?void 0:e.context}bind(e){this.animator=e,this._mixer=new h_(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=Fb(this.model,(i,s,r)=>r==null?!0:!(r.type==="Object3D"||r.isObject3D===!0||RO(r)||r.tracks!==void 0));return console.assert(e!==this.model),new wu(e)}update(){var t,i;if(!this.animator||(this.evaluateTransitions(),this.updateActiveStates(),!this._activeState))return;const e=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((t=this.rootMotionHandler)==null||t.onBeforeUpdate()),this._mixer.update(e),this.animator.applyRootMotion&&((i=this.rootMotionHandler)==null||i.onAfterUpdate())}updateActiveStates(){for(let e=0;e<this._activeStates.length;e++){const t=this._activeStates[e],i=t.motion;if(!i.action)this._activeStates.splice(e,1),e--;else{const s=i.action;s.getEffectiveWeight()<=0&&!s.isRunning()&&(aa&&console.debug("REMOVE",t.name,s.getEffectiveWeight(),s.isRunning(),s.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(const e of this.model.layers){const t=e.stateMachine;t.defaultState===void 0&&(aa&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",e),t.defaultState=0);const i=t.states[t.defaultState];this.transitionTo(i,0,this.normalizedStartOffset)}}evaluateTransitions(){var r;let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}const t=this._activeState,i=t.motion.action;for(const o of t.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==null?void 0:c.type)===DI.Trigger&&(c.value=!1)}if(i){const l=t.motion.clip.duration,c=l<=0?1:Math.abs(i.time/l);let u=!1;if(o.hasExitTime?i.timeScale>0?u=c>=o.exitTime:i.timeScale<0&&(u=1-c>=o.exitTime):u=!0,u){i.clampWhenFinished=!0,aa&&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 s=!1;if(t.motion.isLooping&&i&&(i.time>=i.getClip().duration?(s=!0,i.reset(),i.time=0,i.play()):i.time<=0&&i.timeScale<0&&(s=!0,i.reset(),i.time=i.getClip().duration,i.play())),!s&&t&&!e&&i&&this.animator&&t.behaviours){const o=i==null?void 0:i.getClip().duration,a=i.time/o,l=new w0(this._activeState,a,o,this._speed);for(const c of t.behaviours)c.instance&&((r=c.instance.onStateUpdate)==null||r.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&&(aa&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+t),e=0)),e=this.model.layers[t].stateMachine.states[e]),e}transitionTo(e,t,i){var c,u,d,f,p,g,m,A;if(!this.animator)return;const s=0;if(e=this.getState(e,s),!(e!=null&&e.motion)||!e.motion.clip)return;const r=this._activeState===e;if(r){const v=e.motion;!v.action_loopback&&v.clip&&(this._mixer.uncacheAction(v.clip,this.animator.gameObject),v.action_loopback=this.createAction(v.clip))}if((c=this._activeState)!=null&&c.behaviours&&this._activeState.motion.action){const v=(u=this._activeState)==null?void 0:u.motion.clip.duration,b=this._activeState.motion.action.time/v,y=new w0(this._activeState,b,v,this._speed);for(const _ of this._activeState.behaviours)(f=(d=_.instance)==null?void 0:d.onStateExit)==null||f.call(_.instance,this.animator,y,s)}const o=(p=this._activeState)==null?void 0:p.motion.action;o&&o.fadeOut(t),r&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=o);const a=this._activeState;this._activeState=e;const l=(g=e.motion)==null?void 0:g.action;if(l){i=Math.max(0,Math.min(1,i)),l.isRunning()&&l.stop(),l.reset(),l.timeScale=this._speed,e.speed!==void 0&&(l.timeScale*=e.speed),l.enabled=!0;const v=e.motion.clip.duration;if(l.time=i*v,l.timeScale<0&&(l.time=v-l.time),l.clampWhenFinished=!0,l.setLoop(mm,0),t>0?l.fadeIn(t):l.setEffectiveWeight(1),l.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(l),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){const b=new w0(e,i,v,this._speed);for(const y of this._activeState.behaviours)(A=(m=y.instance)==null?void 0:m.onStateEnter)==null||A.call(y.instance,this.animator,b,s)}}else aa&&(e.__warned_no_motion||(e.__warned_no_motion=!0,console.warn("No action",e.motion,this)));aa&&console.log("TRANSITION FROM "+(a==null?void 0:a.name)+" TO "+e.name,t,o,l,l==null?void 0:l.getEffectiveTimeScale(),l==null?void 0:l.getEffectiveWeight(),l==null?void 0:l.isRunning(),l==null?void 0:l.isScheduled(),l==null?void 0:l.paused)}createAction(e){var i,s;if(this._mixer.existingAction(e)&&this._mixer.uncacheAction(e,(i=this.animator)==null?void 0:i.gameObject),(s=this.animator)!=null&&s.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new ZY(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(i=>i.name===e.parameter);if(!t)return!1;switch(e.mode){case Dc.If:return t.value===!0;case Dc.IfNot:return t.value===!1;case Dc.Greater:return t.value>e.threshold;case Dc.Less:return t.value<e.threshold;case Dc.Equals:return t.value===e.threshold;case Dc.NotEqual:return t.value!==e.threshold}return!1}createActions(e){var t,i;for(const s of this.model.layers){const r=s.stateMachine;for(let o=0;o<r.states.length;o++){const a=r.states[o];a.transitions||(a.transitions=[]);for(const l of a.transitions)l.conditions||(l.conditions=[]);if(a.motion||(a.motion=cU(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==null?void 0:l.clip}if(!a.motion.clip){const l=new wo(void 0,void 0,[]);a.motion.clip=l}if((i=a.motion)!=null&&i.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=G.get(l.typeName),u=new c;u.isStateMachineBehaviour&&(u._context=this.context??void 0,_u(u,l.properties),l.instance=u),aa&&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 i=0;i<t.states.length;i++){const s=t.states[i];s!=null&&s.motion&&(s.motion.action&&(yield s.motion.action),s.motion.action_loopback&&(yield s.motion.action_loopback))}}}}class OB{constructor(e,t){h(this,"track");h(this,"createdInterpolant");h(this,"originalEvaluate");h(this,"customEvaluate");this.track=e;const i=e,s=i.createInterpolant.bind(e);i.createInterpolant=()=>(i.createInterpolant=s,this.createdInterpolant=s(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=r=>{if(!this.originalEvaluate)return;const o=this.originalEvaluate(r);return t(r,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 An=class{constructor(e,t,i,s,r){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 xe);if(this.context=e,this.root=t,this.clip=i,An.firstKeyframeRotation[i.uuid]||(An.firstKeyframeRotation[i.uuid]=new xe),r){const o=r.values;An.firstKeyframeRotation[i.uuid].set(o[0],o[1],o[2],o[3])}An.spaceRotation[i.uuid]||(An.spaceRotation[i.uuid]=new xe),An.effectiveSpaceRotation[i.uuid]||(An.effectiveSpaceRotation[i.uuid]=new xe),An.clipOffsetRotation[i.uuid]=new xe,r&&An.clipOffsetRotation[i.uuid].set(r.values[0],r.values[1],r.values[2],r.values[3]).invert(),this.handlePosition(i,s),this.handleRotation(i,r)}set action(e){this._action=e}get action(){return this._action}onStart(e){if(e.getClip()!==this.clip)return;const t=An.lastObjRotation[this.root.uuid];if(An.spaceRotation[this.clip.uuid].copy(t),xy){const i=new xn().setFromQuaternion(t);console.log("START",this.clip.name,$e.toDegrees(i.y))}}getClipRotationOffset(){return An.clipOffsetRotation[this.clip.uuid]}handlePosition(e,t){if(t){const i=this.root;xy&&i.add(new Xf),An.lastObjPosition[i.uuid]||(An.lastObjPosition[i.uuid]=new S);const s=new S,r=new S;let o=0;this.positionWrapper=new OB(t,(a,l)=>{const c=this.action.getEffectiveWeight();if(xy&&i.position.length()>8&&i.position.set(0,i.position.y,0),a>o){s.set(l[0],l[1],l[2]),s.sub(r),s.multiplyScalar(c),s.applyQuaternion(this.getClipRotationOffset());const u=this.clip.uuid;s.applyQuaternion(An.spaceRotation[u]),this.positionChange.copy(s)}return r.fromArray(l),o=a,l[0]=0,l[1]=0,l[2]=0,l})}}handleRotation(e,t){if(t){if(xy){const a=t.values,l=new xn().setFromQuaternion(new xe(a[0],a[1],a[2],a[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",$e.toDegrees(l.y));const c=t.values.length-4,u=new xe().set(a[c],a[c+1],a[c+2],a[c+3]),d=new xn().setFromQuaternion(u);console.log(e.name,t.name,"LAST ROTATION IN TRACK",$e.toDegrees(d.y))}const i=this.root;An.lastObjRotation[i.uuid]||(An.lastObjRotation[i.uuid]=new xe);let s=0;const r=new xe,o=new xe;this.rotationWrapper=new OB(t,(a,l)=>(a>s&&(o.set(l[0],l[1],l[2],l[3]),r.invert(),o.multiply(r),this.rotationChange.copy(o)),r.fromArray(l),s=a,l[0]=0,l[1]=0,l[2]=0,l[3]=1,l))}}onBeforeUpdate(){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(){if(!this.action)return;const e=this.action.getEffectiveWeight();this.positionChange.multiplyScalar(e),this.rotationChange.slerp(An.identityQuaternion,1-e)}};let zo=An;h(zo,"lastObjPosition",{}),h(zo,"lastObjRotation",{}),h(zo,"firstKeyframeRotation",{}),h(zo,"spaceRotation",{}),h(zo,"effectiveSpaceRotation",{}),h(zo,"clipOffsetRotation",{}),h(zo,"identityQuaternion",new xe);class ZY{constructor(e){h(this,"controller");h(this,"handler",[]);h(this,"root");h(this,"summedPosition",new S);h(this,"summedRotation",new xe);this.controller=e}createClip(e,t,i){this.root=t,t&&"name"in t&&t.name;const s=this.findRootTrack(i,".position"),r=this.findRootTrack(i,".quaternion"),o=new zo(this.controller.context,t,i,s,r);this.handler.push(o);const a=e.clipAction(i);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),zo.lastObjRotation[this.root.uuid].copy(this.root.quaternion)}findRootTrack(e,t){const i=e.tracks;if(!i)return null;for(const s of i)if(s.name.endsWith(t))return s;return null}}var $Y=Object.defineProperty,eK=Object.getOwnPropertyDescriptor,z_=(n,e,t,i)=>{for(var s=i>1?void 0:i?eK(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&$Y(e,t,s),s};const Zw=oe("debuganimator");class Ys extends Ce{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(t){this._animatorController&&this._animatorController.model===t||(t?t instanceof wu?this._animatorController=t:(Zw&&console.log("Assign animator controller",t,this),this._animatorController=new wu(t)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}Play(t,i=-1,s=Number.NEGATIVE_INFINITY,r=0){this.play(t,i,s,r)}play(t,i=-1,s=Number.NEGATIVE_INFINITY,r=0){var o;(o=this.runtimeAnimatorController)==null||o.play(t,i,s,r)}Reset(){this.reset()}reset(){var t;(t=this._animatorController)==null||t.reset()}SetBool(t,i){this.setBool(t,i)}setBool(t,i){var s;(s=this.runtimeAnimatorController)==null||s.setBool(t,i)}GetBool(t){return this.getBool(t)}getBool(t){var i;return((i=this.runtimeAnimatorController)==null?void 0:i.getBool(t))??!1}SetFloat(t,i){this.setFloat(t,i)}setFloat(t,i){var s;(s=this.runtimeAnimatorController)==null||s.setFloat(t,i)}GetFloat(t){return this.getFloat(t)}getFloat(t){var i;return((i=this.runtimeAnimatorController)==null?void 0:i.getFloat(t))??-1}SetInteger(t,i){this.setInteger(t,i)}setInteger(t,i){var s;(s=this.runtimeAnimatorController)==null||s.setInteger(t,i)}GetInteger(t){return this.getInteger(t)}getInteger(t){var i;return((i=this.runtimeAnimatorController)==null?void 0:i.getInteger(t))??-1}SetTrigger(t){this.setTrigger(t)}setTrigger(t){var i;Zw&&console.log("SetTrigger",t),(i=this.runtimeAnimatorController)==null||i.setTrigger(t)}ResetTrigger(t){this.resetTrigger(t)}resetTrigger(t){var i;(i=this.runtimeAnimatorController)==null||i.resetTrigger(t)}IsInTransition(){return this.isInTransition()}isInTransition(){var t;return((t=this.runtimeAnimatorController)==null?void 0:t.isInTransition())??!1}SetSpeed(t){return this.setSpeed(t)}setSpeed(t){var i;t!==this.speed&&(this.speed=t,(i=this._animatorController)==null||i.setSpeed(t))}set minMaxSpeed(t){this.speed=$e.lerp(t.x,t.y,Math.random())}set minMaxOffsetNormalized(t){this.normalizedStartOffset=$e.lerp(t.x,t.y,Math.random()),this.runtimeAnimatorController&&(this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset)}awake(){if(Zw&&console.log("ANIMATOR",this.name,this),!!this.gameObject&&this.runtimeAnimatorController){const t=this.runtimeAnimatorController.clone();t?(console.assert(this.runtimeAnimatorController!==t),this.runtimeAnimatorController=t,console.assert(this.runtimeAnimatorController===t),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 t;this.keepAnimatorControllerStateOnDisable||(t=this._animatorController)==null||t.reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}}z_([x()],Ys.prototype,"applyRootMotion",2);z_([x()],Ys.prototype,"hasRootMotion",2);z_([x()],Ys.prototype,"keepAnimatorControllerStateOnDisable",2);z_([x()],Ys.prototype,"runtimeAnimatorController",1);class tK extends an{constructor(e,t=1,i=16,s=2){const r=new At,o=i+s*2,a=new Float32Array((o*3+3)*3);r.setAttribute("position",new rt(a,3));const l=new dn({color:65280}),c=new dn({color:16776960});super(r,[c,l]),this.audio=e,this.range=t,this.divisionsInnerAngle=i,this.divisionsOuterAngle=s,this.type="PositionalAudioHelper",this.update()}update(){const e=this.audio,t=this.range,i=this.divisionsInnerAngle,s=this.divisionsOuterAngle,r=Hs.degToRad(e.panner.coneInnerAngle),o=Hs.degToRad(e.panner.coneOuterAngle),a=r/2,l=o/2;let c=0,u=0,d,f;const p=this.geometry,g=p.attributes.position;p.clearGroups();function m(A,v,b,y){const _=(v-A)/b;for(g.setXYZ(c,0,0,0),u++,d=A;d<v;d+=_)f=c+u,g.setXYZ(f,Math.sin(d)*t,0,Math.cos(d)*t),g.setXYZ(f+1,Math.sin(Math.min(d+_,v))*t,0,Math.cos(Math.min(d+_,v))*t),g.setXYZ(f+2,0,0,0),u+=3;p.addGroup(c,u,y),c+=u,u=0}m(-l,-a,s,0),m(-a,a,i,1),m(a,l,s,0),g.needsUpdate=!0,r===o&&(this.material[0].visible=!1)}dispose(){this.geometry.dispose(),this.material[0].dispose(),this.material[1].dispose()}}var iK=Object.defineProperty,nK=Object.getOwnPropertyDescriptor,fh=(n,e,t,i)=>{for(var s=i>1?void 0:i?nK(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&iK(e,t,s),s};const ys=oe("debugaudio");var pg;const Vn=(pg=class extends Ce{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||Iu())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":ys&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,Vn._userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&Vn._userInteractionRegistered&&this.wasPlaying&&this.play();break}});h(this,"onApplicationMuteChanged",()=>{var e,t;this.context.application.muted?(e=this.sound)==null||e.setVolume(0):(t=this.sound)==null||t.setVolume(this.volume)});h(this,"lerp",(e,t,i)=>e*(1-i)+t*i);h(this,"_lastContextTime",0);h(this,"_hasEnded",!0);h(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return Vn._didCallBeginWaitForUserInteraction||(Vn._didCallBeginWaitForUserInteraction=!0,Vn._beginWaitForUserInteraction()),Vn._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),Vn._didCallBeginWaitForUserInteraction||(Vn._didCallBeginWaitForUserInteraction=!0,Vn._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);const i=(()=>{if(i!=null&&!Vn._userInteractionRegistered){Vn._userInteractionRegistered=!0,ys&&console.log("🔊 registered interaction, can play audio now"),document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i);for(const s of this.callbacks)s();this.callbacks.length=0}}).bind(this);document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(ys&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}get Sound(){if(!this.sound&&Vn._userInteractionRegistered){const e=Z.getComponent(this.context.mainCamera,Ff)??Z.findObjectOfType(Ff,this.context);e!=null&&e.listener&&(this.sound=new uO(e.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}awake(){this.audioLoader=new X0,this.playOnAwake&&(this.shouldPlay=!0)}onEnable(){Vn._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Vn._beginWaitForUserInteraction(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.loadAndPlay(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(ab.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(ab.MuteChanged,this.onApplicationMuteChanged),this.stop()}onLoaded(e){ys&&console.log("audio buffer loaded"),Vn.registerWaitForAllowAudio(()=>{ys&&console.log("finished loading",e);const t=this.Sound;if(!t){console.warn("Failed getting sound",this.name);return}t.isPlaying&&t.stop(),t.setBuffer(e),t.loop=this._loop,this.context.application.muted?t.setVolume(0):t.setVolume(this.volume),t.autoplay=this.shouldPlay,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),ys&&console.log(this.name,this.shouldPlay,Vn.userInteractionRegistered,this),this.shouldPlay&&Vn._userInteractionRegistered&&this.play()})}applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const t=this.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(ys&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break}this.spatialBlend>0?ys&&!this.helper&&(this.helper=new tK(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&(ys&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new X0),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){ys&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,ys&&console.log("load audio",this.clip),this.audioLoader.load(this.clip,this.onLoaded.bind(this),()=>{},console.error)}}play(e=void 0){var t;if(!this.audioLoader||!this.sound||e&&e!==this.clip){this.loadAndPlay(e);return}if(this.shouldPlay=!0,this._hasEnded=!1,ys&&console.log("play",(t=this.sound)==null?void 0:t.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const i=this.context.application.muted;i&&this.sound.setVolume(0),this.sound.play(i?.1:0)}}pause(){var e;ys&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=(e=this.sound)==null?void 0:e.context.currentTime,this.sound.pause())}stop(){var e;ys&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=(e=this.sound)==null?void 0:e.context.currentTime,ys&&console.log(this._lastContextTime),this.sound.stop())}get isPlaying(){var e;return((e=this.sound)==null?void 0:e.isPlaying)??!1}set isPlaying(e){}get time(){var e,t;return(e=this.sound)!=null&&e.source?((t=this.sound.source)==null?void 0:t.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;const t=this.isPlaying;this.stop(),this.sound.offset=e,t&&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,ys&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},h(pg,"_didCallBeginWaitForUserInteraction",!1),h(pg,"callbacks",[]),h(pg,"_userInteractionRegistered",!1),pg);let wn=Vn;fh([x(URL)],wn.prototype,"clip",2);fh([x()],wn.prototype,"playOnAwake",2);fh([x()],wn.prototype,"loop",1);fh([x()],wn.prototype,"spatialBlend",1);fh([x()],wn.prototype,"minDistance",1);fh([x()],wn.prototype,"maxDistance",1);fh([x()],wn.prototype,"volume",1);fh([x()],wn.prototype,"rollOffMode",2);var sK=Object.defineProperty,rK=Object.getOwnPropertyDescriptor,oK=(n,e,t,i)=>{for(var s=i>1?void 0:i?rK(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&sK(e,t,s),s};class UA extends Ce{constructor(){super(...arguments);h(this,"constraintActive",!0);h(this,"locked",!1);h(this,"sources",[])}}oK([x(Ie)],UA.prototype,"sources",2);const LB={type:"change"},$w={type:"start"},FB={type:"end"};let aK=class extends Nn{constructor(e,t){super(),this.object=e,this.domElement=t,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:zh.ROTATE,MIDDLE:zh.DOLLY,RIGHT:zh.PAN},this.touches={ONE:Gh.ROTATE,TWO:Gh.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 a.phi},this.getAzimuthalAngle=function(){return a.theta},this.getDistance=function(){return this.object.position.distanceTo(this.target)},this.listenToKeyEvents=function(O){O.addEventListener("keydown",U),this._domElementKeyEvents=O},this.saveState=function(){i.target0.copy(i.target),i.position0.copy(i.object.position),i.zoom0=i.object.zoom},this.reset=function(){i.target.copy(i.target0),i.object.position.copy(i.position0),i.object.zoom=i.zoom0,i.object.updateProjectionMatrix(),i.dispatchEvent(LB),i.update(),r=s.NONE},this.update=function(){const O=new S,ve=new xe().setFromUnitVectors(e.up,new S(0,1,0)),Ke=ve.clone().invert(),ze=new S,We=new xe,Ue=2*Math.PI;return function(){const Ut=i.object.getWorldPosition(e.position);O.copy(Ut).sub(i.target),O.applyQuaternion(ve),a.setFromVector3(O),i.autoRotate&&r===s.NONE&&P(w()),i.enableDamping?(a.theta+=l.theta*i.dampingFactor,a.phi+=l.phi*i.dampingFactor):(a.theta+=l.theta,a.phi+=l.phi);let Tt=i.minAzimuthAngle,j=i.maxAzimuthAngle;return isFinite(Tt)&&isFinite(j)&&(Tt<-Math.PI?Tt+=Ue:Tt>Math.PI&&(Tt-=Ue),j<-Math.PI?j+=Ue:j>Math.PI&&(j-=Ue),Tt<=j?a.theta=Math.max(Tt,Math.min(j,a.theta)):a.theta=a.theta>(Tt+j)/2?Math.max(Tt,a.theta):Math.min(j,a.theta)),a.phi=Math.max(i.minPolarAngle,Math.min(i.maxPolarAngle,a.phi)),a.makeSafe(),u=Hs.lerp(u,c,i.enableDamping?i.dampingFactor:1),a.radius*=u,a.radius=Math.max(i.minDistance,Math.min(i.maxDistance,a.radius)),i.enableDamping===!0?i.target.addScaledVector(d,i.dampingFactor):i.target.add(d),O.setFromSpherical(a),O.applyQuaternion(Ke),Ut.copy(i.target).add(O),i.object.parent?i.object.parent.worldToLocal(Ut):i.object.position.copy(Ut),i.object.lookAt(i.target),i.enableDamping===!0?(l.theta*=1-i.dampingFactor,l.phi*=1-i.dampingFactor,d.multiplyScalar(1-i.dampingFactor)):(l.set(0,0,0),d.set(0,0,0)),c=1,f||ze.distanceToSquared(i.object.position)>o||8*(1-We.dot(i.object.quaternion))>o?(i.dispatchEvent(LB),ze.copy(i.object.position),We.copy(i.object.quaternion),f=!1,!0):!1}}(),this.dispose=function(){i.domElement.removeEventListener("contextmenu",Ee),i.domElement.removeEventListener("pointerdown",Ze),i.domElement.removeEventListener("pointercancel",ht),i.domElement.removeEventListener("wheel",Ft),i.domElement.removeEventListener("pointermove",je),i.domElement.removeEventListener("pointerup",ft),i._domElementKeyEvents!==null&&i._domElementKeyEvents.removeEventListener("keydown",U)};const i=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 o=1e-6,a=new wS,l=new wS;let c=1,u=1;const d=new S;let f=!1;const p=new V,g=new V,m=new V,A=new V,v=new V,b=new V,y=new V,_=new V,C=new V,E=[],T={};function w(){return 2*Math.PI/60/60*i.autoRotateSpeed}function M(){return Math.pow(.95,i.zoomSpeed)}function P(O){l.theta-=O}function k(O){l.phi-=O}const Q=function(){const O=new S;return function(Ke,ze){O.setFromMatrixColumn(ze,0),O.multiplyScalar(-Ke),d.add(O)}}(),z=function(){const O=new S;return function(Ke,ze){i.screenSpacePanning===!0?O.setFromMatrixColumn(ze,1):(O.setFromMatrixColumn(ze,0),O.crossVectors(i.object.up,O)),O.multiplyScalar(Ke),d.add(O)}}(),L=function(){const O=new S,ve=new S;return function(ze,We){const Ue=i.domElement;if(i.object.isPerspectiveCamera){i.object.getWorldPosition(ve),O.copy(ve).sub(i.target);let Rt=O.length();Rt*=Math.tan(i.object.fov/2*Math.PI/180),Q(2*ze*Rt/Ue.clientHeight,i.object.matrixWorld),z(2*We*Rt/Ue.clientHeight,i.object.matrixWorld)}else i.object.isOrthographicCamera?(Q(ze*(i.object.right-i.object.left)/i.object.zoom/Ue.clientWidth,i.object.matrixWorld),z(We*(i.object.top-i.object.bottom)/i.object.zoom/Ue.clientHeight,i.object.matrixWorld)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),i.enablePan=!1)}}();function H(O){i.object.isPerspectiveCamera?c/=O:i.object.isOrthographicCamera?(i.object.zoom=Math.max(i.minZoom,Math.min(i.maxZoom,i.object.zoom*O)),i.object.updateProjectionMatrix(),f=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),i.enableZoom=!1)}function $(O){i.object.isPerspectiveCamera?c*=O:i.object.isOrthographicCamera?(i.object.zoom=Math.max(i.minZoom,Math.min(i.maxZoom,i.object.zoom/O)),i.object.updateProjectionMatrix(),f=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),i.enableZoom=!1)}function J(O){p.set(O.clientX,O.clientY)}function K(O){y.set(O.clientX,O.clientY)}function ue(O){A.set(O.clientX,O.clientY)}function he(O){g.set(O.clientX,O.clientY),m.subVectors(g,p).multiplyScalar(i.rotateSpeed);const ve=i.domElement;P(2*Math.PI*m.x/ve.clientHeight),k(2*Math.PI*m.y/ve.clientHeight),p.copy(g),i.update()}function Re(O){_.set(O.clientX,O.clientY),C.subVectors(_,y),C.y>0?H(M()):C.y<0&&$(M()),y.copy(_),i.update()}function ge(O){v.set(O.clientX,O.clientY),b.subVectors(v,A).multiplyScalar(i.panSpeed),L(b.x,b.y),A.copy(v),i.update()}function ie(O){O.deltaY<0?$(M()):O.deltaY>0&&H(M()),i.update()}function le(O){let ve=!1;switch(O.code){case i.keys.UP:O.ctrlKey||O.metaKey||O.shiftKey?k(2*Math.PI*i.rotateSpeed/i.domElement.clientHeight):L(0,i.keyPanSpeed),ve=!0;break;case i.keys.BOTTOM:O.ctrlKey||O.metaKey||O.shiftKey?k(-2*Math.PI*i.rotateSpeed/i.domElement.clientHeight):L(0,-i.keyPanSpeed),ve=!0;break;case i.keys.LEFT:O.ctrlKey||O.metaKey||O.shiftKey?P(2*Math.PI*i.rotateSpeed/i.domElement.clientHeight):L(i.keyPanSpeed,0),ve=!0;break;case i.keys.RIGHT:O.ctrlKey||O.metaKey||O.shiftKey?P(-2*Math.PI*i.rotateSpeed/i.domElement.clientHeight):L(-i.keyPanSpeed,0),ve=!0;break}ve&&(O.preventDefault(),i.update())}function we(){if(E.length===1)p.set(E[0].pageX,E[0].pageY);else{const O=.5*(E[0].pageX+E[1].pageX),ve=.5*(E[0].pageY+E[1].pageY);p.set(O,ve)}}function W(){if(E.length===1)A.set(E[0].pageX,E[0].pageY);else{const O=.5*(E[0].pageX+E[1].pageX),ve=.5*(E[0].pageY+E[1].pageY);A.set(O,ve)}}function Fe(){const O=E[0].pageX-E[1].pageX,ve=E[0].pageY-E[1].pageY,Ke=Math.sqrt(O*O+ve*ve);y.set(0,Ke)}function Be(){i.enableZoom&&Fe(),i.enablePan&&W()}function qe(){i.enableZoom&&Fe(),i.enableRotate&&we()}function be(O){if(E.length==1)g.set(O.pageX,O.pageY);else{const Ke=He(O),ze=.5*(O.pageX+Ke.x),We=.5*(O.pageY+Ke.y);g.set(ze,We)}m.subVectors(g,p).multiplyScalar(i.rotateSpeed);const ve=i.domElement;P(2*Math.PI*m.x/ve.clientHeight),k(2*Math.PI*m.y/ve.clientHeight),p.copy(g)}function lt(O){if(E.length===1)v.set(O.pageX,O.pageY);else{const ve=He(O),Ke=.5*(O.pageX+ve.x),ze=.5*(O.pageY+ve.y);v.set(Ke,ze)}b.subVectors(v,A).multiplyScalar(i.panSpeed),L(b.x,b.y),A.copy(v)}function pe(O){const ve=He(O),Ke=O.pageX-ve.x,ze=O.pageY-ve.y,We=Math.sqrt(Ke*Ke+ze*ze);_.set(0,We),C.set(0,Math.pow(_.y/y.y,i.zoomSpeed)),H(C.y),y.copy(_)}function fe(O){i.enableZoom&&pe(O),i.enablePan&<(O)}function ke(O){i.enableZoom&&pe(O),i.enableRotate&&be(O)}function Ze(O){i.enabled!==!1&&(E.length===0&&(i.domElement.addEventListener("pointermove",je),i.domElement.addEventListener("pointerup",ft)),De(O),O.pointerType==="touch"?D(O):st(O))}function je(O){i.enabled!==!1&&(O.pointerType==="touch"?ce(O):Wt(O))}function ft(O){Ve(O),E.length===0&&(i.domElement.removeEventListener("pointermove",je),i.domElement.removeEventListener("pointerup",ft)),i.dispatchEvent(FB),r=s.NONE}function ht(O){Ve(O)}function st(O){let ve;switch(O.button){case 0:ve=i.mouseButtons.LEFT;break;case 1:ve=i.mouseButtons.MIDDLE;break;case 2:ve=i.mouseButtons.RIGHT;break;default:ve=-1}switch(ve){case zh.DOLLY:if(i.enableZoom===!1)return;K(O),r=s.DOLLY;break;case zh.ROTATE:if(O.ctrlKey||O.metaKey||O.shiftKey){if(i.enablePan===!1)return;ue(O),r=s.PAN}else{if(i.enableRotate===!1)return;J(O),r=s.ROTATE}break;case zh.PAN:if(O.ctrlKey||O.metaKey||O.shiftKey){if(i.enableRotate===!1)return;J(O),r=s.ROTATE}else{if(i.enablePan===!1)return;ue(O),r=s.PAN}break;default:r=s.NONE}r!==s.NONE&&i.dispatchEvent($w)}function Wt(O){switch(r){case s.ROTATE:if(i.enableRotate===!1)return;he(O);break;case s.DOLLY:if(i.enableZoom===!1)return;Re(O);break;case s.PAN:if(i.enablePan===!1)return;ge(O);break}}function Ft(O){i.enabled===!1||i.enableZoom===!1||r!==s.NONE||(O.preventDefault(),i.dispatchEvent($w),ie(O),i.dispatchEvent(FB))}function U(O){i.enabled===!1||i.enablePan===!1||le(O)}function D(O){switch(ct(O),E.length){case 1:switch(i.touches.ONE){case Gh.ROTATE:if(i.enableRotate===!1)return;we(),r=s.TOUCH_ROTATE;break;case Gh.PAN:if(i.enablePan===!1)return;W(),r=s.TOUCH_PAN;break;default:r=s.NONE}break;case 2:switch(i.touches.TWO){case Gh.DOLLY_PAN:if(i.enableZoom===!1&&i.enablePan===!1)return;Be(),r=s.TOUCH_DOLLY_PAN;break;case Gh.DOLLY_ROTATE:if(i.enableZoom===!1&&i.enableRotate===!1)return;qe(),r=s.TOUCH_DOLLY_ROTATE;break;default:r=s.NONE}break;default:r=s.NONE}r!==s.NONE&&i.dispatchEvent($w)}function ce(O){switch(ct(O),r){case s.TOUCH_ROTATE:if(i.enableRotate===!1)return;be(O),i.update();break;case s.TOUCH_PAN:if(i.enablePan===!1)return;lt(O),i.update();break;case s.TOUCH_DOLLY_PAN:if(i.enableZoom===!1&&i.enablePan===!1)return;fe(O),i.update();break;case s.TOUCH_DOLLY_ROTATE:if(i.enableZoom===!1&&i.enableRotate===!1)return;ke(O),i.update();break;default:r=s.NONE}}function Ee(O){i.enabled!==!1&&O.preventDefault()}function De(O){E.push(O)}function Ve(O){delete T[O.pointerId];for(let ve=0;ve<E.length;ve++)if(E[ve].pointerId==O.pointerId){E.splice(ve,1);return}}function ct(O){let ve=T[O.pointerId];ve===void 0&&(ve=new V,T[O.pointerId]=ve),ve.set(O.pageX,O.pageY)}function He(O){const ve=O.pointerId===E[0].pointerId?E[1]:E[0];return T[ve.pointerId]}i.domElement.addEventListener("contextmenu",Ee),i.domElement.addEventListener("pointerdown",Ze),i.domElement.addEventListener("pointercancel",ht),i.domElement.addEventListener("wheel",Ft,{passive:!1}),this.update()}};class lK{static createButton(e,t={},i){const s=document.createElement("button");let r=!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(){p.end()}),u.appendChild(d);var f=document.createElementNS("http://www.w3.org/2000/svg","path");f.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),f.setAttribute("stroke","#fff"),f.setAttribute("stroke-width",2),d.appendChild(f),t.optionalFeatures.push("dom-overlay"),t.domOverlay={root:u},r=!0}let p=null,g=null;async function m(v){var _;const b=/WebXRViewer\//i.test(navigator.userAgent),y=t.domOverlay.root;b&&((_=t.domOverlay)!=null&&_.root?(g=y.parentNode,g&&(console.log("Reparent DOM Overlay to body",y,y.style.display),y.style.display="",y.style.visibility="",document.body.appendChild(y))):console.warn("WebXRViewer: No DOM Overlay found")),v.addEventListener("end",A),await e.xr.setSession(v),s.textContent="STOP AR",r&&(t.domOverlay.root.style.display=""),p=v}function A(){p.removeEventListener("end",A),s.textContent="START AR";const v=t.domOverlay.root;g&&g.appendChild(v),r&&(v.style.display="none"),p=null}s.style.display="",s.style.cursor="pointer",s.style.left="calc(50% - 50px)",s.style.width="100px",s.textContent="START AR",s.onmouseenter=function(){s.style.opacity="1.0"},s.onmouseleave=function(){s.style.opacity="0.5"},s.onclick=function(){p===null?(i==null||i.call(this,t),navigator.xr.requestSession("immersive-ar",t).then(m)):p.end()}}function a(){s.disabled=!0,s.style.display="",s.style.cursor="auto",s.style.left="calc(50% - 75px)",s.style.width="150px",s.onmouseenter=null,s.onmouseleave=null,s.onclick=null}function l(){a(),s.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 s.id="ARButton",s.style.display="none",c(s),navigator.xr.isSessionSupported("immersive-ar").then(function(u){u?o():l()}).catch(l),s;{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 kb=class{static createButton(e,t){const i=document.createElement("button");function s(){let l=null;async function c(d){d.addEventListener("end",u),await e.xr.setSession(d),i.textContent="EXIT VR",l=d}function u(){l.removeEventListener("end",u),i.textContent="ENTER VR",l=null}i.style.display="",i.style.cursor="pointer",i.style.left="calc(50% - 50px)",i.style.width="100px",i.textContent="ENTER VR",i.onmouseenter=function(){i.style.opacity="1.0"},i.onmouseleave=function(){i.style.opacity="0.5"},i.onclick=function(){if(l===null){const d={optionalFeatures:t.optionalFeatures};navigator.xr.requestSession("immersive-vr",d).then(c)}else l.end()}}function r(){i.disabled=!0,i.style.display="",i.style.cursor="auto",i.style.left="calc(50% - 75px)",i.style.width="150px",i.onmouseenter=null,i.onmouseleave=null,i.onclick=null}function o(){r(),i.textContent="VR NOT SUPPORTED"}function a(l){l.style.position="absolute",l.style.bottom="20px",l.style.padding="12px 6px",l.style.border="1px solid #fff",l.style.borderRadius="4px",l.style.background="rgba(0,0,0,0.1)",l.style.color="#fff",l.style.font="normal 13px sans-serif",l.style.textAlign="center",l.style.opacity="0.5",l.style.outline="none",l.style.zIndex="999"}if("xr"in navigator)return i.id="VRButton",i.style.display="none",a(i),navigator.xr.isSessionSupported("immersive-vr").then(function(l){l?s():o(),kb.xrSessionIsGranted&&(console.log("XR session is granted - will enter immersive web now"),i.click())}),i;{const l=document.createElement("a");return window.isSecureContext===!1?(l.href=document.location.href.replace(/^http:/,"https:"),l.innerHTML="WEBXR NEEDS HTTPS"):(l.href="https://immersiveweb.dev/",l.innerHTML="WEBXR NOT AVAILABLE"),l.style.left="calc(50% - 90px)",l.style.width="180px",l.style.textDecoration="none",a(l),l}}static registerSessionGrantedListener(){if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent))return;navigator.xr.addEventListener("sessiongranted",()=>{kb.xrSessionIsGranted=!0})}}};let Kg=kb;h(Kg,"xrSessionIsGranted",!1);Kg.registerSessionGrantedListener();const mb="noVoip",or=oe("debugvoip"),cK=oe("voip");class hK{constructor(e){h(this,"id");this.id=e}}class uK{constructor(e,t,i,s){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=i,this.peerId=s}close(){var e;or&&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 i;if(!this.stream)return;const t=(i=this.stream)==null?void 0:i.getAudioTracks();for(const s of t)s.enabled=!e}async startVoipCall(){if(!await Jl.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}or&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),or&&console.log(this.stream),this.call=this.peer.call(this.peerId,this.stream,{metadata:{userId:this.userId}}),this.call.on("error",t=>{console.error(t)}),this.call.on("stream",t=>{or&&console.log("received stream from remote again",t)}),this.peer.on("close",this.onCallClose.bind(this)),this.callErrorListener=t=>{var i;t.message.includes(this.peerId)?(console.log("Could not connect to "+this.peerId),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.close(),(i=this.stream)==null||i.getTracks().forEach(function(s){s.stop()}),this.stream=null):console.error(t)},this.peer.on("error",this.callErrorListener)}onCallClose(e){or&&console.log("call closed",e)}}class dK{constructor(e,t,i){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=i}get currentStream(){return this.stream}get currentAudio(){return this.audio}get currentAnalyzer(){return this.analyzer}openAudioStream(e){const t=e.getAudioTracks();for(const i of t)if(i.kind==="audio"&&i.readyState==="live"){this.open(i);return}console.warn("failed finding valid audio stream to begin call")}open(e){console.assert(e.kind==="audio","invalid track kind, expected audio but received "+e.kind),!this.waitingForStart&&(this.waitingForStart=!0,wn.userInteractionRegistered||or&&console.log("Incoming call, waiting for user interaction before opening audio"),wn.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){or&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);const t=new B1;this.audio=new c_(t),this.audio.setVolume(this.voip.muteInput?0:1),this.audio.setMediaStreamSource(this.stream);const i=document.createElement("audio");this.audioElement=i,i.style.display="none",document.body.appendChild(i),i.srcObject=this.stream,i.sinkId!==void 0&&navigator.mediaDevices.enumerateDevices().then(s=>{if(i){console.log(s);for(const r of s)if(r.label==="Speakerphone"){i.sinkId=r.deviceId;break}}}),or&&console.log("call is setup, you should hear something now"),this.analyzer=new dO(this.audio,32)}}))}close(){var e,t,i;this.closed=!0,(e=this.call)!=null&&e.open&&this.call.close(),(t=this.audio)==null||t.disconnect(),(i=this.stream)==null||i.getTracks().forEach(s=>{s.stop()}),this.stream=null,this.audioElement&&this.audioElement.remove()}}class Jl extends Ce{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(t){var s;if(t===this._inputMuted||(this._inputMuted=t,!this.currentIncomingCalls))return;const i=this._inputMuted?0:1;for(const r in this.currentIncomingCalls){const o=this.currentIncomingCalls[r];(s=o==null?void 0:o.currentAudio)==null||s.setVolume(i)}}get muteInput(){return this._inputMuted}set muteOutput(t){if(t!==this._outputMuted&&(this._outputMuted=t,!!this.connections))for(const i in this.connections){const s=this.connections[i];s==null||s.updateMute(t)}}get muteOutput(){return this._outputMuted}getFrequency(t){if(t===null){for(const s in this.currentIncomingCalls){const r=this.currentIncomingCalls[s];if(r&&r.currentAnalyzer)return r.currentAnalyzer.getAverageFrequency()}return null}const i=this.currentIncomingCalls[t];return i&&i.currentAnalyzer?i.currentAnalyzer.getAverageFrequency():null}awake(){if(oe(mb)){console.log("VOIP is disabled by url parameter: "+mb);return}if(this.requireParam&&!cK){console.debug("VOIP must be enabled explicitly by url parameter");return}if(fm()&&pl()){console.log("VOIP is currently not supported on Safari iOS");return}this.peer=new ib,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,this.context.connection.beginListen($i.JoinedRoom,t=>{navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}),this.context.connection.beginListen("peer-update-id",t=>{if(t.id!==this.context.connection.connectionId){const i=this.connections[t.id];if(i&&i.close(),this.peer&&this.context.connection.connectionId){const s=new uK(this,this.peer,this.context.connection.connectionId,t.peerId);this.connections[t.id]=s,s.startVoipCall()}}}),this.context.connection.beginListen($i.UserLeftRoom,t=>{const{userId:i}=t,s=this.connections[i];this.connections[i]=null,s&&s.close();const r=this.currentIncomingCalls[i];or&&console.log("UserLeftRoom",t,i,r),r&&(r.close(),this.currentIncomingCalls[i]=null)}),this.peer.on("open",this.onOpenPeerConnection.bind(this))}onEnable(){}onDisable(){console.log("TODO: close all");for(const t in this.currentIncomingCalls)try{const i=this.currentIncomingCalls[t];i==null||i.close();const s=this.connections[t];s==null||s.close()}catch(i){console.error(i)}}async onOpenPeerConnection(t){or&&console.log("Peer connection established and received id"),this.model=new hK(t),this.context.connection.send("peer-update-id",this.model,rr.OnRoomJoin),this.peer&&(this.peer.on("call",this.onReceiveCall.bind(this)),this.peer.on("connection",function(i){or&&console.log("CONNECTION",i),i.on("data",function(s){or&&console.log("Received",s)})}))}async onReceiveCall(t){const{metadata:i}=t;console.assert(i.userId);const{userId:s}=i,r=this.currentIncomingCalls[s];if(r&&r.close(),or&&console.log("received call"),await Jl.HasMicrophonePermissions()){const o=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});t.answer(o)}else t.answer(null);this.currentIncomingCalls[s]=new dK(this,this.gameObject,t),t.on("stream",o=>{var a;or&&console.log("receive caller stream, will setup audio now"),(a=this.currentIncomingCalls[s])==null||a.openAudioStream(o)}),t.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}}var fK=Object.defineProperty,pK=Object.getOwnPropertyDescriptor,hU=(n,e,t,i)=>{for(var s=i>1?void 0:i?pK(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&fK(e,t,s),s};class ph extends Ce{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 t;return(t=this.webAR)==null?void 0:t.webxr.Rig}get arScale(){return this._arScale}set arScale(t){t!==this._arScale&&(this._arScale=t,this.setScale(t))}start(){const t=Z.findObjectOfType(Ct);t&&(t.Rig.updateMatrix(),this._initalMatrix.copy(t.Rig.matrix))}onBegin(t){var i;this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose=this.gameObject.matrix.clone(),this._rigStartPose=(i=this.rig)==null?void 0:i.matrix.clone(),this._gotFirstHitTestResult=!1,t.addEventListener("selectstart",this._selectStartFn),t.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(t,i,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(t,r),!0}return!1}placeAt(t,i){this._placementPose||(this._placementPose=new Pe),this._placementPose.copy(i);const s=this.gameObject.matrixWorld.clone().invert();if(this._placementPose.premultiply(s),t){if(this.invertForward){const r=new Pe().makeRotationY(Math.PI);this._placementPose.premultiply(r)}this._rig=t,this.setScale(this.arScale)}else this._rig=null;this.gameObject.visible=!0}onEnd(t,i){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose&&this.gameObject.matrix.copy(this._startPose),t&&(t.matrixAutoUpdate=!0,this._rigStartPose&&this._rigStartPose.decompose(t.position,t.quaternion,t.scale)),cr.markDirty(this.gameObject,!0),setTimeout(()=>{this.gameObject.matrixAutoUpdate=!0,this.gameObject.visible=!0},100)}onSelectStart(){this._isTouching=!0}onSelectEnd(){this._isTouching=!1}setScale(t){const i=this._rig;!i||!this._placementPose||(this._rigStartPose||(this._rigStartPose=i.matrix.clone()),i.matrixAutoUpdate=!1,i.matrix.multiplyMatrices(new Pe().makeScale(t,t,t),this._placementPose),i.matrix.decompose(i.position,i.quaternion,i.scale),i.updateMatrixWorld(),console.log("Place",i.position))}}hU([x()],ph.prototype,"invertForward",2);hU([x()],ph.prototype,"arScale",1);const gK="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/";class mK{constructor(e,t,i,s,r=null){this.controller=t,this.handModel=e,this.bones=[],r===null&&(r=new ep,r.setPath(i||gK)),r.load(`${s}.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(u=>{const d=a.getObjectByName(u);d!==void 0?d.jointName=u:console.warn(`Couldn't find ${u} in ${s} hand mesh`),this.bones.push(d)})})}updateMesh(){const e=this.controller.joints;for(let t=0;t<this.bones.length;t++){const i=this.bones[t];if(i){const s=e[i.jointName];if(s.visible){const r=s.position;i.position.copy(r),i.quaternion.copy(s.quaternion)}}}}}const AK=.01,vK="index-finger-tip";class yK extends Ie{constructor(e,t=null){super(),this.controller=e,this.motionController=null,this.envMap=null,this.loader=t,this.mesh=null,e.addEventListener("connected",i=>{const s=i.data;s.hand&&!this.motionController&&(this.xrInputSource=s,this.motionController=new mK(this,e,this.path,s.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[vK];return e?e.position:null}intersectBoxObject(e){const t=this.getPointerPosition();if(t){const i=new Zo(t,AK),s=new Cs().setFromObject(e);return i.intersectsBox(s)}else return!1}checkButton(e){this.intersectBoxObject(e)?e.onPress():e.onClear(),e.isPressed()&&e.whilePressed()}}const bK=.05,UB=.02,wy=.01,NB=.02,zB=1,Ed=.4,_K=.002,ig=.01,Cy=.003,GB=.035,yi=16,Jr=12,eC=110,xK=new S(0,1,0),wK=new S(0,0,1),CK=.02,SK=1.5;class EK extends Ie{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",i=>{const s=i.data;s.hand&&(this.visible=!0,this.xrInputSource=s,this.pointerObject===null&&this.createPointer())})}_drawVerticesRing(e,t,i){const s=t.clone();for(let r=0;r<yi;r++){s.applyAxisAngle(wK,Math.PI*2/yi);const o=i*yi+r;e[3*o]=s.x,e[3*o+1]=s.y,e[3*o+2]=s.z}}_updatePointerVertices(e){const t=this.pointerGeometry.attributes.position.array,i=new S(_K,0,-1*(GB-e));this._drawVerticesRing(t,i,0);const s=new S(Math.sin(Math.PI*eC/180)*e,Math.cos(Math.PI*eC/180)*e,0);for(let c=0;c<Jr;c++)this._drawVerticesRing(t,s,c+1),s.applyAxisAngle(xK,Math.PI*eC/180/(Jr*-2));const r=yi*(1+Jr),o=yi*(1+Jr)+1,a=new S(0,0,-1*(GB-e));t[r*3]=a.x,t[r*3+1]=a.y,t[r*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 nt(t,3))}createPointer(){let e,t;const i=new Array(((Jr+1)*yi+2)*3).fill(0),s=[];for(this.pointerGeometry=new At,this.pointerGeometry.setAttribute("position",new nt(i,3)),this._updatePointerVertices(ig),e=0;e<Jr;e++){for(t=0;t<yi-1;t++)s.push(e*yi+t,e*yi+t+1,(e+1)*yi+t),s.push(e*yi+t+1,(e+1)*yi+t+1,(e+1)*yi+t);s.push((e+1)*yi-1,e*yi,(e+2)*yi-1),s.push(e*yi,(e+1)*yi,(e+2)*yi-1)}const r=yi*(1+Jr),o=yi*(1+Jr)+1;for(e=0;e<yi-1;e++)s.push(r,e+1,e),s.push(o,e+yi*Jr,e+yi*Jr+1);s.push(r,0,yi-1),s.push(o,yi*(Jr+1)-1,yi*Jr);const a=new vi;a.transparent=!0,a.opacity=Ed,this.pointerGeometry.setIndex(s),this.pointerMesh=new me(this.pointerGeometry,a),this.pointerMesh.position.set(0,0,-1*ig),this.pointerObject=new Ie,this.pointerObject.add(this.pointerMesh),this.raycaster=new qf;const l=new Gr(CK,10,10),c=new vi;c.transparent=!0,c.opacity=Ed,this.cursorObject=new me(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"],i=e.position.distanceTo(t.position),s=e.position.clone().add(t.position).multiplyScalar(.5);this.pointerObject.position.copy(s),this.pointerObject.quaternion.copy(this.controller.quaternion),this.pinched=i<=UB;const r=(i-wy)/(bK-wy),o=(i-wy)/(UB-wy);if(r>1)this._updatePointerVertices(ig),this.pointerMesh.position.set(0,0,-1*ig),this.pointerMesh.material.opacity=Ed;else if(r>0){const a=(ig-Cy)*r+Cy;this._updatePointerVertices(a),o<1?(this.pointerMesh.position.set(0,0,-1*a-(1-o)*NB),this.pointerMesh.material.opacity=Ed+(1-o)*(zB-Ed)):(this.pointerMesh.position.set(0,0,-1*a),this.pointerMesh.material.opacity=Ed)}else this._updatePointerVertices(Cy),this.pointerMesh.position.set(0,0,-1*Cy-NB),this.pointerMesh.material.opacity=zB;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 i=this.raycaster.intersectObjects(e,t),s=new S(0,0,-1);if(i.length>0){const o=i[0].distance;this.cursorObject.position.copy(s.multiplyScalar(o))}else this.cursorObject.position.copy(s.multiplyScalar(SK))}}setCursor(e){const t=new S(0,0,-1);this.raycaster&&!this.attached&&this.cursorObject.position.copy(t.multiplyScalar(e))}}const Ki={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 uU(n){const e=await fetch(n);if(e.ok)return e.json();throw new Error(e.statusText)}async function IK(n){if(!n)throw new Error("No basePath supplied");return await uU(`${n}/profilesList.json`)}async function MK(n,e,t=null,i=!0){if(!n)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No basePath supplied");const s=await IK(e);let r;if(n.profiles.some(l=>{const c=s[l];return c&&(r={profileId:l,profilePath:`${e}/${c.path}`,deprecated:!!c.deprecated}),!!r}),!r){if(!t)throw new Error("No matching profile name found");const l=s[t];if(!l)throw new Error(`No matching profile name found and default profile "${t}" missing.`);r={profileId:t,profilePath:`${e}/${l.path}`,deprecated:!!l.deprecated}}const o=await uU(r.profilePath);let a;if(i){let l;if(n.handedness==="any"?l=o.layouts[Object.keys(o.layouts)[0]]:l=o.layouts[n.handedness],!l)throw new Error(`No matching handedness, ${n.handedness}, in profile ${r.profileId}`);l.assetPath&&(a=r.profilePath.replace("profile.json",l.assetPath))}return{profile:o,assetPath:a}}const TK={xAxis:0,yAxis:0,button:0,state:Ki.ComponentState.DEFAULT};function PK(n=0,e=0){let t=n,i=e;if(Math.sqrt(n*n+e*e)>1){const o=Math.atan2(e,n);t=Math.cos(o),i=Math.sin(o)}return{normalizedXAxis:t*.5+.5,normalizedYAxis:i*.5+.5}}class RK{constructor(e){this.componentProperty=e.componentProperty,this.states=e.states,this.valueNodeName=e.valueNodeName,this.valueNodeProperty=e.valueNodeProperty,this.valueNodeProperty===Ki.VisualResponseProperty.TRANSFORM&&(this.minNodeName=e.minNodeName,this.maxNodeName=e.maxNodeName),this.value=0,this.updateFromComponent(TK)}updateFromComponent({xAxis:e,yAxis:t,button:i,state:s}){const{normalizedXAxis:r,normalizedYAxis:o}=PK(e,t);switch(this.componentProperty){case Ki.ComponentProperty.X_AXIS:this.value=this.states.includes(s)?r:.5;break;case Ki.ComponentProperty.Y_AXIS:this.value=this.states.includes(s)?o:.5;break;case Ki.ComponentProperty.BUTTON:this.value=this.states.includes(s)?i:0;break;case Ki.ComponentProperty.STATE:this.valueNodeProperty===Ki.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(s):this.value=this.states.includes(s)?1:0;break;default:throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}}class BK{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(i=>{const s=new RK(t.visualResponses[i]);this.visualResponses[i]=s}),this.gamepadIndices=Object.assign({},t.gamepadIndices),this.values={state:Ki.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=Ki.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=Ki.ComponentState.PRESSED:(t.touched||this.values.button>Ki.ButtonTouchThreshold)&&(this.values.state=Ki.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===Ki.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>Ki.AxisTouchThreshold&&(this.values.state=Ki.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===Ki.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>Ki.AxisTouchThreshold&&(this.values.state=Ki.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(t=>{t.updateFromComponent(this.values)})}}class DK{constructor(e,t,i){if(!e)throw new Error("No xrInputSource supplied");if(!t)throw new Error("No profile supplied");this.xrInputSource=e,this.assetUrl=i,this.id=t.profileId,this.layoutDescription=t.layouts[e.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(s=>{const r=this.layoutDescription.components[s];this.components[s]=new BK(s,r)}),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 kK="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",OK="generic-trigger";class LK extends Ie{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(i=>{const{valueNode:s,minNode:r,maxNode:o,value:a,valueNodeProperty:l}=i;s&&(l===Ki.VisualResponseProperty.VISIBILITY?s.visible=a:l===Ki.VisualResponseProperty.TRANSFORM&&(s.quaternion.slerpQuaternions(r.quaternion,o.quaternion,a),s.position.lerpVectors(r.position,o.position,a)))})}))}}function FK(n,e){Object.values(n.components).forEach(t=>{const{type:i,touchPointNodeName:s,visualResponses:r}=t;if(i===Ki.ComponentType.TOUCHPAD)if(t.touchPointNode=e.getObjectByName(s),t.touchPointNode){const o=new Gr(.001),a=new vi({color:255}),l=new me(o,a);t.touchPointNode.add(l)}else console.warn(`Could not find touch dot, ${t.touchPointNodeName}, in touchpad component ${t.id}`);Object.values(r).forEach(o=>{const{valueNodeName:a,minNodeName:l,maxNodeName:c,valueNodeProperty:u}=o;if(u===Ki.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 QB(n,e){FK(n.motionController,e),n.envMap&&e.traverse(t=>{t.isMesh&&(t.material.envMap=n.envMap,t.material.needsUpdate=!0)}),n.layers.mask!=0&&e.traverse(t=>{t.layers.mask=n.layers.mask}),n.add(e)}class UK{constructor(e=null){this.gltfLoader=e,this.path=kK,this._assetCache={},this.gltfLoader||(this.gltfLoader=new ep)}createControllerModel(e){const t=new LK;let i=null;return e.addEventListener("connected",s=>{const r=s.data;r.targetRayMode!=="tracked-pointer"||!r.gamepad||MK(r,this.path,OK).then(({profile:o,assetPath:a})=>{t.motionController=new DK(r,o,a);const l=this._assetCache[t.motionController.assetUrl];if(l)i=l.scene.clone(),QB(t,i);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,i=c.scene.clone(),QB(t,i)},null,()=>{throw new Error(`Asset ${t.motionController.assetUrl} missing or malformed.`)})}}).catch(o=>{console.warn(o)})}),e.addEventListener("disconnected",()=>{t.motionController=null,t.remove(i),i=null}),t}}const ng=oe("debugavatar");class G_{constructor(e,t,i,s){h(this,"root");h(this,"head");h(this,"leftHand");h(this,"rigthHand");var r;this.root=e,this.head=t,this.leftHand=i,this.rigthHand=s,(r=this.root)==null||r.traverse(o=>o.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class Q_{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 i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){const r=new Oa;i=Z.instantiate(Af(t,e.scene),r)}}else i=t;if(!i)return null;const s=this.findAvatar(i);return s.isValid?(ng&&console.log("[Custom Avatar] valid config",t,ng?s:""),s):(console.warn("[Custom Avatar] config isn't valid",t,ng?s:""),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(ng&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const s=await fetch("./"+t);let r=null;if(s.ok){const a=await s.blob();a&&(r=await a.arrayBuffer())}if(!r&&(r=await oI(t,t,0,"no url here go away",!0),!r))return null;const o=await Yo().parseSync(e,r,null,0);return(o==null?void 0:o.scene)??null}const i=new ep;return RA(i,e),new Promise((s,r)=>{const o=this.avatarRegistryUrl+"/"+t;i.load(o,async a=>{await Yo().createBuiltinComponents(e,o,a,null,void 0),s(a.scene)},a=>{ng&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),s(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let i=t;i.children.length==1&&(i=e.children[0]);let s=this.findAvatarPart(i,["head"]);const r=this.findAvatarPart(i,["left","hand"]),o=this.findAvatarPart(i,["right","hand"]);if(!s){s=t;const l=new S;new Cs().setFromObject(s).getSize(l);const c=Math.max(l.x,l.y,l.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+c+" meters! Should be < 0.3m"),c>.3&&s.scale.multiplyScalar(1/c*.3)}return new G_(t,s,r,o)}findAvatarPart(e,t){const i=e.name.toLowerCase();let s=!0;for(const r of t){if(!s)break;i.indexOf(r)===-1&&(s=!1)}if(s)return e;if(e.children)for(const r of e.children){const o=this.findAvatarPart(r,t);if(o)return o}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}const Ud=oe("debugflags");var vn=(n=>(n[n.Never=0]="Never",n[n.Browser=1]="Browser",n[n.AR=2]="AR",n[n.VR=4]="VR",n[n.FirstPerson=8]="FirstPerson",n[n.ThirdPerson=16]="ThirdPerson",n[n.All=4294967295]="All",n))(vn||{});const mT=class{constructor(){h(this,"Mask",17)}Has(e){return(this.Mask&e)!==0}Set(e){Ud&&console.warn("Set XR flag state to",e),this.Mask=e,as.Apply()}Enable(e){this.Mask|=e,as.Apply()}Disable(e){this.Mask&=~e,as.Apply()}Toggle(e){this.Mask^=e,as.Apply()}EnableAll(){this.Mask=-1,as.Apply()}DisableAll(){this.Mask=0,as.Apply()}};let mo=mT;h(mo,"Global",new mT);const ga=class extends Ce{constructor(){super(...arguments);h(this,"visibleIn")}static Apply(){for(const t of this.registry)t.UpdateVisible(mo.Global)}awake(){ga.registry.push(this)}onEnable(){ga.firstApply?this.UpdateVisible(mo.Global):(ga.firstApply=!0,ga.Apply())}onDestroy(){const t=ga.registry.indexOf(this);t>=0&&ga.registry.splice(t,1)}get isOn(){return this.gameObject.visible}UpdateVisible(t=null){let i;const s=t;s&&typeof s=="number"&&(console.assert(typeof s=="number","XRFlag.UpdateVisible: state must be a number",s),Ud&&console.log(s),ga.buffer.Mask=s,t=ga.buffer);const r=t;if(r?(Ud&&console.warn(this.name,"use passed in mask",r.Mask,this.visibleIn),i=r.Has(this.visibleIn)):(Ud&&console.log(this.name,"use global mask"),mo.Global.Has(this.visibleIn)),i!==void 0)if(i)Ud&&console.log(this.name,"is visible",this.gameObject.uuid),Z.setActive(this.gameObject,!0);else{if(Ud&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}};let as=ga;h(as,"registry",[]),h(as,"firstApply"),h(as,"buffer",new mo);const Pc=oe("debugavatar"),Go=class extends Ce{constructor(){super(...arguments);h(this,"connectionId");h(this,"avatar")}static getAvatar(t){return t>=0&&t<Go.instances.length?Go.instances[t]:null}static onAvatarMarkerCreated(t){return Go._onNewAvatarMarkerAdded.push(t),t}static onAvatarMarkerDestroyed(t){return Go._onAvatarMarkerDestroyed.push(t),t}awake(){Go.instances.push(this),Pc&&console.log(this);for(const t of Go._onNewAvatarMarkerAdded)t({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Go.instances.splice(Go.instances.indexOf(this),1);for(const t of Go._onAvatarMarkerDestroyed)t({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}setVisible(t){this.avatar&&("setVisible"in this.avatar?this.avatar.setVisible(t):Z.setActive(this.avatar,t))}};let Yn=Go;h(Yn,"instances",[]),h(Yn,"_onNewAvatarMarkerAdded",[]),h(Yn,"_onAvatarMarkerDestroyed",[]);const lm=class{constructor(e,t,i){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 Ie);h(this,"_handLeftTarget",new Ie);h(this,"_handRightTarget",new Ie);h(this,"_canInterpolate",!1);this.context=e,this.guid=t,this.webxr=i,this.setupCustomAvatar(this.webxr.defaultAvatar)}setVisible(e){this._isVisible=e,this.updateVisibility()}get isWebXRAvatar(){return!0}updateFlags(){if(!this.flags)return;let e=this.isLocalAvatar?vn.FirstPerson:vn.ThirdPerson;this.context.isInVR?e|=vn.VR:this.context.isInAR?e|=vn.AR:e|=vn.Browser;for(const t of this.flags)t.gameObject.visible=!0,t.UpdateVisible(e)}async setAvatarOverride(e){return this.hasAvatarOverride=e!==null,this.hasAvatarOverride&&this.lastAvatarId!==e&&(this.lastAvatarId=e,e!=null&&e.length>0)?await this.setupCustomAvatar(e):null}tryUpdate(e,t){if(e.guid===this.guid&&(this.lastAvatarId!==e.avatarId&&e.avatarId&&e.avatarId.length>0&&(this.lastAvatarId=e.avatarId,this.setupCustomAvatar(e.avatarId)),this.lastUpdate=e.time,this.head)){const i=this.webxr.IsInAR?Ba.Handheld:Ba.Headset;let s=this.head;this.context.players.setPlayerView(e.guid,s,i),cr.markDirty(this.head),this._canInterpolate=!0;const r=this.isLocalAvatar?this.head:this._headTarget;if(r.position.set(e.position.x,e.position.y,e.position.z),r.quaternion.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),r.scale.set(e.scale,e.scale,e.scale),r.scale.multiply(this.headScale),this.handLeft){const o=this.isLocalAvatar?this.handLeft:this._handLeftTarget;o.position.set(e.posLeftHand.x,e.posLeftHand.y,e.posLeftHand.z),o.quaternion.set(e.rotLeftHand._x,e.rotLeftHand._y,e.rotLeftHand._z,e.rotLeftHand._w),o.quaternion.multiply(lm.invertRotation),o.scale.set(e.scale,e.scale,e.scale),o.scale.multiply(this.handLeftScale),cr.markDirty(this.handLeft)}if(this.handRight){const o=this.isLocalAvatar?this.handRight:this._handRightTarget;o.position.set(e.posRightHand.x,e.posRightHand.y,e.posRightHand.z),o.quaternion.set(e.rotRightHand._x,e.rotRightHand._y,e.rotRightHand._z,e.rotRightHand._w),o.quaternion.multiply(lm.invertRotation),o.scale.set(e.scale,e.scale,e.scale),o.scale.multiply(this.handRightScale),cr.markDirty(this.handRight)}}}update(){if(this.isLocalAvatar||!this._canInterpolate)return;const e=this.context.time.deltaTime/.1;this.head&&(this.head.position.lerp(this._headTarget.position,e),this.head.quaternion.slerp(this._headTarget.quaternion,e),this.head.scale.lerp(this._headTarget.scale,e)),this.handLeft&&this._handLeftTarget&&(this.handLeft.position.lerp(this._handLeftTarget.position,e),this.handLeft.quaternion.slerp(this._handLeftTarget.quaternion,e),this.handLeft.scale.lerp(this._handLeftTarget.scale,e)),this.handRight&&this._handRightTarget&&(this.handRight.position.lerp(this._handRightTarget.position,e),this.handRight.quaternion.slerp(this._handRightTarget.quaternion,e),this.handRight.scale.lerp(this._handRightTarget.scale,e))}destroy(){var e,t;Pc&&console.log("Destroy avatar",this.guid),(e=this.root)==null||e.removeFromParent(),(t=this.avatarMarker)==null||t.destroy(),this.lastAvatarId=null,this.head&&Ws.Remove(this.context,this.head)}updateVisibility(){const e=this.root;e&&Z.setActive(e,this._isVisible)}async setupCustomAvatar(e){var s,r,o;if(Pc&&console.log("LOAD",e,this),!e||typeof e=="string"&&e.length<=0)return!1;this.head&&Ws.Remove(this.context,this.head);const t=e;if((t==null?void 0:t.loadAssetAsync)!==void 0){await t.loadAssetAsync();const a=t.asset;Z.setActive(a,!1),e=Z.instantiate(a),Z.setActive(e,!0)}Pc&&console.log(e);const i=await lm.loader.getOrCreateNewAvatarInstance(this.context,e);if(Pc&&console.log(i,i==null?void 0:i.isValid,this.lastAvatarId,e),i!=null&&i.isValid){if(this.root=i.root,this.root.position.set(0,0,0),this.root.quaternion.set(0,0,0,1),this.root.scale.set(1,1,1),this.avatarMarker=Z.addNewComponent(this.root,Yn),this.avatarMarker.connectionId=this.guid,this.avatarMarker.avatar=this,this.head&&this.head!==i.head&&((s=this.head)==null||s.removeFromParent()),this.head=i.head,this.headScale.copy(this.head.scale),this.head&&!this.isLocalAvatar&&Ws.Add(this.context,this.head,this.avatarMarker),i.leftHand&&((r=this.handLeft)==null||r.removeFromParent()),this.handLeft=i.leftHand??this.handLeft,this.handLeft?this.handLeftScale.copy(this.handLeft.scale):this.handLeftScale.set(1,1,1),i.rigthHand&&((o=this.handRight)==null||o.removeFromParent()),this.handRight=i.rigthHand??this.handRight,this.handRight?this.handRightScale.copy(this.handRight.scale):this.handRightScale.set(1,1,1),this.context.scene.add(this.root),this.flags==null&&(this.flags=[]),this.flags.length=0,this.flags.push(...Z.getComponentsInChildren(this.root,as)),this.flags.length<=0&&this.head){const a=Z.addNewComponent(this.head,as);a.visibleIn=vn.ThirdPerson|vn.VR,this.flags.push(a),Pc&&console.log("Added flag to head: "+a.visibleIn,this.head.name)}return Pc&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return Pc&&console.warn("build avatar failed"),!1}};let Ma=lm;h(Ma,"loader",new Q_),h(Ma,"invertRotation",new xe().setFromAxisAngle(new S(0,1,0),Math.PI));class Ws{static Add(e,t,i=null){if(t){for(const s of this.Pois)if(s.obj===t)return;this.Pois.push({obj:t,avatar:i}),this.LastChangeTime=e.time.time}}static Remove(e,t){var i;if(t){for(const s of this.Pois)if(s.obj===t){this.Pois.splice(this.Pois.indexOf(s),1),this.LastChangeTime=(e==null?void 0:e.time.time)??((i=kt.Current)==null?void 0:i.time.time);return}}}}h(Ws,"Pois",[]),h(Ws,"LastChangeTime",0);class NK{constructor(){h(this,"guid");h(this,"position",new S)}}class Om extends Ce{constructor(){super(...arguments);h(this,"target",null);h(this,"avatar",null);h(this,"_model",null);h(this,"_targetModel",new NK);h(this,"_currentTargetObject",null);h(this,"_lastUpdateTime",0);h(this,"_lookDuration",0);h(this,"_lastPoiChangedTime",0)}set controlledTarget(t){this.target=t;const i=G.get("MoveRandom");if(i&&this.target){const s=Z.getComponent(this.target,i);s&&s.destroy()}}awake(){if(this.avatar=Z.getComponentInParent(this.gameObject,Yn),this.avatar){const t=Z.getComponentInParent(this.gameObject,Yn);this._model=new w_(this.context.connection,this.guid),t!=null&&t.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",t=>{var i;this.target&&t&&t.guid===((i=this.avatar)==null?void 0:i.guid)&&hn(this.target,t.position)})}update(){var i;if((!this.context.connection.isConnected||(i=this._model)!=null&&i.hasOwnership)&&(Ws.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Ws.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const s=wt(this._currentTargetObject);hn(this.target,s),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(s))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const i=Ws.Pois;if(i.length>0){const s=i[Math.floor(Math.random()*i.length)];if(s&&s.obj){if(s.avatar&&s.avatar===this.avatar)return;this._currentTargetObject=s.obj}}}}}class up extends Ce{constructor(){super(...arguments);h(this,"canGrab",!0)}onPointerClick(t){}}class dp extends Ce{constructor(){super(...arguments);h(this,"isUsed",!0);h(this,"usedBy",null)}}var fa=(n=>(n[n.Average=0]="Average",n[n.Multiply=1]="Multiply",n[n.Minimum=2]="Minimum",n[n.Maximum=3]="Maximum",n))(fa||{}),H_=(n=>(n[n.Discrete=0]="Discrete",n[n.Continuous=1]="Continuous",n))(H_||{}),sn=(n=>(n[n.None=0]="None",n[n.FreezePositionX=2]="FreezePositionX",n[n.FreezePositionY=4]="FreezePositionY",n[n.FreezePositionZ=8]="FreezePositionZ",n[n.FreezePosition=14]="FreezePosition",n[n.FreezeRotationX=16]="FreezeRotationX",n[n.FreezeRotationY=32]="FreezeRotationY",n[n.FreezeRotationZ=64]="FreezeRotationZ",n[n.FreezeRotation=112]="FreezeRotation",n[n.FreezeAll=126]="FreezeAll",n))(sn||{}),Kd=(n=>(n[n.None=0]="None",n[n.X=2]="X",n[n.Y=4]="Y",n[n.Z=8]="Z",n[n.All=-1]="All",n))(Kd||{});const Qr=function(n,e){return function(t,i,s){zK(t,i,s,n,e)}};function zK(n,e,t,i,s){if(!(!s&&!i&&!n.onValidate)){if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",n,e,t),yn("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,qo.Error);return}if(n.__internalAwake){const r=Symbol(e),o=n.__internalAwake;n.__internalAwake=function(){this[r]===void 0&&(this[r]=this[e],Object.defineProperty(this,e,{set:function(a){var l;if(this[PS]===!0)this[r]=a;else{i==null||i.call(this,a);const c=this[r];this[r]=a,(l=this.onValidate)==null||l.call(this,e,c)}},get:function(){return s==null||s.call(this),this[r]}})),o.call(this)}}}}const GK=function(n){return function(e,t,i){const s=n.prototype,r=Object.getOwnPropertyDescriptor(s,t);if(!(r!=null&&r.value)){console.warn("Can not apply prefix: type does not have method named",t,n);return}const o=r.value,a=e[t];Object.defineProperty(s,t,{value:function(...l){const c=a==null?void 0: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 QK=Object.defineProperty,HK=Object.getOwnPropertyDescriptor,Zl=(n,e,t,i)=>{for(var s=i>1?void 0:i?HK(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&QK(e,t,s),s};class VK{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 vf(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((r,o)=>{var l;if((l=this.context.physics.engine)!=null&&l.isUpdating||this.mute)return;const a=this.position[o];Math.abs(a-r)<1e-5||(this.position[o]=r,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new vf(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((r,o)=>{var l;if((l=this.context.physics.engine)!=null&&l.isUpdating||this.mute)return;const a=this.quaternion[o];Math.abs(a-r)<1e-5||(this.quaternion[o]=r,this.rotationChanged=!0)}));const i=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),s=new Pe;this.obj.matrixWorld.multiplyMatrices=(r,o)=>(s.equals(r)||(this.positionChanged=!0,this.rotationChanged=!0,s.copy(r)),i(r,o))}stop(){var e,t;(e=this._positionWatch)==null||e.revoke(),(t=this._rotationWatch)==null||t.revoke()}}var LC;const hE=(LC=class extends Ce{constructor(){super(...arguments);h(this,"mass",1);h(this,"useGravity",!0);h(this,"constraints",sn.None);h(this,"isKinematic",!1);h(this,"drag",0);h(this,"angularDrag",1);h(this,"detectCollisions",!0);h(this,"sleepThreshold",.01);h(this,"collisionDetectionMode",H_.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&sn.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&sn.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&sn.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&sn.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&sn.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&sn.FreezeRotationZ)!==0}set lockPositionX(e){e?this.constraints|=sn.FreezePositionX:this.constraints&=~sn.FreezePositionX}set lockPositionY(e){e?this.constraints|=sn.FreezePositionY:this.constraints&=~sn.FreezePositionY}set lockPositionZ(e){e?this.constraints|=sn.FreezePositionZ:this.constraints&=~sn.FreezePositionZ}set lockRotationX(e){e?this.constraints|=sn.FreezeRotationX:this.constraints&=~sn.FreezeRotationX}set lockRotationY(e){e?this.constraints|=sn.FreezeRotationY:this.constraints&=~sn.FreezeRotationY}set lockRotationZ(e){e?this.constraints|=sn.FreezeRotationZ:this.constraints&=~sn.FreezeRotationZ}set gravityScale(e){this._gravityScale=e}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new VK(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),Nr.LateUpdate)}onDisable(){var e,t;(e=this._watch)==null||e.stop(),(t=this.context.physics.engine)==null||t.removeBody(this)}onDestroy(){var e;(e=this.context.physics.engine)==null||e.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){var e,t,i,s;for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,(e=this.context.physics.engine)==null||e.updateProperties(this)),(t=this._watch)!=null&&t.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(i=this.context.physics.engine)==null||i.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(s=this._watch)==null||s.syncValues(),this.captureVelocity(),yield}teleport(e,t=!0){var i;(i=this._watch)==null||i.reset(!0),t?this.gameObject.position.set(e.x,e.y,e.z):this.setWorldPosition(e.x,e.y,e.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(){var e;(e=this.context.physics.engine)==null||e.resetForces(this,!0)}resetTorques(){var e;(e=this.context.physics.engine)==null||e.resetTorques(this,!0)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var e;(e=this.context.physics.engine)==null||e.wakeup(this)}applyForce(e,t){var i;(i=this.context.physics.engine)==null||i.addForce(this,e,!0)}applyImpulse(e){var t;(t=this.context.physics.engine)==null||t.applyImpulse(this,e,!0)}setForce(e,t,i){var s,r;(s=this.context.physics.engine)==null||s.resetForces(this,!0),(r=this.context.physics.engine)==null||r.addForce(this,{x:e,y:t,z:i},!0)}getVelocity(){var t;const e=(t=this.context.physics.engine)==null?void 0:t.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(e,t,i){var s,r;if(e instanceof S){const o=e;(s=this.context.physics.engine)==null||s.setLinearVelocity(this,o,!0);return}t===void 0||i===void 0||(r=this.context.physics.engine)==null||r.setLinearVelocity(this,{x:e,y:t,z:i},!0)}setAngularVelocity(e,t,i){var s,r;if(e instanceof S){const o=e;(s=this.context.physics.engine)==null||s.setAngularVelocity(this,o,!0);return}t===void 0||i===void 0||(r=this.context.physics.engine)==null||r.setAngularVelocity(this,{x:e,y:t,z:i},!0)}getAngularVelocity(){var t;const e=(t=this.context.physics.engine)==null?void 0:t.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(e,t,i){this.setAngularVelocity(e,t,i)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(e=null){}captureVelocity(){const e=wt(this.gameObject);hE.tempPosition.copy(e);const t=e.sub(this._lastPosition);this._lastPosition.copy(hE.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}},h(LC,"tempPosition",new S),LC);let ji=hE;Zl([Qr(),x()],ji.prototype,"mass",2);Zl([Qr(),x()],ji.prototype,"useGravity",2);Zl([Qr(),x()],ji.prototype,"constraints",2);Zl([Qr(),x()],ji.prototype,"isKinematic",2);Zl([Qr(),x()],ji.prototype,"drag",2);Zl([Qr(),x()],ji.prototype,"angularDrag",2);Zl([Qr(),x()],ji.prototype,"detectCollisions",2);Zl([Qr(),x()],ji.prototype,"sleepThreshold",2);Zl([Qr(),x()],ji.prototype,"collisionDetectionMode",2);class Fr{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,i,s){return e.prep(4,12),e.writeFloat32(s),e.writeFloat32(i),e.writeFloat32(t),e.offset()}}class dU{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 Fr).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Fr).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Fr).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,s,r,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(r),e.prep(4,12),e.writeFloat32(s),e.writeFloat32(i),e.writeFloat32(t),e.offset()}}class yl{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 yl).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+__),(t||new yl).__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 dU).__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 Ic=oe("debugsync"),Lm="STRS";z1(Lm,yl.getRootAsSyncedTransformModel);const la=new Yf;function fU(n,e,t=!0){la.clear();const i=la.createString(n);yl.startSyncedTransformModel(la),yl.addGuid(la,i),yl.addFast(la,t);const s=e.worldPosition,r=e.worldEuler,o=e.gameObject.scale;yl.addTransform(la,dU.createTransform(la,s.x,s.y,s.z,r.x,r.y,r.z,o.x,o.y,o.z));const a=yl.endSyncedTransformModel(la);return la.finish(a,Lm),la.asUint8Array()}class th extends Ce{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 xn);h(this,"receivedUpdate",!1);h(this,"lastWorldPos");h(this,"lastWorldRotation")}requestOwnership(){Ic&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){var t;return((t=this._model)==null?void 0:t.hasOwnership)??void 0}isOwned(){var t;return(t=this._model)==null?void 0:t.isOwned}awake(){Ic&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new S,this._targetRotation=new xe,this.lastWorldPos=new S,this.lastWorldRotation=new xe,this.rb=Z.getComponentInChildren(this.gameObject,ji),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new w_(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen($i.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(Lm,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&LL(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen($i.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(Lm,this.receivedDataCallback)}tryGetLastState(){const t=this.context.connection.tryGetState(this.guid);t&&this.onReceivedData(t)}onReceivedData(t){var i;if(!this.destroyed&&typeof t.guid=="function"&&t.guid()===this.guid){Ic&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,t),this.receivedUpdate=!0,this._receivedFastUpdate=t.fast();const s=t.transform();if(s){cr.markDirty(this.gameObject,!0);const r=s.position();r&&(this.interpolatePosition&&((i=this._targetPosition)==null||i.set(r.x(),r.y(),r.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(r.x(),r.y(),r.z()));const o=s.rotation();o&&(this.tempEuler.set(o.x(),o.y(),o.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&TO(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){Ic&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());let t=this.worldPosition,i=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const o=t.distanceTo(this.lastWorldPos),a=i.angleTo(this.lastWorldRotation),l=this._model.hasOwnership||this.fastMode?1e-4:.001;(o>l||a>l)&&(this._model.hasOwnership?this._needsUpdate=!0:(Ic&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,t.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,i.copy(this.lastWorldRotation),cr.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const a=this._receivedFastUpdate||this.fastMode?.5:.3;let l=!1;if(this.interpolatePosition&&this._targetPosition){const c=this.worldPosition;c.lerp(this._targetPosition,a),this.worldPosition=c,l=!0}if(this.interpolateRotation&&this._targetRotation){const c=this.worldQuaternion;c.slerp(this._targetRotation,a),this.worldQuaternion=c,l=!0}l&&cr.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(t),this.lastWorldRotation.copy(i),!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&&(Ic&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new S(0,0,0))>1e3&&(Ic&&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)){Ic&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this.overridePhysics&&this.rb,this._needsUpdate=!1;const o=fU(this.guid,this,!!r);this.context.connection.sendBinary(o)}}}var Xo={};Xo.d=(n,e)=>{for(var t in e)Xo.o(e,t)&&!Xo.o(n,t)&&Object.defineProperty(n,t,{enumerable:!0,get:e[t]})};Xo.o=(n,e)=>Object.prototype.hasOwnProperty.call(n,e);Xo.r=n=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})};var Sn={};Xo.d(Sn,{w8:()=>ui,cg:()=>RN,gO:()=>Gm,wb:()=>kI,zV:()=>Cu,HS:()=>NA,Ec:()=>Ou,gF:()=>Of,ol:()=>Hm,pz:()=>EU,tx:()=>lo,hj:()=>OI,FV:()=>HA,sV:()=>fN,xv:()=>Qm,mx:()=>wU,gE:()=>CU,ZP:()=>Dee,Vx:()=>BN});var kI={};Xo.r(kI);Xo.d(kI,{get:()=>pU,set:()=>WK});var OI={};Xo.r(OI);Xo.d(OI,{alphaTestTransformer:()=>W_,asPreprocessorValueTransformer:()=>IU,toPreprocessorTriggerTransformer:()=>WI,toUserDataTransformer:()=>tZ,uniformOrUserDataTransformer:()=>oo});const uE={fontFamily:null,fontSize:.05,fontKerning:"normal",fontStyle:"normal",fontWeight:"400",offset:.005,lineHeight:1.2,lineBreak:`- ,.:?!
|
|
4179
|
+
`}function DB(n){return`(${n.r}, ${n.g}, ${n.b})`}function kB(n){return`(${n.x}, ${n.y})`}const pT=class{constructor(e,t,i){h(this,"id");h(this,"trigger");h(this,"action");h(this,"exclusive",!1);this.id="Behavior_"+TI(e)+"_"+pT.global_id++,this.trigger=t,this.action=i}makeExclusive(e){return this.exclusive=e,this}writeTo(e,t,i){if(!this.trigger||!this.action)return;i.beginBlock(`def Preliminary_Behavior "${this.id}"`),i.appendLine(`rel actions = <${this.action.id}>`),i.appendLine(`uniform bool exclusive = ${this.exclusive}`);let s="";if(Array.isArray(this.trigger)){s="[";for(let r=0;r<this.trigger.length;r++){const o=this.trigger[r];s+="<"+o.id+">",r+1<this.trigger.length&&(s+=", ")}s+="]"}else s=`<${this.trigger.id}>`;if(i.appendLine(`rel triggers = ${s} `),i.appendLine(),Array.isArray(this.trigger))for(const r of this.trigger)r.writeTo(t,i),i.appendLine();else this.trigger.writeTo(t,i);i.appendLine(),this.action.writeTo(t,i),i.closeBlock()}};let ls=pT;h(ls,"global_id",0);function aE(n,e){var i,s;let t="";if(Array.isArray(n)){let r="[ ";for(let o=0;o<n.length;o++){let a=n[o];if(typeof a=="string")r+=a;else if(typeof a=="object"){a.isObject3D&&(a=e.findById(a.uuid));const l=(i=a.getPath)==null?void 0:i.call(a);r+=l}o+1<n.length&&(r+=", ")}r+=" ]",t=r}else typeof n=="object"&&(n.isObject3D&&(n=e.findById(n.uuid)),t=(s=n.getPath)==null?void 0:s.call(n));return t=t.replace(e.name,e.name+"/Scenes/Scene"),t}const gT=class{constructor(e,t){h(this,"id");h(this,"targetId");h(this,"tokenId");h(this,"type");h(this,"distance");e&&(this.targetId=e),t?this.id=t:this.id="Trigger_"+gT.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=aE(this.targetId,e)),t.appendLine("rel affectedObjects = "+this.targetId)),this.tokenId&&t.appendLine(`token info:id = "${this.tokenId}"`),this.type&&t.appendLine(`token type = "${this.type}"`),typeof this.distance=="number"&&t.appendLine(`double distance = ${this.distance}`),t.closeBlock()}};let kl=gT;h(kl,"global_id",0);class dr{static sceneStartTrigger(){const e=new kl;return e.targetId=void 0,e.tokenId="SceneTransition",e.type="enter",e}static tapTrigger(e){const t=new kl(e);return t.tokenId="TapGesture",t}static isTapTrigger(e){return(e==null?void 0:e.tokenId)==="TapGesture"}static proximityToCameraTrigger(e,t){const i=new kl(e);return i.tokenId="ProximityToCamera",i.distance=t,i}}class zc{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 i of this.actions)i&&t.appendLine("<"+i.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 i of this.actions)i&&(i.writeTo(e,t),t.appendLine());t.closeBlock()}}h(zc,"global_id",0);var PI=(n=>(n[n.pop=0]="pop",n[n.blink=1]="blink",n[n.bounce=2]="bounce",n[n.flip=3]="flip",n[n.float=4]="float",n[n.jiggle=5]="jiggle",n[n.pulse=6]="pulse",n[n.spin=7]="spin",n))(PI||{}),lE=(n=>(n.Relative="relative",n.Absolute="absolute",n))(lE||{});const Db=class{constructor(e,t){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");e&&(this.affectedObjects=e),t?this.id=t:this.id="Action",this.id+="_"+Db.global_id++}clone(){const e=new Db,t=e.id;return Object.assign(e,this),e.id=t,e}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),this.affectedObjects&&(typeof this.affectedObjects!="string"&&(this.affectedObjects=aE(this.affectedObjects,e)),t.appendLine("rel affectedObjects = "+this.affectedObjects)),typeof this.duration=="number"&&t.appendLine(`double duration = ${this.duration} `),this.easeType&&t.appendLine(`token easeType = "${this.easeType}"`),this.tokenId&&t.appendLine(`token info:id = "${this.tokenId}"`),this.motionType&&t.appendLine(`token motionType = "${this.motionType}"`),typeof this.moveDistance=="number"&&t.appendLine(`double moveDistance = ${this.moveDistance} `),this.style&&t.appendLine(`token style = "${this.style}"`),this.type&&t.appendLine(`token type = "${this.type}"`),this.front&&t.appendLine(`vector3d front = (${this.front.x}, ${this.front.y}, ${this.front.z})`),this.up&&t.appendLine(`vector3d upVector = (${this.up.x}, ${this.up.y}, ${this.up.z})`),typeof this.start=="number"&&t.appendLine(`double start = ${this.start} `),typeof this.animationSpeed=="number"&&t.appendLine(`double animationSpeed = ${this.animationSpeed} `),typeof this.reversed=="boolean"&&t.appendLine(`bool reversed = ${this.reversed}`),typeof this.pingPong=="boolean"&&t.appendLine(`bool reverses = ${this.pingPong}`),this.xFormTarget&&(typeof this.xFormTarget!="string"&&(this.xFormTarget=aE(this.xFormTarget,e)),t.appendLine(`rel xformTarget = ${this.xFormTarget}`)),typeof this.audio=="string"&&t.appendLine(`asset audio = @${this.audio}@`),typeof this.gain=="number"&&t.appendLine(`double gain = ${this.gain}`),typeof this.auralMode=="string"&&t.appendLine(`token auralMode = "${this.auralMode}"`),typeof this.multiplePerformOperation=="string"&&t.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),t.closeBlock()}};let Pr=Db;h(Pr,"global_id",0);let Xd=class Fd{constructor(e,t,i){h(this,"x",0);h(this,"y",0);h(this,"z",0);this.x=e,this.y=t,this.z=i}static get up(){return new Fd(0,1,0)}static get right(){return new Fd(1,0,0)}static get forward(){return new Fd(0,0,1)}static get back(){return new Fd(0,0,-1)}static get zero(){return new Fd(0,0,0)}};var oU=(n=>(n.Play="play",n.Pause="pause",n.Stop="stop",n))(oU||{}),cE=(n=>(n.Spatial="spatial",n.NonSpatial="nonSpatial",n.Ambient="ambient",n))(cE||{});class ai{static sequence(...e){return new zc("group_"+zc.getId(),e).makeSequence()}static parallel(...e){return new zc("group_"+zc.getId(),e).makeParallel()}static fadeAction(e,t,i){const s=new Pr(e);return s.tokenId="Visibility",s.type=i?"show":"hide",s.duration=t,s.style="basic",s.motionType="none",s.moveDistance=0,s.easeType="none",s}static startAnimationAction(e,t,i=0,s=1,r=!1,o=!1){const a=new Pr(e);if(a.tokenId="StartAnimation",a.start=t,a.duration=i,a.animationSpeed=s,a.reversed=r,a.pingPong=o,r&&(a.start-=i),o){a.pingPong=!1;const l=a.clone();return l.reversed=!r,l.start=a.start,l.reversed&&(l.start-=i),ai.sequence(a,l)}return a}static waitAction(e){const t=new Pr;return t.tokenId="Wait",t.duration=e,t}static lookAtCameraAction(e,t=9999999999999,i,s){const r=new Pr(e);return r.tokenId="LookAtCamera",r.duration=t,r.front=i??Xd.forward,r.up=s??Xd.up,r}static emphasize(e,t,i=2,s=1,r="basic"){const o=new Pr(e);return o.tokenId="Emphasize",o.duration=t,o.style=r??"basic",o.motionType=PI[i],o.moveDistance=s,o}static transformAction(e,t,i,s,r="inout"){const o=new Pr(e);return o.tokenId="Transform",o.duration=i,o.type=s,o.easeType=r,Array.isArray(t)&&console.error("Transform target must not be an array",t),o.xFormTarget=t,o}static playAudioAction(e,t,i="play",s=1,r="spatial"){const o=new Pr(e);return o.tokenId="Audio",o.type=i,o.audio=t,o.gain=s,o.auralMode=r,o.multiplePerformOperation="allow",o}}class QY{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 RI extends QY{constructor(t,i,s,r){super(t);h(this,"matrix");h(this,"material");h(this,"geometry");h(this,"_enableAction");h(this,"_disableAction");this.matrix=i,this.material=s,this.geometry=r}onApply(t){var r,o;const i=this.model;if(!i)return;(r=i.parent)!=null&&r.isDynamic||go.createEmptyParent(i);const s=i.clone();this.matrix&&(s.matrix=this.matrix),this.material&&(s.material=this.material),this.geometry&&(s.geometry=this.geometry),(o=i.parent)==null||o.add(s)}enable(){return this._enableAction?this._enableAction:(this._enableAction=ai.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=ai.fadeAction(this.object,0,!1),this._disableAction)}}class BI{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 HY=Object.defineProperty,VY=Object.getOwnPropertyDescriptor,aU=(n,e,t,i)=>{for(var s=i>1?void 0:i?VY(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&HY(e,t,s),s};class LA extends Ce{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 t=wt(this.from).clone(),i=wt(this.to).clone(),s=t.distanceTo(i);this._centerPos.copy(t),this._centerPos.add(i),this._centerPos.multiplyScalar(.5),hn(this.gameObject,this.centered?this._centerPos:t),this.gameObject.lookAt(wt(this.to).clone()),this.gameObject.scale.set(this.width,this.width,s)}}aU([x(Z)],LA.prototype,"from",2);aU([x(Z)],LA.prototype,"to",2);var WY=Object.defineProperty,jY=Object.getOwnPropertyDescriptor,FA=(n,e,t,i)=>{for(var s=i>1?void 0:i?jY(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&WY(e,t,s),s};const Ec=oe("debuganimation");class Eo extends Ce{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 t;return(t=this.animations)!=null&&t.length?this.animations[0]:null}set clip(t){if(!this.__didAwake){Ec&&console.log("Assign clip during serialization",t),this._tempAnimationClipBeforeGameObjectExisted=t;return}t&&(Ec&&console.log("Assign clip",t,!!this.gameObject),this.gameObject.animations||(this.gameObject.animations=[]),!this.animations.includes(t)&&(this.animations.length>0?this.animations.splice(0,0,t):this.animations.push(t)))}set clips(t){this.animations=t}set animations(t){Ec&&console.log("assign animations",t),this.gameObject.animations=t}get animations(){return this.gameObject.animations}get currentAction(){return this._currentActions[0]}get currentActions(){return this._currentActions}get actions(){return this._actions}set actions(t){this._actions=t}awake(){Ec&&console.log(this),this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.playAutomatically&&this.init()}onEnable(){var t;if(this.playAutomatically&&((t=this.animations)==null?void 0:t.length)>0&&this.currentActions.length<=0){const i=Math.floor(Math.random()*this.actions.length);this.play(i)}}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(t){var i;return(i=this.actions)==null?void 0:i.find(s=>s.getClip().name===t)}get isPlaying(){for(let t=0;t<this._currentActions.length;t++)if(this._currentActions[t].isRunning())return!0;return!1}play(t=0,i){if(Ec&&console.log("PLAY",t),this.init(),!this.mixer){Ec&&console.warn("Missing mixer",this);return}t===void 0&&(t=0);let s=t;if(typeof t=="number"){if(t>=this.animations.length){Ec&&console.log("No animation at index",t);return}s=this.animations[t]}else typeof t=="string"&&(s=this.animations.find(o=>o.name===t));if(!s){console.error("Could not find clip",t);return}i||(i={}),i.minMaxOffsetNormalized||(i.minMaxOffsetNormalized=this.minMaxOffsetNormalized),i.minMaxSpeed||(i.minMaxSpeed=this.minMaxSpeed),i.loop===void 0&&(i.loop=this.loop),i.clampWhenFinished===void 0&&(i.clampWhenFinished=this.clampWhenFinished);for(const o of this.actions)if(o.getClip()===s)return this.internalOnPlay(o,i);if(!(s instanceof wo)){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,i)}internalOnPlay(t,i){var s=this.currentAction;if(s===t&&s.isRunning()&&s.time<s.getClip().duration){const l=this.tryFindHandle(t);if(l)return l.getPromise()}const r=(i==null?void 0:i.exclusive)??!0;i!=null&&i.fadeDuration?(r&&(s==null||s.fadeOut(i.fadeDuration)),t.fadeIn(i.fadeDuration)):r&&(s==null||s.stop()),t.reset(),t.enabled=!0,t.time=0,t.timeScale=1;const o=t.getClip();i!=null&&i.minMaxOffsetNormalized&&(t.time=$e.lerp(i.minMaxOffsetNormalized.x,i.minMaxOffsetNormalized.y,Math.random())*o.duration),i!=null&&i.minMaxSpeed&&(t.timeScale=$e.lerp(i.minMaxSpeed.x,i.minMaxSpeed.y,Math.random())),i!=null&&i.clampWhenFinished&&(t.clampWhenFinished=!0),(i==null?void 0:i.startTime)!==void 0&&(t.time=i.startTime),(i==null?void 0:i.loop)!==void 0?t.loop=i.loop?JE:mm:t.loop=mm,t.play(),Ec&&console.log("PLAY",t.getClip().name,t);const a=new qY(t,this.mixer,i,l=>{this._handles.splice(this._handles.indexOf(a),1)});return this._handles.push(a),a.getPromise()}tryFindHandle(t){for(const i of this._handles)if(i.action===t)return i}init(){this._didInit||(this._didInit=!0,this.gameObject&&(this.actions=[],this.mixer=new h_(this.gameObject)))}}FA([x()],Eo.prototype,"playAutomatically",2);FA([x()],Eo.prototype,"randomStartTime",2);FA([x()],Eo.prototype,"loop",2);FA([x()],Eo.prototype,"clampWhenFinished",2);FA([x(wo)],Eo.prototype,"clips",1);class qY{constructor(e,t,i,s){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=s,this._options=i}getPromise(){return this.promise?this.promise:(this.promise=new Promise((e,t)=>{this._resolveCallback=e,this._rejectCallback=t,this.resolve=this.onResolve.bind(this),this.reject=this.onReject.bind(this)}),this._loopCallback=this.onLoop.bind(this),this._finishedCallback=this.onFinished.bind(this),this.mixer.addEventListener("loop",this._loopCallback),this.mixer.addEventListener("finished",this._finishedCallback),this.promise)}_update(){this._options&&this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){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,i;this.dispose(),(t=this._resolvedOrRejectedCallback)==null||t.call(this,this),(i=this._rejectCallback)==null||i.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 XY=Object.defineProperty,YY=Object.getOwnPropertyDescriptor,uh=(n,e,t,i)=>{for(var s=i>1?void 0:i?YY(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&XY(e,t,s),s};class dh{constructor(){h(this,"time");h(this,"value");h(this,"inTangent");h(this,"inWeight");h(this,"outTangent");h(this,"outWeight");h(this,"weightedMode")}}uh([x()],dh.prototype,"time",2);uh([x()],dh.prototype,"value",2);uh([x()],dh.prototype,"inTangent",2);uh([x()],dh.prototype,"inWeight",2);uh([x()],dh.prototype,"outTangent",2);uh([x()],dh.prototype,"outWeight",2);uh([x()],dh.prototype,"weightedMode",2);const lU=class{constructor(){h(this,"keys")}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(n){if(!this.keys||this.keys.length==0)return 0;if(this.keys[0].time>=n)return this.keys[0].value;for(let e=0;e<this.keys.length;e++){const t=this.keys[e];if(t.time<=n)if(e+1<this.keys.length){const s=this.keys[e+1];if(s.time<n)continue;return!isFinite(t.outTangent)||!isFinite(s.inTangent)?t.value:lU.interpolateValue(n,t,s)}else return t.value}return this.keys[this.keys.length-1].value}static interpolateValue(n,e,t){const i=e.time,s=e.value,r=e.outTangent,o=t.time,a=t.value,l=t.inTangent,c=o-i,u=c*c,d=u*c,f=((r+l)*c-2*(a-s))/d,p=(3*(a-s)-(l+2*r)*c)/u,g=r,m=s,A=n-i,v=A*A,b=v*A;return f*b+p*v+g*A+m}};let ku=lU;uh([x(dh)],ku.prototype,"keys",2);const Yd=oe("debugusdzanimation");class F_{constructor(e,t,i){h(this,"ext");h(this,"root");h(this,"clip");this.ext=e,this.root=t,this.clip=i}get start(){return this.ext.getStartTime01(this.root,this.clip)}get duration(){return this.clip.duration}}class U_{constructor(e,t,i,s){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=i,this.clip=s}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,i,s,r,o;return Math.max(((t=(e=this.pos)==null?void 0:e.times)==null?void 0:t.length)??0,((s=(i=this.rot)==null?void 0:i.times)==null?void 0:s.length)??0,((o=(r=this.scale)==null?void 0:r.times)==null?void 0:o.length)??0)}getDuration(){var t,i,s;const e=((t=this.pos)==null?void 0:t.times)??((i=this.rot)==null?void 0:i.times)??((s=this.scale)==null?void 0:s.times);return e?e[e.length-1]:0}getStartTime(e){let t=0;for(let i=0;i<e.length;i++){const s=e[i];if(s===this)return t;t+=s.getDuration()}return t}}class N_{constructor(){h(this,"dict",new Map);h(this,"rootTargetMap",new Map);h(this,"serializers",[])}get extensionName(){return"animation"}getStartTime01(e,t){const i=this.rootTargetMap.get(e);if(!i)return 1/0;let s=-1;for(const r of i){const o=this.dict.get(r);let a=0;if(o!=null&&o.length){for(const l of o){if(l.clip===t)break;a+=l.getDuration()}s=Math.max(s,a)}else console.warn("No animation found on root",e,t,o)}return s}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],o=e.getObjectByName(r);if(!o){console.warn("no object found for track",s.name,"using "+e.name+" instead");continue}this.dict.has(o)||this.dict.set(o,[]);const a=this.dict.get(o);if(!a)continue;let l=a.find(u=>u.clip===t);l||(l=new U_(this,e,o,t),a.push(l)),l.addTrack(s);const c=this.rootTargetMap.get(e);c!=null&&c.includes(o)||c==null||c.push(o)}return new F_(this,e,t)}onAfterHierarchy(e){Yd&&console.log(this.dict)}onAfterBuildDocument(e){var t,i;for(const s of this.serializers){const r=(t=s.model)==null?void 0:t.parent,o=(r==null?void 0:r.isDynamic)===!0;Yd&&console.log(o,(i=s.model)==null?void 0:i.parent),o&&s.registerCallback(r)}}onExportObject(e,t,i){Z.foreachComponent(e,r=>{const o=r;typeof o.createAnimation=="function"&&o.createAnimation(this,t,i)},!1);const s=new KY(e,this.dict);this.serializers.push(s),s.registerCallback(t)}}class KY{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)),Yd&&console.log("REPARENT",e),this.model=e,this.model.addEventListener("serialize",this.callback)}onSerialize(e,t){var c,u,d,f,p,g;if(!this.model)return;Yd&&console.log("SERIALIZE",this.model.name,this.object.type);const i=this.object,s=this.dict.get(i);if(!s)return;const r=new Pe,o=new S,a=new xe,l=new S(1,1,1);e.appendLine("matrix4d xformOp:transform.timeSamples = {"),e.indent++;for(const m of s){let A=(c=m.pos)==null?void 0:c.times,v=(u=m.rot)==null?void 0:u.times,b=(d=m.scale)==null?void 0:d.times,y=[];if(A)for(const w of A)y.push(w);if(v)for(const w of v)y.push(w);if(b)for(const w of b)y.push(w);if(y.sort((w,M)=>w-M),y=[...new Set(y)],!y||y.length===0){console.error("got an animated object but no time values??",i,m);continue}const _=m.getStartTime(s);Yd&&e.appendLine(m.clip.name+": start="+_.toFixed(3)+", length="+m.getDuration().toFixed(3)+", frames="+m.getFrames());const C=(f=m.pos)==null?void 0:f.createInterpolant(),E=(p=m.rot)==null?void 0:p.createInterpolant(),T=(g=m.scale)==null?void 0:g.createInterpolant();C||o.set(i.position.x,i.position.y,i.position.z),E||a.set(i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w),T||l.set(i.scale.x,i.scale.y,i.scale.z);for(let w=0;w<y.length;w++){const M=y[w];if(C){const k=C.evaluate(M);o.set(k[0],k[1],k[2])}if(E){const k=E.evaluate(M);a.set(k[0],k[1],k[2],k[3])}if(T){const k=T.evaluate(M);l.set(k[0],k[1],k[2])}r.compose(o,a,l);let P=`${(_+M)*m.frameRate}: ${rU(r)},`;Yd&&(P="#"+w+" "+P),e.appendLine(P)}}e.indent--,e.appendLine("}")}}class JY{constructor(){h(this,"_context")}get context(){return this._context??kt.Current}get isStateMachineBehaviour(){return!0}}class w0{constructor(e,t,i,s){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=i,this._speed=s}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 cU(n,e){return{name:"",isLooping:!1,guid:(e==null?void 0:e.generateUUID())??Hs.generateUUID(),index:-1,clip:new wo(n,1,[])}}var Dc=(n=>(n[n.If=1]="If",n[n.IfNot=2]="IfNot",n[n.Greater=3]="Greater",n[n.Less=4]="Less",n[n.Equals=6]="Equals",n[n.NotEqual=7]="NotEqual",n))(Dc||{}),DI=(n=>(n[n.Float=1]="Float",n[n.Int=3]="Int",n[n.Bool=4]="Bool",n[n.Trigger=9]="Trigger",n))(DI||{});const aa=oe("debuganimatorcontroller"),xy=oe("debugrootmotion");class wu{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,aa&&console.log(this)}play(e,t=-1,i=Number.NEGATIVE_INFINITY,s=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}const o=this.model.layers[t].stateMachine;for(const a of o.states)if(a.name===e||a.hash===e){aa&&console.log("transition to ",a),this.transitionTo(a,s,i);return}console.warn("Could not find "+e+" to play")}reset(){this.setStartTransition()}setBool(e,t){var s,r;const i=typeof e=="string"?"name":"hash";return(r=(s=this.model)==null?void 0:s.parameters)==null?void 0:r.filter(o=>o[i]===e).forEach(o=>o.value=t)}getBool(e){var i,s,r;const t=typeof e=="string"?"name":"hash";return((r=(s=(i=this.model)==null?void 0:i.parameters)==null?void 0:s.find(o=>o[t]===e))==null?void 0:r.value)??!1}setFloat(e,t){var s,r;const i=typeof e=="string"?"name":"hash";return(r=(s=this.model)==null?void 0:s.parameters)==null?void 0:r.filter(o=>o[i]===e).forEach(o=>o.value=t)}getFloat(e){var i,s,r;const t=typeof e=="string"?"name":"hash";return((r=(s=(i=this.model)==null?void 0:i.parameters)==null?void 0:s.find(o=>o[t]===e))==null?void 0:r.value)??0}setInteger(e,t){var s,r;const i=typeof e=="string"?"name":"hash";return(r=(s=this.model)==null?void 0:s.parameters)==null?void 0:r.filter(o=>o[i]===e).forEach(o=>o.value=t)}getInteger(e){var i,s,r;const t=typeof e=="string"?"name":"hash";return((r=(s=(i=this.model)==null?void 0:i.parameters)==null?void 0:s.find(o=>o[t]===e))==null?void 0:r.value)??0}setTrigger(e){var i,s;aa&&console.log("SET TRIGGER",e);const t=typeof e=="string"?"name":"hash";return(s=(i=this.model)==null?void 0:i.parameters)==null?void 0:s.filter(r=>r[t]===e).forEach(r=>r.value=!0)}resetTrigger(e){var i,s;const t=typeof e=="string"?"name":"hash";return(s=(i=this.model)==null?void 0:i.parameters)==null?void 0:s.filter(r=>r[t]===e).forEach(r=>r.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 i of t.stateMachine.states)if(i.name===e)return i}return null}get context(){var e;return(e=this.animator)==null?void 0:e.context}bind(e){this.animator=e,this._mixer=new h_(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=Fb(this.model,(i,s,r)=>r==null?!0:!(r.type==="Object3D"||r.isObject3D===!0||RO(r)||r.tracks!==void 0));return console.assert(e!==this.model),new wu(e)}update(){var t,i;if(!this.animator||(this.evaluateTransitions(),this.updateActiveStates(),!this._activeState))return;const e=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((t=this.rootMotionHandler)==null||t.onBeforeUpdate()),this._mixer.update(e),this.animator.applyRootMotion&&((i=this.rootMotionHandler)==null||i.onAfterUpdate())}updateActiveStates(){for(let e=0;e<this._activeStates.length;e++){const t=this._activeStates[e],i=t.motion;if(!i.action)this._activeStates.splice(e,1),e--;else{const s=i.action;s.getEffectiveWeight()<=0&&!s.isRunning()&&(aa&&console.debug("REMOVE",t.name,s.getEffectiveWeight(),s.isRunning(),s.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(const e of this.model.layers){const t=e.stateMachine;t.defaultState===void 0&&(aa&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",e),t.defaultState=0);const i=t.states[t.defaultState];this.transitionTo(i,0,this.normalizedStartOffset)}}evaluateTransitions(){var r;let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}const t=this._activeState,i=t.motion.action;for(const o of t.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==null?void 0:c.type)===DI.Trigger&&(c.value=!1)}if(i){const l=t.motion.clip.duration,c=l<=0?1:Math.abs(i.time/l);let u=!1;if(o.hasExitTime?i.timeScale>0?u=c>=o.exitTime:i.timeScale<0&&(u=1-c>=o.exitTime):u=!0,u){i.clampWhenFinished=!0,aa&&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 s=!1;if(t.motion.isLooping&&i&&(i.time>=i.getClip().duration?(s=!0,i.reset(),i.time=0,i.play()):i.time<=0&&i.timeScale<0&&(s=!0,i.reset(),i.time=i.getClip().duration,i.play())),!s&&t&&!e&&i&&this.animator&&t.behaviours){const o=i==null?void 0:i.getClip().duration,a=i.time/o,l=new w0(this._activeState,a,o,this._speed);for(const c of t.behaviours)c.instance&&((r=c.instance.onStateUpdate)==null||r.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&&(aa&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+t),e=0)),e=this.model.layers[t].stateMachine.states[e]),e}transitionTo(e,t,i){var c,u,d,f,p,g,m,A;if(!this.animator)return;const s=0;if(e=this.getState(e,s),!(e!=null&&e.motion)||!e.motion.clip)return;const r=this._activeState===e;if(r){const v=e.motion;!v.action_loopback&&v.clip&&(this._mixer.uncacheAction(v.clip,this.animator.gameObject),v.action_loopback=this.createAction(v.clip))}if((c=this._activeState)!=null&&c.behaviours&&this._activeState.motion.action){const v=(u=this._activeState)==null?void 0:u.motion.clip.duration,b=this._activeState.motion.action.time/v,y=new w0(this._activeState,b,v,this._speed);for(const _ of this._activeState.behaviours)(f=(d=_.instance)==null?void 0:d.onStateExit)==null||f.call(_.instance,this.animator,y,s)}const o=(p=this._activeState)==null?void 0:p.motion.action;o&&o.fadeOut(t),r&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=o);const a=this._activeState;this._activeState=e;const l=(g=e.motion)==null?void 0:g.action;if(l){i=Math.max(0,Math.min(1,i)),l.isRunning()&&l.stop(),l.reset(),l.timeScale=this._speed,e.speed!==void 0&&(l.timeScale*=e.speed),l.enabled=!0;const v=e.motion.clip.duration;if(l.time=i*v,l.timeScale<0&&(l.time=v-l.time),l.clampWhenFinished=!0,l.setLoop(mm,0),t>0?l.fadeIn(t):l.setEffectiveWeight(1),l.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(l),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){const b=new w0(e,i,v,this._speed);for(const y of this._activeState.behaviours)(A=(m=y.instance)==null?void 0:m.onStateEnter)==null||A.call(y.instance,this.animator,b,s)}}else aa&&(e.__warned_no_motion||(e.__warned_no_motion=!0,console.warn("No action",e.motion,this)));aa&&console.log("TRANSITION FROM "+(a==null?void 0:a.name)+" TO "+e.name,t,o,l,l==null?void 0:l.getEffectiveTimeScale(),l==null?void 0:l.getEffectiveWeight(),l==null?void 0:l.isRunning(),l==null?void 0:l.isScheduled(),l==null?void 0:l.paused)}createAction(e){var i,s;if(this._mixer.existingAction(e)&&this._mixer.uncacheAction(e,(i=this.animator)==null?void 0:i.gameObject),(s=this.animator)!=null&&s.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new ZY(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(i=>i.name===e.parameter);if(!t)return!1;switch(e.mode){case Dc.If:return t.value===!0;case Dc.IfNot:return t.value===!1;case Dc.Greater:return t.value>e.threshold;case Dc.Less:return t.value<e.threshold;case Dc.Equals:return t.value===e.threshold;case Dc.NotEqual:return t.value!==e.threshold}return!1}createActions(e){var t,i;for(const s of this.model.layers){const r=s.stateMachine;for(let o=0;o<r.states.length;o++){const a=r.states[o];a.transitions||(a.transitions=[]);for(const l of a.transitions)l.conditions||(l.conditions=[]);if(a.motion||(a.motion=cU(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==null?void 0:l.clip}if(!a.motion.clip){const l=new wo(void 0,void 0,[]);a.motion.clip=l}if((i=a.motion)!=null&&i.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=G.get(l.typeName),u=new c;u.isStateMachineBehaviour&&(u._context=this.context??void 0,_u(u,l.properties),l.instance=u),aa&&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 i=0;i<t.states.length;i++){const s=t.states[i];s!=null&&s.motion&&(s.motion.action&&(yield s.motion.action),s.motion.action_loopback&&(yield s.motion.action_loopback))}}}}class OB{constructor(e,t){h(this,"track");h(this,"createdInterpolant");h(this,"originalEvaluate");h(this,"customEvaluate");this.track=e;const i=e,s=i.createInterpolant.bind(e);i.createInterpolant=()=>(i.createInterpolant=s,this.createdInterpolant=s(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=r=>{if(!this.originalEvaluate)return;const o=this.originalEvaluate(r);return t(r,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 An=class{constructor(e,t,i,s,r){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 xe);if(this.context=e,this.root=t,this.clip=i,An.firstKeyframeRotation[i.uuid]||(An.firstKeyframeRotation[i.uuid]=new xe),r){const o=r.values;An.firstKeyframeRotation[i.uuid].set(o[0],o[1],o[2],o[3])}An.spaceRotation[i.uuid]||(An.spaceRotation[i.uuid]=new xe),An.effectiveSpaceRotation[i.uuid]||(An.effectiveSpaceRotation[i.uuid]=new xe),An.clipOffsetRotation[i.uuid]=new xe,r&&An.clipOffsetRotation[i.uuid].set(r.values[0],r.values[1],r.values[2],r.values[3]).invert(),this.handlePosition(i,s),this.handleRotation(i,r)}set action(e){this._action=e}get action(){return this._action}onStart(e){if(e.getClip()!==this.clip)return;const t=An.lastObjRotation[this.root.uuid];if(An.spaceRotation[this.clip.uuid].copy(t),xy){const i=new xn().setFromQuaternion(t);console.log("START",this.clip.name,$e.toDegrees(i.y))}}getClipRotationOffset(){return An.clipOffsetRotation[this.clip.uuid]}handlePosition(e,t){if(t){const i=this.root;xy&&i.add(new Xf),An.lastObjPosition[i.uuid]||(An.lastObjPosition[i.uuid]=new S);const s=new S,r=new S;let o=0;this.positionWrapper=new OB(t,(a,l)=>{const c=this.action.getEffectiveWeight();if(xy&&i.position.length()>8&&i.position.set(0,i.position.y,0),a>o){s.set(l[0],l[1],l[2]),s.sub(r),s.multiplyScalar(c),s.applyQuaternion(this.getClipRotationOffset());const u=this.clip.uuid;s.applyQuaternion(An.spaceRotation[u]),this.positionChange.copy(s)}return r.fromArray(l),o=a,l[0]=0,l[1]=0,l[2]=0,l})}}handleRotation(e,t){if(t){if(xy){const a=t.values,l=new xn().setFromQuaternion(new xe(a[0],a[1],a[2],a[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",$e.toDegrees(l.y));const c=t.values.length-4,u=new xe().set(a[c],a[c+1],a[c+2],a[c+3]),d=new xn().setFromQuaternion(u);console.log(e.name,t.name,"LAST ROTATION IN TRACK",$e.toDegrees(d.y))}const i=this.root;An.lastObjRotation[i.uuid]||(An.lastObjRotation[i.uuid]=new xe);let s=0;const r=new xe,o=new xe;this.rotationWrapper=new OB(t,(a,l)=>(a>s&&(o.set(l[0],l[1],l[2],l[3]),r.invert(),o.multiply(r),this.rotationChange.copy(o)),r.fromArray(l),s=a,l[0]=0,l[1]=0,l[2]=0,l[3]=1,l))}}onBeforeUpdate(){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(){if(!this.action)return;const e=this.action.getEffectiveWeight();this.positionChange.multiplyScalar(e),this.rotationChange.slerp(An.identityQuaternion,1-e)}};let zo=An;h(zo,"lastObjPosition",{}),h(zo,"lastObjRotation",{}),h(zo,"firstKeyframeRotation",{}),h(zo,"spaceRotation",{}),h(zo,"effectiveSpaceRotation",{}),h(zo,"clipOffsetRotation",{}),h(zo,"identityQuaternion",new xe);class ZY{constructor(e){h(this,"controller");h(this,"handler",[]);h(this,"root");h(this,"summedPosition",new S);h(this,"summedRotation",new xe);this.controller=e}createClip(e,t,i){this.root=t,t&&"name"in t&&t.name;const s=this.findRootTrack(i,".position"),r=this.findRootTrack(i,".quaternion"),o=new zo(this.controller.context,t,i,s,r);this.handler.push(o);const a=e.clipAction(i);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),zo.lastObjRotation[this.root.uuid].copy(this.root.quaternion)}findRootTrack(e,t){const i=e.tracks;if(!i)return null;for(const s of i)if(s.name.endsWith(t))return s;return null}}var $Y=Object.defineProperty,eK=Object.getOwnPropertyDescriptor,z_=(n,e,t,i)=>{for(var s=i>1?void 0:i?eK(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&$Y(e,t,s),s};const Zw=oe("debuganimator");class Ys extends Ce{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(t){this._animatorController&&this._animatorController.model===t||(t?t instanceof wu?this._animatorController=t:(Zw&&console.log("Assign animator controller",t,this),this._animatorController=new wu(t)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}Play(t,i=-1,s=Number.NEGATIVE_INFINITY,r=0){this.play(t,i,s,r)}play(t,i=-1,s=Number.NEGATIVE_INFINITY,r=0){var o;(o=this.runtimeAnimatorController)==null||o.play(t,i,s,r)}Reset(){this.reset()}reset(){var t;(t=this._animatorController)==null||t.reset()}SetBool(t,i){this.setBool(t,i)}setBool(t,i){var s;(s=this.runtimeAnimatorController)==null||s.setBool(t,i)}GetBool(t){return this.getBool(t)}getBool(t){var i;return((i=this.runtimeAnimatorController)==null?void 0:i.getBool(t))??!1}SetFloat(t,i){this.setFloat(t,i)}setFloat(t,i){var s;(s=this.runtimeAnimatorController)==null||s.setFloat(t,i)}GetFloat(t){return this.getFloat(t)}getFloat(t){var i;return((i=this.runtimeAnimatorController)==null?void 0:i.getFloat(t))??-1}SetInteger(t,i){this.setInteger(t,i)}setInteger(t,i){var s;(s=this.runtimeAnimatorController)==null||s.setInteger(t,i)}GetInteger(t){return this.getInteger(t)}getInteger(t){var i;return((i=this.runtimeAnimatorController)==null?void 0:i.getInteger(t))??-1}SetTrigger(t){this.setTrigger(t)}setTrigger(t){var i;Zw&&console.log("SetTrigger",t),(i=this.runtimeAnimatorController)==null||i.setTrigger(t)}ResetTrigger(t){this.resetTrigger(t)}resetTrigger(t){var i;(i=this.runtimeAnimatorController)==null||i.resetTrigger(t)}IsInTransition(){return this.isInTransition()}isInTransition(){var t;return((t=this.runtimeAnimatorController)==null?void 0:t.isInTransition())??!1}SetSpeed(t){return this.setSpeed(t)}setSpeed(t){var i;t!==this.speed&&(this.speed=t,(i=this._animatorController)==null||i.setSpeed(t))}set minMaxSpeed(t){this.speed=$e.lerp(t.x,t.y,Math.random())}set minMaxOffsetNormalized(t){this.normalizedStartOffset=$e.lerp(t.x,t.y,Math.random()),this.runtimeAnimatorController&&(this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset)}awake(){if(Zw&&console.log("ANIMATOR",this.name,this),!!this.gameObject&&this.runtimeAnimatorController){const t=this.runtimeAnimatorController.clone();t?(console.assert(this.runtimeAnimatorController!==t),this.runtimeAnimatorController=t,console.assert(this.runtimeAnimatorController===t),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 t;this.keepAnimatorControllerStateOnDisable||(t=this._animatorController)==null||t.reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}}z_([x()],Ys.prototype,"applyRootMotion",2);z_([x()],Ys.prototype,"hasRootMotion",2);z_([x()],Ys.prototype,"keepAnimatorControllerStateOnDisable",2);z_([x()],Ys.prototype,"runtimeAnimatorController",1);class tK extends an{constructor(e,t=1,i=16,s=2){const r=new At,o=i+s*2,a=new Float32Array((o*3+3)*3);r.setAttribute("position",new rt(a,3));const l=new dn({color:65280}),c=new dn({color:16776960});super(r,[c,l]),this.audio=e,this.range=t,this.divisionsInnerAngle=i,this.divisionsOuterAngle=s,this.type="PositionalAudioHelper",this.update()}update(){const e=this.audio,t=this.range,i=this.divisionsInnerAngle,s=this.divisionsOuterAngle,r=Hs.degToRad(e.panner.coneInnerAngle),o=Hs.degToRad(e.panner.coneOuterAngle),a=r/2,l=o/2;let c=0,u=0,d,f;const p=this.geometry,g=p.attributes.position;p.clearGroups();function m(A,v,b,y){const _=(v-A)/b;for(g.setXYZ(c,0,0,0),u++,d=A;d<v;d+=_)f=c+u,g.setXYZ(f,Math.sin(d)*t,0,Math.cos(d)*t),g.setXYZ(f+1,Math.sin(Math.min(d+_,v))*t,0,Math.cos(Math.min(d+_,v))*t),g.setXYZ(f+2,0,0,0),u+=3;p.addGroup(c,u,y),c+=u,u=0}m(-l,-a,s,0),m(-a,a,i,1),m(a,l,s,0),g.needsUpdate=!0,r===o&&(this.material[0].visible=!1)}dispose(){this.geometry.dispose(),this.material[0].dispose(),this.material[1].dispose()}}var iK=Object.defineProperty,nK=Object.getOwnPropertyDescriptor,fh=(n,e,t,i)=>{for(var s=i>1?void 0:i?nK(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&iK(e,t,s),s};const ys=oe("debugaudio");var pg;const Vn=(pg=class extends Ce{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||Iu())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":ys&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,Vn._userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&Vn._userInteractionRegistered&&this.wasPlaying&&this.play();break}});h(this,"onApplicationMuteChanged",()=>{var e,t;this.context.application.muted?(e=this.sound)==null||e.setVolume(0):(t=this.sound)==null||t.setVolume(this.volume)});h(this,"lerp",(e,t,i)=>e*(1-i)+t*i);h(this,"_lastContextTime",0);h(this,"_hasEnded",!0);h(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return Vn._didCallBeginWaitForUserInteraction||(Vn._didCallBeginWaitForUserInteraction=!0,Vn._beginWaitForUserInteraction()),Vn._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),Vn._didCallBeginWaitForUserInteraction||(Vn._didCallBeginWaitForUserInteraction=!0,Vn._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);const i=(()=>{if(i!=null&&!Vn._userInteractionRegistered){Vn._userInteractionRegistered=!0,ys&&console.log("🔊 registered interaction, can play audio now"),document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i);for(const s of this.callbacks)s();this.callbacks.length=0}}).bind(this);document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(ys&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}get Sound(){if(!this.sound&&Vn._userInteractionRegistered){const e=Z.getComponent(this.context.mainCamera,Ff)??Z.findObjectOfType(Ff,this.context);e!=null&&e.listener&&(this.sound=new uO(e.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}awake(){this.audioLoader=new X0,this.playOnAwake&&(this.shouldPlay=!0)}onEnable(){Vn._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Vn._beginWaitForUserInteraction(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.loadAndPlay(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(ab.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(ab.MuteChanged,this.onApplicationMuteChanged),this.stop()}onLoaded(e){ys&&console.log("audio buffer loaded"),Vn.registerWaitForAllowAudio(()=>{ys&&console.log("finished loading",e);const t=this.Sound;if(!t){console.warn("Failed getting sound",this.name);return}t.isPlaying&&t.stop(),t.setBuffer(e),t.loop=this._loop,this.context.application.muted?t.setVolume(0):t.setVolume(this.volume),t.autoplay=this.shouldPlay,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),ys&&console.log(this.name,this.shouldPlay,Vn.userInteractionRegistered,this),this.shouldPlay&&Vn._userInteractionRegistered&&this.play()})}applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const t=this.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(ys&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break}this.spatialBlend>0?ys&&!this.helper&&(this.helper=new tK(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&(ys&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new X0),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){ys&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,ys&&console.log("load audio",this.clip),this.audioLoader.load(this.clip,this.onLoaded.bind(this),()=>{},console.error)}}play(e=void 0){var t;if(!this.audioLoader||!this.sound||e&&e!==this.clip){this.loadAndPlay(e);return}if(this.shouldPlay=!0,this._hasEnded=!1,ys&&console.log("play",(t=this.sound)==null?void 0:t.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const i=this.context.application.muted;i&&this.sound.setVolume(0),this.sound.play(i?.1:0)}}pause(){var e;ys&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=(e=this.sound)==null?void 0:e.context.currentTime,this.sound.pause())}stop(){var e;ys&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=(e=this.sound)==null?void 0:e.context.currentTime,ys&&console.log(this._lastContextTime),this.sound.stop())}get isPlaying(){var e;return((e=this.sound)==null?void 0:e.isPlaying)??!1}set isPlaying(e){}get time(){var e,t;return(e=this.sound)!=null&&e.source?((t=this.sound.source)==null?void 0:t.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;const t=this.isPlaying;this.stop(),this.sound.offset=e,t&&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,ys&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},h(pg,"_didCallBeginWaitForUserInteraction",!1),h(pg,"callbacks",[]),h(pg,"_userInteractionRegistered",!1),pg);let wn=Vn;fh([x(URL)],wn.prototype,"clip",2);fh([x()],wn.prototype,"playOnAwake",2);fh([x()],wn.prototype,"loop",1);fh([x()],wn.prototype,"spatialBlend",1);fh([x()],wn.prototype,"minDistance",1);fh([x()],wn.prototype,"maxDistance",1);fh([x()],wn.prototype,"volume",1);fh([x()],wn.prototype,"rollOffMode",2);var sK=Object.defineProperty,rK=Object.getOwnPropertyDescriptor,oK=(n,e,t,i)=>{for(var s=i>1?void 0:i?rK(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&sK(e,t,s),s};class UA extends Ce{constructor(){super(...arguments);h(this,"constraintActive",!0);h(this,"locked",!1);h(this,"sources",[])}}oK([x(Ie)],UA.prototype,"sources",2);const LB={type:"change"},$w={type:"start"},FB={type:"end"};let aK=class extends Nn{constructor(e,t){super(),this.object=e,this.domElement=t,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:zh.ROTATE,MIDDLE:zh.DOLLY,RIGHT:zh.PAN},this.touches={ONE:Gh.ROTATE,TWO:Gh.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 a.phi},this.getAzimuthalAngle=function(){return a.theta},this.getDistance=function(){return this.object.position.distanceTo(this.target)},this.listenToKeyEvents=function(O){O.addEventListener("keydown",U),this._domElementKeyEvents=O},this.saveState=function(){i.target0.copy(i.target),i.position0.copy(i.object.position),i.zoom0=i.object.zoom},this.reset=function(){i.target.copy(i.target0),i.object.position.copy(i.position0),i.object.zoom=i.zoom0,i.object.updateProjectionMatrix(),i.dispatchEvent(LB),i.update(),r=s.NONE},this.update=function(){const O=new S,ve=new xe().setFromUnitVectors(e.up,new S(0,1,0)),Ke=ve.clone().invert(),ze=new S,We=new xe,Ue=2*Math.PI;return function(){const Ut=i.object.getWorldPosition(e.position);O.copy(Ut).sub(i.target),O.applyQuaternion(ve),a.setFromVector3(O),i.autoRotate&&r===s.NONE&&P(w()),i.enableDamping?(a.theta+=l.theta*i.dampingFactor,a.phi+=l.phi*i.dampingFactor):(a.theta+=l.theta,a.phi+=l.phi);let Tt=i.minAzimuthAngle,j=i.maxAzimuthAngle;return isFinite(Tt)&&isFinite(j)&&(Tt<-Math.PI?Tt+=Ue:Tt>Math.PI&&(Tt-=Ue),j<-Math.PI?j+=Ue:j>Math.PI&&(j-=Ue),Tt<=j?a.theta=Math.max(Tt,Math.min(j,a.theta)):a.theta=a.theta>(Tt+j)/2?Math.max(Tt,a.theta):Math.min(j,a.theta)),a.phi=Math.max(i.minPolarAngle,Math.min(i.maxPolarAngle,a.phi)),a.makeSafe(),i.enableDamping?u=Hs.lerp(u,c,i.dampingFactor):u=c,a.radius*=u,a.radius=Math.max(i.minDistance,Math.min(i.maxDistance,a.radius)),i.enableDamping===!0?i.target.addScaledVector(d,i.dampingFactor):i.target.add(d),O.setFromSpherical(a),O.applyQuaternion(Ke),Ut.copy(i.target).add(O),i.object.parent?i.object.parent.worldToLocal(Ut):i.object.position.copy(Ut),i.object.lookAt(i.target),i.enableDamping===!0?(l.theta*=1-i.dampingFactor,l.phi*=1-i.dampingFactor,d.multiplyScalar(1-i.dampingFactor)):(l.set(0,0,0),d.set(0,0,0)),c=1,f||ze.distanceToSquared(i.object.position)>o||8*(1-We.dot(i.object.quaternion))>o?(i.dispatchEvent(LB),ze.copy(i.object.position),We.copy(i.object.quaternion),f=!1,!0):!1}}(),this.dispose=function(){i.domElement.removeEventListener("contextmenu",Ee),i.domElement.removeEventListener("pointerdown",Ze),i.domElement.removeEventListener("pointercancel",ht),i.domElement.removeEventListener("wheel",Ft),i.domElement.removeEventListener("pointermove",je),i.domElement.removeEventListener("pointerup",ft),i._domElementKeyEvents!==null&&i._domElementKeyEvents.removeEventListener("keydown",U)};const i=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 o=1e-6,a=new wS,l=new wS;let c=1,u=1;const d=new S;let f=!1;const p=new V,g=new V,m=new V,A=new V,v=new V,b=new V,y=new V,_=new V,C=new V,E=[],T={};function w(){return 2*Math.PI/60/60*i.autoRotateSpeed}function M(){return Math.pow(.95,i.zoomSpeed)}function P(O){l.theta-=O}function k(O){l.phi-=O}const Q=function(){const O=new S;return function(Ke,ze){O.setFromMatrixColumn(ze,0),O.multiplyScalar(-Ke),d.add(O)}}(),z=function(){const O=new S;return function(Ke,ze){i.screenSpacePanning===!0?O.setFromMatrixColumn(ze,1):(O.setFromMatrixColumn(ze,0),O.crossVectors(i.object.up,O)),O.multiplyScalar(Ke),d.add(O)}}(),L=function(){const O=new S,ve=new S;return function(ze,We){const Ue=i.domElement;if(i.object.isPerspectiveCamera){i.object.getWorldPosition(ve),O.copy(ve).sub(i.target);let Rt=O.length();Rt*=Math.tan(i.object.fov/2*Math.PI/180),Q(2*ze*Rt/Ue.clientHeight,i.object.matrixWorld),z(2*We*Rt/Ue.clientHeight,i.object.matrixWorld)}else i.object.isOrthographicCamera?(Q(ze*(i.object.right-i.object.left)/i.object.zoom/Ue.clientWidth,i.object.matrixWorld),z(We*(i.object.top-i.object.bottom)/i.object.zoom/Ue.clientHeight,i.object.matrixWorld)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),i.enablePan=!1)}}();function H(O){i.object.isPerspectiveCamera?c/=O:i.object.isOrthographicCamera?(i.object.zoom=Math.max(i.minZoom,Math.min(i.maxZoom,i.object.zoom*O)),i.object.updateProjectionMatrix(),f=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),i.enableZoom=!1)}function $(O){i.object.isPerspectiveCamera?c*=O:i.object.isOrthographicCamera?(i.object.zoom=Math.max(i.minZoom,Math.min(i.maxZoom,i.object.zoom/O)),i.object.updateProjectionMatrix(),f=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),i.enableZoom=!1)}function J(O){p.set(O.clientX,O.clientY)}function K(O){y.set(O.clientX,O.clientY)}function ue(O){A.set(O.clientX,O.clientY)}function he(O){g.set(O.clientX,O.clientY),m.subVectors(g,p).multiplyScalar(i.rotateSpeed);const ve=i.domElement;P(2*Math.PI*m.x/ve.clientHeight),k(2*Math.PI*m.y/ve.clientHeight),p.copy(g),i.update()}function Re(O){_.set(O.clientX,O.clientY),C.subVectors(_,y),C.y>0?H(M()):C.y<0&&$(M()),y.copy(_),i.update()}function ge(O){v.set(O.clientX,O.clientY),b.subVectors(v,A).multiplyScalar(i.panSpeed),L(b.x,b.y),A.copy(v),i.update()}function ie(O){O.deltaY<0?$(M()):O.deltaY>0&&H(M()),i.update()}function le(O){let ve=!1;switch(O.code){case i.keys.UP:O.ctrlKey||O.metaKey||O.shiftKey?k(2*Math.PI*i.rotateSpeed/i.domElement.clientHeight):L(0,i.keyPanSpeed),ve=!0;break;case i.keys.BOTTOM:O.ctrlKey||O.metaKey||O.shiftKey?k(-2*Math.PI*i.rotateSpeed/i.domElement.clientHeight):L(0,-i.keyPanSpeed),ve=!0;break;case i.keys.LEFT:O.ctrlKey||O.metaKey||O.shiftKey?P(2*Math.PI*i.rotateSpeed/i.domElement.clientHeight):L(i.keyPanSpeed,0),ve=!0;break;case i.keys.RIGHT:O.ctrlKey||O.metaKey||O.shiftKey?P(-2*Math.PI*i.rotateSpeed/i.domElement.clientHeight):L(-i.keyPanSpeed,0),ve=!0;break}ve&&(O.preventDefault(),i.update())}function we(){if(E.length===1)p.set(E[0].pageX,E[0].pageY);else{const O=.5*(E[0].pageX+E[1].pageX),ve=.5*(E[0].pageY+E[1].pageY);p.set(O,ve)}}function W(){if(E.length===1)A.set(E[0].pageX,E[0].pageY);else{const O=.5*(E[0].pageX+E[1].pageX),ve=.5*(E[0].pageY+E[1].pageY);A.set(O,ve)}}function Fe(){const O=E[0].pageX-E[1].pageX,ve=E[0].pageY-E[1].pageY,Ke=Math.sqrt(O*O+ve*ve);y.set(0,Ke)}function Be(){i.enableZoom&&Fe(),i.enablePan&&W()}function qe(){i.enableZoom&&Fe(),i.enableRotate&&we()}function be(O){if(E.length==1)g.set(O.pageX,O.pageY);else{const Ke=He(O),ze=.5*(O.pageX+Ke.x),We=.5*(O.pageY+Ke.y);g.set(ze,We)}m.subVectors(g,p).multiplyScalar(i.rotateSpeed);const ve=i.domElement;P(2*Math.PI*m.x/ve.clientHeight),k(2*Math.PI*m.y/ve.clientHeight),p.copy(g)}function lt(O){if(E.length===1)v.set(O.pageX,O.pageY);else{const ve=He(O),Ke=.5*(O.pageX+ve.x),ze=.5*(O.pageY+ve.y);v.set(Ke,ze)}b.subVectors(v,A).multiplyScalar(i.panSpeed),L(b.x,b.y),A.copy(v)}function pe(O){const ve=He(O),Ke=O.pageX-ve.x,ze=O.pageY-ve.y,We=Math.sqrt(Ke*Ke+ze*ze);_.set(0,We),C.set(0,Math.pow(_.y/y.y,i.zoomSpeed)),H(C.y),y.copy(_)}function fe(O){i.enableZoom&&pe(O),i.enablePan&<(O)}function ke(O){i.enableZoom&&pe(O),i.enableRotate&&be(O)}function Ze(O){i.enabled!==!1&&(E.length===0&&(i.domElement.addEventListener("pointermove",je),i.domElement.addEventListener("pointerup",ft)),De(O),O.pointerType==="touch"?D(O):st(O))}function je(O){i.enabled!==!1&&(O.pointerType==="touch"?ce(O):Wt(O))}function ft(O){Ve(O),E.length===0&&(i.domElement.removeEventListener("pointermove",je),i.domElement.removeEventListener("pointerup",ft)),i.dispatchEvent(FB),r=s.NONE}function ht(O){Ve(O)}function st(O){let ve;switch(O.button){case 0:ve=i.mouseButtons.LEFT;break;case 1:ve=i.mouseButtons.MIDDLE;break;case 2:ve=i.mouseButtons.RIGHT;break;default:ve=-1}switch(ve){case zh.DOLLY:if(i.enableZoom===!1)return;K(O),r=s.DOLLY;break;case zh.ROTATE:if(O.ctrlKey||O.metaKey||O.shiftKey){if(i.enablePan===!1)return;ue(O),r=s.PAN}else{if(i.enableRotate===!1)return;J(O),r=s.ROTATE}break;case zh.PAN:if(O.ctrlKey||O.metaKey||O.shiftKey){if(i.enableRotate===!1)return;J(O),r=s.ROTATE}else{if(i.enablePan===!1)return;ue(O),r=s.PAN}break;default:r=s.NONE}r!==s.NONE&&i.dispatchEvent($w)}function Wt(O){switch(r){case s.ROTATE:if(i.enableRotate===!1)return;he(O);break;case s.DOLLY:if(i.enableZoom===!1)return;Re(O);break;case s.PAN:if(i.enablePan===!1)return;ge(O);break}}function Ft(O){i.enabled===!1||i.enableZoom===!1||r!==s.NONE||(O.preventDefault(),i.dispatchEvent($w),ie(O),i.dispatchEvent(FB))}function U(O){i.enabled===!1||i.enablePan===!1||le(O)}function D(O){switch(ct(O),E.length){case 1:switch(i.touches.ONE){case Gh.ROTATE:if(i.enableRotate===!1)return;we(),r=s.TOUCH_ROTATE;break;case Gh.PAN:if(i.enablePan===!1)return;W(),r=s.TOUCH_PAN;break;default:r=s.NONE}break;case 2:switch(i.touches.TWO){case Gh.DOLLY_PAN:if(i.enableZoom===!1&&i.enablePan===!1)return;Be(),r=s.TOUCH_DOLLY_PAN;break;case Gh.DOLLY_ROTATE:if(i.enableZoom===!1&&i.enableRotate===!1)return;qe(),r=s.TOUCH_DOLLY_ROTATE;break;default:r=s.NONE}break;default:r=s.NONE}r!==s.NONE&&i.dispatchEvent($w)}function ce(O){switch(ct(O),r){case s.TOUCH_ROTATE:if(i.enableRotate===!1)return;be(O),i.update();break;case s.TOUCH_PAN:if(i.enablePan===!1)return;lt(O),i.update();break;case s.TOUCH_DOLLY_PAN:if(i.enableZoom===!1&&i.enablePan===!1)return;fe(O),i.update();break;case s.TOUCH_DOLLY_ROTATE:if(i.enableZoom===!1&&i.enableRotate===!1)return;ke(O),i.update();break;default:r=s.NONE}}function Ee(O){i.enabled!==!1&&O.preventDefault()}function De(O){E.push(O)}function Ve(O){delete T[O.pointerId];for(let ve=0;ve<E.length;ve++)if(E[ve].pointerId==O.pointerId){E.splice(ve,1);return}}function ct(O){let ve=T[O.pointerId];ve===void 0&&(ve=new V,T[O.pointerId]=ve),ve.set(O.pageX,O.pageY)}function He(O){const ve=O.pointerId===E[0].pointerId?E[1]:E[0];return T[ve.pointerId]}i.domElement.addEventListener("contextmenu",Ee),i.domElement.addEventListener("pointerdown",Ze),i.domElement.addEventListener("pointercancel",ht),i.domElement.addEventListener("wheel",Ft,{passive:!1}),this.update()}};class lK{static createButton(e,t={},i){const s=document.createElement("button");let r=!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(){p.end()}),u.appendChild(d);var f=document.createElementNS("http://www.w3.org/2000/svg","path");f.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),f.setAttribute("stroke","#fff"),f.setAttribute("stroke-width",2),d.appendChild(f),t.optionalFeatures.push("dom-overlay"),t.domOverlay={root:u},r=!0}let p=null,g=null;async function m(v){var _;const b=/WebXRViewer\//i.test(navigator.userAgent),y=t.domOverlay.root;b&&((_=t.domOverlay)!=null&&_.root?(g=y.parentNode,g&&(console.log("Reparent DOM Overlay to body",y,y.style.display),y.style.display="",y.style.visibility="",document.body.appendChild(y))):console.warn("WebXRViewer: No DOM Overlay found")),v.addEventListener("end",A),await e.xr.setSession(v),s.textContent="STOP AR",r&&(t.domOverlay.root.style.display=""),p=v}function A(){p.removeEventListener("end",A),s.textContent="START AR";const v=t.domOverlay.root;g&&g.appendChild(v),r&&(v.style.display="none"),p=null}s.style.display="",s.style.cursor="pointer",s.style.left="calc(50% - 50px)",s.style.width="100px",s.textContent="START AR",s.onmouseenter=function(){s.style.opacity="1.0"},s.onmouseleave=function(){s.style.opacity="0.5"},s.onclick=function(){p===null?(i==null||i.call(this,t),navigator.xr.requestSession("immersive-ar",t).then(m)):p.end()}}function a(){s.disabled=!0,s.style.display="",s.style.cursor="auto",s.style.left="calc(50% - 75px)",s.style.width="150px",s.onmouseenter=null,s.onmouseleave=null,s.onclick=null}function l(){a(),s.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 s.id="ARButton",s.style.display="none",c(s),navigator.xr.isSessionSupported("immersive-ar").then(function(u){u?o():l()}).catch(l),s;{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 kb=class{static createButton(e,t){const i=document.createElement("button");function s(){let l=null;async function c(d){d.addEventListener("end",u),await e.xr.setSession(d),i.textContent="EXIT VR",l=d}function u(){l.removeEventListener("end",u),i.textContent="ENTER VR",l=null}i.style.display="",i.style.cursor="pointer",i.style.left="calc(50% - 50px)",i.style.width="100px",i.textContent="ENTER VR",i.onmouseenter=function(){i.style.opacity="1.0"},i.onmouseleave=function(){i.style.opacity="0.5"},i.onclick=function(){if(l===null){const d={optionalFeatures:t.optionalFeatures};navigator.xr.requestSession("immersive-vr",d).then(c)}else l.end()}}function r(){i.disabled=!0,i.style.display="",i.style.cursor="auto",i.style.left="calc(50% - 75px)",i.style.width="150px",i.onmouseenter=null,i.onmouseleave=null,i.onclick=null}function o(){r(),i.textContent="VR NOT SUPPORTED"}function a(l){l.style.position="absolute",l.style.bottom="20px",l.style.padding="12px 6px",l.style.border="1px solid #fff",l.style.borderRadius="4px",l.style.background="rgba(0,0,0,0.1)",l.style.color="#fff",l.style.font="normal 13px sans-serif",l.style.textAlign="center",l.style.opacity="0.5",l.style.outline="none",l.style.zIndex="999"}if("xr"in navigator)return i.id="VRButton",i.style.display="none",a(i),navigator.xr.isSessionSupported("immersive-vr").then(function(l){l?s():o(),kb.xrSessionIsGranted&&(console.log("XR session is granted - will enter immersive web now"),i.click())}),i;{const l=document.createElement("a");return window.isSecureContext===!1?(l.href=document.location.href.replace(/^http:/,"https:"),l.innerHTML="WEBXR NEEDS HTTPS"):(l.href="https://immersiveweb.dev/",l.innerHTML="WEBXR NOT AVAILABLE"),l.style.left="calc(50% - 90px)",l.style.width="180px",l.style.textDecoration="none",a(l),l}}static registerSessionGrantedListener(){if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent))return;navigator.xr.addEventListener("sessiongranted",()=>{kb.xrSessionIsGranted=!0})}}};let Kg=kb;h(Kg,"xrSessionIsGranted",!1);Kg.registerSessionGrantedListener();const mb="noVoip",or=oe("debugvoip"),cK=oe("voip");class hK{constructor(e){h(this,"id");this.id=e}}class uK{constructor(e,t,i,s){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=i,this.peerId=s}close(){var e;or&&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 i;if(!this.stream)return;const t=(i=this.stream)==null?void 0:i.getAudioTracks();for(const s of t)s.enabled=!e}async startVoipCall(){if(!await Jl.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}or&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),or&&console.log(this.stream),this.call=this.peer.call(this.peerId,this.stream,{metadata:{userId:this.userId}}),this.call.on("error",t=>{console.error(t)}),this.call.on("stream",t=>{or&&console.log("received stream from remote again",t)}),this.peer.on("close",this.onCallClose.bind(this)),this.callErrorListener=t=>{var i;t.message.includes(this.peerId)?(console.log("Could not connect to "+this.peerId),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.close(),(i=this.stream)==null||i.getTracks().forEach(function(s){s.stop()}),this.stream=null):console.error(t)},this.peer.on("error",this.callErrorListener)}onCallClose(e){or&&console.log("call closed",e)}}class dK{constructor(e,t,i){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=i}get currentStream(){return this.stream}get currentAudio(){return this.audio}get currentAnalyzer(){return this.analyzer}openAudioStream(e){const t=e.getAudioTracks();for(const i of t)if(i.kind==="audio"&&i.readyState==="live"){this.open(i);return}console.warn("failed finding valid audio stream to begin call")}open(e){console.assert(e.kind==="audio","invalid track kind, expected audio but received "+e.kind),!this.waitingForStart&&(this.waitingForStart=!0,wn.userInteractionRegistered||or&&console.log("Incoming call, waiting for user interaction before opening audio"),wn.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){or&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);const t=new B1;this.audio=new c_(t),this.audio.setVolume(this.voip.muteInput?0:1),this.audio.setMediaStreamSource(this.stream);const i=document.createElement("audio");this.audioElement=i,i.style.display="none",document.body.appendChild(i),i.srcObject=this.stream,i.sinkId!==void 0&&navigator.mediaDevices.enumerateDevices().then(s=>{if(i){console.log(s);for(const r of s)if(r.label==="Speakerphone"){i.sinkId=r.deviceId;break}}}),or&&console.log("call is setup, you should hear something now"),this.analyzer=new dO(this.audio,32)}}))}close(){var e,t,i;this.closed=!0,(e=this.call)!=null&&e.open&&this.call.close(),(t=this.audio)==null||t.disconnect(),(i=this.stream)==null||i.getTracks().forEach(s=>{s.stop()}),this.stream=null,this.audioElement&&this.audioElement.remove()}}class Jl extends Ce{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(t){var s;if(t===this._inputMuted||(this._inputMuted=t,!this.currentIncomingCalls))return;const i=this._inputMuted?0:1;for(const r in this.currentIncomingCalls){const o=this.currentIncomingCalls[r];(s=o==null?void 0:o.currentAudio)==null||s.setVolume(i)}}get muteInput(){return this._inputMuted}set muteOutput(t){if(t!==this._outputMuted&&(this._outputMuted=t,!!this.connections))for(const i in this.connections){const s=this.connections[i];s==null||s.updateMute(t)}}get muteOutput(){return this._outputMuted}getFrequency(t){if(t===null){for(const s in this.currentIncomingCalls){const r=this.currentIncomingCalls[s];if(r&&r.currentAnalyzer)return r.currentAnalyzer.getAverageFrequency()}return null}const i=this.currentIncomingCalls[t];return i&&i.currentAnalyzer?i.currentAnalyzer.getAverageFrequency():null}awake(){if(oe(mb)){console.log("VOIP is disabled by url parameter: "+mb);return}if(this.requireParam&&!cK){console.debug("VOIP must be enabled explicitly by url parameter");return}if(fm()&&pl()){console.log("VOIP is currently not supported on Safari iOS");return}this.peer=new ib,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,this.context.connection.beginListen($i.JoinedRoom,t=>{navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}),this.context.connection.beginListen("peer-update-id",t=>{if(t.id!==this.context.connection.connectionId){const i=this.connections[t.id];if(i&&i.close(),this.peer&&this.context.connection.connectionId){const s=new uK(this,this.peer,this.context.connection.connectionId,t.peerId);this.connections[t.id]=s,s.startVoipCall()}}}),this.context.connection.beginListen($i.UserLeftRoom,t=>{const{userId:i}=t,s=this.connections[i];this.connections[i]=null,s&&s.close();const r=this.currentIncomingCalls[i];or&&console.log("UserLeftRoom",t,i,r),r&&(r.close(),this.currentIncomingCalls[i]=null)}),this.peer.on("open",this.onOpenPeerConnection.bind(this))}onEnable(){}onDisable(){console.log("TODO: close all");for(const t in this.currentIncomingCalls)try{const i=this.currentIncomingCalls[t];i==null||i.close();const s=this.connections[t];s==null||s.close()}catch(i){console.error(i)}}async onOpenPeerConnection(t){or&&console.log("Peer connection established and received id"),this.model=new hK(t),this.context.connection.send("peer-update-id",this.model,rr.OnRoomJoin),this.peer&&(this.peer.on("call",this.onReceiveCall.bind(this)),this.peer.on("connection",function(i){or&&console.log("CONNECTION",i),i.on("data",function(s){or&&console.log("Received",s)})}))}async onReceiveCall(t){const{metadata:i}=t;console.assert(i.userId);const{userId:s}=i,r=this.currentIncomingCalls[s];if(r&&r.close(),or&&console.log("received call"),await Jl.HasMicrophonePermissions()){const o=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});t.answer(o)}else t.answer(null);this.currentIncomingCalls[s]=new dK(this,this.gameObject,t),t.on("stream",o=>{var a;or&&console.log("receive caller stream, will setup audio now"),(a=this.currentIncomingCalls[s])==null||a.openAudioStream(o)}),t.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}}var fK=Object.defineProperty,pK=Object.getOwnPropertyDescriptor,hU=(n,e,t,i)=>{for(var s=i>1?void 0:i?pK(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&fK(e,t,s),s};class ph extends Ce{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 t;return(t=this.webAR)==null?void 0:t.webxr.Rig}get arScale(){return this._arScale}set arScale(t){t!==this._arScale&&(this._arScale=t,this.setScale(t))}start(){const t=Z.findObjectOfType(Ct);t&&(t.Rig.updateMatrix(),this._initalMatrix.copy(t.Rig.matrix))}onBegin(t){var i;this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose=this.gameObject.matrix.clone(),this._rigStartPose=(i=this.rig)==null?void 0:i.matrix.clone(),this._gotFirstHitTestResult=!1,t.addEventListener("selectstart",this._selectStartFn),t.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(t,i,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(t,r),!0}return!1}placeAt(t,i){this._placementPose||(this._placementPose=new Pe),this._placementPose.copy(i);const s=this.gameObject.matrixWorld.clone().invert();if(this._placementPose.premultiply(s),t){if(this.invertForward){const r=new Pe().makeRotationY(Math.PI);this._placementPose.premultiply(r)}this._rig=t,this.setScale(this.arScale)}else this._rig=null;this.gameObject.visible=!0}onEnd(t,i){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose&&this.gameObject.matrix.copy(this._startPose),t&&(t.matrixAutoUpdate=!0,this._rigStartPose&&this._rigStartPose.decompose(t.position,t.quaternion,t.scale)),cr.markDirty(this.gameObject,!0),setTimeout(()=>{this.gameObject.matrixAutoUpdate=!0,this.gameObject.visible=!0},100)}onSelectStart(){this._isTouching=!0}onSelectEnd(){this._isTouching=!1}setScale(t){const i=this._rig;!i||!this._placementPose||(this._rigStartPose||(this._rigStartPose=i.matrix.clone()),i.matrixAutoUpdate=!1,i.matrix.multiplyMatrices(new Pe().makeScale(t,t,t),this._placementPose),i.matrix.decompose(i.position,i.quaternion,i.scale),i.updateMatrixWorld(),console.log("Place",i.position))}}hU([x()],ph.prototype,"invertForward",2);hU([x()],ph.prototype,"arScale",1);const gK="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/";class mK{constructor(e,t,i,s,r=null){this.controller=t,this.handModel=e,this.bones=[],r===null&&(r=new ep,r.setPath(i||gK)),r.load(`${s}.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(u=>{const d=a.getObjectByName(u);d!==void 0?d.jointName=u:console.warn(`Couldn't find ${u} in ${s} hand mesh`),this.bones.push(d)})})}updateMesh(){const e=this.controller.joints;for(let t=0;t<this.bones.length;t++){const i=this.bones[t];if(i){const s=e[i.jointName];if(s.visible){const r=s.position;i.position.copy(r),i.quaternion.copy(s.quaternion)}}}}}const AK=.01,vK="index-finger-tip";class yK extends Ie{constructor(e,t=null){super(),this.controller=e,this.motionController=null,this.envMap=null,this.loader=t,this.mesh=null,e.addEventListener("connected",i=>{const s=i.data;s.hand&&!this.motionController&&(this.xrInputSource=s,this.motionController=new mK(this,e,this.path,s.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[vK];return e?e.position:null}intersectBoxObject(e){const t=this.getPointerPosition();if(t){const i=new Zo(t,AK),s=new Cs().setFromObject(e);return i.intersectsBox(s)}else return!1}checkButton(e){this.intersectBoxObject(e)?e.onPress():e.onClear(),e.isPressed()&&e.whilePressed()}}const bK=.05,UB=.02,wy=.01,NB=.02,zB=1,Ed=.4,_K=.002,ig=.01,Cy=.003,GB=.035,yi=16,Jr=12,eC=110,xK=new S(0,1,0),wK=new S(0,0,1),CK=.02,SK=1.5;class EK extends Ie{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",i=>{const s=i.data;s.hand&&(this.visible=!0,this.xrInputSource=s,this.pointerObject===null&&this.createPointer())})}_drawVerticesRing(e,t,i){const s=t.clone();for(let r=0;r<yi;r++){s.applyAxisAngle(wK,Math.PI*2/yi);const o=i*yi+r;e[3*o]=s.x,e[3*o+1]=s.y,e[3*o+2]=s.z}}_updatePointerVertices(e){const t=this.pointerGeometry.attributes.position.array,i=new S(_K,0,-1*(GB-e));this._drawVerticesRing(t,i,0);const s=new S(Math.sin(Math.PI*eC/180)*e,Math.cos(Math.PI*eC/180)*e,0);for(let c=0;c<Jr;c++)this._drawVerticesRing(t,s,c+1),s.applyAxisAngle(xK,Math.PI*eC/180/(Jr*-2));const r=yi*(1+Jr),o=yi*(1+Jr)+1,a=new S(0,0,-1*(GB-e));t[r*3]=a.x,t[r*3+1]=a.y,t[r*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 nt(t,3))}createPointer(){let e,t;const i=new Array(((Jr+1)*yi+2)*3).fill(0),s=[];for(this.pointerGeometry=new At,this.pointerGeometry.setAttribute("position",new nt(i,3)),this._updatePointerVertices(ig),e=0;e<Jr;e++){for(t=0;t<yi-1;t++)s.push(e*yi+t,e*yi+t+1,(e+1)*yi+t),s.push(e*yi+t+1,(e+1)*yi+t+1,(e+1)*yi+t);s.push((e+1)*yi-1,e*yi,(e+2)*yi-1),s.push(e*yi,(e+1)*yi,(e+2)*yi-1)}const r=yi*(1+Jr),o=yi*(1+Jr)+1;for(e=0;e<yi-1;e++)s.push(r,e+1,e),s.push(o,e+yi*Jr,e+yi*Jr+1);s.push(r,0,yi-1),s.push(o,yi*(Jr+1)-1,yi*Jr);const a=new vi;a.transparent=!0,a.opacity=Ed,this.pointerGeometry.setIndex(s),this.pointerMesh=new me(this.pointerGeometry,a),this.pointerMesh.position.set(0,0,-1*ig),this.pointerObject=new Ie,this.pointerObject.add(this.pointerMesh),this.raycaster=new qf;const l=new Gr(CK,10,10),c=new vi;c.transparent=!0,c.opacity=Ed,this.cursorObject=new me(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"],i=e.position.distanceTo(t.position),s=e.position.clone().add(t.position).multiplyScalar(.5);this.pointerObject.position.copy(s),this.pointerObject.quaternion.copy(this.controller.quaternion),this.pinched=i<=UB;const r=(i-wy)/(bK-wy),o=(i-wy)/(UB-wy);if(r>1)this._updatePointerVertices(ig),this.pointerMesh.position.set(0,0,-1*ig),this.pointerMesh.material.opacity=Ed;else if(r>0){const a=(ig-Cy)*r+Cy;this._updatePointerVertices(a),o<1?(this.pointerMesh.position.set(0,0,-1*a-(1-o)*NB),this.pointerMesh.material.opacity=Ed+(1-o)*(zB-Ed)):(this.pointerMesh.position.set(0,0,-1*a),this.pointerMesh.material.opacity=Ed)}else this._updatePointerVertices(Cy),this.pointerMesh.position.set(0,0,-1*Cy-NB),this.pointerMesh.material.opacity=zB;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 i=this.raycaster.intersectObjects(e,t),s=new S(0,0,-1);if(i.length>0){const o=i[0].distance;this.cursorObject.position.copy(s.multiplyScalar(o))}else this.cursorObject.position.copy(s.multiplyScalar(SK))}}setCursor(e){const t=new S(0,0,-1);this.raycaster&&!this.attached&&this.cursorObject.position.copy(t.multiplyScalar(e))}}const Ki={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 uU(n){const e=await fetch(n);if(e.ok)return e.json();throw new Error(e.statusText)}async function IK(n){if(!n)throw new Error("No basePath supplied");return await uU(`${n}/profilesList.json`)}async function MK(n,e,t=null,i=!0){if(!n)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No basePath supplied");const s=await IK(e);let r;if(n.profiles.some(l=>{const c=s[l];return c&&(r={profileId:l,profilePath:`${e}/${c.path}`,deprecated:!!c.deprecated}),!!r}),!r){if(!t)throw new Error("No matching profile name found");const l=s[t];if(!l)throw new Error(`No matching profile name found and default profile "${t}" missing.`);r={profileId:t,profilePath:`${e}/${l.path}`,deprecated:!!l.deprecated}}const o=await uU(r.profilePath);let a;if(i){let l;if(n.handedness==="any"?l=o.layouts[Object.keys(o.layouts)[0]]:l=o.layouts[n.handedness],!l)throw new Error(`No matching handedness, ${n.handedness}, in profile ${r.profileId}`);l.assetPath&&(a=r.profilePath.replace("profile.json",l.assetPath))}return{profile:o,assetPath:a}}const TK={xAxis:0,yAxis:0,button:0,state:Ki.ComponentState.DEFAULT};function PK(n=0,e=0){let t=n,i=e;if(Math.sqrt(n*n+e*e)>1){const o=Math.atan2(e,n);t=Math.cos(o),i=Math.sin(o)}return{normalizedXAxis:t*.5+.5,normalizedYAxis:i*.5+.5}}class RK{constructor(e){this.componentProperty=e.componentProperty,this.states=e.states,this.valueNodeName=e.valueNodeName,this.valueNodeProperty=e.valueNodeProperty,this.valueNodeProperty===Ki.VisualResponseProperty.TRANSFORM&&(this.minNodeName=e.minNodeName,this.maxNodeName=e.maxNodeName),this.value=0,this.updateFromComponent(TK)}updateFromComponent({xAxis:e,yAxis:t,button:i,state:s}){const{normalizedXAxis:r,normalizedYAxis:o}=PK(e,t);switch(this.componentProperty){case Ki.ComponentProperty.X_AXIS:this.value=this.states.includes(s)?r:.5;break;case Ki.ComponentProperty.Y_AXIS:this.value=this.states.includes(s)?o:.5;break;case Ki.ComponentProperty.BUTTON:this.value=this.states.includes(s)?i:0;break;case Ki.ComponentProperty.STATE:this.valueNodeProperty===Ki.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(s):this.value=this.states.includes(s)?1:0;break;default:throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}}class BK{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(i=>{const s=new RK(t.visualResponses[i]);this.visualResponses[i]=s}),this.gamepadIndices=Object.assign({},t.gamepadIndices),this.values={state:Ki.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=Ki.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=Ki.ComponentState.PRESSED:(t.touched||this.values.button>Ki.ButtonTouchThreshold)&&(this.values.state=Ki.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===Ki.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>Ki.AxisTouchThreshold&&(this.values.state=Ki.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===Ki.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>Ki.AxisTouchThreshold&&(this.values.state=Ki.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(t=>{t.updateFromComponent(this.values)})}}class DK{constructor(e,t,i){if(!e)throw new Error("No xrInputSource supplied");if(!t)throw new Error("No profile supplied");this.xrInputSource=e,this.assetUrl=i,this.id=t.profileId,this.layoutDescription=t.layouts[e.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(s=>{const r=this.layoutDescription.components[s];this.components[s]=new BK(s,r)}),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 kK="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",OK="generic-trigger";class LK extends Ie{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(i=>{const{valueNode:s,minNode:r,maxNode:o,value:a,valueNodeProperty:l}=i;s&&(l===Ki.VisualResponseProperty.VISIBILITY?s.visible=a:l===Ki.VisualResponseProperty.TRANSFORM&&(s.quaternion.slerpQuaternions(r.quaternion,o.quaternion,a),s.position.lerpVectors(r.position,o.position,a)))})}))}}function FK(n,e){Object.values(n.components).forEach(t=>{const{type:i,touchPointNodeName:s,visualResponses:r}=t;if(i===Ki.ComponentType.TOUCHPAD)if(t.touchPointNode=e.getObjectByName(s),t.touchPointNode){const o=new Gr(.001),a=new vi({color:255}),l=new me(o,a);t.touchPointNode.add(l)}else console.warn(`Could not find touch dot, ${t.touchPointNodeName}, in touchpad component ${t.id}`);Object.values(r).forEach(o=>{const{valueNodeName:a,minNodeName:l,maxNodeName:c,valueNodeProperty:u}=o;if(u===Ki.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 QB(n,e){FK(n.motionController,e),n.envMap&&e.traverse(t=>{t.isMesh&&(t.material.envMap=n.envMap,t.material.needsUpdate=!0)}),n.layers.mask!=0&&e.traverse(t=>{t.layers.mask=n.layers.mask}),n.add(e)}class UK{constructor(e=null){this.gltfLoader=e,this.path=kK,this._assetCache={},this.gltfLoader||(this.gltfLoader=new ep)}createControllerModel(e){const t=new LK;let i=null;return e.addEventListener("connected",s=>{const r=s.data;r.targetRayMode!=="tracked-pointer"||!r.gamepad||MK(r,this.path,OK).then(({profile:o,assetPath:a})=>{t.motionController=new DK(r,o,a);const l=this._assetCache[t.motionController.assetUrl];if(l)i=l.scene.clone(),QB(t,i);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,i=c.scene.clone(),QB(t,i)},null,()=>{throw new Error(`Asset ${t.motionController.assetUrl} missing or malformed.`)})}}).catch(o=>{console.warn(o)})}),e.addEventListener("disconnected",()=>{t.motionController=null,t.remove(i),i=null}),t}}const ng=oe("debugavatar");class G_{constructor(e,t,i,s){h(this,"root");h(this,"head");h(this,"leftHand");h(this,"rigthHand");var r;this.root=e,this.head=t,this.leftHand=i,this.rigthHand=s,(r=this.root)==null||r.traverse(o=>o.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class Q_{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 i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){const r=new Oa;i=Z.instantiate(Af(t,e.scene),r)}}else i=t;if(!i)return null;const s=this.findAvatar(i);return s.isValid?(ng&&console.log("[Custom Avatar] valid config",t,ng?s:""),s):(console.warn("[Custom Avatar] config isn't valid",t,ng?s:""),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(ng&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const s=await fetch("./"+t);let r=null;if(s.ok){const a=await s.blob();a&&(r=await a.arrayBuffer())}if(!r&&(r=await oI(t,t,0,"no url here go away",!0),!r))return null;const o=await Yo().parseSync(e,r,null,0);return(o==null?void 0:o.scene)??null}const i=new ep;return RA(i,e),new Promise((s,r)=>{const o=this.avatarRegistryUrl+"/"+t;i.load(o,async a=>{await Yo().createBuiltinComponents(e,o,a,null,void 0),s(a.scene)},a=>{ng&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),s(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let i=t;i.children.length==1&&(i=e.children[0]);let s=this.findAvatarPart(i,["head"]);const r=this.findAvatarPart(i,["left","hand"]),o=this.findAvatarPart(i,["right","hand"]);if(!s){s=t;const l=new S;new Cs().setFromObject(s).getSize(l);const c=Math.max(l.x,l.y,l.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+c+" meters! Should be < 0.3m"),c>.3&&s.scale.multiplyScalar(1/c*.3)}return new G_(t,s,r,o)}findAvatarPart(e,t){const i=e.name.toLowerCase();let s=!0;for(const r of t){if(!s)break;i.indexOf(r)===-1&&(s=!1)}if(s)return e;if(e.children)for(const r of e.children){const o=this.findAvatarPart(r,t);if(o)return o}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}const Ud=oe("debugflags");var vn=(n=>(n[n.Never=0]="Never",n[n.Browser=1]="Browser",n[n.AR=2]="AR",n[n.VR=4]="VR",n[n.FirstPerson=8]="FirstPerson",n[n.ThirdPerson=16]="ThirdPerson",n[n.All=4294967295]="All",n))(vn||{});const mT=class{constructor(){h(this,"Mask",17)}Has(e){return(this.Mask&e)!==0}Set(e){Ud&&console.warn("Set XR flag state to",e),this.Mask=e,as.Apply()}Enable(e){this.Mask|=e,as.Apply()}Disable(e){this.Mask&=~e,as.Apply()}Toggle(e){this.Mask^=e,as.Apply()}EnableAll(){this.Mask=-1,as.Apply()}DisableAll(){this.Mask=0,as.Apply()}};let mo=mT;h(mo,"Global",new mT);const ga=class extends Ce{constructor(){super(...arguments);h(this,"visibleIn")}static Apply(){for(const t of this.registry)t.UpdateVisible(mo.Global)}awake(){ga.registry.push(this)}onEnable(){ga.firstApply?this.UpdateVisible(mo.Global):(ga.firstApply=!0,ga.Apply())}onDestroy(){const t=ga.registry.indexOf(this);t>=0&&ga.registry.splice(t,1)}get isOn(){return this.gameObject.visible}UpdateVisible(t=null){let i;const s=t;s&&typeof s=="number"&&(console.assert(typeof s=="number","XRFlag.UpdateVisible: state must be a number",s),Ud&&console.log(s),ga.buffer.Mask=s,t=ga.buffer);const r=t;if(r?(Ud&&console.warn(this.name,"use passed in mask",r.Mask,this.visibleIn),i=r.Has(this.visibleIn)):(Ud&&console.log(this.name,"use global mask"),mo.Global.Has(this.visibleIn)),i!==void 0)if(i)Ud&&console.log(this.name,"is visible",this.gameObject.uuid),Z.setActive(this.gameObject,!0);else{if(Ud&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}};let as=ga;h(as,"registry",[]),h(as,"firstApply"),h(as,"buffer",new mo);const Pc=oe("debugavatar"),Go=class extends Ce{constructor(){super(...arguments);h(this,"connectionId");h(this,"avatar")}static getAvatar(t){return t>=0&&t<Go.instances.length?Go.instances[t]:null}static onAvatarMarkerCreated(t){return Go._onNewAvatarMarkerAdded.push(t),t}static onAvatarMarkerDestroyed(t){return Go._onAvatarMarkerDestroyed.push(t),t}awake(){Go.instances.push(this),Pc&&console.log(this);for(const t of Go._onNewAvatarMarkerAdded)t({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Go.instances.splice(Go.instances.indexOf(this),1);for(const t of Go._onAvatarMarkerDestroyed)t({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}setVisible(t){this.avatar&&("setVisible"in this.avatar?this.avatar.setVisible(t):Z.setActive(this.avatar,t))}};let Yn=Go;h(Yn,"instances",[]),h(Yn,"_onNewAvatarMarkerAdded",[]),h(Yn,"_onAvatarMarkerDestroyed",[]);const lm=class{constructor(e,t,i){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 Ie);h(this,"_handLeftTarget",new Ie);h(this,"_handRightTarget",new Ie);h(this,"_canInterpolate",!1);this.context=e,this.guid=t,this.webxr=i,this.setupCustomAvatar(this.webxr.defaultAvatar)}setVisible(e){this._isVisible=e,this.updateVisibility()}get isWebXRAvatar(){return!0}updateFlags(){if(!this.flags)return;let e=this.isLocalAvatar?vn.FirstPerson:vn.ThirdPerson;this.context.isInVR?e|=vn.VR:this.context.isInAR?e|=vn.AR:e|=vn.Browser;for(const t of this.flags)t.gameObject.visible=!0,t.UpdateVisible(e)}async setAvatarOverride(e){return this.hasAvatarOverride=e!==null,this.hasAvatarOverride&&this.lastAvatarId!==e&&(this.lastAvatarId=e,e!=null&&e.length>0)?await this.setupCustomAvatar(e):null}tryUpdate(e,t){if(e.guid===this.guid&&(this.lastAvatarId!==e.avatarId&&e.avatarId&&e.avatarId.length>0&&(this.lastAvatarId=e.avatarId,this.setupCustomAvatar(e.avatarId)),this.lastUpdate=e.time,this.head)){const i=this.webxr.IsInAR?Ba.Handheld:Ba.Headset;let s=this.head;this.context.players.setPlayerView(e.guid,s,i),cr.markDirty(this.head),this._canInterpolate=!0;const r=this.isLocalAvatar?this.head:this._headTarget;if(r.position.set(e.position.x,e.position.y,e.position.z),r.quaternion.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),r.scale.set(e.scale,e.scale,e.scale),r.scale.multiply(this.headScale),this.handLeft){const o=this.isLocalAvatar?this.handLeft:this._handLeftTarget;o.position.set(e.posLeftHand.x,e.posLeftHand.y,e.posLeftHand.z),o.quaternion.set(e.rotLeftHand._x,e.rotLeftHand._y,e.rotLeftHand._z,e.rotLeftHand._w),o.quaternion.multiply(lm.invertRotation),o.scale.set(e.scale,e.scale,e.scale),o.scale.multiply(this.handLeftScale),cr.markDirty(this.handLeft)}if(this.handRight){const o=this.isLocalAvatar?this.handRight:this._handRightTarget;o.position.set(e.posRightHand.x,e.posRightHand.y,e.posRightHand.z),o.quaternion.set(e.rotRightHand._x,e.rotRightHand._y,e.rotRightHand._z,e.rotRightHand._w),o.quaternion.multiply(lm.invertRotation),o.scale.set(e.scale,e.scale,e.scale),o.scale.multiply(this.handRightScale),cr.markDirty(this.handRight)}}}update(){if(this.isLocalAvatar||!this._canInterpolate)return;const e=this.context.time.deltaTime/.1;this.head&&(this.head.position.lerp(this._headTarget.position,e),this.head.quaternion.slerp(this._headTarget.quaternion,e),this.head.scale.lerp(this._headTarget.scale,e)),this.handLeft&&this._handLeftTarget&&(this.handLeft.position.lerp(this._handLeftTarget.position,e),this.handLeft.quaternion.slerp(this._handLeftTarget.quaternion,e),this.handLeft.scale.lerp(this._handLeftTarget.scale,e)),this.handRight&&this._handRightTarget&&(this.handRight.position.lerp(this._handRightTarget.position,e),this.handRight.quaternion.slerp(this._handRightTarget.quaternion,e),this.handRight.scale.lerp(this._handRightTarget.scale,e))}destroy(){var e,t;Pc&&console.log("Destroy avatar",this.guid),(e=this.root)==null||e.removeFromParent(),(t=this.avatarMarker)==null||t.destroy(),this.lastAvatarId=null,this.head&&Ws.Remove(this.context,this.head)}updateVisibility(){const e=this.root;e&&Z.setActive(e,this._isVisible)}async setupCustomAvatar(e){var s,r,o;if(Pc&&console.log("LOAD",e,this),!e||typeof e=="string"&&e.length<=0)return!1;this.head&&Ws.Remove(this.context,this.head);const t=e;if((t==null?void 0:t.loadAssetAsync)!==void 0){await t.loadAssetAsync();const a=t.asset;Z.setActive(a,!1),e=Z.instantiate(a),Z.setActive(e,!0)}Pc&&console.log(e);const i=await lm.loader.getOrCreateNewAvatarInstance(this.context,e);if(Pc&&console.log(i,i==null?void 0:i.isValid,this.lastAvatarId,e),i!=null&&i.isValid){if(this.root=i.root,this.root.position.set(0,0,0),this.root.quaternion.set(0,0,0,1),this.root.scale.set(1,1,1),this.avatarMarker=Z.addNewComponent(this.root,Yn),this.avatarMarker.connectionId=this.guid,this.avatarMarker.avatar=this,this.head&&this.head!==i.head&&((s=this.head)==null||s.removeFromParent()),this.head=i.head,this.headScale.copy(this.head.scale),this.head&&!this.isLocalAvatar&&Ws.Add(this.context,this.head,this.avatarMarker),i.leftHand&&((r=this.handLeft)==null||r.removeFromParent()),this.handLeft=i.leftHand??this.handLeft,this.handLeft?this.handLeftScale.copy(this.handLeft.scale):this.handLeftScale.set(1,1,1),i.rigthHand&&((o=this.handRight)==null||o.removeFromParent()),this.handRight=i.rigthHand??this.handRight,this.handRight?this.handRightScale.copy(this.handRight.scale):this.handRightScale.set(1,1,1),this.context.scene.add(this.root),this.flags==null&&(this.flags=[]),this.flags.length=0,this.flags.push(...Z.getComponentsInChildren(this.root,as)),this.flags.length<=0&&this.head){const a=Z.addNewComponent(this.head,as);a.visibleIn=vn.ThirdPerson|vn.VR,this.flags.push(a),Pc&&console.log("Added flag to head: "+a.visibleIn,this.head.name)}return Pc&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return Pc&&console.warn("build avatar failed"),!1}};let Ma=lm;h(Ma,"loader",new Q_),h(Ma,"invertRotation",new xe().setFromAxisAngle(new S(0,1,0),Math.PI));class Ws{static Add(e,t,i=null){if(t){for(const s of this.Pois)if(s.obj===t)return;this.Pois.push({obj:t,avatar:i}),this.LastChangeTime=e.time.time}}static Remove(e,t){var i;if(t){for(const s of this.Pois)if(s.obj===t){this.Pois.splice(this.Pois.indexOf(s),1),this.LastChangeTime=(e==null?void 0:e.time.time)??((i=kt.Current)==null?void 0:i.time.time);return}}}}h(Ws,"Pois",[]),h(Ws,"LastChangeTime",0);class NK{constructor(){h(this,"guid");h(this,"position",new S)}}class Om extends Ce{constructor(){super(...arguments);h(this,"target",null);h(this,"avatar",null);h(this,"_model",null);h(this,"_targetModel",new NK);h(this,"_currentTargetObject",null);h(this,"_lastUpdateTime",0);h(this,"_lookDuration",0);h(this,"_lastPoiChangedTime",0)}set controlledTarget(t){this.target=t;const i=G.get("MoveRandom");if(i&&this.target){const s=Z.getComponent(this.target,i);s&&s.destroy()}}awake(){if(this.avatar=Z.getComponentInParent(this.gameObject,Yn),this.avatar){const t=Z.getComponentInParent(this.gameObject,Yn);this._model=new w_(this.context.connection,this.guid),t!=null&&t.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",t=>{var i;this.target&&t&&t.guid===((i=this.avatar)==null?void 0:i.guid)&&hn(this.target,t.position)})}update(){var i;if((!this.context.connection.isConnected||(i=this._model)!=null&&i.hasOwnership)&&(Ws.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Ws.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const s=wt(this._currentTargetObject);hn(this.target,s),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(s))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const i=Ws.Pois;if(i.length>0){const s=i[Math.floor(Math.random()*i.length)];if(s&&s.obj){if(s.avatar&&s.avatar===this.avatar)return;this._currentTargetObject=s.obj}}}}}class up extends Ce{constructor(){super(...arguments);h(this,"canGrab",!0)}onPointerClick(t){}}class dp extends Ce{constructor(){super(...arguments);h(this,"isUsed",!0);h(this,"usedBy",null)}}var fa=(n=>(n[n.Average=0]="Average",n[n.Multiply=1]="Multiply",n[n.Minimum=2]="Minimum",n[n.Maximum=3]="Maximum",n))(fa||{}),H_=(n=>(n[n.Discrete=0]="Discrete",n[n.Continuous=1]="Continuous",n))(H_||{}),sn=(n=>(n[n.None=0]="None",n[n.FreezePositionX=2]="FreezePositionX",n[n.FreezePositionY=4]="FreezePositionY",n[n.FreezePositionZ=8]="FreezePositionZ",n[n.FreezePosition=14]="FreezePosition",n[n.FreezeRotationX=16]="FreezeRotationX",n[n.FreezeRotationY=32]="FreezeRotationY",n[n.FreezeRotationZ=64]="FreezeRotationZ",n[n.FreezeRotation=112]="FreezeRotation",n[n.FreezeAll=126]="FreezeAll",n))(sn||{}),Kd=(n=>(n[n.None=0]="None",n[n.X=2]="X",n[n.Y=4]="Y",n[n.Z=8]="Z",n[n.All=-1]="All",n))(Kd||{});const Qr=function(n,e){return function(t,i,s){zK(t,i,s,n,e)}};function zK(n,e,t,i,s){if(!(!s&&!i&&!n.onValidate)){if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",n,e,t),yn("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,qo.Error);return}if(n.__internalAwake){const r=Symbol(e),o=n.__internalAwake;n.__internalAwake=function(){this[r]===void 0&&(this[r]=this[e],Object.defineProperty(this,e,{set:function(a){var l;if(this[PS]===!0)this[r]=a;else{i==null||i.call(this,a);const c=this[r];this[r]=a,(l=this.onValidate)==null||l.call(this,e,c)}},get:function(){return s==null||s.call(this),this[r]}})),o.call(this)}}}}const GK=function(n){return function(e,t,i){const s=n.prototype,r=Object.getOwnPropertyDescriptor(s,t);if(!(r!=null&&r.value)){console.warn("Can not apply prefix: type does not have method named",t,n);return}const o=r.value,a=e[t];Object.defineProperty(s,t,{value:function(...l){const c=a==null?void 0: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 QK=Object.defineProperty,HK=Object.getOwnPropertyDescriptor,Zl=(n,e,t,i)=>{for(var s=i>1?void 0:i?HK(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&QK(e,t,s),s};class VK{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 vf(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((r,o)=>{var l;if((l=this.context.physics.engine)!=null&&l.isUpdating||this.mute)return;const a=this.position[o];Math.abs(a-r)<1e-5||(this.position[o]=r,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new vf(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((r,o)=>{var l;if((l=this.context.physics.engine)!=null&&l.isUpdating||this.mute)return;const a=this.quaternion[o];Math.abs(a-r)<1e-5||(this.quaternion[o]=r,this.rotationChanged=!0)}));const i=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),s=new Pe;this.obj.matrixWorld.multiplyMatrices=(r,o)=>(s.equals(r)||(this.positionChanged=!0,this.rotationChanged=!0,s.copy(r)),i(r,o))}stop(){var e,t;(e=this._positionWatch)==null||e.revoke(),(t=this._rotationWatch)==null||t.revoke()}}var LC;const hE=(LC=class extends Ce{constructor(){super(...arguments);h(this,"mass",1);h(this,"useGravity",!0);h(this,"constraints",sn.None);h(this,"isKinematic",!1);h(this,"drag",0);h(this,"angularDrag",1);h(this,"detectCollisions",!0);h(this,"sleepThreshold",.01);h(this,"collisionDetectionMode",H_.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&sn.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&sn.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&sn.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&sn.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&sn.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&sn.FreezeRotationZ)!==0}set lockPositionX(e){e?this.constraints|=sn.FreezePositionX:this.constraints&=~sn.FreezePositionX}set lockPositionY(e){e?this.constraints|=sn.FreezePositionY:this.constraints&=~sn.FreezePositionY}set lockPositionZ(e){e?this.constraints|=sn.FreezePositionZ:this.constraints&=~sn.FreezePositionZ}set lockRotationX(e){e?this.constraints|=sn.FreezeRotationX:this.constraints&=~sn.FreezeRotationX}set lockRotationY(e){e?this.constraints|=sn.FreezeRotationY:this.constraints&=~sn.FreezeRotationY}set lockRotationZ(e){e?this.constraints|=sn.FreezeRotationZ:this.constraints&=~sn.FreezeRotationZ}set gravityScale(e){this._gravityScale=e}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new VK(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),Nr.LateUpdate)}onDisable(){var e,t;(e=this._watch)==null||e.stop(),(t=this.context.physics.engine)==null||t.removeBody(this)}onDestroy(){var e;(e=this.context.physics.engine)==null||e.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){var e,t,i,s;for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,(e=this.context.physics.engine)==null||e.updateProperties(this)),(t=this._watch)!=null&&t.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(i=this.context.physics.engine)==null||i.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(s=this._watch)==null||s.syncValues(),this.captureVelocity(),yield}teleport(e,t=!0){var i;(i=this._watch)==null||i.reset(!0),t?this.gameObject.position.set(e.x,e.y,e.z):this.setWorldPosition(e.x,e.y,e.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(){var e;(e=this.context.physics.engine)==null||e.resetForces(this,!0)}resetTorques(){var e;(e=this.context.physics.engine)==null||e.resetTorques(this,!0)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var e;(e=this.context.physics.engine)==null||e.wakeup(this)}applyForce(e,t){var i;(i=this.context.physics.engine)==null||i.addForce(this,e,!0)}applyImpulse(e){var t;(t=this.context.physics.engine)==null||t.applyImpulse(this,e,!0)}setForce(e,t,i){var s,r;(s=this.context.physics.engine)==null||s.resetForces(this,!0),(r=this.context.physics.engine)==null||r.addForce(this,{x:e,y:t,z:i},!0)}getVelocity(){var t;const e=(t=this.context.physics.engine)==null?void 0:t.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(e,t,i){var s,r;if(e instanceof S){const o=e;(s=this.context.physics.engine)==null||s.setLinearVelocity(this,o,!0);return}t===void 0||i===void 0||(r=this.context.physics.engine)==null||r.setLinearVelocity(this,{x:e,y:t,z:i},!0)}setAngularVelocity(e,t,i){var s,r;if(e instanceof S){const o=e;(s=this.context.physics.engine)==null||s.setAngularVelocity(this,o,!0);return}t===void 0||i===void 0||(r=this.context.physics.engine)==null||r.setAngularVelocity(this,{x:e,y:t,z:i},!0)}getAngularVelocity(){var t;const e=(t=this.context.physics.engine)==null?void 0:t.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(e,t,i){this.setAngularVelocity(e,t,i)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(e=null){}captureVelocity(){const e=wt(this.gameObject);hE.tempPosition.copy(e);const t=e.sub(this._lastPosition);this._lastPosition.copy(hE.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}},h(LC,"tempPosition",new S),LC);let ji=hE;Zl([Qr(),x()],ji.prototype,"mass",2);Zl([Qr(),x()],ji.prototype,"useGravity",2);Zl([Qr(),x()],ji.prototype,"constraints",2);Zl([Qr(),x()],ji.prototype,"isKinematic",2);Zl([Qr(),x()],ji.prototype,"drag",2);Zl([Qr(),x()],ji.prototype,"angularDrag",2);Zl([Qr(),x()],ji.prototype,"detectCollisions",2);Zl([Qr(),x()],ji.prototype,"sleepThreshold",2);Zl([Qr(),x()],ji.prototype,"collisionDetectionMode",2);class Fr{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,i,s){return e.prep(4,12),e.writeFloat32(s),e.writeFloat32(i),e.writeFloat32(t),e.offset()}}class dU{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 Fr).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Fr).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Fr).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,s,r,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(r),e.prep(4,12),e.writeFloat32(s),e.writeFloat32(i),e.writeFloat32(t),e.offset()}}class yl{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 yl).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+__),(t||new yl).__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 dU).__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 Ic=oe("debugsync"),Lm="STRS";z1(Lm,yl.getRootAsSyncedTransformModel);const la=new Yf;function fU(n,e,t=!0){la.clear();const i=la.createString(n);yl.startSyncedTransformModel(la),yl.addGuid(la,i),yl.addFast(la,t);const s=e.worldPosition,r=e.worldEuler,o=e.gameObject.scale;yl.addTransform(la,dU.createTransform(la,s.x,s.y,s.z,r.x,r.y,r.z,o.x,o.y,o.z));const a=yl.endSyncedTransformModel(la);return la.finish(a,Lm),la.asUint8Array()}class th extends Ce{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 xn);h(this,"receivedUpdate",!1);h(this,"lastWorldPos");h(this,"lastWorldRotation")}requestOwnership(){Ic&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){var t;return((t=this._model)==null?void 0:t.hasOwnership)??void 0}isOwned(){var t;return(t=this._model)==null?void 0:t.isOwned}awake(){Ic&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new S,this._targetRotation=new xe,this.lastWorldPos=new S,this.lastWorldRotation=new xe,this.rb=Z.getComponentInChildren(this.gameObject,ji),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new w_(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen($i.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(Lm,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&LL(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen($i.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(Lm,this.receivedDataCallback)}tryGetLastState(){const t=this.context.connection.tryGetState(this.guid);t&&this.onReceivedData(t)}onReceivedData(t){var i;if(!this.destroyed&&typeof t.guid=="function"&&t.guid()===this.guid){Ic&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,t),this.receivedUpdate=!0,this._receivedFastUpdate=t.fast();const s=t.transform();if(s){cr.markDirty(this.gameObject,!0);const r=s.position();r&&(this.interpolatePosition&&((i=this._targetPosition)==null||i.set(r.x(),r.y(),r.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(r.x(),r.y(),r.z()));const o=s.rotation();o&&(this.tempEuler.set(o.x(),o.y(),o.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&TO(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){Ic&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());let t=this.worldPosition,i=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const o=t.distanceTo(this.lastWorldPos),a=i.angleTo(this.lastWorldRotation),l=this._model.hasOwnership||this.fastMode?1e-4:.001;(o>l||a>l)&&(this._model.hasOwnership?this._needsUpdate=!0:(Ic&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,t.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,i.copy(this.lastWorldRotation),cr.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const a=this._receivedFastUpdate||this.fastMode?.5:.3;let l=!1;if(this.interpolatePosition&&this._targetPosition){const c=this.worldPosition;c.lerp(this._targetPosition,a),this.worldPosition=c,l=!0}if(this.interpolateRotation&&this._targetRotation){const c=this.worldQuaternion;c.slerp(this._targetRotation,a),this.worldQuaternion=c,l=!0}l&&cr.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(t),this.lastWorldRotation.copy(i),!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&&(Ic&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new S(0,0,0))>1e3&&(Ic&&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)){Ic&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this.overridePhysics&&this.rb,this._needsUpdate=!1;const o=fU(this.guid,this,!!r);this.context.connection.sendBinary(o)}}}var Xo={};Xo.d=(n,e)=>{for(var t in e)Xo.o(e,t)&&!Xo.o(n,t)&&Object.defineProperty(n,t,{enumerable:!0,get:e[t]})};Xo.o=(n,e)=>Object.prototype.hasOwnProperty.call(n,e);Xo.r=n=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})};var Sn={};Xo.d(Sn,{w8:()=>ui,cg:()=>RN,gO:()=>Gm,wb:()=>kI,zV:()=>Cu,HS:()=>NA,Ec:()=>Ou,gF:()=>Of,ol:()=>Hm,pz:()=>EU,tx:()=>lo,hj:()=>OI,FV:()=>HA,sV:()=>fN,xv:()=>Qm,mx:()=>wU,gE:()=>CU,ZP:()=>Dee,Vx:()=>BN});var kI={};Xo.r(kI);Xo.d(kI,{get:()=>pU,set:()=>WK});var OI={};Xo.r(OI);Xo.d(OI,{alphaTestTransformer:()=>W_,asPreprocessorValueTransformer:()=>IU,toPreprocessorTriggerTransformer:()=>WI,toUserDataTransformer:()=>tZ,uniformOrUserDataTransformer:()=>oo});const uE={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},WK=function(n){for(const e in n)uE[e]=n[e]},pU=function(n){return Object.prototype.hasOwnProperty.call(uE,n)||console.warn(`ThreeMeshUI::DefaultValues is trying to retrieve non-existing property '${n}'`),uE[n]};class ui{constructor(e,t=null,i=!0){this._id=e,this._value=t,this._needsUpdate=!0,this._needsProcess=!1,this._needsRender=!1,this._isPrimitive=i}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 pU(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 jK extends ui{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 i=e._parent._value;if(i!==null){const s=i._renderOrder._actualValue,r=1+i._children._uis.indexOf(e);this._actualValue=s+r}}for(const i of e._children._uis)i._renderOrder._value==="auto"&&(i._renderOrder._needsUpdate=!0);this._outputValue(t)}_outputValue(e){e[this._id]=this._actualValue}get value(){return this._value}}class Ou extends ui{constructor(e,t=null,i=!0){super(e,t,i),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 i=t[`_${this._id}`];i!==void 0&&i._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 qK extends Ou{constructor(){super("offset","inherit",!1)}update(e,t){super.update(e,t),e._parent._value!==null&&(e.position.z=this._notInheritedValue)}}class XK extends Ou{constructor(){super("fontSmooth","inherit",!0),this._needsUpdate=!1,this.isValid=KK,this.output=this._outputValue}}const YK=["inherit","none","antialiased"];function KK(n){return YK.indexOf(n)===-1?(console.warn(`.fontSmoothing value '${n}' is not valid. Aborted`),!1):!0}var JK=n=>{var e={};return Xo.d(e,n),e};const Je=JK({BackSide:()=>Dn,BufferAttribute:()=>rt,BufferGeometry:()=>At,Color:()=>ye,DoubleSide:()=>Ii,EventDispatcher:()=>Nn,FileLoader:()=>On,FrontSide:()=>qs,LinearFilter:()=>Ot,Mesh:()=>me,Object3D:()=>Ie,Plane:()=>ho,PlaneGeometry:()=>$n,ShaderMaterial:()=>Lt,Texture:()=>Gt,TextureLoader:()=>jc,Vector2:()=>V,Vector3:()=>S,Vector4:()=>ot});class zi extends ui{constructor(e,t,i=!0){super(e,"unset",i),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 i of e._children._uis){const s=i[`_${this._id}`];(s._input?s._input:s._value)==="inherit"&&(i[`_${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 V_ extends zi{constructor(e,t){super(e,t,!1),this._input=new Je.Vector4(0,0,0,0),this._inline=null,this._value=new Je.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 Je.Vector4){e.copy(t);return}if((typeof t=="string"||t instanceof String)&&(t=t.split(" ")),Array.isArray(t))switch(t=t.map(i=>parseFloat(i)),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 ZK extends V_{constructor(){super("padding",new Je.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 $K extends V_{constructor(){super("margin",new Je.Vector4(0,0,0,0))}computeOutputValue(e){super.computeOutputValue(e),e._renderer._needsRender=!0,e._parent._value&&(e._parent._value._flexDirection._needsProcess=!0)}}const HB=function(n,e,t){n[e]=t},eJ=function(n,e,t){t!==null&&(n[e]=t)};class Sy{constructor(e){this._definition=e}set definition(e){this._definition=e}mediate(e,t,i,s=null){for(const r in this._definition){const o=this._definition[r];if(i[r]!==void 0){const a=o.t?o.t:HB;a(t,o.m,i[r]),s&&a(s,o.m,i[r])}}}static mediate(e,t,i,s,r=null){if(t)for(const o in s){const a=s[o];if(i[o]!==void 0){const l=a.t?a.t:HB;l(t,a.m,i[o]),r&&l(r,a.m,i[o])}}}}class tJ extends ui{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 dE=function(n,e,t=6){return n.toFixed(t)===e.toFixed(t)};class VB extends ui{constructor(e,t){super(e,t,!0),this.output=this._outputValue}set value(e){this.isValid(e)&&(dE(this._value,e)||(this._value=e,this._needsUpdate=!0))}get value(){return this._value}}class WB extends Ou{constructor(e){super(e,"inherit",!0),this.isValid=nJ}}const iJ=[Je.FrontSide,Je.BackSide,Je.DoubleSide];function nJ(n){return iJ.indexOf(n)===-1?(console.warn(`SideProperty value '${n}' is not valid. Abort`),!1):!0}class sJ extends Je.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 i=this._getFallbackCharacter(e);if(i&&(t=this._chars[i],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 i=this.getTypographicGlyph(t),s=e[t];for(const r in s)i["_"+r]=e[t][r]}}_checkReadiness(){this._readyCondition()&&oJ(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 rJ={type:"ready"};function oJ(n){n._isReady=!0,n.dispatchEvent(rJ)}const NA=sJ;class aJ extends ui{constructor(e=null){super("font",e,!1),this._needsUpdate=!1,this._fontVariant=null,this._handleFontReadyClosure=null,this.isValid=lJ}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 NA)this._fontVariant=this._value;else{const i=e._fontFamily._value;i&&(this._fontVariant=i.getVariant(e._fontWeight._value,e._fontStyle._value))}this._fontVariant&&(this._fontVariant._alterElementProperties(e),this._handleFontReadyClosure=cJ(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 lJ(n){return n instanceof NA?!0:(console.warn(`.font value '${n}' is not valid. It requires a FontVariant instance. Aborted`),!1)}function cJ(n,e){return function(){e._needsUpdate=!0,n._glyphs._needsProcess=!0,e._fontVariant.removeEventListener("ready",e._handleFontReadyClosure),e._handleFontReadyClosure=null}}class hJ extends zi{constructor(e){super("display",e),this._value="flex",this._allowsInherit=!1,this._needsUpdate=!1,this.isValidValue=dJ}computeOutputValue(e){e._visible._value=this._output!=="none"}}const uJ=["none","flex"];function dJ(n){return uJ.indexOf(n)===-1?(console.warn(`(.style) display value '${n}' is not valid. Aborted`),!1):!0}class fJ extends zi{constructor(e){super("boxSizing",e),this._allowsInherit=!1,this.isValidValue=gJ}computeOutputValue(e){this._value=this._inheritedInput,e._bounds._needsUpdate=!0}}const pJ=["border-box","content-box"];function gJ(n){return pJ.indexOf(n)===-1?(console.warn(`(.style) boxSizing value '${n}' is not valid. Aborted`),!1):!0}class Fm extends zi{constructor(e,t){super(e,t,!1),this._value=new Je.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 tC extends zi{constructor(e,t){super(e,t,!0),this.isValidValue=mJ,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 mJ(n){return n<0&&n>1?(console.warn(`(.style) styleFactorProperty('${this.id}') value '${n}' is not valid)`),!1):!0}class AJ extends zi{constructor(e){super("backgroundImage",e,!0),this._input=null,this._allowsInherit=!1,this._textureSize=new Je.Vector2(1,1),this.isValidValue=vJ}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 Je.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 vJ(n){return!0}class yJ extends zi{constructor(e){super("backgroundSize",e,!0),this.isValidValue=_J,this.output=this._outputValue}}const bJ=["cover","contain","stretch"];function _J(n){return bJ.indexOf(n)===-1?(console.warn(`(.style) backgroundSize value '${n}' is not valid. Aborted`),!1):!0}class xJ extends zi{constructor(e){super("overflow",e,!0),this.isValidValue=CJ,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 i of e._children._uis)i._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 i=t._overflow;if((i._value==="hidden"||i._clippingPlanes!==null)&&!this._clippingPlanes){this._clippingPlanes=[new Je.Plane(new Je.Vector3(0,-1,0),1),new Je.Plane(new Je.Vector3(-1,0,0),1),new Je.Plane(new Je.Vector3(0,1,0),1),new Je.Plane(new Je.Vector3(1,0,0),1)];for(let s=0;s<this._clippingPlanes.length;s++)this._clippingPlanes[s].parent=t;i._clippingPlanes!==null&&this._clippingPlanes.push(...i._clippingPlanes),this._renderStrategy=this._hiddenRender,this._needsRender=!0}else(i._value==="visible"||i._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,i=t._bounds._offsetHeight,s=t._bounds._offsetWidth,r=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=i/2-(r.x+o.x);break;case 1:l.constant=s/2-(r.y+o.y);break;case 2:l.constant=i/2-(r.z+o.z);break;case 3:l.constant=s/2-(r.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 i=e._children._uis[t];i._overflow._needsRender=!0}}}const wJ=["visible","hidden"];function CJ(n){return wJ.indexOf(n)===-1?(console.warn(`(.style) overflow value '${n}' is not valid. Aborted`),!1):!0}const Df="rem",gU="em",Ab="%",SJ=[Df,gU,Ab],mU=function(n){return SJ.indexOf(n)===-1?Df:n};class EJ extends V_{constructor(e){super("borderRadius",e),this._valueUV=this._value.clone(),this._input=new Je.Vector4(0,0,0,0),this._mediation=!0,this._cornerTL=new Je.Vector2(0,1),this._cornerTR=new Je.Vector2(1,1),this._cornerBR=new Je.Vector2(1,0),this._cornerBL=new Je.Vector2(0,0);const t=new Ey(this._valueUV,["x","y"]),i=new Ey(this._valueUV,["z","w"]),s=new Ey(this._valueUV,["x","w"]),r=new Ey(this._valueUV,["y","z"]);t.complementaryMediation=i,i.complementaryMediation=t,s.complementaryMediation=r,r.complementaryMediation=s,this._sideMediators=[t,i,s,r],this._units=Df}set units(e){this._units=mU(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,i=e._bounds._offsetHeight;if(this._units===Ab&&this._valueUV.divideScalar(100),this._units===Df&&this._valueUV.divideScalar(Math.min(t,i)),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 s=t>i?i/t:1,r=t<i?t/i:1;this._units===Ab&&(s=r=1),this._cornerTL.x=this._valueUV.x*s,this._cornerTL.y=1-this._valueUV.x*r,this._cornerTR.x=1-this._valueUV.y*s,this._cornerTR.y=1-this._valueUV.y*r,this._cornerBR.x=1-this._valueUV.z*s,this._cornerBR.y=this._valueUV.z*r,this._cornerBL.x=this._valueUV.w*s,this._cornerBL.y=this._valueUV.w*r}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 Ey{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 IJ extends V_{constructor(e){super("borderWidth",e,!1),this._valueUV=this._value.clone(),this.output=this._outputValue,this._units=Df}set units(e){this._units=mU(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,i=e._bounds._offsetHeight;if(this._units===Ab&&(console.log("Percent"),console.log(this._valueUV)),this._units===Df)t!==0&&(this._valueUV.w/=t,this._valueUV.y/=t),i!==0&&(this._valueUV.x/=i,this._valueUV.z/=i);else if(this._units===gU){if(t!==0){const s=t>i?i/t:1;this._valueUV.y*=s,this._valueUV.w*=s}if(i!==0){const s=t<i?t/i:1;this._valueUV.x*=s,this._valueUV.z*=s}}}}class MJ extends ui{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 AU extends Fm{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 ol extends ui{constructor(e="untitled"){super(e,void 0,!1)}update(e,t){}output(e){}}class TJ extends ui{constructor(){super("inlineJustificator",null,!1),this._value=null}update(e,t){}process(e){const t=e._bounds._innerHeight,i=e._layouter._value,s=Math.abs(i.height);let r=(()=>{switch(e._alignItems._value){case"inherit":case"start":return t/2;case"end":return s-t/2;case"stretch":case"center":return s/2}})();const o=e._padding._value,a=e._borderWidth._value;r+=(-o.x+o.z)/2+(-a.x+a.z)/2,i.forEach(l=>{l.y+=r,l.forEach(c=>{c.offsetY+=r})})}}const PJ=["start","center","end","stretch"],RJ=function(n){return PJ.indexOf(n)===-1?(console.warn(`(.style) alignItems value '${n}' is not valid. Aborted`),!1):!0};class LI extends zi{constructor(){super("alignItems","inherit",!0),this.isValidValue=RJ}}class FI extends zi{constructor(){super("textAlign","inherit",!0),this.isValidValue=DJ}}const BJ=["left","right","center","justify","justify-left","justify-right","justify-center"],DJ=function(n){return BJ.indexOf(n)===-1?(console.warn(`(.style) textAlign value '${n}' is not valid. Aborted`),!1):!0};class UI extends zi{constructor(){super("flexDirection","inherit",!0),this.isValid=OJ}}const kJ=["row","row-reverse","column","column-reverse"];function OJ(n){return kJ.indexOf(n)===-1?(console.warn(`(.style) flexDirection value '${n}' is not valid. Aborted`),!1):!0}class NI extends zi{constructor(){super("justifyContent","inherit",!0),this.isValidValue=FJ}}const LJ=["start","center","end","space-between","space-around","space-evenly"];function FJ(n){return LJ.indexOf(n)===-1?(console.warn(`(.style) justifyContent value '${n}' is not valid. Aborted`),!1):!0}class UJ extends zi{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 vU extends zi{constructor(){super("position","static",!0),this._allowsInherit=!1,this._value="static",this._needsUpdate=!1,this.computeOutputValue=this._computeFromInherited,this.isValidValue=zJ}_computeFromInherited(e){super._computeFromInherited(e),e._parent._value&&(e._parent._value._children._needsProcess=!0)}}const NJ=["static","absolute"];function zJ(n){return NJ.indexOf(n)===-1?(console.warn(`(.style) position value '${n}' is not valid. Aborted`),!1):!0}class yU extends zi{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 i of e._children._uis)i[`_${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 GJ extends yU{constructor(){super("width")}}class QJ extends yU{constructor(){super("height")}computeOutputValue(e){super.computeOutputValue(e)}}class bU extends ol{constructor(){super("textContent"),this._needsUpdate=!1}set value(e){}process(e){let t="";for(let i=0;i<e.children.length;i++){const s=e.children[i];s.isUI&&(t+=s.textContent)}this._value=t}}class _U extends zi{constructor(e){super("fontStyle",e,!0),this.isValidValue=VJ}}const HJ=["normal","italic"];function VJ(n){return HJ.indexOf(n)===-1?(console.warn(`(.style) fontStyle value '${n}' is not valid. Aborted`),!1):!0}class xU extends zi{constructor(){super("fontWeight","inherit",!0),this.isValid=jJ}}const WJ=["100","200","300","400","500","600","700","800","900","light","normal","bold","bolder"];function jJ(n){return WJ.indexOf(n.toString())===-1?(console.warn(`(.style) fontWeight value '${n}' is not valid. Aborted`),!1):!0}class wU{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 qJ extends wU{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 CU{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 SU{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 EU extends SU{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 XJ extends EU{constructor(e){super(e)}get uv(){return this.typographic.uv}}class vb extends CU{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 vb(this._font,{char:e,width:this._width,height:this._heigth,xadvance:this._xadvance,xoffset:this._xoffset,yoffset:this._yoffset,uv:null})}asInlineGlyph(){return new XJ(this)}}class YJ extends Je.PlaneGeometry{constructor(e,t){let i=1,s=1;const r=e.typographic.font.size,o=t._segments.value;i=Math.ceil(e.typographic.width/r*o),s=Math.ceil(e.typographic.height/r*o),super(e.width,e.height,i,s),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,i=e.uv.bottom-e.uv.top,s=this.getAttribute("uv").array.slice(),r=[];for(let o=0;o<s.length;o+=2){const a=s[o],l=s[o+1];r.push(e.uv.left+t*a),r.push(e.uv.top+i*l)}this.setAttribute("uvG",new Je.BufferAttribute(new Float32Array(r),2))}_nullifyUVs(){const e=[],t=this.getAttribute("uv").array.length;for(let i=0;i<t;i++)e.push(0);this.setAttribute("uvG",new Je.BufferAttribute(new Float32Array(e),2))}_transformGeometry(e){this.translate(e.width/2,-e.height/2,0)}}const KJ=`
|
|
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 i;const t=Z.getComponent(this.gameObject,Ui);if(t)if(((i=t.sharedMaterial)==null?void 0:i.type)!=="ShadowMaterial"){const s=new _1;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 t=Z.getComponent(this.gameObject,Ui);if(t){const i=t.sharedMaterial;i.depthWrite=!0,i.stencilWrite=!0,i.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(t){t&&(t.depthWrite=!1,t.stencilWrite=!1)}}mz([x()],dv.prototype,"mode",2);mz([x(xi)],dv.prototype,"shadowColor",2);var _re=Object.defineProperty,xre=Object.getOwnPropertyDescriptor,Cx=(n,e,t,i)=>{for(var s=i>1?void 0:i?xre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&_re(e,t,s),s},HC;const Az=(HC=class extends Ce{constructor(){super(...arguments);h(this,"target",null);h(this,"followFactor",.1);h(this,"rotateFactor",.1);h(this,"positionAxes",Kd.All);h(this,"flipForward",!1);h(this,"_firstUpdate",!0)}onBeforeRender(){this.updateNow(!1)}updateNow(e){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const t=wt(this.target),i=this._firstUpdate||e?1:$e.clamp01(this.context.time.deltaTime*this.followFactor),s=this.worldPosition;this.positionAxes&Kd.X&&(s.x=$e.lerp(s.x,t.x,i)),this.positionAxes&Kd.Y&&(s.y=$e.lerp(s.y,t.y,i)),this.positionAxes&Kd.Z&&(s.z=$e.lerp(s.z,t.z,i)),this.worldPosition=s}if(this.rotateFactor>0){const t=Ln(this.target);this.flipForward&&t.premultiply(Az._invertForward);const i=this._firstUpdate||e?1:$e.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(t,i)}this._firstUpdate=!1}}},h(HC,"_invertForward",new xe().setFromAxisAngle(new S(0,1,0),Math.PI)),HC);let Ch=Az;Cx([x(Ie)],Ch.prototype,"target",2);Cx([x()],Ch.prototype,"followFactor",2);Cx([x()],Ch.prototype,"rotateFactor",2);Cx([x()],Ch.prototype,"positionAxes",2);class wre extends me{constructor(e){const t=new Cre(e),i=new $n(t.image.width*.001,t.image.height*.001),s=new vi({map:t,toneMapped:!1,transparent:!0});super(i,s);function r(o){s.map.dispatchDOMEvent(o)}this.addEventListener("mousedown",r),this.addEventListener("mousemove",r),this.addEventListener("mouseup",r),this.addEventListener("click",r),this.dispose=function(){i.dispose(),s.dispose(),s.map.dispose(),ME.delete(e),this.removeEventListener("mousedown",r),this.removeEventListener("mousemove",r),this.removeEventListener("mouseup",r),this.removeEventListener("click",r)}}}class Cre extends Q2{constructor(e){super(KD(e)),this.dom=e,this.anisotropy=16,this.encoding=yt,this.minFilter=Ot,this.magFilter=Ot;const t=new MutationObserver(()=>{this.scheduleUpdate||(this.scheduleUpdate=setTimeout(()=>this.update(),16))}),i={attributes:!0,childList:!0,subtree:!0,characterData:!0};t.observe(e,i),this.observer=t}dispatchDOMEvent(e){e.data&&Sre(this.dom,e.type,e.data.x,e.data.y)}update(){this.image=KD(this.dom),this.needsUpdate=!0,this.scheduleUpdate=null}dispose(){this.observer&&this.observer.disconnect(),this.scheduleUpdate=clearTimeout(this.scheduleUpdate),super.dispose()}}const ME=new WeakMap;function KD(n){const e=document.createRange(),t=new ye;function i(f){const p=[];let g=!1;function m(){if(g&&(g=!1,f.restore()),p.length===0)return;let A=-1/0,v=-1/0,b=1/0,y=1/0;for(let _=0;_<p.length;_++){const C=p[_];A=Math.max(A,C.x),v=Math.max(v,C.y),b=Math.min(b,C.x+C.width),y=Math.min(y,C.y+C.height)}f.save(),f.beginPath(),f.rect(A,v,b-A,y-v),f.clip(),g=!0}return{add:function(A){p.push(A),m()},remove:function(){p.pop(),m()}}}function s(f,p,g,m){m!==""&&(f.textTransform==="uppercase"&&(m=m.toUpperCase()),u.font=f.fontWeight+" "+f.fontSize+" "+f.fontFamily,u.textBaseline="top",u.fillStyle=f.color,u.fillText(m,p,g+parseFloat(f.fontSize)*.1))}function r(f,p,g,m,A){g<2*A&&(A=g/2),m<2*A&&(A=m/2),u.beginPath(),u.moveTo(f+A,p),u.arcTo(f+g,p,f+g,p+m,A),u.arcTo(f+g,p+m,f,p+m,A),u.arcTo(f,p+m,f,p,A),u.arcTo(f,p,f+g,p,A),u.closePath()}function o(f,p,g,m,A,v){const b=f[p+"Width"],y=f[p+"Style"],_=f[p+"Color"];b!=="0px"&&y!=="none"&&_!=="transparent"&&_!=="rgba(0, 0, 0, 0)"&&(u.strokeStyle=_,u.lineWidth=parseFloat(b),u.beginPath(),u.moveTo(g,m),u.lineTo(g+A,m+v),u.stroke())}function a(f,p){let g=0,m=0,A=0,v=0;if(f.nodeType===Node.TEXT_NODE){e.selectNode(f);const y=e.getBoundingClientRect();g=y.left-l.left-.5,m=y.top-l.top-.5,A=y.width,v=y.height,s(p,g,m,f.nodeValue.trim())}else{if(f.nodeType===Node.COMMENT_NODE)return;if(f instanceof HTMLCanvasElement){if(f.style.display==="none")return;u.save();const y=window.devicePixelRatio;u.scale(1/y,1/y),u.drawImage(f,0,0),u.restore()}else{if(f.style.display==="none")return;const y=f.getBoundingClientRect();g=y.left-l.left-.5,m=y.top-l.top-.5,A=y.width,v=y.height,p=window.getComputedStyle(f),r(g,m,A,v,parseFloat(p.borderRadius));const _=p.backgroundColor;_!=="transparent"&&_!=="rgba(0, 0, 0, 0)"&&(u.fillStyle=_,u.fill());const C=["borderTop","borderLeft","borderBottom","borderRight"];let E=!0,T=null;for(const w of C){if(T!==null&&(E=p[w+"Width"]===p[T+"Width"]&&p[w+"Color"]===p[T+"Color"]&&p[w+"Style"]===p[T+"Style"]),E===!1)break;T=w}if(E===!0){const w=parseFloat(p.borderTopWidth);p.borderTopWidth!=="0px"&&p.borderTopStyle!=="none"&&p.borderTopColor!=="transparent"&&p.borderTopColor!=="rgba(0, 0, 0, 0)"&&(u.strokeStyle=p.borderTopColor,u.lineWidth=w,u.stroke())}else o(p,"borderTop",g,m,A,0),o(p,"borderLeft",g,m,0,v),o(p,"borderBottom",g,m+v,A,0),o(p,"borderRight",g+A,m,0,v);if(f instanceof HTMLInputElement){let w=p.accentColor;(w===void 0||w==="auto")&&(w=p.color),t.set(w);const P=Math.sqrt(.299*t.r**2+.587*t.g**2+.114*t.b**2)<.5?"white":"#111111";if(f.type==="radio"&&(r(g,m,A,v,v),u.fillStyle="white",u.strokeStyle=w,u.lineWidth=1,u.fill(),u.stroke(),f.checked&&(r(g+2,m+2,A-4,v-4,v),u.fillStyle=w,u.strokeStyle=P,u.lineWidth=2,u.fill(),u.stroke())),f.type==="checkbox"&&(r(g,m,A,v,2),u.fillStyle=f.checked?w:"white",u.strokeStyle=f.checked?P:w,u.lineWidth=1,u.stroke(),u.fill(),f.checked)){const k=u.textAlign;u.textAlign="center";const Q={color:P,fontFamily:p.fontFamily,fontSize:v+"px",fontWeight:"bold"};s(Q,g+A/2,m,"✔"),u.textAlign=k}if(f.type==="range"){const[k,Q,z]=["min","max","value"].map(H=>parseFloat(f[H])),L=(z-k)/(Q-k)*(A-v);r(g,m+v/4,A,v/2,v/4),u.fillStyle=P,u.strokeStyle=w,u.lineWidth=1,u.fill(),u.stroke(),r(g,m+v/4,L+v/2,v/2,v/4),u.fillStyle=w,u.fill(),r(g+L,m,v,v,v/2),u.fillStyle=w,u.fill()}(f.type==="color"||f.type==="text"||f.type==="number")&&(d.add({x:g,y:m,width:A,height:v}),s(p,g+parseInt(p.paddingLeft),m+parseInt(p.paddingTop),f.value),d.remove())}}}const b=p.overflow==="auto"||p.overflow==="hidden";b&&d.add({x:g,y:m,width:A,height:v});for(let y=0;y<f.childNodes.length;y++)a(f.childNodes[y],p);b&&d.remove()}const l=n.getBoundingClientRect();let c=ME.get(n);c===void 0&&(c=document.createElement("canvas"),c.width=l.width,c.height=l.height,ME.set(n,c));const u=c.getContext("2d"),d=new i(u);return a(n),c}function Sre(n,e,t,i){const s={clientX:t*n.offsetWidth+n.offsetLeft,clientY:i*n.offsetHeight+n.offsetTop,view:n.ownerDocument.defaultView};window.dispatchEvent(new MouseEvent(e,s));const r=n.getBoundingClientRect();t=t*r.width+r.left,i=i*r.height+r.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&&i>l.top&&i<l.bottom&&(a.dispatchEvent(new MouseEvent(e,s)),a instanceof HTMLInputElement&&a.type==="range"&&(e==="mousedown"||e==="click"))){const[c,u]=["min","max"].map(g=>parseFloat(a[g])),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(n)}const D0=new V,Pd={type:"",data:D0};class Ere extends po{constructor(e,t){super();const i=this,s=new qf,r=new Pe,o=e.domElement;function a(f){f.stopPropagation();const p=e.domElement.getBoundingClientRect();D0.x=(f.clientX-p.left)/p.width*2-1,D0.y=-(f.clientY-p.top)/p.height*2+1,s.setFromCamera(D0,t);const g=s.intersectObjects(i.children,!1);if(g.length>0){const m=g[0],A=m.object,v=m.uv;Pd.type=f.type,Pd.data.set(v.x,1-v.y),A.dispatchEvent(Pd)}}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(f){const p=f.target;r.identity().extractRotation(p.matrixWorld),s.ray.origin.setFromMatrixPosition(p.matrixWorld),s.ray.direction.set(0,0,-1).applyMatrix4(r);const g=s.intersectObjects(i.children,!1);if(g.length>0){const m=g[0],A=m.object,v=m.uv;Pd.type=l[f.type],Pd.data.set(v.x,1-v.y),A.dispatchEvent(Pd)}}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 KM extends Ce{constructor(){super(...arguments);h(this,"id",null);h(this,"keepAspect",!1)}start(){if(!this.id||!this.context.mainCamera)return;const t=document.getElementById(this.id);if(!t){console.warn('Could not find element with id "'+this.id+'"');return}t.style.display="block",t.style.visibility="hidden";const i=new Ere(this.context.renderer,this.context.mainCamera);this.gameObject.add(i);const s=new wre(t);i.add(s),s.visible=!1,console.log(s);const r=s.material;r.transparent=!0,setTimeout(()=>{s.visible=!0;const o=d_(this.gameObject).clone();f_(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const a=new Cs;a.setFromObject(i),this.setWorldRotation(o.x,o.y,o.z);const l=a.max.x-a.min.x,c=a.max.y-a.min.y;if(this.keepAspect){const d=l/c;l>c?s.scale.set(1/l,1/c/d,1):s.scale.set(1/l*d,1/c,1)}else s.scale.set(1/l,1/c,1);const u=this.gameObject.scale;s.scale.multiply(u)},1)}}var Ire=Object.defineProperty,Mre=Object.getOwnPropertyDescriptor,fv=(n,e,t,i)=>{for(var s=i>1?void 0:i?Mre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Ire(e,t,s),s};const em=oe("debugspatialtrigger"),JD=new xo,ZD=new xo;function Tre(n,e){return JD.mask=n,ZD.mask=e,JD.test(ZD)}class Da extends Ce{constructor(){super(...arguments);h(this,"triggerMask",0);h(this,"onEnter");h(this,"onStay");h(this,"onExit");h(this,"currentIntersected",[]);h(this,"lastIntersected",[])}start(){em&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const t of pv.triggers)Tre(t.triggerMask,this.triggerMask)&&t.test(this.gameObject)&&this.currentIntersected.push(t);for(let t=this.lastIntersected.length-1;t>=0;t--){const i=this.lastIntersected[t];this.currentIntersected.indexOf(i)<0&&(this.onExitTrigger(i),this.lastIntersected.splice(t,1))}for(const t of this.currentIntersected)this.lastIntersected.indexOf(t)<0&&this.onEnterTrigger(t),this.onStayTrigger(t);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}onEnterTrigger(t){var i;em&&console.log("ENTER TRIGGER",this.name,t.name,this,t),t.raiseOnEnterEvent(this),(i=this.onEnter)==null||i.invoke(this,t)}onExitTrigger(t){var i;em&&console.log("EXIT TRIGGER",this.name,t.name,this,t),t.raiseOnExitEvent(this),(i=this.onExit)==null||i.invoke(this,t)}onStayTrigger(t){var i;t.raiseOnStayEvent(this),(i=this.onStay)==null||i.invoke(this,t)}}fv([x()],Da.prototype,"triggerMask",2);fv([x(ur)],Da.prototype,"onEnter",2);fv([x(ur)],Da.prototype,"onStay",2);fv([x(ur)],Da.prototype,"onExit",2);var VC;const k0=(VC=class extends Ce{constructor(){super(...arguments);h(this,"triggerMask");h(this,"boxHelper")}start(){em&&console.log(this.name,this.triggerMask,this)}onEnable(){var e;k0.triggers.push(this),this.boxHelper||(this.boxHelper=Z.addNewComponent(this.gameObject,fo),(e=this.boxHelper)==null||e.showHelper(null,em))}onDisable(){k0.triggers.splice(k0.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){Z.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof Da&&t.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){Z.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof Da&&t.onStayTrigger(this)},!1)}raiseOnExitEvent(e){Z.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof Da&&t.onExitTrigger(this)},!1)}},h(VC,"triggers",[]),VC);let pv=k0;fv([x()],pv.prototype,"triggerMask",2);var Pre=Object.defineProperty,Rre=Object.getOwnPropertyDescriptor,Bre=(n,e,t,i)=>{for(var s=i>1?void 0:i?Rre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Pre(e,t,s),s};const Dr=oe("debugspectator");class Sx extends Ce{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(t){this._mode=t}get isSpectating(){var t;return((t=this._handler)==null?void 0:t.currentTarget)!==void 0}isSpectatingUser(t){var i;return((i=this.target)==null?void 0:i.userId)===t}isFollowedBy(t){var i;return(i=this.followers)==null?void 0:i.includes(t)}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(t){var i;if(this._handler){const s=(i=this._handler.currentTarget)==null?void 0:i.userId,r=this.context.players.getPlayerView(this.localId);t===void 0||this.context.isInXR===!1&&(r==null?void 0:r.currentObject)===t.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),Z.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(t,s)):this._handler.currentTarget!==t&&(this._handler.set(t),Z.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(t,s))}}get target(){var t;return(t=this._handler)==null?void 0:t.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){var t,i;return this.isSpectating&&((t=this.target)==null?void 0:t.currentObject)===((i=this.context.players.getPlayerView(this.localId))==null?void 0:i.currentObject)}awake(){if(this._debug=new Ore(this.context,this),this._networking=new Ure(this.context,this),this._networking.awake(),Z.setActive(this.gameObject,!1),this.cam=Z.getComponent(this.gameObject,Ni),!this.cam){console.error("Spectator camera needs camera component",this);return}!this._handler&&this.cam&&(this._handler=new Dre(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),Ct.addEventListener(Ei.RequestVRSession,this.eventSub_WebXRRequestStartEvent),Ct.addEventListener(Ei.XRStarted,this.eventSub_WebXRStartEvent),Ct.addEventListener(Ei.XRStopped,this.eventSub_WebXREndEvent),this.orbit=Z.getComponent(this.context.mainCamera,ec)}onDestroy(){var t;this.stopSpectating(),Ct.removeEventListener(Ei.RequestVRSession,this.eventSub_WebXRStartEvent),Ct.removeEventListener(Ei.XRStarted,this.eventSub_WebXRStartEvent),Ct.removeEventListener(Ei.XRStopped,this.eventSub_WebXREndEvent),(t=this._handler)==null||t.destroy(),this._networking.destroy()}isSupportedPlatform(){const t=window.navigator.userAgent,i=/Windows|MacOS/.test(t),s=/Windows NT/.test(t)&&/Edg/.test(t)&&!/Win64/.test(t);return i&&!s}onXRSessionRequestStart(t){this.isSupportedPlatform()&&Z.setActive(this.gameObject,!0)}onXRSessionStart(t){this.isSupportedPlatform()&&(Dr&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onXRSessionEnded(t){var i,s;this.context.removeCamera(this.cam),Z.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),(i=this._handler)==null||i.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,Ba.Headset),this.target=this.context.players.getPlayerView(this.localId)),Dr&&console.log("Follow self",this.target)}onAfterRender(){var c,u,d;if(!this.cam)return;const t=this.context.renderer,i=t.xr.enabled;if(!t.xr.isPresenting&&!((c=this._handler)!=null&&c.currentTarget))return;(u=this._handler)==null||u.update(this._mode);const s=t.getRenderTarget();let r=null;if(!s){if(!t.state.bindFramebuffer||!t.state.bindXRFramebuffer)return;r=t._framebuffer,t.state.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const o=this.context.mainCameraComponent;if(o){const f=o.backgroundColor;f&&t.setClearColor(f,f.alpha),this.cam.backgroundColor=f,this.cam.clearFlags=o.clearFlags,this.cam.nearClipPlane=o.nearClipPlane,this.cam.farClipPlane=o.farClipPlane}else t.setClearColor(new ye(1,1,1));t.setRenderTarget(null),t.xr.enabled=!1;const a=(d=this.cam)==null?void 0:d.cam;this.context.updateAspect(a);const l=t.xr.isPresenting;t.xr.isPresenting=!1,t.setSize(this.context.domWidth,this.context.domHeight),t.render(this.context.scene,a),t.xr.isPresenting=l,t.xr.enabled=i,s?t.setRenderTarget(s):t.state.bindXRFramebuffer(r),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const t=this._mode===0;for(const i of Yn.instances)if(i.avatar&&"isLocalAvatar"in i.avatar){let s=vn.All;this.isSpectatingSelf&&(s=t&&i.avatar.isLocalAvatar?vn.FirstPerson:vn.ThirdPerson);const r=i.avatar.flags;if(!r)continue;for(const o of r)o.UpdateVisible(s)}}resetAvatarFlags(){var t;for(const i of Yn.instances)if(i.avatar&&"flags"in i.avatar){const s=i.avatar.flags;if(!s)continue;for(const r of s)(t=i.avatar)!=null&&t.isLocalAvatar?r.UpdateVisible(vn.FirstPerson):r.UpdateVisible(vn.ThirdPerson)}}}Bre([x()],Sx.prototype,"useKeys",2);class Dre{constructor(e,t,i){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=i}get currentTarget(){return this.view}set(e){const t=e==null?void 0:e.currentObject;if(!t){this.spectator.stopSpectating();return}t!==this.currentObject&&(this.currentObject=t,this.view=e,this.follow||(this.follow=Z.addNewComponent(this.cam.gameObject,Ch)),this.target||(this.target=new Ie),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Dr&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Dr&&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&&Z.destroy(this.follow)}update(e){var s,r,o,a,l,c;if(((s=this.currentTarget)==null?void 0:s.isConnected)===!1||((r=this.currentTarget)==null?void 0:r.removed)===!0){Dr&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&((o=this.currentTarget)==null?void 0:o.currentObject)!==this.currentObject&&(Dr&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const t=this.context.mainCamera;t&&(this.cam.cam.near!==t.near||this.cam.cam.far!==t.far)&&(this.cam.cam.near=t.near,this.cam.cam.far=t.far,this.cam.cam.updateProjectionMatrix());const i=(a=this.follow)==null?void 0:a.target;if(!(!i||!this.follow)){switch(e){case 0:((l=this.view)==null?void 0:l.viewDevice)!==Ba.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),i.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,i.position.set(0,.5,1.5);break}this.follow.flipForward=!1,((c=this.view)==null?void 0:c.viewDevice)!==Ba.Browser?i.quaternion.copy(kre):i.quaternion.identity()}}}const kre=new xe().setFromAxisAngle(new S(0,1,0),Math.PI);class Ore{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",s=>{if(!this.spectator.useKeys)return;s.key==="Escape"&&this.spectator.stopSpectating()});let i=0;this.context.input.addEventListener(Aa.PointerDown,s=>{i=this.context.time.time}),this.context.input.addEventListener(Aa.PointerUp,s=>{const r=this.context.time.time-i;r>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&r<.3&&this.trySelectObject()})}trySelectObject(){const e=new ea;e.setMask(16777215);const t=this.context.physics.raycast(e);if(Dr&&console.log(...t),t!=null&&t.length)for(const i of t){if(i.distance<.2)continue;const s=i.object,r=Z.getComponentInParent(s,Yn),o=r==null?void 0:r.connectionId;if(o){const a=this.context.players.getPlayerView(o);this.spectator.target=a,Dr&&console.log("spectate",o,r);break}}}}class Lre{constructor(e,t,i){h(this,"guid");h(this,"dontSave",!0);h(this,"targetUserId");h(this,"stoppedFollowing");this.guid=e,this.targetUserId=t,this.stoppedFollowing=i}}class Fre{constructor(e,t){h(this,"guid");h(this,"userId");this.guid=e.guid,this.userId=t}}class Ure{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($i.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($i.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(e,t){if(Dr&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",e,t),this.context.connection.connectionId){const i=(e==null?void 0:e.userId)===void 0,s=i?t:e==null?void 0:e.userId,r=new Lre(this.context.connection.connectionId,s,i);this.context.connection.send("spectator-follower-changed",r)}}onRequestFollowMe(e=!1){if(Dr&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const t=e?void 0:this.context.connection.connectionId,i=new Fre(this.spectator,t);this.context.connection.send("spectator-request-follow",i)}}onUserJoinedRoom(){oe("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){const t=e.targetUserId,i=e.guid;if(Dr&&console.log(e),t===this.context.connection.connectionId)if(e.stoppedFollowing){const s=this.followers.indexOf(i);s!==-1&&(this.followers.splice(s,1),this.removeDisconnectedFollowers(),console.log(i,"unfollows you",this.followers.length))}else this.followers.includes(i)||(this.followers.push(i),this.removeDisconnectedFollowers(),console.log(i,"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 Dr&&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):(Dr&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}var Nre=Object.defineProperty,zre=Object.getOwnPropertyDescriptor,$s=(n,e,t,i)=>{for(var s=i>1?void 0:i?zre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Nre(e,t,s),s};const TE=oe("debugspriterenderer"),Gre=oe("wireframe"),Lb=class{static getOrCreateGeometry(e){if(e._geometry)return e._geometry;if(e.guid&&Lb.cache[e.guid])return TE&&console.log("Take cached geometry for sprite",e.guid),Lb.cache[e.guid];const t=new At;e._geometry=t;const i=new Float32Array(e.triangles.length*3),s=new Float32Array(e.triangles.length*2);for(let r=0;r<e.triangles.length;r+=1){const o=e.triangles[r];i[r*3]=-e.vertices[o].x,i[r*3+1]=e.vertices[o].y,i[r*3+2]=0;const a=e.uv[o];s[r*2]=a.x,s[r*2+1]=1-a.y}return t.setAttribute("position",new rt(i,3)),t.setAttribute("uv",new rt(s,2)),e.guid&&(this.cache[e.guid]=t),TE&&console.log("Built sprite geometry",e,t),t}};let tm=Lb;h(tm,"cache",{});class ac{constructor(){h(this,"guid");h(this,"texture");h(this,"triangles");h(this,"uv");h(this,"vertices");h(this,"_geometry")}}$s([x()],ac.prototype,"guid",2);$s([x(Gt)],ac.prototype,"texture",2);$s([cp()],ac.prototype,"triangles",2);$s([cp()],ac.prototype,"uv",2);$s([cp()],ac.prototype,"vertices",2);const EC=Symbol("spriteOwner");class gv{constructor(){h(this,"sprites")}}$s([x(ac)],gv.prototype,"sprites",2);class Lp{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 i=t==null?void 0:t.texture;i&&(i.encoding=yt,i.minFilter==Yt&&i.magFilter==Yt&&(i.anisotropy=1),i.needsUpdate=!0)}}$s([x(gv)],Lp.prototype,"spriteSheet",2);$s([x()],Lp.prototype,"index",2);class qa extends Ce{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(t){if(t!==this._spriteSheet)if(typeof t=="number"){const i=Math.floor(t);i===t&&(this.spriteIndex=i);return}else this._spriteSheet=t,this.updateSprite()}set spriteIndex(t){this._spriteSheet&&(this._spriteSheet.index=t,this.updateSprite())}get spriteIndex(){var t;return((t=this._spriteSheet)==null?void 0:t.index)??0}get spriteFrames(){var t,i;return((i=(t=this._spriteSheet)==null?void 0:t.spriteSheet)==null?void 0:i.sprites.length)??0}awake(){this._currentSprite=void 0,TE&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(){var i,s,r;if(!this.__didAwake||!((s=(i=this.sprite)==null?void 0:i.spriteSheet)!=null&&s.sprites))return;const t=this.sprite.spriteSheet.sprites[this.spriteIndex];if(this._currentSprite)this._currentSprite.geometry=tm.getOrCreateGeometry(t),this._currentSprite.material.map=t.texture;else{const o=new vi({color:16777215,side:Ii});if(!o)return;if(Gre&&(o.wireframe=!0),this.color&&(o.color||(o.color=new ye),o.color.copy(this.color),o.opacity=this.color.alpha),o.transparent=!0,t.texture&&!o.wireframe){let a=t.texture;a[EC]!==void 0&&a[EC]!==this&&this.spriteFrames>1&&(a=t.texture=a.clone()),a[EC]=this,o.map=a}this.sharedMaterial=o,this._currentSprite=new me(tm.getOrCreateGeometry(t),o)}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,(r=this._spriteSheet)==null||r.update()}}$s([x()],qa.prototype,"drawMode",2);$s([x(xi)],qa.prototype,"color",2);$s([x(Bt)],qa.prototype,"sharedMaterial",2);$s([x(Lp)],qa.prototype,"sprite",1);$s([x()],qa.prototype,"transparent",2);$s([x()],qa.prototype,"cutoutThreshold",2);$s([x()],qa.prototype,"castShadows",2);class ya{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 ya).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+__),(t||new ya).__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 Fr).__init(this.bb_pos+t,this.bb):null}rot(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new Fr).__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 Qre=Object.defineProperty,Hre=Object.getOwnPropertyDescriptor,Vre=(n,e,t,i)=>{for(var s=i>1?void 0:i?Hre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Qre(e,t,s),s};const Tb="SCAM";z1(Tb,ya.getRootAsSyncedCameraModel);const _r=new Yf;class Wre{constructor(e,t){h(this,"userId");h(this,"guid");this.guid=t,this.userId=e}send(e,t){if(e){_r.clear();const i=_r.createString(this.guid),s=_r.createString(this.userId);ya.startSyncedCameraModel(_r),ya.addGuid(_r,i),ya.addUserId(_r,s);const r=wt(e),o=d_(e);ya.addPos(_r,Fr.createVec3(_r,r.x,r.y,r.z)),ya.addRot(_r,Fr.createVec3(_r,o.x,o.y,o.z));const a=ya.endSyncedCameraModel(_r);_r.finish(a,Tb),t.sendBinary(_r.asUint8Array())}}}var WC;const PE=(WC=class extends Ce{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(e){const t=this.userToCamMap[e];return t?this.remoteCams[t].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(Tb,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(Tb,this._receiveCallback)}update(){for(const s in this.remoteCams){const r=this.remoteCams[s],o=this.context.time.realtimeSinceStartup-r.lastUpdate;if(!r||o>this._camTimeoutInSeconds){console.log("Remote cam timeout",r,o),r!=null&&r.obj&&Z.destroy(r.obj),delete this.remoteCams[s],r&&delete this.userToCamMap[r.userId],PE.instances.push(r),this.context.players.removePlayerView(r.userId,Ba.Browser);continue}}if(Ct.IsInWebXR)return;const e=this.context.mainCamera;if(e===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new Wre(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const t=wt(e),i=Ln(e);(t.distanceTo(this._lastWorldPosition)>.001||i.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(t),this._lastWorldQuaternion.copy(i),!((!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(e,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,e,Ba.Browser))}onReceivedRemoteCameraInfoBin(e){const t=e.guid();if(!t)return;const i=e.userId();if(!i||!this.context.connection.userIsInRoom(i)||!this.cameraPrefab)return;let s=this.remoteCams[t];if(!s)if("isObject3D"in this.cameraPrefab){const l=new Oa;l.context=this.context;const c=Z.instantiate(this.cameraPrefab,l);s=this.remoteCams[t]={obj:c,lastUpdate:this.context.time.realtimeSinceStartup,userId:i},s.obj.visible=!0,this.gameObject.add(c),this.userToCamMap[i]=t,PE.instances.push(s);const u=Z.getOrAddComponent(c,Yn);u.connectionId=i,u.avatar=c}else return;const r=s.obj;this.context.players.setPlayerView(i,r,Ba.Browser),s.lastUpdate=this.context.time.realtimeSinceStartup,cr.markDirty(r);const o=e.pos();o&&Mf(r,o.x(),o.y(),o.z());const a=e.rot();a&&f_(r,a.x(),a.y(),a.z())}},h(WC,"instances",[]),WC);let Ex=PE;Vre([x([Ie,Jn])],Ex.prototype,"cameraPrefab",2);var jre=Object.defineProperty,qre=Object.getOwnPropertyDescriptor,mv=(n,e,t,i)=>{for(var s=i>1?void 0:i?qre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&jre(e,t,s),s};const IC="view",MC=oe("debugsyncedroom");class Sh extends Ce{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(){MC&&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 t=oe(IC);if(t&&typeof t=="string"&&t.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(t,!0);return}(this.joinRandomRoom||oe(this.urlParameterName))&&this.tryJoinRoom()}onDisable(){this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}tryJoinRandomRoom(){this.setRandomRoomUrlParameter(),this.tryJoinRoom()}tryJoinRoom(t=0){t===void 0&&(t=0);let i=!1;if(this.urlParameterName){const s=oe(this.urlParameterName);if(s&&typeof s=="string"){i=!0;const r=Ck(s);this.roomName=r}else if(this.joinRandomRoom&&(console.log("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),t<1))return this.tryJoinRoom(t+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&&!i?(MC&&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(),MC&&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(){const t=oe(IC);return t||oe(this.urlParameterName)}setRandomRoomUrlParameter(){const t=eA(),i=this.generateRoomName();oe(this.urlParameterName)?t.set(this.urlParameterName,i):t.append(this.urlParameterName,i),NE(i,t)}generateRoomName(){return wk()+"_"+xk(100,999)}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){const t=window.location.search,i=new URLSearchParams(t);return i.has(this.urlParameterName)&&i.delete(this.urlParameterName),i.set(IC,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+i.toString()}return null}}mv([x()],Sh.prototype,"roomName",2);mv([x()],Sh.prototype,"urlParameterName",2);mv([x()],Sh.prototype,"joinRandomRoom",2);mv([x()],Sh.prototype,"requireRoomParameter",2);mv([x()],Sh.prototype,"autoRejoin",2);function Xre(){const n=oe("testwindowcount")||0;n&&n>0&&Yre(n)}function Yre(n){if(oe("testwindow"))return null;const e=new URL(window.location.href);dm(e.searchParams,mb,1),dm(e.searchParams,"testwindow",1);const t=e.toString(),i=[];window.onbeforeunload=()=>{for(const l of i)l.close()};const s=.05,r=128;let o=0,a=0;for(let l=0;l<n;l++){o*r+r*.01>=window.innerWidth&&(a+=1,o=0);const c=o*(r*(1+s))+window.screenLeft,u=a*(r*(1+s))+window.screenTop+90+60*a;o+=1;const d=window.open(t,"test window "+l,`popup=yes width=${r} height=${r} top=${u} left=${c}`);if(!d){console.warn("Failed to open window");continue}i.push(d),d.onload=()=>{d.onbeforeunload=()=>{for(let f=0;f<i.length;f++){const p=i[f];p!==d&&p.close()}i.length=0}}}return i}class JM extends Ce{awake(){Xre()}}class ZM extends Ce{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(Lm,t=>{});else{this.models=[];for(let t=0;t<this.transformsPerFrame;t++)this.models.push(new vz(this.context.connection.connectionId+"_simulatedTransform_"+t,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 Yf(1024));const t=this.builder;for(let i=0;i<this.transformsPerFrame;i++){t.clear();const s=fU(this.context.connection.connectionId,this);this.context.connection.sendBinary(s)}}else if(this.models)for(let t=0;t<this.models.length;t++){const i=this.models[t];i.dontSave=!0,i.update(this,null),this.context.connection.send("TestSimulateUserData-"+t,i)}}}}class vz{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 i=e.worldPosition;this.position.x=i.x,this.position.y=i.y,this.position.z=i.z;const s=e.worldQuaternion;if(this.rotation.x=s.x,this.rotation.y=s.y,this.rotation.z=s.z,this.rotation.w=s.w,this.fast=!1,t){const r=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=r.x,this.velocity.y=r.y,this.velocity.z=r.z}}}h(vz,"temp",new S);var Kre=Object.defineProperty,Jre=Object.getOwnPropertyDescriptor,Fp=(n,e,t,i)=>{for(var s=i>1?void 0:i?Jre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Kre(e,t,s),s};class Xa extends Ps{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=Hl.MEDIUM,this.resolutionScale.defaultValue=1/window.devicePixelRatio}onCreateEffect(){console.log(this);const t=new J7({kernelSize:Hl.VERY_LARGE});return this.offset.onValueChanged=i=>t.offset=i,this.rotation.onValueChanged=i=>t.rotation=i,this.focusArea.onValueChanged=i=>t.focusArea=i,this.feather.onValueChanged=i=>t.feather=i,this.kernelSize.onValueChanged=i=>t.blurPass.kernelSize=i,this.resolutionScale.onValueChanged=i=>t.resolution.scale=i/window.devicePixelRatio,t}}Fp([x(Et)],Xa.prototype,"offset",2);Fp([x(Et)],Xa.prototype,"rotation",2);Fp([x(Et)],Xa.prototype,"focusArea",2);Fp([x(Et)],Xa.prototype,"feather",2);Fp([x(Et)],Xa.prototype,"kernelSize",2);Fp([x(Et)],Xa.prototype,"resolutionScale",2);To("TiltShiftEffect",Xa);var Zre=Object.defineProperty,$re=Object.getOwnPropertyDescriptor,eoe=(n,e,t,i)=>{for(var s=i>1?void 0:i?$re(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Zre(e,t,s),s};class Av extends Ps{constructor(){super(...arguments);h(this,"mode")}get typeName(){return"ToneMapping"}get isToneMapping(){return!0}init(){this.mode.defaultValue=Qs}apply(){this.mode.onValueChanged=this._apply.bind(this),this._apply(this.mode.value)}unapply(){this.context.renderer.toneMapping=Qs}_apply(t){switch(t){case 0:this.context.renderer.toneMapping=gm;break;case 1:this.context.renderer.toneMapping=qE;break;case 2:this.context.renderer.toneMapping=XE;break}}}eoe([x(Et)],Av.prototype,"mode",2);To("Tonemapping",Av);const Uh=new qf,sr=new S,Tc=new S,Di=new xe,$D={X:new S(1,0,0),Y:new S(0,1,0),Z:new S(0,0,1)},TC={type:"change"},ek={type:"mouseDown"},tk={type:"mouseUp",mode:null},ik={type:"objectChange"};class toe extends Ie{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 i=new aoe;this._gizmo=i,this.add(i);const s=new loe;this._plane=s,this.add(s);const r=this;function o(b,y){let _=y;Object.defineProperty(r,b,{get:function(){return _!==void 0?_:y},set:function(C){_!==C&&(_=C,s[b]=C,i[b]=C,r.dispatchEvent({type:b+"-changed",value:C}),r.dispatchEvent(TC))}}),r[b]=y,s[b]=y,i[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 xe,u=new xe,d=new S,f=new xe,p=new S,g=new S,m=new S,A=0,v=new S;o("worldPosition",a),o("worldPositionStart",l),o("worldQuaternion",c),o("worldQuaternionStart",u),o("cameraPosition",d),o("cameraQuaternion",f),o("pointStart",p),o("pointEnd",g),o("rotationAxis",m),o("rotationAngle",A),o("eye",v),this._offset=new S,this._startNorm=new S,this._endNorm=new S,this._cameraScale=new S,this._parentPosition=new S,this._parentQuaternion=new xe,this._parentQuaternionInv=new xe,this._parentScale=new S,this._worldScaleStart=new S,this._worldQuaternionInv=new xe,this._worldScale=new S,this._positionStart=new S,this._quaternionStart=new xe,this._scaleStart=new S,this._getPointer=ioe.bind(this),this._onPointerDown=soe.bind(this),this._onPointerHover=noe.bind(this),this._onPointerMove=roe.bind(this),this._onPointerUp=ooe.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;Uh.setFromCamera(e,this.camera);const t=PC(this._gizmo.picker[this.mode],Uh);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){Uh.setFromCamera(e,this.camera);const t=PC(this._plane,Uh,!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,ek.mode=this.mode,this.dispatchEvent(ek)}}pointerMove(e){const t=this.axis,i=this.mode,s=this.object;let r=this.space;if(i==="scale"?r="local":(t==="E"||t==="XYZE"||t==="XYZ")&&(r="world"),s===void 0||t===null||this.dragging===!1||e.button!==-1)return;Uh.setFromCamera(e,this.camera);const o=PC(this._plane,Uh,!0);if(o){if(this.pointEnd.copy(o.point).sub(this.worldPositionStart),i==="translate")this._offset.copy(this.pointEnd).sub(this.pointStart),r==="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),r==="local"&&t!=="XYZ"?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),s.position.copy(this._offset).add(this._positionStart),this.translationSnap&&(r==="local"&&(s.position.applyQuaternion(Di.copy(this._quaternionStart).invert()),t.search("X")!==-1&&(s.position.x=Math.round(s.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(s.position.y=Math.round(s.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(s.position.z=Math.round(s.position.z/this.translationSnap)*this.translationSnap),s.position.applyQuaternion(this._quaternionStart)),r==="world"&&(s.parent&&s.position.add(sr.setFromMatrixPosition(s.parent.matrixWorld)),t.search("X")!==-1&&(s.position.x=Math.round(s.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(s.position.y=Math.round(s.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(s.position.z=Math.round(s.position.z/this.translationSnap)*this.translationSnap),s.parent&&s.position.sub(sr.setFromMatrixPosition(s.parent.matrixWorld))));else if(i==="scale"){if(t.search("XYZ")!==-1){let a=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(a*=-1),Tc.set(a,a,a)}else sr.copy(this.pointStart),Tc.copy(this.pointEnd),sr.applyQuaternion(this._worldQuaternionInv),Tc.applyQuaternion(this._worldQuaternionInv),Tc.divide(sr),t.search("X")===-1&&(Tc.x=1),t.search("Y")===-1&&(Tc.y=1),t.search("Z")===-1&&(Tc.z=1);s.scale.copy(this._scaleStart).multiply(Tc),this.scaleSnap&&(t.search("X")!==-1&&(s.scale.x=Math.round(s.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Y")!==-1&&(s.scale.y=Math.round(s.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Z")!==-1&&(s.scale.z=Math.round(s.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(i==="rotate"){this._offset.copy(this.pointEnd).sub(this.pointStart);const a=20/this.worldPosition.distanceTo(sr.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(sr.copy(this.rotationAxis).cross(this.eye))*a):(t==="X"||t==="Y"||t==="Z")&&(this.rotationAxis.copy($D[t]),sr.copy($D[t]),r==="local"&&sr.applyQuaternion(this.worldQuaternion),this.rotationAngle=this._offset.dot(sr.cross(this.eye).normalize())*a),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),r==="local"&&t!=="E"&&t!=="XYZE"?(s.quaternion.copy(this._quaternionStart),s.quaternion.multiply(Di.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),s.quaternion.copy(Di.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),s.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(TC),this.dispatchEvent(ik)}}pointerUp(e){e.button===0&&(this.dragging&&this.axis!==null&&(tk.mode=this.mode,this.dispatchEvent(tk)),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(TC),this.dispatchEvent(ik),this.pointStart.copy(this.pointEnd))}getRaycaster(){return Uh}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 ioe(n){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:n.button};{const e=this.domElement.getBoundingClientRect();return{x:(n.clientX-e.left)/e.width*2-1,y:-(n.clientY-e.top)/e.height*2+1,button:n.button}}}function noe(n){if(this.enabled)switch(n.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(n));break}}function soe(n){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(n.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(n)),this.pointerDown(this._getPointer(n)))}function roe(n){this.enabled&&this.pointerMove(this._getPointer(n))}function ooe(n){this.enabled&&(this.domElement.releasePointerCapture(n.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(n)))}function PC(n,e,t){const i=e.intersectObject(n,!0);for(let s=0;s<i.length;s++)if(i[s].object.visible||t)return i[s];return!1}const Hy=new xn,bi=new S(0,1,0),nk=new S(0,0,0),sk=new Pe,Vy=new xe,O0=new xe,ua=new S,rk=new Pe,Pg=new S(1,0,0),Wh=new S(0,1,0),Rg=new S(0,0,1),Wy=new S,cg=new S,hg=new S;class aoe extends Ie{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const e=new vi({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),t=new dn({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),i=e.clone();i.opacity=.15;const s=t.clone();s.opacity=.5;const r=e.clone();r.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 f=e.clone();f.color.setHex(16776960),f.opacity=.25,e.clone().color.setHex(16776960);const g=e.clone();g.color.setHex(7895160);const m=new Yi(0,.04,.1,12);m.translate(0,.05,0);const A=new gi(.08,.08,.08);A.translate(0,.04,0);const v=new At;v.setAttribute("position",new nt([0,0,0,1,0,0],3));const b=new Yi(.0075,.0075,.5,3);b.translate(0,.25,0);function y(H,$){const J=new _a(H,.0075,3,64,$*Math.PI*2);return J.rotateY(Math.PI/2),J.rotateX(Math.PI/2),J}function _(){const H=new At;return H.setAttribute("position",new nt([0,0,0,1,1,1],3)),H}const C={X:[[new me(m,r),[.5,0,0],[0,0,-Math.PI/2]],[new me(m,r),[-.5,0,0],[0,0,Math.PI/2]],[new me(b,r),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new me(m,o),[0,.5,0]],[new me(m,o),[0,-.5,0],[Math.PI,0,0]],[new me(b,o)]],Z:[[new me(m,a),[0,0,.5],[Math.PI/2,0,0]],[new me(m,a),[0,0,-.5],[-Math.PI/2,0,0]],[new me(b,a),null,[Math.PI/2,0,0]]],XYZ:[[new me(new Sa(.1,0),d.clone()),[0,0,0]]],XY:[[new me(new gi(.15,.15,.01),u.clone()),[.15,.15,0]]],YZ:[[new me(new gi(.15,.15,.01),l.clone()),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new me(new gi(.15,.15,.01),c.clone()),[.15,0,.15],[-Math.PI/2,0,0]]]},E={X:[[new me(new Yi(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]],[new me(new Yi(.2,0,.6,4),i),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new me(new Yi(.2,0,.6,4),i),[0,.3,0]],[new me(new Yi(.2,0,.6,4),i),[0,-.3,0],[0,0,Math.PI]]],Z:[[new me(new Yi(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]],[new me(new Yi(.2,0,.6,4),i),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new me(new Sa(.2,0),i)]],XY:[[new me(new gi(.2,.2,.01),i),[.15,.15,0]]],YZ:[[new me(new gi(.2,.2,.01),i),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new me(new gi(.2,.2,.01),i),[.15,0,.15],[-Math.PI/2,0,0]]]},T={START:[[new me(new Sa(.01,2),s),null,null,null,"helper"]],END:[[new me(new Sa(.01,2),s),null,null,null,"helper"]],DELTA:[[new an(_(),s),null,null,null,"helper"]],X:[[new an(v,s.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new an(v,s.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new an(v,s.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},w={XYZE:[[new me(y(.5,1),g),null,[0,Math.PI/2,0]]],X:[[new me(y(.5,.5),r)]],Y:[[new me(y(.5,.5),o),null,[0,0,-Math.PI/2]]],Z:[[new me(y(.5,.5),a),null,[0,Math.PI/2,0]]],E:[[new me(y(.75,1),f),null,[0,Math.PI/2,0]]]},M={AXIS:[[new an(v,s.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},P={XYZE:[[new me(new Gr(.25,10,8),i)]],X:[[new me(new _a(.5,.1,4,24),i),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new me(new _a(.5,.1,4,24),i),[0,0,0],[Math.PI/2,0,0]]],Z:[[new me(new _a(.5,.1,4,24),i),[0,0,0],[0,0,-Math.PI/2]]],E:[[new me(new _a(.75,.1,2,24),i)]]},k={X:[[new me(A,r),[.5,0,0],[0,0,-Math.PI/2]],[new me(b,r),[0,0,0],[0,0,-Math.PI/2]],[new me(A,r),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new me(A,o),[0,.5,0]],[new me(b,o)],[new me(A,o),[0,-.5,0],[0,0,Math.PI]]],Z:[[new me(A,a),[0,0,.5],[Math.PI/2,0,0]],[new me(b,a),[0,0,0],[Math.PI/2,0,0]],[new me(A,a),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new me(new gi(.15,.15,.01),u),[.15,.15,0]]],YZ:[[new me(new gi(.15,.15,.01),l),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new me(new gi(.15,.15,.01),c),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new me(new gi(.1,.1,.1),d.clone())]]},Q={X:[[new me(new Yi(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]],[new me(new Yi(.2,0,.6,4),i),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new me(new Yi(.2,0,.6,4),i),[0,.3,0]],[new me(new Yi(.2,0,.6,4),i),[0,-.3,0],[0,0,Math.PI]]],Z:[[new me(new Yi(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]],[new me(new Yi(.2,0,.6,4),i),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new me(new gi(.2,.2,.01),i),[.15,.15,0]]],YZ:[[new me(new gi(.2,.2,.01),i),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new me(new gi(.2,.2,.01),i),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new me(new gi(.2,.2,.2),i),[0,0,0]]]},z={X:[[new an(v,s.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new an(v,s.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new an(v,s.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function L(H){const $=new Ie;for(const J in H)for(let K=H[J].length;K--;){const ue=H[J][K][0].clone(),he=H[J][K][1],Re=H[J][K][2],ge=H[J][K][3],ie=H[J][K][4];ue.name=J,ue.tag=ie,he&&ue.position.set(he[0],he[1],he[2]),Re&&ue.rotation.set(Re[0],Re[1],Re[2]),ge&&ue.scale.set(ge[0],ge[1],ge[2]),ue.updateMatrix();const le=ue.geometry.clone();le.applyMatrix4(ue.matrix),ue.geometry=le,ue.renderOrder=1/0,ue.position.set(0,0,0),ue.rotation.set(0,0,0),ue.scale.set(1,1,1),$.add(ue)}return $}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=L(C)),this.add(this.gizmo.rotate=L(w)),this.add(this.gizmo.scale=L(k)),this.add(this.picker.translate=L(E)),this.add(this.picker.rotate=L(P)),this.add(this.picker.scale=L(Q)),this.add(this.helper.translate=L(T)),this.add(this.helper.rotate=L(M)),this.add(this.helper.scale=L(z)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}updateMatrixWorld(e){const i=(this.mode==="scale"?"local":this.space)==="local"?this.worldQuaternion:O0;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 o=s[r];o.visible=!0,o.rotation.set(0,0,0),o.position.copy(this.worldPosition);let a;if(this.camera.isOrthographicCamera?a=(this.camera.top-this.camera.bottom)/this.camera.zoom:a=this.worldPosition.distanceTo(this.cameraPosition)*Math.min(1.9*Math.tan(Math.PI*this.camera.fov/360)/this.camera.zoom,7),o.scale.set(1,1,1).multiplyScalar(a*this.size/4),o.tag==="helper"){o.visible=!1,o.name==="AXIS"?(o.position.copy(this.worldPositionStart),o.visible=!!this.axis,this.axis==="X"&&(Di.setFromEuler(Hy.set(0,0,0)),o.quaternion.copy(i).multiply(Di),Math.abs(bi.copy(Pg).applyQuaternion(i).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="Y"&&(Di.setFromEuler(Hy.set(0,0,Math.PI/2)),o.quaternion.copy(i).multiply(Di),Math.abs(bi.copy(Wh).applyQuaternion(i).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="Z"&&(Di.setFromEuler(Hy.set(0,Math.PI/2,0)),o.quaternion.copy(i).multiply(Di),Math.abs(bi.copy(Rg).applyQuaternion(i).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="XYZE"&&(Di.setFromEuler(Hy.set(0,Math.PI/2,0)),bi.copy(this.rotationAxis),o.quaternion.setFromRotationMatrix(sk.lookAt(nk,bi,Wh)),o.quaternion.multiply(Di),o.visible=this.dragging),this.axis==="E"&&(o.visible=!1)):o.name==="START"?(o.position.copy(this.worldPositionStart),o.visible=this.dragging):o.name==="END"?(o.position.copy(this.worldPosition),o.visible=this.dragging):o.name==="DELTA"?(o.position.copy(this.worldPositionStart),o.quaternion.copy(this.worldQuaternionStart),sr.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),sr.applyQuaternion(this.worldQuaternionStart.clone().invert()),o.scale.copy(sr),o.visible=this.dragging):(o.quaternion.copy(i),this.dragging?o.position.copy(this.worldPositionStart):o.position.copy(this.worldPosition),this.axis&&(o.visible=this.axis.search(o.name)!==-1));continue}o.quaternion.copy(i),this.mode==="translate"||this.mode==="scale"?(o.name==="X"&&Math.abs(bi.copy(Pg).applyQuaternion(i).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="Y"&&Math.abs(bi.copy(Wh).applyQuaternion(i).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="Z"&&Math.abs(bi.copy(Rg).applyQuaternion(i).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="XY"&&Math.abs(bi.copy(Rg).applyQuaternion(i).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="YZ"&&Math.abs(bi.copy(Pg).applyQuaternion(i).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="XZ"&&Math.abs(bi.copy(Wh).applyQuaternion(i).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1)):this.mode==="rotate"&&(Vy.copy(i),bi.copy(this.eye).applyQuaternion(Di.copy(i).invert()),o.name.search("E")!==-1&&o.quaternion.setFromRotationMatrix(sk.lookAt(this.eye,nk,Wh)),o.name==="X"&&(Di.setFromAxisAngle(Pg,Math.atan2(-bi.y,bi.z)),Di.multiplyQuaternions(Vy,Di),o.quaternion.copy(Di)),o.name==="Y"&&(Di.setFromAxisAngle(Wh,Math.atan2(bi.x,bi.z)),Di.multiplyQuaternions(Vy,Di),o.quaternion.copy(Di)),o.name==="Z"&&(Di.setFromAxisAngle(Rg,Math.atan2(bi.y,bi.x)),Di.multiplyQuaternions(Vy,Di),o.quaternion.copy(Di))),o.visible=o.visible&&(o.name.indexOf("X")===-1||this.showX),o.visible=o.visible&&(o.name.indexOf("Y")===-1||this.showY),o.visible=o.visible&&(o.name.indexOf("Z")===-1||this.showZ),o.visible=o.visible&&(o.name.indexOf("E")===-1||this.showX&&this.showY&&this.showZ),o.material._color=o.material._color||o.material.color.clone(),o.material._opacity=o.material._opacity||o.material.opacity,o.material.color.copy(o.material._color),o.material.opacity=o.material._opacity,this.enabled&&this.axis&&(o.name===this.axis||this.axis.split("").some(function(l){return o.name===l}))&&(o.material.color.setHex(16776960),o.material.opacity=1)}super.updateMatrixWorld(e)}}class loe extends me{constructor(){super(new $n(1e5,1e5,2,2),new vi({visible:!1,wireframe:!0,side:Ii,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"),Wy.copy(Pg).applyQuaternion(t==="local"?this.worldQuaternion:O0),cg.copy(Wh).applyQuaternion(t==="local"?this.worldQuaternion:O0),hg.copy(Rg).applyQuaternion(t==="local"?this.worldQuaternion:O0),bi.copy(cg),this.mode){case"translate":case"scale":switch(this.axis){case"X":bi.copy(this.eye).cross(Wy),ua.copy(Wy).cross(bi);break;case"Y":bi.copy(this.eye).cross(cg),ua.copy(cg).cross(bi);break;case"Z":bi.copy(this.eye).cross(hg),ua.copy(hg).cross(bi);break;case"XY":ua.copy(hg);break;case"YZ":ua.copy(Wy);break;case"XZ":bi.copy(hg),ua.copy(cg);break;case"XYZ":case"E":ua.set(0,0,0);break}break;case"rotate":default:ua.set(0,0,0)}ua.length()===0?this.quaternion.copy(this.cameraQuaternion):(rk.lookAt(sr.set(0,0,0),ua,bi),this.quaternion.setFromRotationMatrix(rk)),super.updateMatrixWorld(e)}}var coe=Object.defineProperty,hoe=Object.getOwnPropertyDescriptor,Ix=(n,e,t,i)=>{for(var s=i>1?void 0:i?hoe(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&coe(e,t,s),s};class ed extends Ce{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 t;this.isGizmo&&!bA||this.context.mainCamera&&(this.control||(this.control=new toe(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(i=>{const s=i;if(s.layers.set(2),s){const r=s.material;r&&(r.opacity=.3)}}),this.orbit=Z.getComponentInParent(this.context.mainCamera,ec)??void 0),this.control&&(this.context.scene.add(this.control),this.control.attach(this.gameObject),this.changeEventListener=this.onControlChangedEvent.bind(this),(t=this.control)==null||t.addEventListener("dragging-changed",this.changeEventListener),this.addWindowEvents()))}onDisable(){var t,i;(t=this.control)==null||t.removeFromParent(),this.changeEventListener&&((i=this.control)==null||i.removeEventListener("dragging-changed",this.changeEventListener)),this.removeWindowEvents()}enableSnapping(){this.control&&(this.control.setTranslationSnap(this.translationSnap),this.control.setRotationSnap(Hs.degToRad(this.rotationSnapAngle)),this.control.setScaleSnap(this.scaleSnap))}disableSnapping(){this.control&&(this.control.setTranslationSnap(null),this.control.setRotationSnap(null),this.control.setScaleSnap(null))}onControlChangedEvent(t){const i=this.orbit;if(i&&(i.enabled=!t.value),t.value){const s=Z.getComponentInParent(this.gameObject,th);s&&s.requestOwnership()}}addWindowEvents(){const t=this.control;t&&(this.windowKeyDownListener||(this.windowKeyDownListener=i=>{if(this.enabled)switch(i.keyCode){case 81:t.setSpace(t.space==="local"?"world":"local");break;case 16:this.enableSnapping();break;case 87:t.setMode("translate");break;case 69:t.setMode("rotate");break;case 82:t.setMode("scale");break;case 187:case 107:t.setSize(t.size+.1);break;case 189:case 109:t.setSize(Math.max(t.size-.1,.1));break;case 88:t.showX=!t.showX;break;case 89:t.showY=!t.showY;break;case 90:t.showZ=!t.showZ;break;case 32:t.enabled=!t.enabled;break}}),this.windowKeyUpListener||(this.windowKeyUpListener=i=>{if(this.enabled)switch(i.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)}}Ix([x()],ed.prototype,"isGizmo",2);Ix([x()],ed.prototype,"translationSnap",2);Ix([x()],ed.prototype,"rotationSnapAngle",2);Ix([x()],ed.prototype,"scaleSnap",2);var uoe=Object.defineProperty,doe=Object.getOwnPropertyDescriptor,$M=(n,e,t,i)=>{for(var s=i>1?void 0:i?doe(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&uoe(e,t,s),s};class td extends Ps{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 t=new EF;return this.intensity.onValueChanged=i=>{t.offset=i,this.updateDarkness(t)},this.color.onValueChanged=i=>{this.updateDarkness(t)},t}updateDarkness(t){const i=this.intensity.value;t.darkness=i}}$M([x(Et)],td.prototype,"color",2);$M([x(Et)],td.prototype,"intensity",2);$M([x(Et)],td.prototype,"center",2);To("Vignette",td);var foe=Object.defineProperty,poe=Object.getOwnPropertyDescriptor,goe=(n,e,t,i)=>{for(var s=i>1?void 0:i?poe(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&foe(e,t,s),s};const RC=oe("debugpost");class Mx extends Ce{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 t;(t=this.sharedProfile)==null||t.init(),RC&&(console.log(this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",i=>{i.key==="p"&&(console.log("Toggle volume: "+this.name,!this.enabled),this.enabled=!this.enabled)}))}onDisable(){var t;(t=this._postprocessing)==null||t.unapply()}onBeforeRender(){if(!this.context.isInXR){if(this.context.composer&&!(this.context.composer instanceof nI))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 t;(t=this._postprocessing)==null||t.dispose()}apply(){var i,s;RC&&console.log("Apply PostProcessing",this,(i=this.context.mainCamera)==null?void 0:i.name),Ss()&&(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,(s=this.sharedProfile)!=null&&s.components&&this._effects.push(...this.sharedProfile.components);const t=this.gameObject.getComponentsInChildren(Ps);if(RC&&(t!=null&&t.length)&&console.log("Additional",t),t)for(const r of t)r.active&&this._effects.push(r);this._effects.length>0&&(this._postprocessing||(this._postprocessing=new xx(this.context)),this._postprocessing.apply(this._effects),this._applyPostQueue())}unapply(){var t;(t=this._postprocessing)==null||t.unapply()}_applyPostQueue(){if(this._modificationQueue){for(const t of this._modificationQueue.values())this.onEditorModification(t);this._modificationQueue.clear()}}onEditorModification(t){var i,s;if(t.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(t.propertyName,t),!0;if(!((i=this._effects)!=null&&i.length))return;const r=t.propertyName.split(".");if(r.length===3||r.length===4){const o=r[1],a=r[2];for(const l of this._effects)if(((s=l.typeName)==null?void 0:s.toLowerCase())===o.toLowerCase()){if(a==="active"){l.active=t.value,this.scheduleRecreate();return}if(!jy.has(o)){const c=new Array;jy.set(o,c);const u=Object.keys(l);for(const d of u)l[d]instanceof Et&&c.push(d)}if(jy.has(o)){const c=a.toLowerCase(),u=jy.get(o);for(const d of u)if(d.toLowerCase()===c){const f=l[d];f instanceof Et&&(r.length===4&&r[3]==="active"?(f.overrideState=t.value,this.scheduleRecreate()):f&&f.value!==void 0&&(f.value=t.value));return}}console.warn("Unknown modification",a);return}}return!0}return!1}scheduleRecreate(){const t=++this._recreateId;setTimeout(()=>{t===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}goe([cp(qA)],Mx.prototype,"sharedProfile",2);const jy=new Map;var moe=Object.defineProperty,Aoe=Object.getOwnPropertyDescriptor,voe=(n,e,t,i)=>{for(var s=i>1?void 0:i?Aoe(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&moe(e,t,s),s};class Tx extends Ce{constructor(){super(...arguments);h(this,"backgroundTint",new xi(1,1,1,1));h(this,"_preRender");h(this,"backgroundPlane");h(this,"threeTexture");h(this,"forceTextureInitialization",function(){const t=new vi,i=new $n,s=new pr;s.add(new me(i,t));const r=new Mu;return function(a,l){t.map=l,a.render(s,r)}}())}awake(){Ct.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(t=>t!==this._preRender),this.backgroundPlane&&this.gameObject.remove(this.backgroundPlane)}preRender(){if(!this||!this.gameObject)return;const i=this.context.renderer.xr.getFrame();i&&(!this.threeTexture&&this.context.renderer&&(this.threeTexture=new Gt,this.forceTextureInitialization(this.context.renderer,this.threeTexture)),this.backgroundPlane===void 0&&(this.backgroundPlane=boe(this.backgroundTint),this.gameObject.add(this.backgroundPlane)),this.updateFromFrame(i))}onBeforeRender(t){this.updateFromFrame(t)}updateFromFrame(t){if(!t)return;const i=t.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(i){for(const s of i.views)if("camera"in s&&s.camera){let o=this.context.renderer.xr.getBinding();if(o||(o=new XRWebGLBinding(t.session,this.context.renderer.getContext())),o){let a=null;if("getCameraImage"in o){a=o.getCameraImage(s.camera);const l=this.context.renderer.properties.get(this.threeTexture);l.__webglTexture=a,this.backgroundPlane&&(this.backgroundPlane.setTexture(this.threeTexture),this.backgroundPlane.visible=!0)}}}}}}voe([x()],Tx.prototype,"backgroundTint",2);let yoe=`
|
|
5438
|
+
`)}}}applyShadowMaterial(){var i;const t=Z.getComponent(this.gameObject,Ui);if(t)if(((i=t.sharedMaterial)==null?void 0:i.type)!=="ShadowMaterial"){const s=new _1;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 t=Z.getComponent(this.gameObject,Ui);if(t){const i=t.sharedMaterial;i.depthWrite=!0,i.stencilWrite=!0,i.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(t){t&&(t.depthWrite=!1,t.stencilWrite=!1)}}mz([x()],dv.prototype,"mode",2);mz([x(xi)],dv.prototype,"shadowColor",2);var _re=Object.defineProperty,xre=Object.getOwnPropertyDescriptor,Cx=(n,e,t,i)=>{for(var s=i>1?void 0:i?xre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&_re(e,t,s),s},HC;const Az=(HC=class extends Ce{constructor(){super(...arguments);h(this,"target",null);h(this,"followFactor",.1);h(this,"rotateFactor",.1);h(this,"positionAxes",Kd.All);h(this,"flipForward",!1);h(this,"_firstUpdate",!0)}onBeforeRender(){this.updateNow(!1)}updateNow(e){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const t=wt(this.target),i=this._firstUpdate||e?1:$e.clamp01(this.context.time.deltaTime*this.followFactor),s=this.worldPosition;this.positionAxes&Kd.X&&(s.x=$e.lerp(s.x,t.x,i)),this.positionAxes&Kd.Y&&(s.y=$e.lerp(s.y,t.y,i)),this.positionAxes&Kd.Z&&(s.z=$e.lerp(s.z,t.z,i)),this.worldPosition=s}if(this.rotateFactor>0){const t=Ln(this.target);this.flipForward&&t.premultiply(Az._invertForward);const i=this._firstUpdate||e?1:$e.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(t,i)}this._firstUpdate=!1}}},h(HC,"_invertForward",new xe().setFromAxisAngle(new S(0,1,0),Math.PI)),HC);let Ch=Az;Cx([x(Ie)],Ch.prototype,"target",2);Cx([x()],Ch.prototype,"followFactor",2);Cx([x()],Ch.prototype,"rotateFactor",2);Cx([x()],Ch.prototype,"positionAxes",2);class wre extends me{constructor(e){const t=new Cre(e),i=new $n(t.image.width*.001,t.image.height*.001),s=new vi({map:t,toneMapped:!1,transparent:!0});super(i,s);function r(o){s.map.dispatchDOMEvent(o)}this.addEventListener("mousedown",r),this.addEventListener("mousemove",r),this.addEventListener("mouseup",r),this.addEventListener("click",r),this.dispose=function(){i.dispose(),s.dispose(),s.map.dispose(),ME.delete(e),this.removeEventListener("mousedown",r),this.removeEventListener("mousemove",r),this.removeEventListener("mouseup",r),this.removeEventListener("click",r)}}}class Cre extends Q2{constructor(e){super(KD(e)),this.dom=e,this.anisotropy=16,this.encoding=yt,this.minFilter=Ot,this.magFilter=Ot;const t=new MutationObserver(()=>{this.scheduleUpdate||(this.scheduleUpdate=setTimeout(()=>this.update(),16))}),i={attributes:!0,childList:!0,subtree:!0,characterData:!0};t.observe(e,i),this.observer=t}dispatchDOMEvent(e){e.data&&Sre(this.dom,e.type,e.data.x,e.data.y)}update(){this.image=KD(this.dom),this.needsUpdate=!0,this.scheduleUpdate=null}dispose(){this.observer&&this.observer.disconnect(),this.scheduleUpdate=clearTimeout(this.scheduleUpdate),super.dispose()}}const ME=new WeakMap;function KD(n){const e=document.createRange(),t=new ye;function i(f){const p=[];let g=!1;function m(){if(g&&(g=!1,f.restore()),p.length===0)return;let A=-1/0,v=-1/0,b=1/0,y=1/0;for(let _=0;_<p.length;_++){const C=p[_];A=Math.max(A,C.x),v=Math.max(v,C.y),b=Math.min(b,C.x+C.width),y=Math.min(y,C.y+C.height)}f.save(),f.beginPath(),f.rect(A,v,b-A,y-v),f.clip(),g=!0}return{add:function(A){p.push(A),m()},remove:function(){p.pop(),m()}}}function s(f,p,g,m){m!==""&&(f.textTransform==="uppercase"&&(m=m.toUpperCase()),u.font=f.fontWeight+" "+f.fontSize+" "+f.fontFamily,u.textBaseline="top",u.fillStyle=f.color,u.fillText(m,p,g+parseFloat(f.fontSize)*.1))}function r(f,p,g,m,A){g<2*A&&(A=g/2),m<2*A&&(A=m/2),u.beginPath(),u.moveTo(f+A,p),u.arcTo(f+g,p,f+g,p+m,A),u.arcTo(f+g,p+m,f,p+m,A),u.arcTo(f,p+m,f,p,A),u.arcTo(f,p,f+g,p,A),u.closePath()}function o(f,p,g,m,A,v){const b=f[p+"Width"],y=f[p+"Style"],_=f[p+"Color"];b!=="0px"&&y!=="none"&&_!=="transparent"&&_!=="rgba(0, 0, 0, 0)"&&(u.strokeStyle=_,u.lineWidth=parseFloat(b),u.beginPath(),u.moveTo(g,m),u.lineTo(g+A,m+v),u.stroke())}function a(f,p){let g=0,m=0,A=0,v=0;if(f.nodeType===Node.TEXT_NODE){e.selectNode(f);const y=e.getBoundingClientRect();g=y.left-l.left-.5,m=y.top-l.top-.5,A=y.width,v=y.height,s(p,g,m,f.nodeValue.trim())}else{if(f.nodeType===Node.COMMENT_NODE)return;if(f instanceof HTMLCanvasElement){if(f.style.display==="none")return;u.save();const y=window.devicePixelRatio;u.scale(1/y,1/y),u.drawImage(f,0,0),u.restore()}else{if(f.style.display==="none")return;const y=f.getBoundingClientRect();g=y.left-l.left-.5,m=y.top-l.top-.5,A=y.width,v=y.height,p=window.getComputedStyle(f),r(g,m,A,v,parseFloat(p.borderRadius));const _=p.backgroundColor;_!=="transparent"&&_!=="rgba(0, 0, 0, 0)"&&(u.fillStyle=_,u.fill());const C=["borderTop","borderLeft","borderBottom","borderRight"];let E=!0,T=null;for(const w of C){if(T!==null&&(E=p[w+"Width"]===p[T+"Width"]&&p[w+"Color"]===p[T+"Color"]&&p[w+"Style"]===p[T+"Style"]),E===!1)break;T=w}if(E===!0){const w=parseFloat(p.borderTopWidth);p.borderTopWidth!=="0px"&&p.borderTopStyle!=="none"&&p.borderTopColor!=="transparent"&&p.borderTopColor!=="rgba(0, 0, 0, 0)"&&(u.strokeStyle=p.borderTopColor,u.lineWidth=w,u.stroke())}else o(p,"borderTop",g,m,A,0),o(p,"borderLeft",g,m,0,v),o(p,"borderBottom",g,m+v,A,0),o(p,"borderRight",g+A,m,0,v);if(f instanceof HTMLInputElement){let w=p.accentColor;(w===void 0||w==="auto")&&(w=p.color),t.set(w);const P=Math.sqrt(.299*t.r**2+.587*t.g**2+.114*t.b**2)<.5?"white":"#111111";if(f.type==="radio"&&(r(g,m,A,v,v),u.fillStyle="white",u.strokeStyle=w,u.lineWidth=1,u.fill(),u.stroke(),f.checked&&(r(g+2,m+2,A-4,v-4,v),u.fillStyle=w,u.strokeStyle=P,u.lineWidth=2,u.fill(),u.stroke())),f.type==="checkbox"&&(r(g,m,A,v,2),u.fillStyle=f.checked?w:"white",u.strokeStyle=f.checked?P:w,u.lineWidth=1,u.stroke(),u.fill(),f.checked)){const k=u.textAlign;u.textAlign="center";const Q={color:P,fontFamily:p.fontFamily,fontSize:v+"px",fontWeight:"bold"};s(Q,g+A/2,m,"✔"),u.textAlign=k}if(f.type==="range"){const[k,Q,z]=["min","max","value"].map(H=>parseFloat(f[H])),L=(z-k)/(Q-k)*(A-v);r(g,m+v/4,A,v/2,v/4),u.fillStyle=P,u.strokeStyle=w,u.lineWidth=1,u.fill(),u.stroke(),r(g,m+v/4,L+v/2,v/2,v/4),u.fillStyle=w,u.fill(),r(g+L,m,v,v,v/2),u.fillStyle=w,u.fill()}(f.type==="color"||f.type==="text"||f.type==="number")&&(d.add({x:g,y:m,width:A,height:v}),s(p,g+parseInt(p.paddingLeft),m+parseInt(p.paddingTop),f.value),d.remove())}}}const b=p.overflow==="auto"||p.overflow==="hidden";b&&d.add({x:g,y:m,width:A,height:v});for(let y=0;y<f.childNodes.length;y++)a(f.childNodes[y],p);b&&d.remove()}const l=n.getBoundingClientRect();let c=ME.get(n);c===void 0&&(c=document.createElement("canvas"),c.width=l.width,c.height=l.height,ME.set(n,c));const u=c.getContext("2d"),d=new i(u);return a(n),c}function Sre(n,e,t,i){const s={clientX:t*n.offsetWidth+n.offsetLeft,clientY:i*n.offsetHeight+n.offsetTop,view:n.ownerDocument.defaultView};window.dispatchEvent(new MouseEvent(e,s));const r=n.getBoundingClientRect();t=t*r.width+r.left,i=i*r.height+r.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&&i>l.top&&i<l.bottom&&(a.dispatchEvent(new MouseEvent(e,s)),a instanceof HTMLInputElement&&a.type==="range"&&(e==="mousedown"||e==="click"))){const[c,u]=["min","max"].map(g=>parseFloat(a[g])),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(n)}const D0=new V,Pd={type:"",data:D0};class Ere extends po{constructor(e,t){super();const i=this,s=new qf,r=new Pe,o=e.domElement;function a(f){f.stopPropagation();const p=e.domElement.getBoundingClientRect();D0.x=(f.clientX-p.left)/p.width*2-1,D0.y=-(f.clientY-p.top)/p.height*2+1,s.setFromCamera(D0,t);const g=s.intersectObjects(i.children,!1);if(g.length>0){const m=g[0],A=m.object,v=m.uv;Pd.type=f.type,Pd.data.set(v.x,1-v.y),A.dispatchEvent(Pd)}}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(f){const p=f.target;r.identity().extractRotation(p.matrixWorld),s.ray.origin.setFromMatrixPosition(p.matrixWorld),s.ray.direction.set(0,0,-1).applyMatrix4(r);const g=s.intersectObjects(i.children,!1);if(g.length>0){const m=g[0],A=m.object,v=m.uv;Pd.type=l[f.type],Pd.data.set(v.x,1-v.y),A.dispatchEvent(Pd)}}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 KM extends Ce{constructor(){super(...arguments);h(this,"id",null);h(this,"keepAspect",!1)}start(){if(!this.id||!this.context.mainCamera)return;const t=document.getElementById(this.id);if(!t){console.warn('Could not find element with id "'+this.id+'"');return}t.style.display="block",t.style.visibility="hidden";const i=new Ere(this.context.renderer,this.context.mainCamera);this.gameObject.add(i);const s=new wre(t);i.add(s),s.visible=!1,console.log(s);const r=s.material;r.transparent=!0,setTimeout(()=>{s.visible=!0;const o=d_(this.gameObject).clone();f_(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const a=new Cs;a.setFromObject(i),this.setWorldRotation(o.x,o.y,o.z);const l=a.max.x-a.min.x,c=a.max.y-a.min.y;if(this.keepAspect){const d=l/c;l>c?s.scale.set(1/l,1/c/d,1):s.scale.set(1/l*d,1/c,1)}else s.scale.set(1/l,1/c,1);const u=this.gameObject.scale;s.scale.multiply(u)},1)}}var Ire=Object.defineProperty,Mre=Object.getOwnPropertyDescriptor,fv=(n,e,t,i)=>{for(var s=i>1?void 0:i?Mre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Ire(e,t,s),s};const em=oe("debugspatialtrigger"),JD=new xo,ZD=new xo;function Tre(n,e){return JD.mask=n,ZD.mask=e,JD.test(ZD)}class Da extends Ce{constructor(){super(...arguments);h(this,"triggerMask",0);h(this,"onEnter");h(this,"onStay");h(this,"onExit");h(this,"currentIntersected",[]);h(this,"lastIntersected",[])}start(){em&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const t of pv.triggers)Tre(t.triggerMask,this.triggerMask)&&t.test(this.gameObject)&&this.currentIntersected.push(t);for(let t=this.lastIntersected.length-1;t>=0;t--){const i=this.lastIntersected[t];this.currentIntersected.indexOf(i)<0&&(this.onExitTrigger(i),this.lastIntersected.splice(t,1))}for(const t of this.currentIntersected)this.lastIntersected.indexOf(t)<0&&this.onEnterTrigger(t),this.onStayTrigger(t);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}onEnterTrigger(t){var i;em&&console.log("ENTER TRIGGER",this.name,t.name,this,t),t.raiseOnEnterEvent(this),(i=this.onEnter)==null||i.invoke(this,t)}onExitTrigger(t){var i;em&&console.log("EXIT TRIGGER",this.name,t.name,this,t),t.raiseOnExitEvent(this),(i=this.onExit)==null||i.invoke(this,t)}onStayTrigger(t){var i;t.raiseOnStayEvent(this),(i=this.onStay)==null||i.invoke(this,t)}}fv([x()],Da.prototype,"triggerMask",2);fv([x(ur)],Da.prototype,"onEnter",2);fv([x(ur)],Da.prototype,"onStay",2);fv([x(ur)],Da.prototype,"onExit",2);var VC;const k0=(VC=class extends Ce{constructor(){super(...arguments);h(this,"triggerMask");h(this,"boxHelper")}start(){em&&console.log(this.name,this.triggerMask,this)}onEnable(){var e;k0.triggers.push(this),this.boxHelper||(this.boxHelper=Z.addNewComponent(this.gameObject,fo),(e=this.boxHelper)==null||e.showHelper(null,em))}onDisable(){k0.triggers.splice(k0.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){Z.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof Da&&t.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){Z.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof Da&&t.onStayTrigger(this)},!1)}raiseOnExitEvent(e){Z.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof Da&&t.onExitTrigger(this)},!1)}},h(VC,"triggers",[]),VC);let pv=k0;fv([x()],pv.prototype,"triggerMask",2);var Pre=Object.defineProperty,Rre=Object.getOwnPropertyDescriptor,Bre=(n,e,t,i)=>{for(var s=i>1?void 0:i?Rre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Pre(e,t,s),s};const Dr=oe("debugspectator");class Sx extends Ce{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(t){this._mode=t}get isSpectating(){var t;return((t=this._handler)==null?void 0:t.currentTarget)!==void 0}isSpectatingUser(t){var i;return((i=this.target)==null?void 0:i.userId)===t}isFollowedBy(t){var i;return(i=this.followers)==null?void 0:i.includes(t)}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(t){var i;if(this._handler){const s=(i=this._handler.currentTarget)==null?void 0:i.userId,r=this.context.players.getPlayerView(this.localId);t===void 0||this.context.isInXR===!1&&(r==null?void 0:r.currentObject)===t.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),Z.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(t,s)):this._handler.currentTarget!==t&&(this._handler.set(t),Z.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(t,s))}}get target(){var t;return(t=this._handler)==null?void 0:t.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){var t,i;return this.isSpectating&&((t=this.target)==null?void 0:t.currentObject)===((i=this.context.players.getPlayerView(this.localId))==null?void 0:i.currentObject)}awake(){if(this._debug=new Ore(this.context,this),this._networking=new Ure(this.context,this),this._networking.awake(),Z.setActive(this.gameObject,!1),this.cam=Z.getComponent(this.gameObject,Ni),!this.cam){console.error("Spectator camera needs camera component",this);return}!this._handler&&this.cam&&(this._handler=new Dre(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),Ct.addEventListener(Ei.RequestVRSession,this.eventSub_WebXRRequestStartEvent),Ct.addEventListener(Ei.XRStarted,this.eventSub_WebXRStartEvent),Ct.addEventListener(Ei.XRStopped,this.eventSub_WebXREndEvent),this.orbit=Z.getComponent(this.context.mainCamera,ec)}onDestroy(){var t,i;this.stopSpectating(),Ct.removeEventListener(Ei.RequestVRSession,this.eventSub_WebXRStartEvent),Ct.removeEventListener(Ei.XRStarted,this.eventSub_WebXRStartEvent),Ct.removeEventListener(Ei.XRStopped,this.eventSub_WebXREndEvent),(t=this._handler)==null||t.destroy(),(i=this._networking)==null||i.destroy()}isSupportedPlatform(){const t=window.navigator.userAgent,i=/Windows|MacOS/.test(t),s=/Windows NT/.test(t)&&/Edg/.test(t)&&!/Win64/.test(t);return i&&!s}onXRSessionRequestStart(t){this.isSupportedPlatform()&&Z.setActive(this.gameObject,!0)}onXRSessionStart(t){this.isSupportedPlatform()&&(Dr&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onXRSessionEnded(t){var i,s;this.context.removeCamera(this.cam),Z.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),(i=this._handler)==null||i.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,Ba.Headset),this.target=this.context.players.getPlayerView(this.localId)),Dr&&console.log("Follow self",this.target)}onAfterRender(){var c,u,d;if(!this.cam)return;const t=this.context.renderer,i=t.xr.enabled;if(!t.xr.isPresenting&&!((c=this._handler)!=null&&c.currentTarget))return;(u=this._handler)==null||u.update(this._mode);const s=t.getRenderTarget();let r=null;if(!s){if(!t.state.bindFramebuffer||!t.state.bindXRFramebuffer)return;r=t._framebuffer,t.state.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const o=this.context.mainCameraComponent;if(o){const f=o.backgroundColor;f&&t.setClearColor(f,f.alpha),this.cam.backgroundColor=f,this.cam.clearFlags=o.clearFlags,this.cam.nearClipPlane=o.nearClipPlane,this.cam.farClipPlane=o.farClipPlane}else t.setClearColor(new ye(1,1,1));t.setRenderTarget(null),t.xr.enabled=!1;const a=(d=this.cam)==null?void 0:d.cam;this.context.updateAspect(a);const l=t.xr.isPresenting;t.xr.isPresenting=!1,t.setSize(this.context.domWidth,this.context.domHeight),t.render(this.context.scene,a),t.xr.isPresenting=l,t.xr.enabled=i,s?t.setRenderTarget(s):t.state.bindXRFramebuffer(r),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const t=this._mode===0;for(const i of Yn.instances)if(i.avatar&&"isLocalAvatar"in i.avatar){let s=vn.All;this.isSpectatingSelf&&(s=t&&i.avatar.isLocalAvatar?vn.FirstPerson:vn.ThirdPerson);const r=i.avatar.flags;if(!r)continue;for(const o of r)o.UpdateVisible(s)}}resetAvatarFlags(){var t;for(const i of Yn.instances)if(i.avatar&&"flags"in i.avatar){const s=i.avatar.flags;if(!s)continue;for(const r of s)(t=i.avatar)!=null&&t.isLocalAvatar?r.UpdateVisible(vn.FirstPerson):r.UpdateVisible(vn.ThirdPerson)}}}Bre([x()],Sx.prototype,"useKeys",2);class Dre{constructor(e,t,i){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=i}get currentTarget(){return this.view}set(e){const t=e==null?void 0:e.currentObject;if(!t){this.spectator.stopSpectating();return}t!==this.currentObject&&(this.currentObject=t,this.view=e,this.follow||(this.follow=Z.addNewComponent(this.cam.gameObject,Ch)),this.target||(this.target=new Ie),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Dr&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Dr&&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&&Z.destroy(this.follow)}update(e){var s,r,o,a,l,c;if(((s=this.currentTarget)==null?void 0:s.isConnected)===!1||((r=this.currentTarget)==null?void 0:r.removed)===!0){Dr&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&((o=this.currentTarget)==null?void 0:o.currentObject)!==this.currentObject&&(Dr&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const t=this.context.mainCamera;t&&(this.cam.cam.near!==t.near||this.cam.cam.far!==t.far)&&(this.cam.cam.near=t.near,this.cam.cam.far=t.far,this.cam.cam.updateProjectionMatrix());const i=(a=this.follow)==null?void 0:a.target;if(!(!i||!this.follow)){switch(e){case 0:((l=this.view)==null?void 0:l.viewDevice)!==Ba.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),i.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,i.position.set(0,.5,1.5);break}this.follow.flipForward=!1,((c=this.view)==null?void 0:c.viewDevice)!==Ba.Browser?i.quaternion.copy(kre):i.quaternion.identity()}}}const kre=new xe().setFromAxisAngle(new S(0,1,0),Math.PI);class Ore{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",s=>{if(!this.spectator.useKeys)return;s.key==="Escape"&&this.spectator.stopSpectating()});let i=0;this.context.input.addEventListener(Aa.PointerDown,s=>{i=this.context.time.time}),this.context.input.addEventListener(Aa.PointerUp,s=>{const r=this.context.time.time-i;r>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&r<.3&&this.trySelectObject()})}trySelectObject(){const e=new ea;e.setMask(16777215);const t=this.context.physics.raycast(e);if(Dr&&console.log(...t),t!=null&&t.length)for(const i of t){if(i.distance<.2)continue;const s=i.object,r=Z.getComponentInParent(s,Yn),o=r==null?void 0:r.connectionId;if(o){const a=this.context.players.getPlayerView(o);this.spectator.target=a,Dr&&console.log("spectate",o,r);break}}}}class Lre{constructor(e,t,i){h(this,"guid");h(this,"dontSave",!0);h(this,"targetUserId");h(this,"stoppedFollowing");this.guid=e,this.targetUserId=t,this.stoppedFollowing=i}}class Fre{constructor(e,t){h(this,"guid");h(this,"userId");this.guid=e.guid,this.userId=t}}class Ure{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($i.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($i.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(e,t){if(Dr&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",e,t),this.context.connection.connectionId){const i=(e==null?void 0:e.userId)===void 0,s=i?t:e==null?void 0:e.userId,r=new Lre(this.context.connection.connectionId,s,i);this.context.connection.send("spectator-follower-changed",r)}}onRequestFollowMe(e=!1){if(Dr&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const t=e?void 0:this.context.connection.connectionId,i=new Fre(this.spectator,t);this.context.connection.send("spectator-request-follow",i)}}onUserJoinedRoom(){oe("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){const t=e.targetUserId,i=e.guid;if(Dr&&console.log(e),t===this.context.connection.connectionId)if(e.stoppedFollowing){const s=this.followers.indexOf(i);s!==-1&&(this.followers.splice(s,1),this.removeDisconnectedFollowers(),console.log(i,"unfollows you",this.followers.length))}else this.followers.includes(i)||(this.followers.push(i),this.removeDisconnectedFollowers(),console.log(i,"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 Dr&&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):(Dr&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}var Nre=Object.defineProperty,zre=Object.getOwnPropertyDescriptor,$s=(n,e,t,i)=>{for(var s=i>1?void 0:i?zre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Nre(e,t,s),s};const TE=oe("debugspriterenderer"),Gre=oe("wireframe"),Lb=class{static getOrCreateGeometry(e){if(e._geometry)return e._geometry;if(e.guid&&Lb.cache[e.guid])return TE&&console.log("Take cached geometry for sprite",e.guid),Lb.cache[e.guid];const t=new At;e._geometry=t;const i=new Float32Array(e.triangles.length*3),s=new Float32Array(e.triangles.length*2);for(let r=0;r<e.triangles.length;r+=1){const o=e.triangles[r];i[r*3]=-e.vertices[o].x,i[r*3+1]=e.vertices[o].y,i[r*3+2]=0;const a=e.uv[o];s[r*2]=a.x,s[r*2+1]=1-a.y}return t.setAttribute("position",new rt(i,3)),t.setAttribute("uv",new rt(s,2)),e.guid&&(this.cache[e.guid]=t),TE&&console.log("Built sprite geometry",e,t),t}};let tm=Lb;h(tm,"cache",{});class ac{constructor(){h(this,"guid");h(this,"texture");h(this,"triangles");h(this,"uv");h(this,"vertices");h(this,"_geometry")}}$s([x()],ac.prototype,"guid",2);$s([x(Gt)],ac.prototype,"texture",2);$s([cp()],ac.prototype,"triangles",2);$s([cp()],ac.prototype,"uv",2);$s([cp()],ac.prototype,"vertices",2);const EC=Symbol("spriteOwner");class gv{constructor(){h(this,"sprites")}}$s([x(ac)],gv.prototype,"sprites",2);class Lp{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 i=t==null?void 0:t.texture;i&&(i.encoding=yt,i.minFilter==Yt&&i.magFilter==Yt&&(i.anisotropy=1),i.needsUpdate=!0)}}$s([x(gv)],Lp.prototype,"spriteSheet",2);$s([x()],Lp.prototype,"index",2);class qa extends Ce{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(t){if(t!==this._spriteSheet)if(typeof t=="number"){const i=Math.floor(t);i===t&&(this.spriteIndex=i);return}else this._spriteSheet=t,this.updateSprite()}set spriteIndex(t){this._spriteSheet&&(this._spriteSheet.index=t,this.updateSprite())}get spriteIndex(){var t;return((t=this._spriteSheet)==null?void 0:t.index)??0}get spriteFrames(){var t,i;return((i=(t=this._spriteSheet)==null?void 0:t.spriteSheet)==null?void 0:i.sprites.length)??0}awake(){this._currentSprite=void 0,TE&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(){var i,s,r;if(!this.__didAwake||!((s=(i=this.sprite)==null?void 0:i.spriteSheet)!=null&&s.sprites))return;const t=this.sprite.spriteSheet.sprites[this.spriteIndex];if(this._currentSprite)this._currentSprite.geometry=tm.getOrCreateGeometry(t),this._currentSprite.material.map=t.texture;else{const o=new vi({color:16777215,side:Ii});if(!o)return;if(Gre&&(o.wireframe=!0),this.color&&(o.color||(o.color=new ye),o.color.copy(this.color),o.opacity=this.color.alpha),o.transparent=!0,t.texture&&!o.wireframe){let a=t.texture;a[EC]!==void 0&&a[EC]!==this&&this.spriteFrames>1&&(a=t.texture=a.clone()),a[EC]=this,o.map=a}this.sharedMaterial=o,this._currentSprite=new me(tm.getOrCreateGeometry(t),o)}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,(r=this._spriteSheet)==null||r.update()}}$s([x()],qa.prototype,"drawMode",2);$s([x(xi)],qa.prototype,"color",2);$s([x(Bt)],qa.prototype,"sharedMaterial",2);$s([x(Lp)],qa.prototype,"sprite",1);$s([x()],qa.prototype,"transparent",2);$s([x()],qa.prototype,"cutoutThreshold",2);$s([x()],qa.prototype,"castShadows",2);class ya{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 ya).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+__),(t||new ya).__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 Fr).__init(this.bb_pos+t,this.bb):null}rot(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new Fr).__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 Qre=Object.defineProperty,Hre=Object.getOwnPropertyDescriptor,Vre=(n,e,t,i)=>{for(var s=i>1?void 0:i?Hre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Qre(e,t,s),s};const Tb="SCAM";z1(Tb,ya.getRootAsSyncedCameraModel);const _r=new Yf;class Wre{constructor(e,t){h(this,"userId");h(this,"guid");this.guid=t,this.userId=e}send(e,t){if(e){_r.clear();const i=_r.createString(this.guid),s=_r.createString(this.userId);ya.startSyncedCameraModel(_r),ya.addGuid(_r,i),ya.addUserId(_r,s);const r=wt(e),o=d_(e);ya.addPos(_r,Fr.createVec3(_r,r.x,r.y,r.z)),ya.addRot(_r,Fr.createVec3(_r,o.x,o.y,o.z));const a=ya.endSyncedCameraModel(_r);_r.finish(a,Tb),t.sendBinary(_r.asUint8Array())}}}var WC;const PE=(WC=class extends Ce{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(e){const t=this.userToCamMap[e];return t?this.remoteCams[t].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(Tb,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(Tb,this._receiveCallback)}update(){for(const s in this.remoteCams){const r=this.remoteCams[s],o=this.context.time.realtimeSinceStartup-r.lastUpdate;if(!r||o>this._camTimeoutInSeconds){console.log("Remote cam timeout",r,o),r!=null&&r.obj&&Z.destroy(r.obj),delete this.remoteCams[s],r&&delete this.userToCamMap[r.userId],PE.instances.push(r),this.context.players.removePlayerView(r.userId,Ba.Browser);continue}}if(Ct.IsInWebXR)return;const e=this.context.mainCamera;if(e===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new Wre(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const t=wt(e),i=Ln(e);(t.distanceTo(this._lastWorldPosition)>.001||i.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(t),this._lastWorldQuaternion.copy(i),!((!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(e,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,e,Ba.Browser))}onReceivedRemoteCameraInfoBin(e){const t=e.guid();if(!t)return;const i=e.userId();if(!i||!this.context.connection.userIsInRoom(i)||!this.cameraPrefab)return;let s=this.remoteCams[t];if(!s)if("isObject3D"in this.cameraPrefab){const l=new Oa;l.context=this.context;const c=Z.instantiate(this.cameraPrefab,l);s=this.remoteCams[t]={obj:c,lastUpdate:this.context.time.realtimeSinceStartup,userId:i},s.obj.visible=!0,this.gameObject.add(c),this.userToCamMap[i]=t,PE.instances.push(s);const u=Z.getOrAddComponent(c,Yn);u.connectionId=i,u.avatar=c}else return;const r=s.obj;this.context.players.setPlayerView(i,r,Ba.Browser),s.lastUpdate=this.context.time.realtimeSinceStartup,cr.markDirty(r);const o=e.pos();o&&Mf(r,o.x(),o.y(),o.z());const a=e.rot();a&&f_(r,a.x(),a.y(),a.z())}},h(WC,"instances",[]),WC);let Ex=PE;Vre([x([Ie,Jn])],Ex.prototype,"cameraPrefab",2);var jre=Object.defineProperty,qre=Object.getOwnPropertyDescriptor,mv=(n,e,t,i)=>{for(var s=i>1?void 0:i?qre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&jre(e,t,s),s};const IC="view",MC=oe("debugsyncedroom");class Sh extends Ce{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(){MC&&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 t=oe(IC);if(t&&typeof t=="string"&&t.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(t,!0);return}(this.joinRandomRoom||oe(this.urlParameterName))&&this.tryJoinRoom()}onDisable(){this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}tryJoinRandomRoom(){this.setRandomRoomUrlParameter(),this.tryJoinRoom()}tryJoinRoom(t=0){t===void 0&&(t=0);let i=!1;if(this.urlParameterName){const s=oe(this.urlParameterName);if(s&&typeof s=="string"){i=!0;const r=Ck(s);this.roomName=r}else if(this.joinRandomRoom&&(console.log("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),t<1))return this.tryJoinRoom(t+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&&!i?(MC&&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(),MC&&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(){const t=oe(IC);return t||oe(this.urlParameterName)}setRandomRoomUrlParameter(){const t=eA(),i=this.generateRoomName();oe(this.urlParameterName)?t.set(this.urlParameterName,i):t.append(this.urlParameterName,i),NE(i,t)}generateRoomName(){return wk()+"_"+xk(100,999)}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){const t=window.location.search,i=new URLSearchParams(t);return i.has(this.urlParameterName)&&i.delete(this.urlParameterName),i.set(IC,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+i.toString()}return null}}mv([x()],Sh.prototype,"roomName",2);mv([x()],Sh.prototype,"urlParameterName",2);mv([x()],Sh.prototype,"joinRandomRoom",2);mv([x()],Sh.prototype,"requireRoomParameter",2);mv([x()],Sh.prototype,"autoRejoin",2);function Xre(){const n=oe("testwindowcount")||0;n&&n>0&&Yre(n)}function Yre(n){if(oe("testwindow"))return null;const e=new URL(window.location.href);dm(e.searchParams,mb,1),dm(e.searchParams,"testwindow",1);const t=e.toString(),i=[];window.onbeforeunload=()=>{for(const l of i)l.close()};const s=.05,r=128;let o=0,a=0;for(let l=0;l<n;l++){o*r+r*.01>=window.innerWidth&&(a+=1,o=0);const c=o*(r*(1+s))+window.screenLeft,u=a*(r*(1+s))+window.screenTop+90+60*a;o+=1;const d=window.open(t,"test window "+l,`popup=yes width=${r} height=${r} top=${u} left=${c}`);if(!d){console.warn("Failed to open window");continue}i.push(d),d.onload=()=>{d.onbeforeunload=()=>{for(let f=0;f<i.length;f++){const p=i[f];p!==d&&p.close()}i.length=0}}}return i}class JM extends Ce{awake(){Xre()}}class ZM extends Ce{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(Lm,t=>{});else{this.models=[];for(let t=0;t<this.transformsPerFrame;t++)this.models.push(new vz(this.context.connection.connectionId+"_simulatedTransform_"+t,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 Yf(1024));const t=this.builder;for(let i=0;i<this.transformsPerFrame;i++){t.clear();const s=fU(this.context.connection.connectionId,this);this.context.connection.sendBinary(s)}}else if(this.models)for(let t=0;t<this.models.length;t++){const i=this.models[t];i.dontSave=!0,i.update(this,null),this.context.connection.send("TestSimulateUserData-"+t,i)}}}}class vz{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 i=e.worldPosition;this.position.x=i.x,this.position.y=i.y,this.position.z=i.z;const s=e.worldQuaternion;if(this.rotation.x=s.x,this.rotation.y=s.y,this.rotation.z=s.z,this.rotation.w=s.w,this.fast=!1,t){const r=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=r.x,this.velocity.y=r.y,this.velocity.z=r.z}}}h(vz,"temp",new S);var Kre=Object.defineProperty,Jre=Object.getOwnPropertyDescriptor,Fp=(n,e,t,i)=>{for(var s=i>1?void 0:i?Jre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Kre(e,t,s),s};class Xa extends Ps{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=Hl.MEDIUM,this.resolutionScale.defaultValue=1/window.devicePixelRatio}onCreateEffect(){console.log(this);const t=new J7({kernelSize:Hl.VERY_LARGE});return this.offset.onValueChanged=i=>t.offset=i,this.rotation.onValueChanged=i=>t.rotation=i,this.focusArea.onValueChanged=i=>t.focusArea=i,this.feather.onValueChanged=i=>t.feather=i,this.kernelSize.onValueChanged=i=>t.blurPass.kernelSize=i,this.resolutionScale.onValueChanged=i=>t.resolution.scale=i/window.devicePixelRatio,t}}Fp([x(Et)],Xa.prototype,"offset",2);Fp([x(Et)],Xa.prototype,"rotation",2);Fp([x(Et)],Xa.prototype,"focusArea",2);Fp([x(Et)],Xa.prototype,"feather",2);Fp([x(Et)],Xa.prototype,"kernelSize",2);Fp([x(Et)],Xa.prototype,"resolutionScale",2);To("TiltShiftEffect",Xa);var Zre=Object.defineProperty,$re=Object.getOwnPropertyDescriptor,eoe=(n,e,t,i)=>{for(var s=i>1?void 0:i?$re(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Zre(e,t,s),s};class Av extends Ps{constructor(){super(...arguments);h(this,"mode")}get typeName(){return"ToneMapping"}get isToneMapping(){return!0}init(){this.mode.defaultValue=Qs}apply(){this.mode.onValueChanged=this._apply.bind(this),this._apply(this.mode.value)}unapply(){this.context.renderer.toneMapping=Qs}_apply(t){switch(t){case 0:this.context.renderer.toneMapping=gm;break;case 1:this.context.renderer.toneMapping=qE;break;case 2:this.context.renderer.toneMapping=XE;break}}}eoe([x(Et)],Av.prototype,"mode",2);To("Tonemapping",Av);const Uh=new qf,sr=new S,Tc=new S,Di=new xe,$D={X:new S(1,0,0),Y:new S(0,1,0),Z:new S(0,0,1)},TC={type:"change"},ek={type:"mouseDown"},tk={type:"mouseUp",mode:null},ik={type:"objectChange"};class toe extends Ie{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 i=new aoe;this._gizmo=i,this.add(i);const s=new loe;this._plane=s,this.add(s);const r=this;function o(b,y){let _=y;Object.defineProperty(r,b,{get:function(){return _!==void 0?_:y},set:function(C){_!==C&&(_=C,s[b]=C,i[b]=C,r.dispatchEvent({type:b+"-changed",value:C}),r.dispatchEvent(TC))}}),r[b]=y,s[b]=y,i[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 xe,u=new xe,d=new S,f=new xe,p=new S,g=new S,m=new S,A=0,v=new S;o("worldPosition",a),o("worldPositionStart",l),o("worldQuaternion",c),o("worldQuaternionStart",u),o("cameraPosition",d),o("cameraQuaternion",f),o("pointStart",p),o("pointEnd",g),o("rotationAxis",m),o("rotationAngle",A),o("eye",v),this._offset=new S,this._startNorm=new S,this._endNorm=new S,this._cameraScale=new S,this._parentPosition=new S,this._parentQuaternion=new xe,this._parentQuaternionInv=new xe,this._parentScale=new S,this._worldScaleStart=new S,this._worldQuaternionInv=new xe,this._worldScale=new S,this._positionStart=new S,this._quaternionStart=new xe,this._scaleStart=new S,this._getPointer=ioe.bind(this),this._onPointerDown=soe.bind(this),this._onPointerHover=noe.bind(this),this._onPointerMove=roe.bind(this),this._onPointerUp=ooe.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;Uh.setFromCamera(e,this.camera);const t=PC(this._gizmo.picker[this.mode],Uh);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){Uh.setFromCamera(e,this.camera);const t=PC(this._plane,Uh,!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,ek.mode=this.mode,this.dispatchEvent(ek)}}pointerMove(e){const t=this.axis,i=this.mode,s=this.object;let r=this.space;if(i==="scale"?r="local":(t==="E"||t==="XYZE"||t==="XYZ")&&(r="world"),s===void 0||t===null||this.dragging===!1||e.button!==-1)return;Uh.setFromCamera(e,this.camera);const o=PC(this._plane,Uh,!0);if(o){if(this.pointEnd.copy(o.point).sub(this.worldPositionStart),i==="translate")this._offset.copy(this.pointEnd).sub(this.pointStart),r==="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),r==="local"&&t!=="XYZ"?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),s.position.copy(this._offset).add(this._positionStart),this.translationSnap&&(r==="local"&&(s.position.applyQuaternion(Di.copy(this._quaternionStart).invert()),t.search("X")!==-1&&(s.position.x=Math.round(s.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(s.position.y=Math.round(s.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(s.position.z=Math.round(s.position.z/this.translationSnap)*this.translationSnap),s.position.applyQuaternion(this._quaternionStart)),r==="world"&&(s.parent&&s.position.add(sr.setFromMatrixPosition(s.parent.matrixWorld)),t.search("X")!==-1&&(s.position.x=Math.round(s.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(s.position.y=Math.round(s.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(s.position.z=Math.round(s.position.z/this.translationSnap)*this.translationSnap),s.parent&&s.position.sub(sr.setFromMatrixPosition(s.parent.matrixWorld))));else if(i==="scale"){if(t.search("XYZ")!==-1){let a=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(a*=-1),Tc.set(a,a,a)}else sr.copy(this.pointStart),Tc.copy(this.pointEnd),sr.applyQuaternion(this._worldQuaternionInv),Tc.applyQuaternion(this._worldQuaternionInv),Tc.divide(sr),t.search("X")===-1&&(Tc.x=1),t.search("Y")===-1&&(Tc.y=1),t.search("Z")===-1&&(Tc.z=1);s.scale.copy(this._scaleStart).multiply(Tc),this.scaleSnap&&(t.search("X")!==-1&&(s.scale.x=Math.round(s.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Y")!==-1&&(s.scale.y=Math.round(s.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Z")!==-1&&(s.scale.z=Math.round(s.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(i==="rotate"){this._offset.copy(this.pointEnd).sub(this.pointStart);const a=20/this.worldPosition.distanceTo(sr.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(sr.copy(this.rotationAxis).cross(this.eye))*a):(t==="X"||t==="Y"||t==="Z")&&(this.rotationAxis.copy($D[t]),sr.copy($D[t]),r==="local"&&sr.applyQuaternion(this.worldQuaternion),this.rotationAngle=this._offset.dot(sr.cross(this.eye).normalize())*a),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),r==="local"&&t!=="E"&&t!=="XYZE"?(s.quaternion.copy(this._quaternionStart),s.quaternion.multiply(Di.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),s.quaternion.copy(Di.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),s.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(TC),this.dispatchEvent(ik)}}pointerUp(e){e.button===0&&(this.dragging&&this.axis!==null&&(tk.mode=this.mode,this.dispatchEvent(tk)),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(TC),this.dispatchEvent(ik),this.pointStart.copy(this.pointEnd))}getRaycaster(){return Uh}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 ioe(n){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:n.button};{const e=this.domElement.getBoundingClientRect();return{x:(n.clientX-e.left)/e.width*2-1,y:-(n.clientY-e.top)/e.height*2+1,button:n.button}}}function noe(n){if(this.enabled)switch(n.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(n));break}}function soe(n){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(n.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(n)),this.pointerDown(this._getPointer(n)))}function roe(n){this.enabled&&this.pointerMove(this._getPointer(n))}function ooe(n){this.enabled&&(this.domElement.releasePointerCapture(n.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(n)))}function PC(n,e,t){const i=e.intersectObject(n,!0);for(let s=0;s<i.length;s++)if(i[s].object.visible||t)return i[s];return!1}const Hy=new xn,bi=new S(0,1,0),nk=new S(0,0,0),sk=new Pe,Vy=new xe,O0=new xe,ua=new S,rk=new Pe,Pg=new S(1,0,0),Wh=new S(0,1,0),Rg=new S(0,0,1),Wy=new S,cg=new S,hg=new S;class aoe extends Ie{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const e=new vi({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),t=new dn({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),i=e.clone();i.opacity=.15;const s=t.clone();s.opacity=.5;const r=e.clone();r.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 f=e.clone();f.color.setHex(16776960),f.opacity=.25,e.clone().color.setHex(16776960);const g=e.clone();g.color.setHex(7895160);const m=new Yi(0,.04,.1,12);m.translate(0,.05,0);const A=new gi(.08,.08,.08);A.translate(0,.04,0);const v=new At;v.setAttribute("position",new nt([0,0,0,1,0,0],3));const b=new Yi(.0075,.0075,.5,3);b.translate(0,.25,0);function y(H,$){const J=new _a(H,.0075,3,64,$*Math.PI*2);return J.rotateY(Math.PI/2),J.rotateX(Math.PI/2),J}function _(){const H=new At;return H.setAttribute("position",new nt([0,0,0,1,1,1],3)),H}const C={X:[[new me(m,r),[.5,0,0],[0,0,-Math.PI/2]],[new me(m,r),[-.5,0,0],[0,0,Math.PI/2]],[new me(b,r),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new me(m,o),[0,.5,0]],[new me(m,o),[0,-.5,0],[Math.PI,0,0]],[new me(b,o)]],Z:[[new me(m,a),[0,0,.5],[Math.PI/2,0,0]],[new me(m,a),[0,0,-.5],[-Math.PI/2,0,0]],[new me(b,a),null,[Math.PI/2,0,0]]],XYZ:[[new me(new Sa(.1,0),d.clone()),[0,0,0]]],XY:[[new me(new gi(.15,.15,.01),u.clone()),[.15,.15,0]]],YZ:[[new me(new gi(.15,.15,.01),l.clone()),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new me(new gi(.15,.15,.01),c.clone()),[.15,0,.15],[-Math.PI/2,0,0]]]},E={X:[[new me(new Yi(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]],[new me(new Yi(.2,0,.6,4),i),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new me(new Yi(.2,0,.6,4),i),[0,.3,0]],[new me(new Yi(.2,0,.6,4),i),[0,-.3,0],[0,0,Math.PI]]],Z:[[new me(new Yi(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]],[new me(new Yi(.2,0,.6,4),i),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new me(new Sa(.2,0),i)]],XY:[[new me(new gi(.2,.2,.01),i),[.15,.15,0]]],YZ:[[new me(new gi(.2,.2,.01),i),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new me(new gi(.2,.2,.01),i),[.15,0,.15],[-Math.PI/2,0,0]]]},T={START:[[new me(new Sa(.01,2),s),null,null,null,"helper"]],END:[[new me(new Sa(.01,2),s),null,null,null,"helper"]],DELTA:[[new an(_(),s),null,null,null,"helper"]],X:[[new an(v,s.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new an(v,s.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new an(v,s.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},w={XYZE:[[new me(y(.5,1),g),null,[0,Math.PI/2,0]]],X:[[new me(y(.5,.5),r)]],Y:[[new me(y(.5,.5),o),null,[0,0,-Math.PI/2]]],Z:[[new me(y(.5,.5),a),null,[0,Math.PI/2,0]]],E:[[new me(y(.75,1),f),null,[0,Math.PI/2,0]]]},M={AXIS:[[new an(v,s.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},P={XYZE:[[new me(new Gr(.25,10,8),i)]],X:[[new me(new _a(.5,.1,4,24),i),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new me(new _a(.5,.1,4,24),i),[0,0,0],[Math.PI/2,0,0]]],Z:[[new me(new _a(.5,.1,4,24),i),[0,0,0],[0,0,-Math.PI/2]]],E:[[new me(new _a(.75,.1,2,24),i)]]},k={X:[[new me(A,r),[.5,0,0],[0,0,-Math.PI/2]],[new me(b,r),[0,0,0],[0,0,-Math.PI/2]],[new me(A,r),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new me(A,o),[0,.5,0]],[new me(b,o)],[new me(A,o),[0,-.5,0],[0,0,Math.PI]]],Z:[[new me(A,a),[0,0,.5],[Math.PI/2,0,0]],[new me(b,a),[0,0,0],[Math.PI/2,0,0]],[new me(A,a),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new me(new gi(.15,.15,.01),u),[.15,.15,0]]],YZ:[[new me(new gi(.15,.15,.01),l),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new me(new gi(.15,.15,.01),c),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new me(new gi(.1,.1,.1),d.clone())]]},Q={X:[[new me(new Yi(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]],[new me(new Yi(.2,0,.6,4),i),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new me(new Yi(.2,0,.6,4),i),[0,.3,0]],[new me(new Yi(.2,0,.6,4),i),[0,-.3,0],[0,0,Math.PI]]],Z:[[new me(new Yi(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]],[new me(new Yi(.2,0,.6,4),i),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new me(new gi(.2,.2,.01),i),[.15,.15,0]]],YZ:[[new me(new gi(.2,.2,.01),i),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new me(new gi(.2,.2,.01),i),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new me(new gi(.2,.2,.2),i),[0,0,0]]]},z={X:[[new an(v,s.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new an(v,s.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new an(v,s.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function L(H){const $=new Ie;for(const J in H)for(let K=H[J].length;K--;){const ue=H[J][K][0].clone(),he=H[J][K][1],Re=H[J][K][2],ge=H[J][K][3],ie=H[J][K][4];ue.name=J,ue.tag=ie,he&&ue.position.set(he[0],he[1],he[2]),Re&&ue.rotation.set(Re[0],Re[1],Re[2]),ge&&ue.scale.set(ge[0],ge[1],ge[2]),ue.updateMatrix();const le=ue.geometry.clone();le.applyMatrix4(ue.matrix),ue.geometry=le,ue.renderOrder=1/0,ue.position.set(0,0,0),ue.rotation.set(0,0,0),ue.scale.set(1,1,1),$.add(ue)}return $}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=L(C)),this.add(this.gizmo.rotate=L(w)),this.add(this.gizmo.scale=L(k)),this.add(this.picker.translate=L(E)),this.add(this.picker.rotate=L(P)),this.add(this.picker.scale=L(Q)),this.add(this.helper.translate=L(T)),this.add(this.helper.rotate=L(M)),this.add(this.helper.scale=L(z)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}updateMatrixWorld(e){const i=(this.mode==="scale"?"local":this.space)==="local"?this.worldQuaternion:O0;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 o=s[r];o.visible=!0,o.rotation.set(0,0,0),o.position.copy(this.worldPosition);let a;if(this.camera.isOrthographicCamera?a=(this.camera.top-this.camera.bottom)/this.camera.zoom:a=this.worldPosition.distanceTo(this.cameraPosition)*Math.min(1.9*Math.tan(Math.PI*this.camera.fov/360)/this.camera.zoom,7),o.scale.set(1,1,1).multiplyScalar(a*this.size/4),o.tag==="helper"){o.visible=!1,o.name==="AXIS"?(o.position.copy(this.worldPositionStart),o.visible=!!this.axis,this.axis==="X"&&(Di.setFromEuler(Hy.set(0,0,0)),o.quaternion.copy(i).multiply(Di),Math.abs(bi.copy(Pg).applyQuaternion(i).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="Y"&&(Di.setFromEuler(Hy.set(0,0,Math.PI/2)),o.quaternion.copy(i).multiply(Di),Math.abs(bi.copy(Wh).applyQuaternion(i).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="Z"&&(Di.setFromEuler(Hy.set(0,Math.PI/2,0)),o.quaternion.copy(i).multiply(Di),Math.abs(bi.copy(Rg).applyQuaternion(i).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="XYZE"&&(Di.setFromEuler(Hy.set(0,Math.PI/2,0)),bi.copy(this.rotationAxis),o.quaternion.setFromRotationMatrix(sk.lookAt(nk,bi,Wh)),o.quaternion.multiply(Di),o.visible=this.dragging),this.axis==="E"&&(o.visible=!1)):o.name==="START"?(o.position.copy(this.worldPositionStart),o.visible=this.dragging):o.name==="END"?(o.position.copy(this.worldPosition),o.visible=this.dragging):o.name==="DELTA"?(o.position.copy(this.worldPositionStart),o.quaternion.copy(this.worldQuaternionStart),sr.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),sr.applyQuaternion(this.worldQuaternionStart.clone().invert()),o.scale.copy(sr),o.visible=this.dragging):(o.quaternion.copy(i),this.dragging?o.position.copy(this.worldPositionStart):o.position.copy(this.worldPosition),this.axis&&(o.visible=this.axis.search(o.name)!==-1));continue}o.quaternion.copy(i),this.mode==="translate"||this.mode==="scale"?(o.name==="X"&&Math.abs(bi.copy(Pg).applyQuaternion(i).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="Y"&&Math.abs(bi.copy(Wh).applyQuaternion(i).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="Z"&&Math.abs(bi.copy(Rg).applyQuaternion(i).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="XY"&&Math.abs(bi.copy(Rg).applyQuaternion(i).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="YZ"&&Math.abs(bi.copy(Pg).applyQuaternion(i).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="XZ"&&Math.abs(bi.copy(Wh).applyQuaternion(i).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1)):this.mode==="rotate"&&(Vy.copy(i),bi.copy(this.eye).applyQuaternion(Di.copy(i).invert()),o.name.search("E")!==-1&&o.quaternion.setFromRotationMatrix(sk.lookAt(this.eye,nk,Wh)),o.name==="X"&&(Di.setFromAxisAngle(Pg,Math.atan2(-bi.y,bi.z)),Di.multiplyQuaternions(Vy,Di),o.quaternion.copy(Di)),o.name==="Y"&&(Di.setFromAxisAngle(Wh,Math.atan2(bi.x,bi.z)),Di.multiplyQuaternions(Vy,Di),o.quaternion.copy(Di)),o.name==="Z"&&(Di.setFromAxisAngle(Rg,Math.atan2(bi.y,bi.x)),Di.multiplyQuaternions(Vy,Di),o.quaternion.copy(Di))),o.visible=o.visible&&(o.name.indexOf("X")===-1||this.showX),o.visible=o.visible&&(o.name.indexOf("Y")===-1||this.showY),o.visible=o.visible&&(o.name.indexOf("Z")===-1||this.showZ),o.visible=o.visible&&(o.name.indexOf("E")===-1||this.showX&&this.showY&&this.showZ),o.material._color=o.material._color||o.material.color.clone(),o.material._opacity=o.material._opacity||o.material.opacity,o.material.color.copy(o.material._color),o.material.opacity=o.material._opacity,this.enabled&&this.axis&&(o.name===this.axis||this.axis.split("").some(function(l){return o.name===l}))&&(o.material.color.setHex(16776960),o.material.opacity=1)}super.updateMatrixWorld(e)}}class loe extends me{constructor(){super(new $n(1e5,1e5,2,2),new vi({visible:!1,wireframe:!0,side:Ii,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"),Wy.copy(Pg).applyQuaternion(t==="local"?this.worldQuaternion:O0),cg.copy(Wh).applyQuaternion(t==="local"?this.worldQuaternion:O0),hg.copy(Rg).applyQuaternion(t==="local"?this.worldQuaternion:O0),bi.copy(cg),this.mode){case"translate":case"scale":switch(this.axis){case"X":bi.copy(this.eye).cross(Wy),ua.copy(Wy).cross(bi);break;case"Y":bi.copy(this.eye).cross(cg),ua.copy(cg).cross(bi);break;case"Z":bi.copy(this.eye).cross(hg),ua.copy(hg).cross(bi);break;case"XY":ua.copy(hg);break;case"YZ":ua.copy(Wy);break;case"XZ":bi.copy(hg),ua.copy(cg);break;case"XYZ":case"E":ua.set(0,0,0);break}break;case"rotate":default:ua.set(0,0,0)}ua.length()===0?this.quaternion.copy(this.cameraQuaternion):(rk.lookAt(sr.set(0,0,0),ua,bi),this.quaternion.setFromRotationMatrix(rk)),super.updateMatrixWorld(e)}}var coe=Object.defineProperty,hoe=Object.getOwnPropertyDescriptor,Ix=(n,e,t,i)=>{for(var s=i>1?void 0:i?hoe(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&coe(e,t,s),s};class ed extends Ce{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 t;this.isGizmo&&!bA||this.context.mainCamera&&(this.control||(this.control=new toe(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(i=>{const s=i;if(s.layers.set(2),s){const r=s.material;r&&(r.opacity=.3)}}),this.orbit=Z.getComponentInParent(this.context.mainCamera,ec)??void 0),this.control&&(this.context.scene.add(this.control),this.control.attach(this.gameObject),this.changeEventListener=this.onControlChangedEvent.bind(this),(t=this.control)==null||t.addEventListener("dragging-changed",this.changeEventListener),this.addWindowEvents()))}onDisable(){var t,i;(t=this.control)==null||t.removeFromParent(),this.changeEventListener&&((i=this.control)==null||i.removeEventListener("dragging-changed",this.changeEventListener)),this.removeWindowEvents()}enableSnapping(){this.control&&(this.control.setTranslationSnap(this.translationSnap),this.control.setRotationSnap(Hs.degToRad(this.rotationSnapAngle)),this.control.setScaleSnap(this.scaleSnap))}disableSnapping(){this.control&&(this.control.setTranslationSnap(null),this.control.setRotationSnap(null),this.control.setScaleSnap(null))}onControlChangedEvent(t){const i=this.orbit;if(i&&(i.enabled=!t.value),t.value){const s=Z.getComponentInParent(this.gameObject,th);s&&s.requestOwnership()}}addWindowEvents(){const t=this.control;t&&(this.windowKeyDownListener||(this.windowKeyDownListener=i=>{if(this.enabled)switch(i.keyCode){case 81:t.setSpace(t.space==="local"?"world":"local");break;case 16:this.enableSnapping();break;case 87:t.setMode("translate");break;case 69:t.setMode("rotate");break;case 82:t.setMode("scale");break;case 187:case 107:t.setSize(t.size+.1);break;case 189:case 109:t.setSize(Math.max(t.size-.1,.1));break;case 88:t.showX=!t.showX;break;case 89:t.showY=!t.showY;break;case 90:t.showZ=!t.showZ;break;case 32:t.enabled=!t.enabled;break}}),this.windowKeyUpListener||(this.windowKeyUpListener=i=>{if(this.enabled)switch(i.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)}}Ix([x()],ed.prototype,"isGizmo",2);Ix([x()],ed.prototype,"translationSnap",2);Ix([x()],ed.prototype,"rotationSnapAngle",2);Ix([x()],ed.prototype,"scaleSnap",2);var uoe=Object.defineProperty,doe=Object.getOwnPropertyDescriptor,$M=(n,e,t,i)=>{for(var s=i>1?void 0:i?doe(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&uoe(e,t,s),s};class td extends Ps{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 t=new EF;return this.intensity.onValueChanged=i=>{t.offset=i,this.updateDarkness(t)},this.color.onValueChanged=i=>{this.updateDarkness(t)},t}updateDarkness(t){const i=this.intensity.value;t.darkness=i}}$M([x(Et)],td.prototype,"color",2);$M([x(Et)],td.prototype,"intensity",2);$M([x(Et)],td.prototype,"center",2);To("Vignette",td);var foe=Object.defineProperty,poe=Object.getOwnPropertyDescriptor,goe=(n,e,t,i)=>{for(var s=i>1?void 0:i?poe(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&foe(e,t,s),s};const RC=oe("debugpost");class Mx extends Ce{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 t;(t=this.sharedProfile)==null||t.init(),RC&&(console.log(this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",i=>{i.key==="p"&&(console.log("Toggle volume: "+this.name,!this.enabled),this.enabled=!this.enabled)}))}onDisable(){var t;(t=this._postprocessing)==null||t.unapply()}onBeforeRender(){if(!this.context.isInXR){if(this.context.composer&&!(this.context.composer instanceof nI))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 t;(t=this._postprocessing)==null||t.dispose()}apply(){var i,s;RC&&console.log("Apply PostProcessing",this,(i=this.context.mainCamera)==null?void 0:i.name),Ss()&&(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,(s=this.sharedProfile)!=null&&s.components&&this._effects.push(...this.sharedProfile.components);const t=this.gameObject.getComponentsInChildren(Ps);if(RC&&(t!=null&&t.length)&&console.log("Additional",t),t)for(const r of t)r.active&&this._effects.push(r);this._effects.length>0&&(this._postprocessing||(this._postprocessing=new xx(this.context)),this._postprocessing.apply(this._effects),this._applyPostQueue())}unapply(){var t;(t=this._postprocessing)==null||t.unapply()}_applyPostQueue(){if(this._modificationQueue){for(const t of this._modificationQueue.values())this.onEditorModification(t);this._modificationQueue.clear()}}onEditorModification(t){var i,s;if(t.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(t.propertyName,t),!0;if(!((i=this._effects)!=null&&i.length))return;const r=t.propertyName.split(".");if(r.length===3||r.length===4){const o=r[1],a=r[2];for(const l of this._effects)if(((s=l.typeName)==null?void 0:s.toLowerCase())===o.toLowerCase()){if(a==="active"){l.active=t.value,this.scheduleRecreate();return}if(!jy.has(o)){const c=new Array;jy.set(o,c);const u=Object.keys(l);for(const d of u)l[d]instanceof Et&&c.push(d)}if(jy.has(o)){const c=a.toLowerCase(),u=jy.get(o);for(const d of u)if(d.toLowerCase()===c){const f=l[d];f instanceof Et&&(r.length===4&&r[3]==="active"?(f.overrideState=t.value,this.scheduleRecreate()):f&&f.value!==void 0&&(f.value=t.value));return}}console.warn("Unknown modification",a);return}}return!0}return!1}scheduleRecreate(){const t=++this._recreateId;setTimeout(()=>{t===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}goe([cp(qA)],Mx.prototype,"sharedProfile",2);const jy=new Map;var moe=Object.defineProperty,Aoe=Object.getOwnPropertyDescriptor,voe=(n,e,t,i)=>{for(var s=i>1?void 0:i?Aoe(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&moe(e,t,s),s};class Tx extends Ce{constructor(){super(...arguments);h(this,"backgroundTint",new xi(1,1,1,1));h(this,"_preRender");h(this,"backgroundPlane");h(this,"threeTexture");h(this,"forceTextureInitialization",function(){const t=new vi,i=new $n,s=new pr;s.add(new me(i,t));const r=new Mu;return function(a,l){t.map=l,a.render(s,r)}}())}awake(){Ct.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(t=>t!==this._preRender),this.backgroundPlane&&this.gameObject.remove(this.backgroundPlane)}preRender(){if(!this||!this.gameObject)return;const i=this.context.renderer.xr.getFrame();i&&(!this.threeTexture&&this.context.renderer&&(this.threeTexture=new Gt,this.forceTextureInitialization(this.context.renderer,this.threeTexture)),this.backgroundPlane===void 0&&(this.backgroundPlane=boe(this.backgroundTint),this.gameObject.add(this.backgroundPlane)),this.updateFromFrame(i))}onBeforeRender(t){this.updateFromFrame(t)}updateFromFrame(t){if(!t)return;const i=t.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(i){for(const s of i.views)if("camera"in s&&s.camera){let o=this.context.renderer.xr.getBinding();if(o||(o=new XRWebGLBinding(t.session,this.context.renderer.getContext())),o){let a=null;if("getCameraImage"in o){a=o.getCameraImage(s.camera);const l=this.context.renderer.properties.get(this.threeTexture);l.__webglTexture=a,this.backgroundPlane&&(this.backgroundPlane.setTexture(this.threeTexture),this.backgroundPlane.visible=!0)}}}}}}voe([x()],Tx.prototype,"backgroundTint",2);let yoe=`
|
|
5439
5439
|
uniform sampler2D t2D;
|
|
5440
5440
|
|
|
5441
5441
|
varying vec2 vUv;
|