@needle-tools/engine 3.10.1-beta → 3.10.2-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3666,7 +3666,7 @@ Please change to:
3666
3666
  ${o}? : AssetReference;
3667
3667
 
3668
3668
  in script ${i}.ts
3669
- <a href="https://docs.needle.tools/serializable" target="_blank">documentation</a>`),console.warn(i,o,n[o],n);continue}}}}function J9(n,e){for(const t of Object.keys(e)){const i=e[t];if(typeof i=="object"&&i!==null&&i!==void 0){const s=n[t];if(!s){Fl&&console.log(t,"is undefined on",n);continue}for(const r of Object.keys(i))if(s[r]===void 0&&JB(i[r])&&!JB(s)){const a=Z9(s,r);if(a&&((a==null?void 0:a.writable)===void 0||(a==null?void 0:a.writable)===!1)&&a.set===void 0){Fl&&console.warn('Property is not writable "'+r+'"',s,a,i[r],s[r]);continue}s[r]=i[r]}}}}function Z9(n,e){for(;n;){const t=Object.getOwnPropertyDescriptor(n,e);if(t)return t;n=Object.getPrototypeOf(n)}}function JB(n){switch(typeof n){case"number":case"string":case"boolean":return!0}return!1}function I1(n,e,t,i,s){let r=typeof e=="function"&&e.prototype===void 0,o=e;if(r)try{if(o=e==null?void 0:e.call(e,s),r=!1,o==null)return}catch(h){console.error("Error in callback",h,n)}if(t.type=o,!r&&s instanceof o)return s;if(s&&typeof s=="object"&&W9(s)){if(s.__concreteInstance)return s.__concreteInstance;const h=s;if(!h.$serializedTypes&&o.prototype.$serializedTypes&&(h.$serializedTypes=o.prototype.$serializedTypes),h.$serializedTypes&&h_(h,n,t),s&&o!==void 0)try{const d=new o;Is&&console.log("Create concrete instance for persistent asset",s,"instance:",d),nd(d,s),s.__concreteInstance=d,s=d}catch(d){console.error("Error creating instance or creating values on instance",d,s,o)}return s}if(i||(i={serializer:c_.getSerializerForConstructor(o)}),Array.isArray(n)){const h=[];for(let d=0;d<n.length;d++){const f=n[d],p=I1(f,e,t,i,f);h.push(p)}return h}const a=i.serializer;if(a)return a.onDeserialize(n,t);let l;if(n&&(n.isMaterial||n.isTexture||n.isObject3D))l=n;else{if(n===void 0)return;if(n===null&&(o===Bt||o===Gt||o===ye||o===qr))return null;l=new o(...$9(n))}const c=l;return c.$serializedTypes&&h_(c,n,t),l}function $9(n){if(ub.length=0,typeof n=="object"&&n!==null&&n!==void 0)for(const e of Object.keys(n))ub.push(n[e]);return ub}const R1=Symbol("assigned component properties");function nd(n,e,t){var s;if(e==null||n==null)return;n[R1]=!0;const i=((s=n.constructor)==null?void 0:s.name)??"unknown";t==null||t.registerDefinedKeys(i,n);for(const r of Object.keys(e)){const o=e6(n,r);typeof(o==null?void 0:o.value)!="function"&&(!o||o.writable===!0||(o==null?void 0:o.set)!==void 0)&&(n[r]=e[r])}delete n[R1]}function e6(n,e){let t;do t=Object.getOwnPropertyDescriptor(n,e);while(!t&&(n=Object.getPrototypeOf(n)));return t}const lo=se("debuginput");class db{constructor(e){u(this,"key");u(this,"keyType");u(this,"source");this.key=e.key,this.keyType=e.type,this.source=e}}var La=(n=>(n.PointerDown="pointerdown",n.PointerUp="pointerup",n.PointerMove="pointermove",n.KeyDown="keydown",n.KeyUp="keyup",n.KeyPressed="keypress",n))(La||{}),eU=(n=>(n.Mouse="mouse",n.Touch="touch",n))(eU||{});class tU extends EventTarget{constructor(t){super();u(this,"_doubleClickTimeThreshold",.2);u(this,"_longPressTimeThreshold",1);u(this,"_specialCursorTrigger",0);u(this,"context");u(this,"_pointerDown",[!1]);u(this,"_pointerUp",[!1]);u(this,"_pointerClick",[!1]);u(this,"_pointerDoubleClick",[!1]);u(this,"_pointerPressed",[!1]);u(this,"_pointerPositions",[new K]);u(this,"_pointerPositionsLastFrame",[new K]);u(this,"_pointerPositionsDelta",[new K]);u(this,"_pointerPositionsRC",[new K]);u(this,"_pointerPositionDown",[new K]);u(this,"_pointerDownTime",[]);u(this,"_pointerUpTime",[]);u(this,"_pointerUpTimestamp",[]);u(this,"_pointerIds",[]);u(this,"_pointerTypes",[""]);u(this,"_mouseWheelChanged",[!1]);u(this,"_mouseWheelDeltaY",[0]);u(this,"_pointerEvent",[]);u(this,"_pointerUsed",[]);u(this,"onLostFocus",()=>{for(const t in this.keysPressed)this.keysPressed[t].pressed=!1});u(this,"onEndOfFrame",()=>{for(let t=0;t<this._pointerUp.length;t++)this._pointerUp[t]=!1;for(let t=0;t<this._pointerDown.length;t++)this._pointerDown[t]=!1;for(let t=0;t<this._pointerClick.length;t++)this._pointerClick[t]=!1;for(let t=0;t<this._pointerDoubleClick.length;t++)this._pointerDoubleClick[t]=!1;for(const t of this._pointerPositionsDelta)t.set(0,0);for(let t=0;t<this._mouseWheelChanged.length;t++)this._mouseWheelChanged[t]=!1;for(let t=0;t<this._mouseWheelDeltaY.length;t++)this._mouseWheelDeltaY[t]=0});u(this,"keysPressed",{});u(this,"onKeyDown",t=>{if(!this.context.application.hasFocus)return;const i=this.keysPressed[t.code];i&&i.pressed||(this.keysPressed[t.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:t.key,code:t.code},this.onDispatchEvent("keydown",new db(t)))});u(this,"onKeyPressed",t=>{if(!this.context.application.hasFocus)return;const i=this.keysPressed[t.code];i&&(i.pressed=!0,i.frame=this.context.time.frameCount+1,this.onDispatchEvent("keypress",new db(t)))});u(this,"onKeyUp",t=>{if(!this.context.application.hasFocus)return;const i=this.keysPressed[t.code];i&&(i.pressed=!1,i.frame=this.context.time.frameCount+1,this.onDispatchEvent("keyup",new db(t)))});u(this,"onMouseWheel",t=>{if(this.canReceiveInput(t)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const i=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=i+t.deltaY});u(this,"onTouchStart",t=>{if(!(t.changedTouches.length<=0)&&this.canReceiveInput(t)!==!1)for(let i=0;i<t.changedTouches.length;i++){const s=t.changedTouches[i],r=this.getPointerIndex(s.identifier);lo&&vn(`touch start #${r}, identifier:${s.identifier}`);const o={button:r,clientX:s.clientX,clientY:s.clientY,pointerType:"touch",source:t};this.onDown(o)}});u(this,"onTouchMove",t=>{if(!(t.changedTouches.length<=0))for(let i=0;i<t.changedTouches.length;i++){const s=t.changedTouches[i],o={button:this.getPointerIndex(s.identifier),clientX:s.clientX,clientY:s.clientY,pointerType:"touch",source:t};this.onMove(o)}});u(this,"onTouchUp",t=>{if(!(t.changedTouches.length<=0))for(let i=0;i<t.changedTouches.length;i++){const s=t.changedTouches[i],r=this.getPointerIndex(s.identifier);if(!this.isNewEvent(t.timeStamp,r,this._pointerUpTimestamp))continue;lo&&vn(`touch up #${r}, identifier:${s.identifier}`);const o={button:r,clientX:s.clientX,clientY:s.clientY,pointerType:"touch",source:t};this.onUp(o)}});u(this,"onMouseDown",t=>{if(t.defaultPrevented||this.canReceiveInput(t)===!1)return;let i=t.button;this.onDown({button:i,clientX:t.clientX,clientY:t.clientY,pointerType:"mouse",source:t})});u(this,"onMouseMove",t=>{if(t.defaultPrevented)return;const s={button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:"mouse",source:t,movementX:t.movementX,movementY:t.movementY};this.onMove(s)});u(this,"onMouseUp",t=>{if(t.defaultPrevented)return;let i=t.button;this.isNewEvent(t.timeStamp,i,this._pointerUpTimestamp)&&this.onUp({button:i,clientX:t.clientX,clientY:t.clientY,pointerType:"mouse",source:t})});this.context=t,this.context.post_render_callbacks.push(this.onEndOfFrame),window.addEventListener("touchstart",this.onTouchStart,!1),window.addEventListener("touchmove",this.onTouchMove,{passive:!0}),window.addEventListener("touchend",this.onTouchUp,!1),window.addEventListener("mousedown",this.onMouseDown,!1),window.addEventListener("mousemove",this.onMouseMove,!1),window.addEventListener("mouseup",this.onMouseUp,!1),window.addEventListener("wheel",this.onMouseWheel,{passive:!0}),window.addEventListener("keydown",this.onKeyDown,!1),window.addEventListener("keypress",this.onKeyPressed,!1),window.addEventListener("keyup",this.onKeyUp,!1),window.addEventListener("blur",this.onLostFocus)}get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}setCursorPointer(){this._specialCursorTrigger+=1,this.context.domElement.style.cursor="pointer"}setCursorNormal(){this._specialCursorTrigger-=1,this._specialCursorTrigger=Math.max(0,this._specialCursorTrigger),this._specialCursorTrigger===0&&(this.context.domElement.style.cursor="default")}setPointerUsed(t,i=!0){if(t>=this._pointerUsed.length){if(t>=this._pointerIds.length)return;for(;this._pointerUsed.length<=t;)this._pointerUsed.push(!1)}this._pointerUsed[t]=i}getPointerUsed(t){return t>=this._pointerUsed.length?!1:this._pointerUsed[t]}getPointerPressedCount(){let t=0;for(let i=0;i<this._pointerPressed.length;i++)this._pointerPressed[i]&&t++;return t}getPointerPosition(t){return t>=this._pointerPositions.length?null:this._pointerPositions[t]}getPointerPositionLastFrame(t){return t>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[t]}getPointerPositionDelta(t){return t>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[t]}getPointerPositionRC(t){return t>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[t]}getPointerDown(t){return t>=this._pointerDown.length?!1:this._pointerDown[t]}getPointerUp(t){return t>=this._pointerUp.length?!1:this._pointerUp[t]}getPointerPressed(t){return t>=this._pointerPressed.length?!1:this._pointerPressed[t]}getPointerClicked(t){return t>=this._pointerClick.length?!1:this._pointerClick[t]}getPointerDoubleClicked(t){return t>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[t]}getPointerDownTime(t){return t>=this._pointerDownTime.length?-1:this._pointerDownTime[t]}getPointerUpTime(t){return t>=this._pointerUpTime.length?-1:this._pointerUpTime[t]}getPointerLongPress(t){return t>=this._pointerDownTime.length?!1:this.getPointerPressed(t)&&this.context.time.time-this._pointerDownTime[t]>this._longPressTimeThreshold}getIsMouse(t){return t<0||t>=this._pointerTypes.length?!1:this._pointerTypes[t]==="mouse"}getIsTouch(t){return t<0||t>=this._pointerTypes.length?!1:this._pointerTypes[t]==="touch"}getTouchesPressedCount(){let t=0;for(let i=0;i<this._pointerPressed.length;i++)this._pointerPressed[i]&&this.getIsTouch(i)&&t++;return t}getMouseWheelChanged(t=0){return t>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[t]}getMouseWheelDeltaY(t=0){return t>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[t]}getPointerEvent(t){if(!(t>=this._pointerEvent.length))return this._pointerEvent[t]??void 0}*foreachPointerId(t){for(let i=0;i<this._pointerTypes.length;i++)if(this._pointerIsActive(i)){if(t!==void 0){const s=this._pointerTypes[i];if(Array.isArray(t)){let r=!1;for(const o of t)if(s===o){r=!0;break}if(!r)continue}else if(t!==s)continue}yield i}}*foreachTouchId(){for(let t=0;t<this._pointerTypes.length;t++)this._pointerTypes[t]==="touch"&&this._pointerIsActive[t]&&(yield t)}_pointerIsActive(t){return t<0?!1:this._pointerPressed[t]||this._pointerDown[t]||this._pointerUp[t]}getKeyDown(){for(const t in this.keysPressed){const i=this.keysPressed[t];if(i.startFrame===this.context.time.frameCount)return i.key}return null}getKeyPressed(){for(const t in this.keysPressed){const i=this.keysPressed[t];if(i.pressed)return i.key}return null}isKeyDown(t){var s;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const i=this.getCodeForCommonKeyName(t);if(i!==null){for(const r of i)if(this.isKeyDown(r))return!0;return!1}return((s=this.keysPressed[t])==null?void 0:s.startFrame)===this.context.time.frameCount&&this.keysPressed[t].pressed}isKeyUp(t){var s;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const i=this.getCodeForCommonKeyName(t);if(i!==null){for(const r of i)if(this.isKeyUp(r))return!0;return!1}return((s=this.keysPressed[t])==null?void 0:s.frame)===this.context.time.frameCount&&!this.keysPressed[t].pressed}isKeyPressed(t){var s;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const i=this.getCodeForCommonKeyName(t);if(i!==null){for(const r of i)if(this.isKeyPressed(r))return!0;return!1}return(s=this.keysPressed[t])==null?void 0:s.pressed}getCodeForCommonKeyName(t){if(t.length===1){if(t>="0"&&t<="9")return["Digit"+t];if(t>="a"&&t<="z")return["Key"+t.toUpperCase()];if(t==" ")return["Space"]}switch(t){case"Shift":return["ShiftLeft","ShiftRight"];case"Control":return["ControlLeft","ControlRight"];case"Alt":return["AltLeft","AltRight"]}return null}createPointerDown(t){lo&&vn("Create Pointer down"),this.onDown(t)}createPointerMove(t){lo&&vn("Create Pointer move"),this.onMove(t)}createPointerUp(t){lo&&vn("Create Pointer up"),this.onUp(t)}convertScreenspaceToRaycastSpace(t){t.x=(t.x-this.context.domX)/this.context.domWidth*2-1,t.y=-((t.y-this.context.domY)/this.context.domHeight)*2+1}dispose(){const t=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);t>=0&&this.context.post_render_callbacks.splice(t,1),window.removeEventListener("touchstart",this.onTouchStart,!1),window.removeEventListener("touchmove",this.onTouchMove,!1),window.removeEventListener("touchend",this.onTouchUp,!1),window.removeEventListener("mousedown",this.onMouseDown,!1),window.removeEventListener("mousemove",this.onMouseMove,!1),window.removeEventListener("mouseup",this.onMouseUp,!1),window.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}canReceiveInput(t){return t.target===this.context.renderer.domElement||t.target===this.context.domElement}isNewEvent(t,i,s){for(;s.length<=i;)s.push(-1);return t===s[i]?!1:(s[i]=t,!0)}isInRect(t){if(this.context.isInXR)return!0;const i=this.context.domElement.getBoundingClientRect(),s=t.clientX,r=t.clientY,o=s>=i.x&&s<=i.right&&r>=i.y&&r<=i.bottom;return lo&&!o&&console.log("Not in rect",i,s,r),o}onDown(t){var i;if(lo&&console.log(t.pointerType,"DOWN",t.button),!!this.isInRect(t)){if(t.pointerType==="mouse"){const s=this._pointerUpTimestamp[t.button];if(s>0&&((i=t.source)==null?void 0:i.timeStamp)!==void 0){const r=s-t.source.timeStamp;if(r<30&&r>0){lo&&console.log("Ignoring mouse.down for touch.up");return}}}for(this.setPointerState(t.button,this._pointerPressed,!0),this.setPointerState(t.button,this._pointerDown,!0),this.setPointerStateT(t.button,this._pointerEvent,t.source);t.button>=this._pointerTypes.length;)this._pointerTypes.push(t.pointerType);for(this._pointerTypes[t.button]=t.pointerType;t.button>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new K);for(this._pointerPositionDown[t.button].set(t.clientX,t.clientY);t.button>=this._pointerPositions.length;)this._pointerPositions.push(new K);this._pointerPositions[t.button].set(t.clientX,t.clientY),t.button>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t.button]=this.context.time.time,this.updatePointerPosition(t),this.onDispatchEvent("pointerdown",t)}}onMove(t){const i=this.getPointerPressed(t.button);i===!1&&!this.isInRect(t)||t.pointerType==="touch"&&!i||(lo&&console.log(t.pointerType,"MOVE",t.button),this.updatePointerPosition(t),this.setPointerStateT(t.button,this._pointerEvent,t.source),this.onDispatchEvent("pointermove",t))}onUp(t){var o;if(((o=this._pointerIds)==null?void 0:o.length)>=t.button&&(this._pointerIds[t.button]=-1),!this._pointerPressed[t.button]){lo&&console.log(t.pointerType,"UP",t.button,"was not down");return}for(lo&&console.log(t.pointerType,"UP",t.button),this.setPointerState(t.button,this._pointerPressed,!1),this.setPointerStateT(t.button,this._pointerEvent,t.source),this.setPointerState(t.button,this._pointerUp,!0);t.button>=this._pointerUsed.length;)this._pointerUsed.push(!1);if(this.setPointerState(t.button,this._pointerUsed,!1),this.updatePointerPosition(t),!this._pointerPositionDown[t.button]){lo&&Fo("Received pointer up event without matching down event for button: "+t.button),console.warn("Received pointer up event without matching down event for button: "+t.button);return}const s=t.clientX-this._pointerPositionDown[t.button].x,r=t.clientY-this._pointerPositionDown[t.button].y;if(t.button>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),Math.abs(s)<5&&Math.abs(r)<5){this.setPointerState(t.button,this._pointerClick,!0);const a=this._pointerUpTime[t.button],l=this.context.time.time-a;l<this._doubleClickTimeThreshold&&l>0&&this.setPointerState(t.button,this._pointerDoubleClick,!0)}this._pointerUpTime[t.button]=this.context.time.time,this.onDispatchEvent("pointerup",t)}updatePointerPosition(t){for(;t.button>=this._pointerPositions.length;)this._pointerPositions.push(new K);for(;t.button>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new K);for(;t.button>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new K);const i=this._pointerPositionsLastFrame[t.button];i.copy(this._pointerPositions[t.button]);const s=this._pointerPositionsDelta[t.button],r=t.clientX-i.x,o=t.clientY-i.y;s.x+=r,s.y+=o,this._pointerPositions[t.button].x=t.clientX,this._pointerPositions[t.button].y=t.clientY;const a=t.clientX,l=t.clientY;for(;t.button>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new K);const c=this._pointerPositionsRC[t.button];c.set(a,l),this.convertScreenspaceToRaycastSpace(c)}getPointerIndex(t){const i=this._pointerIds;let s=-1;for(let r=0;r<i.length;r++){if(i[r]===t)return r;s===-1&&i[r]===-1&&(s=r)}return s!==-1?(i[s]=t,s):(i.push(t),i.length-1)}setPointerState(t,i,s){for(;i.length<=t;)i.push(!1);i[t]=s}setPointerStateT(t,i,s){for(;i.length<=t;)i.push(null);i[t]=s}onDispatchEvent(t,i){const s=Dt.Current;try{Dt.Current=this.context;const r=new Event(t);nd(r,i),this.dispatchEvent(r)}finally{Dt.Current=s}}}class t6{constructor(){u(this,"Rad2Deg",180/Math.PI);u(this,"Deg2Rad",Math.PI/180);u(this,"Epsilon",1e-5)}random(){return Math.random()}clamp(e,t,i){return e<t?t:e>i?i:e}clamp01(e){return this.clamp(e,0,1)}lerp(e,t,i){return i=i<0?0:i,i=i>1?1:i,e+(t-e)*i}inverseLerp(e,t,i){return(i-e)/(t-e)}remap(e,t,i,s,r){return s+(r-s)*(e-t)/(i-t)}moveTowards(e,t,i){return e+=i,(i<0&&e<t||i>0&&e>t)&&(e=t),e}toDegrees(e){return e*180/Math.PI}toRadians(e){return e*Math.PI/180}tan(e){return Math.tan(e)}gammaToLinear(e){return Math.pow(e,2.2)}linearToGamma(e){return Math.pow(e,1/2.2)}}const et=new t6;function iU(n,e,t){const i=n.length(),s=e.length(),r=et.lerp(i,s,t);return n.lerp(e,t).normalize().multiplyScalar(r)}const i6=new Le().setFromAxisAngle(new M(0,1,0),Math.PI);function n6(n,e){n.lookAt(e),n.quaternion.multiply(i6)}const VT=new tl(()=>new M,100);function xt(n,e=null,t=!0){const i=e??VT.get();return n?n.parent?(t&&n.updateWorldMatrix(!0,!1),n.matrixWorldNeedsUpdate&&n.updateMatrixWorld(),i.setFromMatrixPosition(n.matrixWorld),i):i.copy(n.position):i.set(0,0,0)}function cn(n,e){if(!n)return;const t=VT.get();e!==t&&t.copy(e),((n==null?void 0:n.parent)??n).worldToLocal(t),n.position.set(t.x,t.y,t.z)}function bp(n,e,t,i){const s=VT.get();s.set(e,t,i),cn(n,s)}const u_=new tl(()=>new Le,100),qu=new Le,jS=new Le;function On(n,e=null){if(!n)return u_.get().identity();const t=e??u_.get();return n.parent?(n.getWorldQuaternion(t),t):t.copy(n.quaternion)}function xr(n,e){if(!n)return;e!==qu&&qu.copy(e);const t=qu,i=n==null?void 0:n.parent;i==null||i.getWorldQuaternion(jS),jS.invert();const s=jS.multiply(t);n.quaternion.set(s.x,s.y,s.z,s.w)}function nU(n,e,t,i,s){qu.set(e,t,i,s),xr(n,qu)}const s6=new tl(()=>new M,100),r6=new M;function as(n,e=null){return e||(e=s6.get()),n?n.parent?(n.getWorldScale(e),e):e.copy(n.scale):e.set(0,0,0)}function P1(n,e){if(!n)return;if(!n.parent){n.scale.copy(e);return}const t=r6;n.parent.getWorldScale(t),n.scale.copy(e),n.scale.divide(t)}const o6=new M,ZB=new Le;function a6(n){return On(n,ZB),o6.set(0,0,1).applyQuaternion(ZB)}const l6=new tl(()=>new M,100),$B=new Le;function c6(n,e){return e||(e=l6.get().set(0,0,1)),On(n,$B),e.applyQuaternion($B)}const eD=new cs,tD=new cs,h6=new M;function sU(n){const e=u_.get();return n.getWorldQuaternion(e),tD.setFromQuaternion(e),tD}function rU(n,e){const t=u_.get();xr(n,t.setFromEuler(e))}function Dx(n){const e=sU(n),t=h6;return t.set(e.x,e.y,e.z),t.x=et.toDegrees(t.x),t.y=et.toDegrees(t.y),t.z=et.toDegrees(t.z),t}function oU(n,e){kx(n,e.x,e.y,e.z,!0)}function kx(n,e,t,i,s=!0){s&&(e=et.toRadians(e),t=et.toRadians(t),i=et.toRadians(i)),eD.set(e,t,i),qu.setFromEuler(eD),xr(n,qu)}function d_(n,e=!0){n&&(e?function t(i){console.groupCollapsed((i.name?i.name:"(no name : "+i.type+")")+" %o",i),i.children.forEach(t),console.groupEnd()}(n):n.traverse(function(t){for(var i="|___",s=t;s.parent!==null;)i=" "+i,s=s.parent;console.log(i+t.name+" <"+t.type+">")}))}function aU(n){if(n){const e=n;return e.blendMode!==void 0&&e.clampWhenFinished!==void 0&&e.enabled!==void 0&&e.fadeIn!==void 0&&e.getClip!==void 0}return!1}const jf=class{static createBlitMaterial(e){return new Ot({uniforms:{map:new Ee(null)},vertexShader:this.vertex,fragmentShader:e})}static copyTexture(e,t){const i=t??this.blipMaterial;i.uniforms.map.value=e,i.needsUpdate=!0,i.uniformsNeedUpdate=!0;const s=this.mesh;s.material=i,s.frustumCulled=!1,this.scene.children.length=0,this.scene.add(s),this.renderer.setSize(e.image.width,e.image.height),this.renderer.clear(),this.renderer.render(this.scene,this.perspectiveCam);const r=new Gt(this.renderer.domElement);return r.name="Copy",r.needsUpdate=!0,r}static textureToCanvas(e,t){if(!e)return null;(t===!0||e.isCompressedTexture===!0)&&(e=lU(e));const i=e.image;if(d6(i)){const s=document.createElement("canvas");s.width=i.width,s.height=i.height;const r=s.getContext("2d");return r?(r.drawImage(i,0,0,i.width,i.height,0,0,s.width,s.height),s):(console.error("Failed getting canvas 2d context"),null)}return null}};let Or=jf;u(Or,"planeGeometry",new Kr(2,2,1,1)),u(Or,"renderer",new Dp({antialias:!1})),u(Or,"perspectiveCam",new Xt),u(Or,"scene",new _r),u(Or,"vertex",`
3669
+ <a href="https://docs.needle.tools/serializable" target="_blank">documentation</a>`),console.warn(i,o,n[o],n);continue}}}}function J9(n,e){for(const t of Object.keys(e)){const i=e[t];if(typeof i=="object"&&i!==null&&i!==void 0){const s=n[t];if(!s){Fl&&console.log(t,"is undefined on",n);continue}for(const r of Object.keys(i))if(s[r]===void 0&&JB(i[r])&&!JB(s)){const a=Z9(s,r);if(a&&((a==null?void 0:a.writable)===void 0||(a==null?void 0:a.writable)===!1)&&a.set===void 0){Fl&&console.warn('Property is not writable "'+r+'"',s,a,i[r],s[r]);continue}s[r]=i[r]}}}}function Z9(n,e){for(;n;){const t=Object.getOwnPropertyDescriptor(n,e);if(t)return t;n=Object.getPrototypeOf(n)}}function JB(n){switch(typeof n){case"number":case"string":case"boolean":return!0}return!1}function I1(n,e,t,i,s){let r=typeof e=="function"&&e.prototype===void 0,o=e;if(r)try{if(o=e==null?void 0:e.call(e,s),r=!1,o==null)return}catch(h){console.error("Error in callback",h,n)}if(t.type=o,!r&&s instanceof o)return s;if(s&&typeof s=="object"&&W9(s)){if(s.__concreteInstance)return s.__concreteInstance;const h=s;if(!h.$serializedTypes&&o.prototype.$serializedTypes&&(h.$serializedTypes=o.prototype.$serializedTypes),h.$serializedTypes&&h_(h,n,t),s&&o!==void 0)try{const d=new o;Is&&console.log("Create concrete instance for persistent asset",s,"instance:",d),nd(d,s),s.__concreteInstance=d,s=d}catch(d){console.error("Error creating instance or creating values on instance",d,s,o)}return s}if(i||(i={serializer:c_.getSerializerForConstructor(o)}),Array.isArray(n)){const h=[];for(let d=0;d<n.length;d++){const f=n[d],p=I1(f,e,t,i,f);h.push(p)}return h}const a=i.serializer;if(a)return a.onDeserialize(n,t);let l;if(n&&(n.isMaterial||n.isTexture||n.isObject3D))l=n;else{if(n===void 0)return;if(n===null&&(o===Bt||o===Gt||o===ye||o===qr))return null;l=new o(...$9(n))}const c=l;return c.$serializedTypes&&h_(c,n,t),l}function $9(n){if(ub.length=0,typeof n=="object"&&n!==null&&n!==void 0)for(const e of Object.keys(n))ub.push(n[e]);return ub}const R1=Symbol("assigned component properties");function nd(n,e,t){var s;if(e==null||n==null)return;n[R1]=!0;const i=((s=n.constructor)==null?void 0:s.name)??"unknown";t==null||t.registerDefinedKeys(i,n);for(const r of Object.keys(e)){const o=e6(n,r);typeof(o==null?void 0:o.value)!="function"&&(!o||o.writable===!0||(o==null?void 0:o.set)!==void 0)&&(n[r]=e[r])}delete n[R1]}function e6(n,e){let t;do t=Object.getOwnPropertyDescriptor(n,e);while(!t&&(n=Object.getPrototypeOf(n)));return t}const lo=se("debuginput");class db{constructor(e){u(this,"key");u(this,"keyType");u(this,"source");this.key=e.key,this.keyType=e.type,this.source=e}}var La=(n=>(n.PointerDown="pointerdown",n.PointerUp="pointerup",n.PointerMove="pointermove",n.KeyDown="keydown",n.KeyUp="keyup",n.KeyPressed="keypress",n))(La||{}),eU=(n=>(n.Mouse="mouse",n.Touch="touch",n))(eU||{});class tU extends EventTarget{constructor(t){super();u(this,"_doubleClickTimeThreshold",.2);u(this,"_longPressTimeThreshold",1);u(this,"_specialCursorTrigger",0);u(this,"context");u(this,"_pointerDown",[!1]);u(this,"_pointerUp",[!1]);u(this,"_pointerClick",[!1]);u(this,"_pointerDoubleClick",[!1]);u(this,"_pointerPressed",[!1]);u(this,"_pointerPositions",[new K]);u(this,"_pointerPositionsLastFrame",[new K]);u(this,"_pointerPositionsDelta",[new K]);u(this,"_pointerPositionsRC",[new K]);u(this,"_pointerPositionDown",[new K]);u(this,"_pointerDownTime",[]);u(this,"_pointerUpTime",[]);u(this,"_pointerUpTimestamp",[]);u(this,"_pointerIds",[]);u(this,"_pointerTypes",[""]);u(this,"_mouseWheelChanged",[!1]);u(this,"_mouseWheelDeltaY",[0]);u(this,"_pointerEvent",[]);u(this,"_pointerUsed",[]);u(this,"onLostFocus",()=>{for(const t in this.keysPressed)this.keysPressed[t].pressed=!1});u(this,"onEndOfFrame",()=>{for(let t=0;t<this._pointerUp.length;t++)this._pointerUp[t]=!1;for(let t=0;t<this._pointerDown.length;t++)this._pointerDown[t]=!1;for(let t=0;t<this._pointerClick.length;t++)this._pointerClick[t]=!1;for(let t=0;t<this._pointerDoubleClick.length;t++)this._pointerDoubleClick[t]=!1;for(const t of this._pointerPositionsDelta)t.set(0,0);for(let t=0;t<this._mouseWheelChanged.length;t++)this._mouseWheelChanged[t]=!1;for(let t=0;t<this._mouseWheelDeltaY.length;t++)this._mouseWheelDeltaY[t]=0});u(this,"keysPressed",{});u(this,"onKeyDown",t=>{if(!this.context.application.hasFocus)return;const i=this.keysPressed[t.code];i&&i.pressed||(this.keysPressed[t.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:t.key,code:t.code},this.onDispatchEvent("keydown",new db(t)))});u(this,"onKeyPressed",t=>{if(!this.context.application.hasFocus)return;const i=this.keysPressed[t.code];i&&(i.pressed=!0,i.frame=this.context.time.frameCount+1,this.onDispatchEvent("keypress",new db(t)))});u(this,"onKeyUp",t=>{if(!this.context.application.hasFocus)return;const i=this.keysPressed[t.code];i&&(i.pressed=!1,i.frame=this.context.time.frameCount+1,this.onDispatchEvent("keyup",new db(t)))});u(this,"onMouseWheel",t=>{if(this.canReceiveInput(t)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const i=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=i+t.deltaY});u(this,"onTouchStart",t=>{if(!(t.changedTouches.length<=0)&&this.canReceiveInput(t)!==!1)for(let i=0;i<t.changedTouches.length;i++){const s=t.changedTouches[i],r=this.getPointerIndex(s.identifier);lo&&vn(`touch start #${r}, identifier:${s.identifier}`);const o={button:r,clientX:s.clientX,clientY:s.clientY,pointerType:"touch",source:t};this.onDown(o)}});u(this,"onTouchMove",t=>{if(!(t.changedTouches.length<=0))for(let i=0;i<t.changedTouches.length;i++){const s=t.changedTouches[i],o={button:this.getPointerIndex(s.identifier),clientX:s.clientX,clientY:s.clientY,pointerType:"touch",source:t};this.onMove(o)}});u(this,"onTouchUp",t=>{if(!(t.changedTouches.length<=0))for(let i=0;i<t.changedTouches.length;i++){const s=t.changedTouches[i],r=this.getPointerIndex(s.identifier);if(!this.isNewEvent(t.timeStamp,r,this._pointerUpTimestamp))continue;lo&&vn(`touch up #${r}, identifier:${s.identifier}`);const o={button:r,clientX:s.clientX,clientY:s.clientY,pointerType:"touch",source:t};this.onUp(o)}});u(this,"onMouseDown",t=>{if(t.defaultPrevented||this.canReceiveInput(t)===!1)return;let i=t.button;this.onDown({button:i,clientX:t.clientX,clientY:t.clientY,pointerType:"mouse",source:t})});u(this,"onMouseMove",t=>{if(t.defaultPrevented)return;const s={button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:"mouse",source:t,movementX:t.movementX,movementY:t.movementY};this.onMove(s)});u(this,"onMouseUp",t=>{if(t.defaultPrevented)return;let i=t.button;this.isNewEvent(t.timeStamp,i,this._pointerUpTimestamp)&&this.onUp({button:i,clientX:t.clientX,clientY:t.clientY,pointerType:"mouse",source:t})});this.context=t,this.context.post_render_callbacks.push(this.onEndOfFrame),window.addEventListener("touchstart",this.onTouchStart,!1),window.addEventListener("touchmove",this.onTouchMove,{passive:!0}),window.addEventListener("touchend",this.onTouchUp,!1),window.addEventListener("mousedown",this.onMouseDown,!1),window.addEventListener("mousemove",this.onMouseMove,!1),window.addEventListener("mouseup",this.onMouseUp,!1),window.addEventListener("wheel",this.onMouseWheel,{passive:!0}),window.addEventListener("keydown",this.onKeyDown,!1),window.addEventListener("keypress",this.onKeyPressed,!1),window.addEventListener("keyup",this.onKeyUp,!1),window.addEventListener("blur",this.onLostFocus)}get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}setCursorPointer(){this._specialCursorTrigger+=1,this.context.domElement.style.cursor="pointer"}setCursorNormal(){this._specialCursorTrigger-=1,this._specialCursorTrigger=Math.max(0,this._specialCursorTrigger),this._specialCursorTrigger===0&&(this.context.domElement.style.cursor="default")}setPointerUsed(t,i=!0){if(t>=this._pointerUsed.length){if(t>=this._pointerIds.length)return;for(;this._pointerUsed.length<=t;)this._pointerUsed.push(!1)}this._pointerUsed[t]=i}getPointerUsed(t){return t>=this._pointerUsed.length?!1:this._pointerUsed[t]}getPointerPressedCount(){let t=0;for(let i=0;i<this._pointerPressed.length;i++)this._pointerPressed[i]&&t++;return t}getPointerPosition(t){return t>=this._pointerPositions.length?null:this._pointerPositions[t]}getPointerPositionLastFrame(t){return t>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[t]}getPointerPositionDelta(t){return t>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[t]}getPointerPositionRC(t){return t>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[t]}getPointerDown(t){return t>=this._pointerDown.length?!1:this._pointerDown[t]}getPointerUp(t){return t>=this._pointerUp.length?!1:this._pointerUp[t]}getPointerPressed(t){return t>=this._pointerPressed.length?!1:this._pointerPressed[t]}getPointerClicked(t){return t>=this._pointerClick.length?!1:this._pointerClick[t]}getPointerDoubleClicked(t){return t>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[t]}getPointerDownTime(t){return t>=this._pointerDownTime.length?-1:this._pointerDownTime[t]}getPointerUpTime(t){return t>=this._pointerUpTime.length?-1:this._pointerUpTime[t]}getPointerLongPress(t){return t>=this._pointerDownTime.length?!1:this.getPointerPressed(t)&&this.context.time.time-this._pointerDownTime[t]>this._longPressTimeThreshold}getIsMouse(t){return t<0||t>=this._pointerTypes.length?!1:this._pointerTypes[t]==="mouse"}getIsTouch(t){return t<0||t>=this._pointerTypes.length?!1:this._pointerTypes[t]==="touch"}getTouchesPressedCount(){let t=0;for(let i=0;i<this._pointerPressed.length;i++)this._pointerPressed[i]&&this.getIsTouch(i)&&t++;return t}getMouseWheelChanged(t=0){return t>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[t]}getMouseWheelDeltaY(t=0){return t>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[t]}getPointerEvent(t){if(!(t>=this._pointerEvent.length))return this._pointerEvent[t]??void 0}*foreachPointerId(t){for(let i=0;i<this._pointerTypes.length;i++)if(this._pointerIsActive(i)){if(t!==void 0){const s=this._pointerTypes[i];if(Array.isArray(t)){let r=!1;for(const o of t)if(s===o){r=!0;break}if(!r)continue}else if(t!==s)continue}yield i}}*foreachTouchId(){for(let t=0;t<this._pointerTypes.length;t++)this._pointerTypes[t]==="touch"&&this._pointerIsActive[t]&&(yield t)}_pointerIsActive(t){return t<0?!1:this._pointerPressed[t]||this._pointerDown[t]||this._pointerUp[t]}getKeyDown(){for(const t in this.keysPressed){const i=this.keysPressed[t];if(i.startFrame===this.context.time.frameCount)return i.key}return null}getKeyPressed(){for(const t in this.keysPressed){const i=this.keysPressed[t];if(i.pressed)return i.key}return null}isKeyDown(t){var s;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const i=this.getCodeForCommonKeyName(t);if(i!==null){for(const r of i)if(this.isKeyDown(r))return!0;return!1}return((s=this.keysPressed[t])==null?void 0:s.startFrame)===this.context.time.frameCount&&this.keysPressed[t].pressed}isKeyUp(t){var s;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const i=this.getCodeForCommonKeyName(t);if(i!==null){for(const r of i)if(this.isKeyUp(r))return!0;return!1}return((s=this.keysPressed[t])==null?void 0:s.frame)===this.context.time.frameCount&&!this.keysPressed[t].pressed}isKeyPressed(t){var s;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const i=this.getCodeForCommonKeyName(t);if(i!==null){for(const r of i)if(this.isKeyPressed(r))return!0;return!1}return(s=this.keysPressed[t])==null?void 0:s.pressed}getCodeForCommonKeyName(t){if(t.length===1){if(t>="0"&&t<="9")return["Digit"+t];if(t>="a"&&t<="z")return["Key"+t.toUpperCase()];if(t==" ")return["Space"]}switch(t){case"Shift":return["ShiftLeft","ShiftRight"];case"Control":return["ControlLeft","ControlRight"];case"Alt":return["AltLeft","AltRight"]}return null}createPointerDown(t){lo&&vn("Create Pointer down"),this.onDown(t)}createPointerMove(t){lo&&vn("Create Pointer move"),this.onMove(t)}createPointerUp(t){lo&&vn("Create Pointer up"),this.onUp(t)}convertScreenspaceToRaycastSpace(t){t.x=(t.x-this.context.domX)/this.context.domWidth*2-1,t.y=-((t.y-this.context.domY)/this.context.domHeight)*2+1}dispose(){const t=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);t>=0&&this.context.post_render_callbacks.splice(t,1),window.removeEventListener("touchstart",this.onTouchStart,!1),window.removeEventListener("touchmove",this.onTouchMove,!1),window.removeEventListener("touchend",this.onTouchUp,!1),window.removeEventListener("mousedown",this.onMouseDown,!1),window.removeEventListener("mousemove",this.onMouseMove,!1),window.removeEventListener("mouseup",this.onMouseUp,!1),window.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}canReceiveInput(t){return t.target===this.context.renderer.domElement||t.target===this.context.domElement}isNewEvent(t,i,s){for(;s.length<=i;)s.push(-1);return t===s[i]?!1:(s[i]=t,!0)}isInRect(t){if(this.context.isInXR)return!0;const i=this.context.domElement.getBoundingClientRect(),s=t.clientX,r=t.clientY,o=s>=i.x&&s<=i.right&&r>=i.y&&r<=i.bottom;return lo&&!o&&console.log("Not in rect",i,s,r),o}onDown(t){var i;if(lo&&console.log(t.pointerType,"DOWN",t.button),!!this.isInRect(t)){if(t.pointerType==="mouse"){const s=this._pointerUpTimestamp[t.button];if(s>0&&((i=t.source)==null?void 0:i.timeStamp)!==void 0){const r=t.source.timeStamp-s;if(r<60&&r>=0){lo&&console.log("Ignoring mouse.down for touch.up");return}}}for(this.setPointerState(t.button,this._pointerPressed,!0),this.setPointerState(t.button,this._pointerDown,!0),this.setPointerStateT(t.button,this._pointerEvent,t.source);t.button>=this._pointerTypes.length;)this._pointerTypes.push(t.pointerType);for(this._pointerTypes[t.button]=t.pointerType;t.button>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new K);for(this._pointerPositionDown[t.button].set(t.clientX,t.clientY);t.button>=this._pointerPositions.length;)this._pointerPositions.push(new K);this._pointerPositions[t.button].set(t.clientX,t.clientY),t.button>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t.button]=this.context.time.time,this.updatePointerPosition(t),this.onDispatchEvent("pointerdown",t)}}onMove(t){const i=this.getPointerPressed(t.button);i===!1&&!this.isInRect(t)||t.pointerType==="touch"&&!i||(lo&&console.log(t.pointerType,"MOVE",t.button),this.updatePointerPosition(t),this.setPointerStateT(t.button,this._pointerEvent,t.source),this.onDispatchEvent("pointermove",t))}onUp(t){var o;if(((o=this._pointerIds)==null?void 0:o.length)>=t.button&&(this._pointerIds[t.button]=-1),!this._pointerPressed[t.button]){lo&&console.log(t.pointerType,"UP",t.button,"was not down");return}for(lo&&console.log(t.pointerType,"UP",t.button),this.setPointerState(t.button,this._pointerPressed,!1),this.setPointerStateT(t.button,this._pointerEvent,t.source),this.setPointerState(t.button,this._pointerUp,!0);t.button>=this._pointerUsed.length;)this._pointerUsed.push(!1);if(this.setPointerState(t.button,this._pointerUsed,!1),this.updatePointerPosition(t),!this._pointerPositionDown[t.button]){lo&&Fo("Received pointer up event without matching down event for button: "+t.button),console.warn("Received pointer up event without matching down event for button: "+t.button);return}const s=t.clientX-this._pointerPositionDown[t.button].x,r=t.clientY-this._pointerPositionDown[t.button].y;if(t.button>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),Math.abs(s)<5&&Math.abs(r)<5){this.setPointerState(t.button,this._pointerClick,!0);const a=this._pointerUpTime[t.button],l=this.context.time.time-a;l<this._doubleClickTimeThreshold&&l>0&&this.setPointerState(t.button,this._pointerDoubleClick,!0)}this._pointerUpTime[t.button]=this.context.time.time,this.onDispatchEvent("pointerup",t)}updatePointerPosition(t){for(;t.button>=this._pointerPositions.length;)this._pointerPositions.push(new K);for(;t.button>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new K);for(;t.button>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new K);const i=this._pointerPositionsLastFrame[t.button];i.copy(this._pointerPositions[t.button]);const s=this._pointerPositionsDelta[t.button],r=t.clientX-i.x,o=t.clientY-i.y;s.x+=r,s.y+=o,this._pointerPositions[t.button].x=t.clientX,this._pointerPositions[t.button].y=t.clientY;const a=t.clientX,l=t.clientY;for(;t.button>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new K);const c=this._pointerPositionsRC[t.button];c.set(a,l),this.convertScreenspaceToRaycastSpace(c)}getPointerIndex(t){const i=this._pointerIds;let s=-1;for(let r=0;r<i.length;r++){if(i[r]===t)return r;s===-1&&i[r]===-1&&(s=r)}return s!==-1?(i[s]=t,s):(i.push(t),i.length-1)}setPointerState(t,i,s){for(;i.length<=t;)i.push(!1);i[t]=s}setPointerStateT(t,i,s){for(;i.length<=t;)i.push(null);i[t]=s}onDispatchEvent(t,i){const s=Dt.Current;try{Dt.Current=this.context;const r=new Event(t);nd(r,i),this.dispatchEvent(r)}finally{Dt.Current=s}}}class t6{constructor(){u(this,"Rad2Deg",180/Math.PI);u(this,"Deg2Rad",Math.PI/180);u(this,"Epsilon",1e-5)}random(){return Math.random()}clamp(e,t,i){return e<t?t:e>i?i:e}clamp01(e){return this.clamp(e,0,1)}lerp(e,t,i){return i=i<0?0:i,i=i>1?1:i,e+(t-e)*i}inverseLerp(e,t,i){return(i-e)/(t-e)}remap(e,t,i,s,r){return s+(r-s)*(e-t)/(i-t)}moveTowards(e,t,i){return e+=i,(i<0&&e<t||i>0&&e>t)&&(e=t),e}toDegrees(e){return e*180/Math.PI}toRadians(e){return e*Math.PI/180}tan(e){return Math.tan(e)}gammaToLinear(e){return Math.pow(e,2.2)}linearToGamma(e){return Math.pow(e,1/2.2)}}const et=new t6;function iU(n,e,t){const i=n.length(),s=e.length(),r=et.lerp(i,s,t);return n.lerp(e,t).normalize().multiplyScalar(r)}const i6=new Le().setFromAxisAngle(new M(0,1,0),Math.PI);function n6(n,e){n.lookAt(e),n.quaternion.multiply(i6)}const VT=new tl(()=>new M,100);function xt(n,e=null,t=!0){const i=e??VT.get();return n?n.parent?(t&&n.updateWorldMatrix(!0,!1),n.matrixWorldNeedsUpdate&&n.updateMatrixWorld(),i.setFromMatrixPosition(n.matrixWorld),i):i.copy(n.position):i.set(0,0,0)}function cn(n,e){if(!n)return;const t=VT.get();e!==t&&t.copy(e),((n==null?void 0:n.parent)??n).worldToLocal(t),n.position.set(t.x,t.y,t.z)}function bp(n,e,t,i){const s=VT.get();s.set(e,t,i),cn(n,s)}const u_=new tl(()=>new Le,100),qu=new Le,jS=new Le;function On(n,e=null){if(!n)return u_.get().identity();const t=e??u_.get();return n.parent?(n.getWorldQuaternion(t),t):t.copy(n.quaternion)}function xr(n,e){if(!n)return;e!==qu&&qu.copy(e);const t=qu,i=n==null?void 0:n.parent;i==null||i.getWorldQuaternion(jS),jS.invert();const s=jS.multiply(t);n.quaternion.set(s.x,s.y,s.z,s.w)}function nU(n,e,t,i,s){qu.set(e,t,i,s),xr(n,qu)}const s6=new tl(()=>new M,100),r6=new M;function as(n,e=null){return e||(e=s6.get()),n?n.parent?(n.getWorldScale(e),e):e.copy(n.scale):e.set(0,0,0)}function P1(n,e){if(!n)return;if(!n.parent){n.scale.copy(e);return}const t=r6;n.parent.getWorldScale(t),n.scale.copy(e),n.scale.divide(t)}const o6=new M,ZB=new Le;function a6(n){return On(n,ZB),o6.set(0,0,1).applyQuaternion(ZB)}const l6=new tl(()=>new M,100),$B=new Le;function c6(n,e){return e||(e=l6.get().set(0,0,1)),On(n,$B),e.applyQuaternion($B)}const eD=new cs,tD=new cs,h6=new M;function sU(n){const e=u_.get();return n.getWorldQuaternion(e),tD.setFromQuaternion(e),tD}function rU(n,e){const t=u_.get();xr(n,t.setFromEuler(e))}function Dx(n){const e=sU(n),t=h6;return t.set(e.x,e.y,e.z),t.x=et.toDegrees(t.x),t.y=et.toDegrees(t.y),t.z=et.toDegrees(t.z),t}function oU(n,e){kx(n,e.x,e.y,e.z,!0)}function kx(n,e,t,i,s=!0){s&&(e=et.toRadians(e),t=et.toRadians(t),i=et.toRadians(i)),eD.set(e,t,i),qu.setFromEuler(eD),xr(n,qu)}function d_(n,e=!0){n&&(e?function t(i){console.groupCollapsed((i.name?i.name:"(no name : "+i.type+")")+" %o",i),i.children.forEach(t),console.groupEnd()}(n):n.traverse(function(t){for(var i="|___",s=t;s.parent!==null;)i=" "+i,s=s.parent;console.log(i+t.name+" <"+t.type+">")}))}function aU(n){if(n){const e=n;return e.blendMode!==void 0&&e.clampWhenFinished!==void 0&&e.enabled!==void 0&&e.fadeIn!==void 0&&e.getClip!==void 0}return!1}const jf=class{static createBlitMaterial(e){return new Ot({uniforms:{map:new Ee(null)},vertexShader:this.vertex,fragmentShader:e})}static copyTexture(e,t){const i=t??this.blipMaterial;i.uniforms.map.value=e,i.needsUpdate=!0,i.uniformsNeedUpdate=!0;const s=this.mesh;s.material=i,s.frustumCulled=!1,this.scene.children.length=0,this.scene.add(s),this.renderer.setSize(e.image.width,e.image.height),this.renderer.clear(),this.renderer.render(this.scene,this.perspectiveCam);const r=new Gt(this.renderer.domElement);return r.name="Copy",r.needsUpdate=!0,r}static textureToCanvas(e,t){if(!e)return null;(t===!0||e.isCompressedTexture===!0)&&(e=lU(e));const i=e.image;if(d6(i)){const s=document.createElement("canvas");s.width=i.width,s.height=i.height;const r=s.getContext("2d");return r?(r.drawImage(i,0,0,i.width,i.height,0,0,s.width,s.height),s):(console.error("Failed getting canvas 2d context"),null)}return null}};let Or=jf;u(Or,"planeGeometry",new Kr(2,2,1,1)),u(Or,"renderer",new Dp({antialias:!1})),u(Or,"perspectiveCam",new Xt),u(Or,"scene",new _r),u(Or,"vertex",`
3670
3670
  varying vec2 vUv;
3671
3671
  void main(){
3672
3672
  vUv = uv;
@@ -4408,7 +4408,7 @@ Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSE
4408
4408
  version 0.6.9
4409
4409
  */var m2=function(n){return URL.createObjectURL(new Blob([n],{type:"text/javascript"}))};try{URL.revokeObjectURL(m2(""))}catch{m2=function(e){return"data:application/javascript;charset=UTF-8,"+encodeURI(e)}}var yn=Uint8Array,Xs=Uint16Array,wp=Uint32Array,iw=new yn([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),nw=new yn([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),J1=new yn([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),N3=function(n,e){for(var t=new Xs(31),i=0;i<31;++i)t[i]=e+=1<<n[i-1];for(var s=new wp(t[30]),i=1;i<30;++i)for(var r=t[i];r<t[i+1];++r)s[r]=r-t[i]<<5|i;return[t,s]},z3=N3(iw,2),G3=z3[0],Z1=z3[1];G3[28]=258,Z1[258]=28;var H3=N3(nw,0),SK=H3[0],g2=H3[1],$1=new Xs(32768);for(var Ii=0;Ii<32768;++Ii){var Qc=(Ii&43690)>>>1|(Ii&21845)<<1;Qc=(Qc&52428)>>>2|(Qc&13107)<<2,Qc=(Qc&61680)>>>4|(Qc&3855)<<4,$1[Ii]=((Qc&65280)>>>8|(Qc&255)<<8)>>>1}var Za=function(n,e,t){for(var i=n.length,s=0,r=new Xs(e);s<i;++s)++r[n[s]-1];var o=new Xs(e);for(s=0;s<e;++s)o[s]=o[s-1]+r[s-1]<<1;var a;if(t){a=new Xs(1<<e);var l=15-e;for(s=0;s<i;++s)if(n[s])for(var c=s<<4|n[s],h=e-n[s],d=o[n[s]-1]++<<h,f=d|(1<<h)-1;d<=f;++d)a[$1[d]>>>l]=c}else for(a=new Xs(i),s=0;s<i;++s)n[s]&&(a[s]=$1[o[n[s]-1]++]>>>15-n[s]);return a},Mh=new yn(288);for(var Ii=0;Ii<144;++Ii)Mh[Ii]=8;for(var Ii=144;Ii<256;++Ii)Mh[Ii]=9;for(var Ii=256;Ii<280;++Ii)Mh[Ii]=7;for(var Ii=280;Ii<288;++Ii)Mh[Ii]=8;var TA=new yn(32);for(var Ii=0;Ii<32;++Ii)TA[Ii]=5;var CK=Za(Mh,9,0),EK=Za(Mh,9,1),MK=Za(TA,5,0),TK=Za(TA,5,1),pC=function(n){for(var e=n[0],t=1;t<n.length;++t)n[t]>e&&(e=n[t]);return e},qo=function(n,e,t){var i=e/8|0;return(n[i]|n[i+1]<<8)>>(e&7)&t},mC=function(n,e){var t=e/8|0;return(n[t]|n[t+1]<<8|n[t+2]<<16)>>(e&7)},yI=function(n){return(n/8|0)+(n&7&&1)},bI=function(n,e,t){(e==null||e<0)&&(e=0),(t==null||t>n.length)&&(t=n.length);var i=new(n instanceof Xs?Xs:n instanceof wp?wp:yn)(t-e);return i.set(n.subarray(e,t)),i},IK=function(n,e,t){var i=n.length;if(!i||t&&!t.l&&i<5)return e||new yn(0);var s=!e||t,r=!t||t.i;t||(t={}),e||(e=new yn(i*3));var o=function(Ce){var We=e.length;if(Ce>We){var He=new yn(Math.max(We*2,Ce));He.set(e),e=He}},a=t.f||0,l=t.p||0,c=t.b||0,h=t.l,d=t.d,f=t.m,p=t.n,m=i*8;do{if(!h){t.f=a=qo(n,l,1);var A=qo(n,l+1,3);if(l+=3,A)if(A==1)h=EK,d=TK,f=9,p=5;else if(A==2){var y=qo(n,l,31)+257,_=qo(n,l+10,15)+4,x=y+qo(n,l+5,31)+1;l+=14;for(var S=new yn(x),I=new yn(19),R=0;R<_;++R)I[J1[R]]=qo(n,l+R*3,7);l+=_*3;for(var E=pC(I),T=(1<<E)-1,k=Za(I,E,1),R=0;R<x;){var W=k[qo(n,l,T)];l+=W&15;var v=W>>>4;if(v<16)S[R++]=v;else{var U=0,z=0;for(v==16?(z=3+qo(n,l,3),l+=2,U=S[R-1]):v==17?(z=3+qo(n,l,7),l+=3):v==18&&(z=11+qo(n,l,127),l+=7);z--;)S[R++]=U}}var Q=S.subarray(0,y),ee=S.subarray(y);f=pC(Q),p=pC(ee),h=Za(Q,f,1),d=Za(ee,p,1)}else throw"invalid block type";else{var v=yI(l)+4,g=n[v-4]|n[v-3]<<8,b=v+g;if(b>i){if(r)throw"unexpected EOF";break}s&&o(c+g),e.set(n.subarray(v,b),c),t.b=c+=g,t.p=l=b*8;continue}if(l>m){if(r)throw"unexpected EOF";break}}s&&o(c+131072);for(var X=(1<<f)-1,J=(1<<p)-1,ie=l;;ie=l){var U=h[mC(n,l)&X],oe=U>>>4;if(l+=U&15,l>m){if(r)throw"unexpected EOF";break}if(!U)throw"invalid length/literal";if(oe<256)e[c++]=oe;else if(oe==256){ie=l,h=null;break}else{var Y=oe-254;if(oe>264){var R=oe-257,te=iw[R];Y=qo(n,l,(1<<te)-1)+G3[R],l+=te}var xe=d[mC(n,l)&J],be=xe>>>4;if(!xe)throw"invalid distance";l+=xe&15;var ee=SK[be];if(be>3){var te=nw[be];ee+=mC(n,l)&(1<<te)-1,l+=te}if(l>m){if(r)throw"unexpected EOF";break}s&&o(c+131072);for(var Se=c+Y;c<Se;c+=4)e[c]=e[c-ee],e[c+1]=e[c+1-ee],e[c+2]=e[c+2-ee],e[c+3]=e[c+3-ee];c=Se}}t.l=h,t.p=ie,t.b=c,h&&(a=1,t.m=f,t.d=d,t.n=p)}while(!a);return c==e.length?e:bI(e,0,c)},Sl=function(n,e,t){t<<=e&7;var i=e/8|0;n[i]|=t,n[i+1]|=t>>>8},Gm=function(n,e,t){t<<=e&7;var i=e/8|0;n[i]|=t,n[i+1]|=t>>>8,n[i+2]|=t>>>16},gC=function(n,e){for(var t=[],i=0;i<n.length;++i)n[i]&&t.push({s:i,f:n[i]});var s=t.length,r=t.slice();if(!s)return[_I,0];if(s==1){var o=new yn(t[0].s+1);return o[t[0].s]=1,[o,1]}t.sort(function(x,S){return x.f-S.f}),t.push({s:-1,f:25001});var a=t[0],l=t[1],c=0,h=1,d=2;for(t[0]={s:-1,f:a.f+l.f,l:a,r:l};h!=s-1;)a=t[t[c].f<t[d].f?c++:d++],l=t[c!=h&&t[c].f<t[d].f?c++:d++],t[h++]={s:-1,f:a.f+l.f,l:a,r:l};for(var f=r[0].s,i=1;i<s;++i)r[i].s>f&&(f=r[i].s);var p=new Xs(f+1),m=eM(t[h-1],p,0);if(m>e){var i=0,A=0,v=m-e,g=1<<v;for(r.sort(function(S,I){return p[I.s]-p[S.s]||S.f-I.f});i<s;++i){var b=r[i].s;if(p[b]>e)A+=g-(1<<m-p[b]),p[b]=e;else break}for(A>>>=v;A>0;){var y=r[i].s;p[y]<e?A-=1<<e-p[y]++-1:++i}for(;i>=0&&A;--i){var _=r[i].s;p[_]==e&&(--p[_],++A)}m=e}return[new yn(p),m]},eM=function(n,e,t){return n.s==-1?Math.max(eM(n.l,e,t+1),eM(n.r,e,t+1)):e[n.s]=t},A2=function(n){for(var e=n.length;e&&!n[--e];);for(var t=new Xs(++e),i=0,s=n[0],r=1,o=function(l){t[i++]=l},a=1;a<=e;++a)if(n[a]==s&&a!=e)++r;else{if(!s&&r>2){for(;r>138;r-=138)o(32754);r>2&&(o(r>10?r-11<<5|28690:r-3<<5|12305),r=0)}else if(r>3){for(o(s),--r;r>6;r-=6)o(8304);r>2&&(o(r-3<<5|8208),r=0)}for(;r--;)o(s);r=1,s=n[a]}return[t.subarray(0,i),e]},Hm=function(n,e){for(var t=0,i=0;i<e.length;++i)t+=n[i]*e[i];return t},Sb=function(n,e,t){var i=t.length,s=yI(e+2);n[s]=i&255,n[s+1]=i>>>8,n[s+2]=n[s]^255,n[s+3]=n[s+1]^255;for(var r=0;r<i;++r)n[s+r+4]=t[r];return(s+4+i)*8},v2=function(n,e,t,i,s,r,o,a,l,c,h){Sl(e,h++,t),++s[256];for(var d=gC(s,15),f=d[0],p=d[1],m=gC(r,15),A=m[0],v=m[1],g=A2(f),b=g[0],y=g[1],_=A2(A),x=_[0],S=_[1],I=new Xs(19),R=0;R<b.length;++R)I[b[R]&31]++;for(var R=0;R<x.length;++R)I[x[R]&31]++;for(var E=gC(I,7),T=E[0],k=E[1],W=19;W>4&&!T[J1[W-1]];--W);var U=c+5<<3,z=Hm(s,Mh)+Hm(r,TA)+o,Q=Hm(s,f)+Hm(r,A)+o+14+3*W+Hm(I,T)+(2*I[16]+3*I[17]+7*I[18]);if(U<=z&&U<=Q)return Sb(e,h,n.subarray(l,l+c));var ee,X,J,ie;if(Sl(e,h,1+(Q<z)),h+=2,Q<z){ee=Za(f,p,0),X=f,J=Za(A,v,0),ie=A;var oe=Za(T,k,0);Sl(e,h,y-257),Sl(e,h+5,S-1),Sl(e,h+10,W-4),h+=14;for(var R=0;R<W;++R)Sl(e,h+3*R,T[J1[R]]);h+=3*W;for(var Y=[b,x],te=0;te<2;++te)for(var xe=Y[te],R=0;R<xe.length;++R){var be=xe[R]&31;Sl(e,h,oe[be]),h+=T[be],be>15&&(Sl(e,h,xe[R]>>>5&127),h+=xe[R]>>>12)}}else ee=CK,X=Mh,J=MK,ie=TA;for(var R=0;R<a;++R)if(i[R]>255){var be=i[R]>>>18&31;Gm(e,h,ee[be+257]),h+=X[be+257],be>7&&(Sl(e,h,i[R]>>>23&31),h+=iw[be]);var Se=i[R]&31;Gm(e,h,J[Se]),h+=ie[Se],Se>3&&(Gm(e,h,i[R]>>>5&8191),h+=nw[Se])}else Gm(e,h,ee[i[R]]),h+=X[i[R]];return Gm(e,h,ee[256]),h+X[256]},RK=new wp([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),_I=new yn(0),PK=function(n,e,t,i,s,r){var o=n.length,a=new yn(i+o+5*(1+Math.ceil(o/7e3))+s),l=a.subarray(i,a.length-s),c=0;if(!e||o<8)for(var h=0;h<=o;h+=65535){var d=h+65535;d<o?c=Sb(l,c,n.subarray(h,d)):(l[h]=r,c=Sb(l,c,n.subarray(h,o)))}else{for(var f=RK[e-1],p=f>>>13,m=f&8191,A=(1<<t)-1,v=new Xs(32768),g=new Xs(A+1),b=Math.ceil(t/3),y=2*b,_=function(me){return(n[me]^n[me+1]<<b^n[me+2]<<y)&A},x=new wp(25e3),S=new Xs(288),I=new Xs(32),R=0,E=0,h=0,T=0,k=0,W=0;h<o;++h){var U=_(h),z=h&32767,Q=g[U];if(v[z]=Q,g[U]=z,k<=h){var ee=o-h;if((R>7e3||T>24576)&&ee>423){c=v2(n,l,0,x,S,I,E,T,W,h-W,c),T=R=E=0,W=h;for(var X=0;X<286;++X)S[X]=0;for(var X=0;X<30;++X)I[X]=0}var J=2,ie=0,oe=m,Y=z-Q&32767;if(ee>2&&U==_(h-Y))for(var te=Math.min(p,ee)-1,xe=Math.min(32767,h),be=Math.min(258,ee);Y<=xe&&--oe&&z!=Q;){if(n[h+J]==n[h+J-Y]){for(var Se=0;Se<be&&n[h+Se]==n[h+Se-Y];++Se);if(Se>J){if(J=Se,ie=Y,Se>te)break;for(var Ce=Math.min(Y,Se-2),We=0,X=0;X<Ce;++X){var He=h-Y+X+32768&32767,lt=v[He],Ct=He-lt+32768&32767;Ct>We&&(We=Ct,Q=He)}}}z=Q,Q=v[z],Y+=z-Q+32768&32767}if(ie){x[T++]=268435456|Z1[J]<<18|g2[ie];var tt=Z1[J]&31,H=g2[ie]&31;E+=iw[tt]+nw[H],++S[257+tt],++I[H],k=h+J,++R}else x[T++]=n[h],++S[n[h]]}}c=v2(n,l,r,x,S,I,E,T,W,h-W,c),!r&&c&7&&(c=Sb(l,c+1,_I))}return bI(a,0,i+yI(c)+s)},BK=function(){for(var n=new wp(256),e=0;e<256;++e){for(var t=e,i=9;--i;)t=(t&1&&3988292384)^t>>>1;n[e]=t}return n}(),DK=function(){var n=-1;return{p:function(e){for(var t=n,i=0;i<e.length;++i)t=BK[t&255^e[i]]^t>>>8;n=t},d:function(){return~n}}},kK=function(n,e,t,i,s){return PK(n,e.level==null?6:e.level,e.mem==null?Math.ceil(Math.max(8,Math.min(13,Math.log(n.length)))*1.5):12+e.mem,t,i,!s)},Q3=function(n,e){var t={};for(var i in n)t[i]=n[i];for(var i in e)t[i]=e[i];return t},ss=function(n,e,t){for(;t;++e)n[e]=t,t>>>=8},OK=function(n){if((n[0]&15)!=8||n[0]>>>4>7||(n[0]<<8|n[1])%31)throw"invalid zlib data";if(n[1]&32)throw"invalid zlib data: preset dictionaries not supported"};function LK(n,e){return kK(n,e||{},0,0)}function r0(n,e){return IK((OK(n),n.subarray(2,-4)),e)}var V3=function(n,e,t,i){for(var s in n){var r=n[s],o=e+s;r instanceof yn?t[o]=[r,i]:Array.isArray(r)?t[o]=[r[0],Q3(i,r[1])]:V3(r,o+"/",t,i)}},y2=typeof TextEncoder<"u"&&new TextEncoder,FK=typeof TextDecoder<"u"&&new TextDecoder,UK=0;try{FK.decode(_I,{stream:!0}),UK=1}catch{}function __(n,e){if(e){for(var t=new yn(n.length),i=0;i<n.length;++i)t[i]=n.charCodeAt(i);return t}if(y2)return y2.encode(n);for(var s=n.length,r=new yn(n.length+(n.length>>1)),o=0,a=function(h){r[o++]=h},i=0;i<s;++i){if(o+5>r.length){var l=new yn(o+8+(s-i<<1));l.set(r),r=l}var c=n.charCodeAt(i);c<128||e?a(c):c<2048?(a(192|c>>6),a(128|c&63)):c>55295&&c<57344?(c=65536+(c&1047552)|n.charCodeAt(++i)&1023,a(240|c>>18),a(128|c>>12&63),a(128|c>>6&63),a(128|c&63)):(a(224|c>>12),a(128|c>>6&63),a(128|c&63))}return bI(r,0,o)}var tM=function(n){var e=0;if(n)for(var t in n){var i=n[t].length;if(i>65535)throw"extra field too long";e+=i+4}return e},b2=function(n,e,t,i,s,r,o,a){var l=i.length,c=t.extra,h=a&&a.length,d=tM(c);ss(n,e,o!=null?33639248:67324752),e+=4,o!=null&&(n[e++]=20,n[e++]=t.os),n[e]=20,e+=2,n[e++]=t.flag<<1|(r==null&&8),n[e++]=s&&8,n[e++]=t.compression&255,n[e++]=t.compression>>8;var f=new Date(t.mtime==null?Date.now():t.mtime),p=f.getFullYear()-1980;if(p<0||p>119)throw"date not in range 1980-2099";if(ss(n,e,p<<25|f.getMonth()+1<<21|f.getDate()<<16|f.getHours()<<11|f.getMinutes()<<5|f.getSeconds()>>>1),e+=4,r!=null&&(ss(n,e,t.crc),ss(n,e+4,r),ss(n,e+8,t.size)),ss(n,e+12,l),ss(n,e+14,d),e+=16,o!=null&&(ss(n,e,h),ss(n,e+6,t.attrs),ss(n,e+10,o),e+=14),n.set(i,e),e+=l,d)for(var m in c){var A=c[m],v=A.length;ss(n,e,+m),ss(n,e+2,v),n.set(A,e+4),e+=4+v}return h&&(n.set(a,e),e+=h),e},NK=function(n,e,t,i,s){ss(n,e,101010256),ss(n,e+8,t),ss(n,e+10,t),ss(n,e+12,i),ss(n,e+16,s)};function zK(n,e){e||(e={});var t={},i=[];V3(n,"",t,e);var s=0,r=0;for(var o in t){var a=t[o],l=a[0],c=a[1],h=c.level==0?0:8,d=__(o),f=d.length,p=c.comment,m=p&&__(p),A=m&&m.length,v=tM(c.extra);if(f>65535)throw"filename too long";var g=h?LK(l,c):l,b=g.length,y=DK();y.p(l),i.push(Q3(c,{size:l.length,crc:y.d(),c:g,f:d,m,u:f!=o.length||m&&p.length!=A,o:s,compression:h})),s+=30+f+v+b,r+=76+2*(f+v)+(A||0)+b}for(var _=new yn(r+22),x=s,S=r-s,I=0;I<i.length;++I){var d=i[I];b2(_,d.o,d,d.f,d.u,d.c.length);var R=30+d.f.length+tM(d.extra);_.set(d.c,d.o+R),b2(_,s,d,d.f,d.u,d.c.length,d.o,d.m),s+=16+R+(d.m?d.m.length:0)}return NK(_,s,i.length,S,x),_}class iM extends DT{constructor(e){super(e),this.type=bn}parse(e){const E=Math.pow(2.7182818,2.2);function T(P,C){let B=0;for(let F=0;F<65536;++F)(F==0||P[F>>3]&1<<(F&7))&&(C[B++]=F);const L=B-1;for(;B<65536;)C[B++]=0;return L}function k(P){for(let C=0;C<16384;C++)P[C]={},P[C].len=0,P[C].lit=0,P[C].p=null}const W={l:0,c:0,lc:0};function U(P,C,B,L,F){for(;B<P;)C=C<<8|Be(L,F),B+=8;B-=P,W.l=C>>B&(1<<P)-1,W.c=C,W.lc=B}const z=new Array(59);function Q(P){for(let B=0;B<=58;++B)z[B]=0;for(let B=0;B<65537;++B)z[P[B]]+=1;let C=0;for(let B=58;B>0;--B){const L=C+z[B]>>1;z[B]=C,C=L}for(let B=0;B<65537;++B){const L=P[B];L>0&&(P[B]=L|z[L]++<<6)}}function ee(P,C,B,L,F,G){const ne=C;let pe=0,ge=0;for(;L<=F;L++){if(ne.value-C.value>B)return!1;U(6,pe,ge,P,ne);const le=W.l;if(pe=W.c,ge=W.lc,G[L]=le,le==63){if(ne.value-C.value>B)throw new Error("Something wrong with hufUnpackEncTable");U(8,pe,ge,P,ne);let Ae=W.l+6;if(pe=W.c,ge=W.lc,L+Ae>F+1)throw new Error("Something wrong with hufUnpackEncTable");for(;Ae--;)G[L++]=0;L--}else if(le>=59){let Ae=le-59+2;if(L+Ae>F+1)throw new Error("Something wrong with hufUnpackEncTable");for(;Ae--;)G[L++]=0;L--}}Q(G)}function X(P){return P&63}function J(P){return P>>6}function ie(P,C,B,L){for(;C<=B;C++){const F=J(P[C]),G=X(P[C]);if(F>>G)throw new Error("Invalid table entry");if(G>14){const ne=L[F>>G-14];if(ne.len)throw new Error("Invalid table entry");if(ne.lit++,ne.p){const pe=ne.p;ne.p=new Array(ne.lit);for(let ge=0;ge<ne.lit-1;++ge)ne.p[ge]=pe[ge]}else ne.p=new Array(1);ne.p[ne.lit-1]=C}else if(G){let ne=0;for(let pe=1<<14-G;pe>0;pe--){const ge=L[(F<<14-G)+ne];if(ge.len||ge.p)throw new Error("Invalid table entry");ge.len=G,ge.lit=C,ne++}}}return!0}const oe={c:0,lc:0};function Y(P,C,B,L){P=P<<8|Be(B,L),C+=8,oe.c=P,oe.lc=C}const te={c:0,lc:0};function xe(P,C,B,L,F,G,ne,pe,ge){if(P==C){L<8&&(Y(B,L,F,G),B=oe.c,L=oe.lc),L-=8;let le=B>>L;if(le=new Uint8Array([le])[0],pe.value+le>ge)return!1;const Ae=ne[pe.value-1];for(;le-- >0;)ne[pe.value++]=Ae}else if(pe.value<ge)ne[pe.value++]=P;else return!1;te.c=B,te.lc=L}function be(P){return P&65535}function Se(P){const C=be(P);return C>32767?C-65536:C}const Ce={a:0,b:0};function We(P,C){const B=Se(P),F=Se(C),G=B+(F&1)+(F>>1),ne=G,pe=G-F;Ce.a=ne,Ce.b=pe}function He(P,C){const B=be(P),L=be(C),F=B-(L>>1)&65535,G=L+F-32768&65535;Ce.a=G,Ce.b=F}function lt(P,C,B,L,F,G,ne){const pe=ne<16384,ge=B>F?F:B;let le=1,Ae,Re;for(;le<=ge;)le<<=1;for(le>>=1,Ae=le,le>>=1;le>=1;){Re=0;const Pe=Re+G*(F-Ae),Je=G*le,ct=G*Ae,$e=L*le,ot=L*Ae;let ut,dt,Si,ai;for(;Re<=Pe;Re+=ct){let si=Re;const Yt=Re+L*(B-Ae);for(;si<=Yt;si+=ot){const Ci=si+$e,xs=si+Je,ii=xs+$e;pe?(We(P[si+C],P[xs+C]),ut=Ce.a,Si=Ce.b,We(P[Ci+C],P[ii+C]),dt=Ce.a,ai=Ce.b,We(ut,dt),P[si+C]=Ce.a,P[Ci+C]=Ce.b,We(Si,ai),P[xs+C]=Ce.a,P[ii+C]=Ce.b):(He(P[si+C],P[xs+C]),ut=Ce.a,Si=Ce.b,He(P[Ci+C],P[ii+C]),dt=Ce.a,ai=Ce.b,He(ut,dt),P[si+C]=Ce.a,P[Ci+C]=Ce.b,He(Si,ai),P[xs+C]=Ce.a,P[ii+C]=Ce.b)}if(B&le){const Ci=si+Je;pe?We(P[si+C],P[Ci+C]):He(P[si+C],P[Ci+C]),ut=Ce.a,P[Ci+C]=Ce.b,P[si+C]=ut}}if(F&le){let si=Re;const Yt=Re+L*(B-Ae);for(;si<=Yt;si+=ot){const Ci=si+$e;pe?We(P[si+C],P[Ci+C]):He(P[si+C],P[Ci+C]),ut=Ce.a,P[Ci+C]=Ce.b,P[si+C]=ut}}Ae=le,le>>=1}return Re}function Ct(P,C,B,L,F,G,ne,pe,ge){let le=0,Ae=0;const Re=ne,Pe=Math.trunc(L.value+(F+7)/8);for(;L.value<Pe;)for(Y(le,Ae,B,L),le=oe.c,Ae=oe.lc;Ae>=14;){const ct=le>>Ae-14&16383,$e=C[ct];if($e.len)Ae-=$e.len,xe($e.lit,G,le,Ae,B,L,pe,ge,Re),le=te.c,Ae=te.lc;else{if(!$e.p)throw new Error("hufDecode issues");let ot;for(ot=0;ot<$e.lit;ot++){const ut=X(P[$e.p[ot]]);for(;Ae<ut&&L.value<Pe;)Y(le,Ae,B,L),le=oe.c,Ae=oe.lc;if(Ae>=ut&&J(P[$e.p[ot]])==(le>>Ae-ut&(1<<ut)-1)){Ae-=ut,xe($e.p[ot],G,le,Ae,B,L,pe,ge,Re),le=te.c,Ae=te.lc;break}}if(ot==$e.lit)throw new Error("hufDecode issues")}}const Je=8-F&7;for(le>>=Je,Ae-=Je;Ae>0;){const ct=C[le<<14-Ae&16383];if(ct.len)Ae-=ct.len,xe(ct.lit,G,le,Ae,B,L,pe,ge,Re),le=te.c,Ae=te.lc;else throw new Error("hufDecode issues")}return!0}function tt(P,C,B,L,F,G){const ne={value:0},pe=B.value,ge=Ge(C,B),le=Ge(C,B);B.value+=4;const Ae=Ge(C,B);if(B.value+=4,ge<0||ge>=65537||le<0||le>=65537)throw new Error("Something wrong with HUF_ENCSIZE");const Re=new Array(65537),Pe=new Array(16384);k(Pe);const Je=L-(B.value-pe);if(ee(P,B,Je,ge,le,Re),Ae>8*(L-(B.value-pe)))throw new Error("Something wrong with hufUncompress");ie(Re,ge,le,Pe),Ct(Re,Pe,P,B,Ae,le,G,F,ne)}function H(P,C,B){for(let L=0;L<B;++L)C[L]=P[C[L]]}function Fe(P){for(let C=1;C<P.length;C++){const B=P[C-1]+P[C]-128;P[C]=B}}function me(P,C){let B=0,L=Math.floor((P.length+1)/2),F=0;const G=P.length-1;for(;!(F>G||(C[F++]=P[B++],F>G));)C[F++]=P[L++]}function Oe(P){let C=P.byteLength;const B=new Array;let L=0;const F=new DataView(P);for(;C>0;){const G=F.getInt8(L++);if(G<0){const ne=-G;C-=ne+1;for(let pe=0;pe<ne;pe++)B.push(F.getUint8(L++))}else{const ne=G;C-=2;const pe=F.getUint8(L++);for(let ge=0;ge<ne+1;ge++)B.push(pe)}}return B}function _e(P,C,B,L,F,G){let ne=new DataView(G.buffer);const pe=B[P.idx[0]].width,ge=B[P.idx[0]].height,le=3,Ae=Math.floor(pe/8),Re=Math.ceil(pe/8),Pe=Math.ceil(ge/8),Je=pe-(Re-1)*8,ct=ge-(Pe-1)*8,$e={value:0},ot=new Array(le),ut=new Array(le),dt=new Array(le),Si=new Array(le),ai=new Array(le);for(let Yt=0;Yt<le;++Yt)ai[Yt]=C[P.idx[Yt]],ot[Yt]=Yt<1?0:ot[Yt-1]+Re*Pe,ut[Yt]=new Float32Array(64),dt[Yt]=new Uint16Array(64),Si[Yt]=new Uint16Array(Re*64);for(let Yt=0;Yt<Pe;++Yt){let Ci=8;Yt==Pe-1&&(Ci=ct);let xs=8;for(let jt=0;jt<Re;++jt){jt==Re-1&&(xs=Je);for(let hi=0;hi<le;++hi)dt[hi].fill(0),dt[hi][0]=F[ot[hi]++],Ze($e,L,dt[hi]),Xe(dt[hi],ut[hi]),Ye(ut[hi]);ft(ut);for(let hi=0;hi<le;++hi)Et(ut[hi],Si[hi],jt*64)}let ii=0;for(let jt=0;jt<le;++jt){const hi=B[P.idx[jt]].type;for(let Hi=8*Yt;Hi<8*Yt+Ci;++Hi){ii=ai[jt][Hi];for(let ml=0;ml<Ae;++ml){const oo=ml*64+(Hi&7)*8;ne.setUint16(ii+0*2*hi,Si[jt][oo+0],!0),ne.setUint16(ii+1*2*hi,Si[jt][oo+1],!0),ne.setUint16(ii+2*2*hi,Si[jt][oo+2],!0),ne.setUint16(ii+3*2*hi,Si[jt][oo+3],!0),ne.setUint16(ii+4*2*hi,Si[jt][oo+4],!0),ne.setUint16(ii+5*2*hi,Si[jt][oo+5],!0),ne.setUint16(ii+6*2*hi,Si[jt][oo+6],!0),ne.setUint16(ii+7*2*hi,Si[jt][oo+7],!0),ii+=8*2*hi}}if(Ae!=Re)for(let Hi=8*Yt;Hi<8*Yt+Ci;++Hi){const ml=ai[jt][Hi]+8*Ae*2*hi,oo=Ae*64+(Hi&7)*8;for(let eu=0;eu<xs;++eu)ne.setUint16(ml+eu*2*hi,Si[jt][oo+eu],!0)}}}const si=new Uint16Array(pe);ne=new DataView(G.buffer);for(let Yt=0;Yt<le;++Yt){B[P.idx[Yt]].decoded=!0;const Ci=B[P.idx[Yt]].type;if(B[Yt].type==2)for(let xs=0;xs<ge;++xs){const ii=ai[Yt][xs];for(let jt=0;jt<pe;++jt)si[jt]=ne.getUint16(ii+jt*2*Ci,!0);for(let jt=0;jt<pe;++jt)ne.setFloat32(ii+jt*2*Ci,ue(si[jt]),!0)}}}function Ze(P,C,B){let L,F=1;for(;F<64;)L=C[P.value],L==65280?F=64:L>>8==255?F+=L&255:(B[F]=L,F++),P.value++}function Xe(P,C){C[0]=ue(P[0]),C[1]=ue(P[1]),C[2]=ue(P[5]),C[3]=ue(P[6]),C[4]=ue(P[14]),C[5]=ue(P[15]),C[6]=ue(P[27]),C[7]=ue(P[28]),C[8]=ue(P[2]),C[9]=ue(P[4]),C[10]=ue(P[7]),C[11]=ue(P[13]),C[12]=ue(P[16]),C[13]=ue(P[26]),C[14]=ue(P[29]),C[15]=ue(P[42]),C[16]=ue(P[3]),C[17]=ue(P[8]),C[18]=ue(P[12]),C[19]=ue(P[17]),C[20]=ue(P[25]),C[21]=ue(P[30]),C[22]=ue(P[41]),C[23]=ue(P[43]),C[24]=ue(P[9]),C[25]=ue(P[11]),C[26]=ue(P[18]),C[27]=ue(P[24]),C[28]=ue(P[31]),C[29]=ue(P[40]),C[30]=ue(P[44]),C[31]=ue(P[53]),C[32]=ue(P[10]),C[33]=ue(P[19]),C[34]=ue(P[23]),C[35]=ue(P[32]),C[36]=ue(P[39]),C[37]=ue(P[45]),C[38]=ue(P[52]),C[39]=ue(P[54]),C[40]=ue(P[20]),C[41]=ue(P[22]),C[42]=ue(P[33]),C[43]=ue(P[38]),C[44]=ue(P[46]),C[45]=ue(P[51]),C[46]=ue(P[55]),C[47]=ue(P[60]),C[48]=ue(P[21]),C[49]=ue(P[34]),C[50]=ue(P[37]),C[51]=ue(P[47]),C[52]=ue(P[50]),C[53]=ue(P[56]),C[54]=ue(P[59]),C[55]=ue(P[61]),C[56]=ue(P[35]),C[57]=ue(P[36]),C[58]=ue(P[48]),C[59]=ue(P[49]),C[60]=ue(P[57]),C[61]=ue(P[58]),C[62]=ue(P[62]),C[63]=ue(P[63])}function Ye(P){const C=.5*Math.cos(.7853975),B=.5*Math.cos(3.14159/16),L=.5*Math.cos(3.14159/8),F=.5*Math.cos(3*3.14159/16),G=.5*Math.cos(5*3.14159/16),ne=.5*Math.cos(3*3.14159/8),pe=.5*Math.cos(7*3.14159/16),ge=new Array(4),le=new Array(4),Ae=new Array(4),Re=new Array(4);for(let Pe=0;Pe<8;++Pe){const Je=Pe*8;ge[0]=L*P[Je+2],ge[1]=ne*P[Je+2],ge[2]=L*P[Je+6],ge[3]=ne*P[Je+6],le[0]=B*P[Je+1]+F*P[Je+3]+G*P[Je+5]+pe*P[Je+7],le[1]=F*P[Je+1]-pe*P[Je+3]-B*P[Je+5]-G*P[Je+7],le[2]=G*P[Je+1]-B*P[Je+3]+pe*P[Je+5]+F*P[Je+7],le[3]=pe*P[Je+1]-G*P[Je+3]+F*P[Je+5]-B*P[Je+7],Ae[0]=C*(P[Je+0]+P[Je+4]),Ae[3]=C*(P[Je+0]-P[Je+4]),Ae[1]=ge[0]+ge[3],Ae[2]=ge[1]-ge[2],Re[0]=Ae[0]+Ae[1],Re[1]=Ae[3]+Ae[2],Re[2]=Ae[3]-Ae[2],Re[3]=Ae[0]-Ae[1],P[Je+0]=Re[0]+le[0],P[Je+1]=Re[1]+le[1],P[Je+2]=Re[2]+le[2],P[Je+3]=Re[3]+le[3],P[Je+4]=Re[3]-le[3],P[Je+5]=Re[2]-le[2],P[Je+6]=Re[1]-le[1],P[Je+7]=Re[0]-le[0]}for(let Pe=0;Pe<8;++Pe)ge[0]=L*P[16+Pe],ge[1]=ne*P[16+Pe],ge[2]=L*P[48+Pe],ge[3]=ne*P[48+Pe],le[0]=B*P[8+Pe]+F*P[24+Pe]+G*P[40+Pe]+pe*P[56+Pe],le[1]=F*P[8+Pe]-pe*P[24+Pe]-B*P[40+Pe]-G*P[56+Pe],le[2]=G*P[8+Pe]-B*P[24+Pe]+pe*P[40+Pe]+F*P[56+Pe],le[3]=pe*P[8+Pe]-G*P[24+Pe]+F*P[40+Pe]-B*P[56+Pe],Ae[0]=C*(P[Pe]+P[32+Pe]),Ae[3]=C*(P[Pe]-P[32+Pe]),Ae[1]=ge[0]+ge[3],Ae[2]=ge[1]-ge[2],Re[0]=Ae[0]+Ae[1],Re[1]=Ae[3]+Ae[2],Re[2]=Ae[3]-Ae[2],Re[3]=Ae[0]-Ae[1],P[0+Pe]=Re[0]+le[0],P[8+Pe]=Re[1]+le[1],P[16+Pe]=Re[2]+le[2],P[24+Pe]=Re[3]+le[3],P[32+Pe]=Re[3]-le[3],P[40+Pe]=Re[2]-le[2],P[48+Pe]=Re[1]-le[1],P[56+Pe]=Re[0]-le[0]}function ft(P){for(let C=0;C<64;++C){const B=P[0][C],L=P[1][C],F=P[2][C];P[0][C]=B+1.5747*F,P[1][C]=B-.1873*L-.4682*F,P[2][C]=B+1.8556*L}}function Et(P,C,B){for(let L=0;L<64;++L)C[B+L]=zu.toHalfFloat(qt(P[L]))}function qt(P){return P<=1?Math.sign(P)*Math.pow(Math.abs(P),2.2):Math.sign(P)*Math.pow(E,Math.abs(P)-1)}function N(P){return new DataView(P.array.buffer,P.offset.value,P.size)}function O(P){const C=P.viewer.buffer.slice(P.offset.value,P.offset.value+P.size),B=new Uint8Array(Oe(C)),L=new Uint8Array(B.length);return Fe(B),me(B,L),new DataView(L.buffer)}function he(P){const C=P.array.slice(P.offset.value,P.offset.value+P.size),B=r0(C),L=new Uint8Array(B.length);return Fe(B),me(B,L),new DataView(L.buffer)}function Te(P){const C=P.viewer,B={value:P.offset.value},L=new Uint16Array(P.width*P.scanlineBlockSize*(P.channels*P.type)),F=new Uint8Array(8192);let G=0;const ne=new Array(P.channels);for(let ct=0;ct<P.channels;ct++)ne[ct]={},ne[ct].start=G,ne[ct].end=ne[ct].start,ne[ct].nx=P.width,ne[ct].ny=P.lines,ne[ct].size=P.type,G+=ne[ct].nx*ne[ct].ny*ne[ct].size;const pe=fe(C,B),ge=fe(C,B);if(ge>=8192)throw new Error("Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(pe<=ge)for(let ct=0;ct<ge-pe+1;ct++)F[ct+pe]=it(C,B);const le=new Uint16Array(65536),Ae=T(F,le),Re=Ge(C,B);tt(P.array,C,B,Re,L,G);for(let ct=0;ct<P.channels;++ct){const $e=ne[ct];for(let ot=0;ot<ne[ct].size;++ot)lt(L,$e.start+ot,$e.nx,$e.size,$e.ny,$e.nx*$e.size,Ae)}H(le,L,G);let Pe=0;const Je=new Uint8Array(L.buffer.byteLength);for(let ct=0;ct<P.lines;ct++)for(let $e=0;$e<P.channels;$e++){const ot=ne[$e],ut=ot.nx*ot.size,dt=new Uint8Array(L.buffer,ot.end*2,ut*2);Je.set(dt,Pe),Pe+=ut*2,ot.end+=ut}return new DataView(Je.buffer)}function Ie(P){const C=P.array.slice(P.offset.value,P.offset.value+P.size),B=r0(C),L=P.lines*P.channels*P.width,F=P.type==1?new Uint16Array(L):new Uint32Array(L);let G=0,ne=0;const pe=new Array(4);for(let ge=0;ge<P.lines;ge++)for(let le=0;le<P.channels;le++){let Ae=0;switch(P.type){case 1:pe[0]=G,pe[1]=pe[0]+P.width,G=pe[1]+P.width;for(let Re=0;Re<P.width;++Re){const Pe=B[pe[0]++]<<8|B[pe[1]++];Ae+=Pe,F[ne]=Ae,ne++}break;case 2:pe[0]=G,pe[1]=pe[0]+P.width,pe[2]=pe[1]+P.width,G=pe[2]+P.width;for(let Re=0;Re<P.width;++Re){const Pe=B[pe[0]++]<<24|B[pe[1]++]<<16|B[pe[2]++]<<8;Ae+=Pe,F[ne]=Ae,ne++}break}}return new DataView(F.buffer)}function Ue(P){const C=P.viewer,B={value:P.offset.value},L=new Uint8Array(P.width*P.lines*(P.channels*P.type*2)),F={version:gt(C,B),unknownUncompressedSize:gt(C,B),unknownCompressedSize:gt(C,B),acCompressedSize:gt(C,B),dcCompressedSize:gt(C,B),rleCompressedSize:gt(C,B),rleUncompressedSize:gt(C,B),rleRawSize:gt(C,B),totalAcUncompressedCount:gt(C,B),totalDcUncompressedCount:gt(C,B),acCompression:gt(C,B)};if(F.version<2)throw new Error("EXRLoader.parse: "+Sa.compression+" version "+F.version+" is unsupported");const G=new Array;let ne=fe(C,B)-2;for(;ne>0;){const $e=V(C.buffer,B),ot=it(C,B),ut=ot>>2&3,dt=(ot>>4)-1,Si=new Int8Array([dt])[0],ai=it(C,B);G.push({name:$e,index:Si,type:ai,compression:ut}),ne-=$e.length+3}const pe=Sa.channels,ge=new Array(P.channels);for(let $e=0;$e<P.channels;++$e){const ot=ge[$e]={},ut=pe[$e];ot.name=ut.name,ot.compression=0,ot.decoded=!1,ot.type=ut.pixelType,ot.pLinear=ut.pLinear,ot.width=P.width,ot.height=P.lines}const le={idx:new Array(3)};for(let $e=0;$e<P.channels;++$e){const ot=ge[$e];for(let ut=0;ut<G.length;++ut){const dt=G[ut];ot.name==dt.name&&(ot.compression=dt.compression,dt.index>=0&&(le.idx[dt.index]=$e),ot.offset=$e)}}let Ae,Re,Pe;if(F.acCompressedSize>0)switch(F.acCompression){case 0:Ae=new Uint16Array(F.totalAcUncompressedCount),tt(P.array,C,B,F.acCompressedSize,Ae,F.totalAcUncompressedCount);break;case 1:const $e=P.array.slice(B.value,B.value+F.totalAcUncompressedCount),ot=r0($e);Ae=new Uint16Array(ot.buffer),B.value+=F.totalAcUncompressedCount;break}if(F.dcCompressedSize>0){const $e={array:P.array,offset:B,size:F.dcCompressedSize};Re=new Uint16Array(he($e).buffer),B.value+=F.dcCompressedSize}if(F.rleRawSize>0){const $e=P.array.slice(B.value,B.value+F.rleCompressedSize),ot=r0($e);Pe=Oe(ot.buffer),B.value+=F.rleCompressedSize}let Je=0;const ct=new Array(ge.length);for(let $e=0;$e<ct.length;++$e)ct[$e]=new Array;for(let $e=0;$e<P.lines;++$e)for(let ot=0;ot<ge.length;++ot)ct[ot].push(Je),Je+=ge[ot].width*P.type*2;_e(le,ct,ge,Ae,Re,L);for(let $e=0;$e<ge.length;++$e){const ot=ge[$e];if(!ot.decoded)switch(ot.compression){case 2:let ut=0,dt=0;for(let Si=0;Si<P.lines;++Si){let ai=ct[$e][ut];for(let si=0;si<ot.width;++si){for(let Yt=0;Yt<2*ot.type;++Yt)L[ai++]=Pe[dt+Yt*ot.width*ot.height];dt++}ut++}break;case 1:default:throw new Error("EXRLoader.parse: unsupported channel compression")}}return new DataView(L.buffer)}function V(P,C){const B=new Uint8Array(P);let L=0;for(;B[C.value+L]!=0;)L+=1;const F=new TextDecoder().decode(B.slice(C.value,C.value+L));return C.value=C.value+L+1,F}function de(P,C,B){const L=new TextDecoder().decode(new Uint8Array(P).slice(C.value,C.value+B));return C.value=C.value+B,L}function ae(P,C){const B=qe(P,C),L=Ge(P,C);return[B,L]}function Ve(P,C){const B=Ge(P,C),L=Ge(P,C);return[B,L]}function qe(P,C){const B=P.getInt32(C.value,!0);return C.value=C.value+4,B}function Ge(P,C){const B=P.getUint32(C.value,!0);return C.value=C.value+4,B}function Be(P,C){const B=P[C.value];return C.value=C.value+1,B}function it(P,C){const B=P.getUint8(C.value);return C.value=C.value+1,B}const gt=function(P,C){let B;return"getBigInt64"in DataView.prototype?B=Number(P.getBigInt64(C.value,!0)):B=P.getUint32(C.value+4,!0)+Number(P.getUint32(C.value,!0)<<32),C.value+=8,B};function yt(P,C){const B=P.getFloat32(C.value,!0);return C.value+=4,B}function q(P,C){return zu.toHalfFloat(yt(P,C))}function ue(P){const C=(P&31744)>>10,B=P&1023;return(P>>15?-1:1)*(C?C===31?B?NaN:1/0:Math.pow(2,C-15)*(1+B/1024):6103515625e-14*(B/1024))}function fe(P,C){const B=P.getUint16(C.value,!0);return C.value+=2,B}function Qe(P,C){return ue(fe(P,C))}function Ke(P,C,B,L){const F=B.value,G=[];for(;B.value<F+L-1;){const ne=V(C,B),pe=qe(P,B),ge=it(P,B);B.value+=3;const le=qe(P,B),Ae=qe(P,B);G.push({name:ne,pixelType:pe,pLinear:ge,xSampling:le,ySampling:Ae})}return B.value+=1,G}function ti(P,C){const B=yt(P,C),L=yt(P,C),F=yt(P,C),G=yt(P,C),ne=yt(P,C),pe=yt(P,C),ge=yt(P,C),le=yt(P,C);return{redX:B,redY:L,greenX:F,greenY:G,blueX:ne,blueY:pe,whiteX:ge,whiteY:le}}function wi(P,C){const B=["NO_COMPRESSION","RLE_COMPRESSION","ZIPS_COMPRESSION","ZIP_COMPRESSION","PIZ_COMPRESSION","PXR24_COMPRESSION","B44_COMPRESSION","B44A_COMPRESSION","DWAA_COMPRESSION","DWAB_COMPRESSION"],L=it(P,C);return B[L]}function dn(P,C){const B=Ge(P,C),L=Ge(P,C),F=Ge(P,C),G=Ge(P,C);return{xMin:B,yMin:L,xMax:F,yMax:G}}function so(P,C){const B=["INCREASING_Y"],L=it(P,C);return B[L]}function Pi(P,C){const B=yt(P,C),L=yt(P,C);return[B,L]}function ro(P,C){const B=yt(P,C),L=yt(P,C),F=yt(P,C);return[B,L,F]}function $n(P,C,B,L,F){if(L==="string"||L==="stringvector"||L==="iccProfile")return de(C,B,F);if(L==="chlist")return Ke(P,C,B,F);if(L==="chromaticities")return ti(P,B);if(L==="compression")return wi(P,B);if(L==="box2i")return dn(P,B);if(L==="lineOrder")return so(P,B);if(L==="float")return yt(P,B);if(L==="v2f")return Pi(P,B);if(L==="v3f")return ro(P,B);if(L==="int")return qe(P,B);if(L==="rational")return ae(P,B);if(L==="timecode")return Ve(P,B);if(L==="preview")return B.value+=F,"skipped";B.value+=F}function oy(P,C,B){const L={};if(P.getUint32(0,!0)!=20000630)throw new Error("THREE.EXRLoader: provided file doesn't appear to be in OpenEXR format.");L.version=P.getUint8(4);const F=P.getUint8(5);L.spec={singleTile:!!(F&2),longName:!!(F&4),deepFormat:!!(F&8),multiPart:!!(F&16)},B.value=8;let G=!0;for(;G;){const ne=V(C,B);if(ne==0)G=!1;else{const pe=V(C,B),ge=Ge(P,B),le=$n(P,C,B,pe,ge);le===void 0?console.warn(`EXRLoader.parse: skipped unknown header attribute type '${pe}'.`):L[ne]=le}}if(F&-5)throw console.error("EXRHeader:",L),new Error("THREE.EXRLoader: provided file is currently unsupported.");return L}function ay(P,C,B,L,F){const G={size:0,viewer:C,array:B,offset:L,width:P.dataWindow.xMax-P.dataWindow.xMin+1,height:P.dataWindow.yMax-P.dataWindow.yMin+1,channels:P.channels.length,bytesPerLine:null,lines:null,inputSize:null,type:P.channels[0].pixelType,uncompress:null,getter:null,format:null,colorSpace:Jn};switch(P.compression){case"NO_COMPRESSION":G.lines=1,G.uncompress=N;break;case"RLE_COMPRESSION":G.lines=1,G.uncompress=O;break;case"ZIPS_COMPRESSION":G.lines=1,G.uncompress=he;break;case"ZIP_COMPRESSION":G.lines=16,G.uncompress=he;break;case"PIZ_COMPRESSION":G.lines=32,G.uncompress=Te;break;case"PXR24_COMPRESSION":G.lines=16,G.uncompress=Ie;break;case"DWAA_COMPRESSION":G.lines=32,G.uncompress=Ue;break;case"DWAB_COMPRESSION":G.lines=256,G.uncompress=Ue;break;default:throw new Error("EXRLoader.parse: "+P.compression+" is unsupported")}if(G.scanlineBlockSize=G.lines,G.type==1)switch(F){case en:G.getter=Qe,G.inputSize=2;break;case bn:G.getter=fe,G.inputSize=2;break}else if(G.type==2)switch(F){case en:G.getter=yt,G.inputSize=4;break;case bn:G.getter=q,G.inputSize=4}else throw new Error("EXRLoader.parse: unsupported pixelType "+G.type+" for "+P.compression+".");G.blockCount=(P.dataWindow.yMax+1)/G.scanlineBlockSize;for(let pe=0;pe<G.blockCount;pe++)gt(C,L);G.outputChannels=G.channels==3?4:G.channels;const ne=G.width*G.height*G.outputChannels;switch(F){case en:G.byteArray=new Float32Array(ne),G.channels<G.outputChannels&&G.byteArray.fill(1,0,ne);break;case bn:G.byteArray=new Uint16Array(ne),G.channels<G.outputChannels&&G.byteArray.fill(15360,0,ne);break;default:console.error("THREE.EXRLoader: unsupported type: ",F);break}return G.bytesPerLine=G.width*G.inputSize*G.channels,G.outputChannels==4?(G.format=Ti,G.colorSpace=Jn):(G.format=Jl,G.colorSpace=gr),G}const Od=new DataView(e),Ld=new Uint8Array(e),Pc={value:0},Sa=oy(Od,e,Pc),Ht=ay(Sa,Od,Ld,Pc,this.type),ly={value:0},oS={R:0,G:1,B:2,A:3,Y:0};for(let P=0;P<Ht.height/Ht.scanlineBlockSize;P++){const C=Ge(Od,Pc);Ht.size=Ge(Od,Pc),Ht.lines=C+Ht.scanlineBlockSize>Ht.height?Ht.height-C:Ht.scanlineBlockSize;const L=Ht.size<Ht.lines*Ht.bytesPerLine?Ht.uncompress(Ht):N(Ht);Pc.value+=Ht.size;for(let F=0;F<Ht.scanlineBlockSize;F++){const G=F+P*Ht.scanlineBlockSize;if(G>=Ht.height)break;for(let ne=0;ne<Ht.channels;ne++){const pe=oS[Sa.channels[ne].name];for(let ge=0;ge<Ht.width;ge++){ly.value=(F*(Ht.channels*Ht.width)+ne*Ht.width+ge)*Ht.inputSize;const le=(Ht.height-1-G)*(Ht.width*Ht.outputChannels)+ge*Ht.outputChannels+pe;Ht.byteArray[le]=Ht.getter(L,ly)}}}}return{header:Sa,width:Ht.width,height:Ht.height,data:Ht.byteArray,format:Ht.format,colorSpace:Ht.colorSpace,type:this.type}}setDataType(e){return this.type=e,this}load(e,t,i,s){function r(o,a){o.colorSpace=a.colorSpace,o.minFilter=Pt,o.magFilter=Pt,o.generateMipmaps=!1,o.flipY=!1,t&&t(o,a)}return super.load(e,r,i,s)}}const AC=se("debugexr");class GK{constructor(e){u(this,"parser");u(this,"name");this.parser=e,this.name="EXT_texture_exr",AC&&console.log(e)}loadTexture(e){const t=this.name,i=this.parser,r=i.json.textures[e];if(AC&&console.log("EXT_texture_exr.loadTexture",e,r),!r.extensions||!r.extensions[t])return null;const o=r.extensions[t],a=new iM(i.options.manager);return AC&&console.log("EXT_texture_exr.loadTexture",o,a),i.loadTextureImage(e,o.source,a)}}window.addEventListener("unhandledrejection",n=>{});const _2="NEEDLE_gameobject_data";class HK{constructor(e){u(this,"parser");this.parser=e}get name(){return _2}afterRoot(e){const t=[];for(let i=0;i<this.parser.json.nodes.length;i++){const s=this.parser.json.nodes[i];if(s&&s.extensions){const r=s.extensions[_2];if(r){const o=this.findAndApplyExtensionData(i,r);t.push(o)}}}return Promise.all(t).then(()=>{})}async findAndApplyExtensionData(e,t){const i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){t.layers===void 0&&(t.layers=0),e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(t.layers),e.userData.tag=t.tag??"none",e.userData.hideFlags=t.hideFlags??0,e.userData.static=t.static??!1,e.visible=t.activeSelf??!0,e.guid=t.guid}}const x2="NEEDLE_lighting_settings",Eu=se("debugenvlight");class QK{constructor(e,t,i){u(this,"parser");u(this,"sourceId");u(this,"context");this.parser=e,this.sourceId=t,this.context=i}get name(){return x2}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[x2];if(i){Eu&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',i);let s;if(e.scene.children.length===1){const r=e.scene.children[0];s=$.addNewComponent(r,x_,!1)}else{const r=new ke;r.name="LightSettings "+this.sourceId,e.scene.add(r),s=$.addNewComponent(r,x_,!1)}s.sourceId=this.sourceId,s.ambientIntensity=i.ambientIntensity,s.ambientLight=new ve().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(s.ambientTrilight=i.ambientTrilight.map(r=>new ve().fromArray(r))),s.ambientMode=i.ambientMode,s.environmentReflectionSource=i.environmentReflectionSource}}return null}}Li.registerCallback(Ws.ContextCreated,n=>{const e=n.context,t=$.findObjectOfType(x_,e);t!=null&&t.sourceId&&(t.enabled=!0)});class x_ extends we{constructor(){super(...arguments);u(this,"ambientMode",tp.Skybox);u(this,"ambientLight");u(this,"ambientTrilight");u(this,"ambientIntensity",1);u(this,"environmentReflectionSource",y_.Skybox);u(this,"_hasReflection",!1);u(this,"_ambientLightObj");u(this,"_hemisphereLightObj");u(this,"_lightProbeObj")}awake(){var i;if(this.sourceId){const s=this.environmentReflectionSource===y_.Skybox?hh.Skybox:hh.Reflection,r=this.context.lightmaps.tryGet(this.sourceId,s,0);this._hasReflection=r!=null,r&&this.context.sceneLighting.internalRegisterReflection(this.sourceId,r)}this.enabled=!1,this.context.sceneLighting.internalRegisterSceneLightSettings(this),Eu&&window.addEventListener("keydown",s=>{if(!this.destroyed)switch(s.key){case"l":this.enabled=!this.enabled;break}});const t=(i=this.gameObject.userData)==null?void 0:i.components;if(t){const s=t.indexOf(this);t.splice(s,1),t.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(t){const i=Math.max(t.r,t.g,t.b);return 2.2*et.lerp(0,1.33,i)}onEnable(){if(Eu&&console.warn("💡🟡 >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==tp.Flat){if(this.ambientLight&&!this._ambientLightObj){const t=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new LT(this.ambientLight,this.ambientIntensity*t),Eu&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,t)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj),this._lightProbeObj&&this._lightProbeObj.removeFromParent()}else if(this.ambientMode===tp.Trilight){if(this.ambientTrilight){const t=this.ambientTrilight[0],i=this.ambientTrilight[this.ambientTrilight.length-1],s=this.calculateIntensityFactor(i);this._hemisphereLightObj=new kT(i,t,this.ambientIntensity*s),this.gameObject.add(this._hemisphereLightObj),Eu&&console.log("Created hemisphere ambient light",this.sourceId,this._hemisphereLightObj,this.ambientIntensity,s)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this._lightProbeObj?this.enabled&&this.destroyed&&this._lightProbeObj&&this.gameObject.add(this._lightProbeObj):this.sourceId&&this.context.sceneLighting.internalGetSceneLightingData(this.sourceId).then(t=>{t&&(this._lightProbeObj=t.lightProbe,this.enabled&&!this.destroyed&&this._lightProbeObj&&(Eu&&console.log("Add",this.sourceId,t),this.gameObject.add(this._lightProbeObj)))});this.sourceId&&this.context.sceneLighting.internalEnableReflection(this.sourceId)}onDisable(){Eu&&console.warn("💡⚫ <<< Disable lighting:",this.sourceId,this),this._lightProbeObj&&this._lightProbeObj.removeFromParent(),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this.sourceId&&this.context.sceneLighting.internalDisableReflection(this.sourceId)}}const vC=se("debugstencil");function VK(n,e){return(n&1<<e.layer)!=0}const WK=Symbol("stencils"),ku=class{constructor(e,t){u(this,"parser");u(this,"source");this.parser=e,this.source=t}static applyStencil(e){if(!e)return;const t=e.sourceId;if(vC&&console.log(t,ku.stencils),!t)return;const i=ku.stencils[t];if(i)for(let s=i.length-1;s>=0;s--){const r=i[s];if(VK(r.layer,e)){vC&&console.log(r),setTimeout(()=>{Zs()&&Jx(e.gameObject)&&(Fo("Stencil not supported on instanced objects"),console.warn("Stencil not supported on instanced objects",e))},500);for(let o=0;o<e.sharedMaterials.length;o++){let a=e.sharedMaterials[o];a&&(a=a.clone(),a[WK]=!0,a.stencilWrite=!0,a.stencilWriteMask=255,a.stencilFuncMask=255,a.stencilRef=r.value,a.stencilFunc=r.compareFunc,a.stencilZPass=r.passOp,a.stencilFail=r.failOp,a.stencilZFail=r.zFailOp,e.sharedMaterials[o]=a)}e.gameObject.renderOrder=r.event*1e3+r.index*50;break}}}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[XK];if(i){vC&&console.log(i);const s=i.stencil;if(s&&Array.isArray(s))for(const r of s){const o={...r};o.compareFunc=jK(o.compareFunc),o.passOp=yC(o.passOp),o.failOp=yC(o.failOp),o.zFailOp=yC(o.zFailOp),ku.stencils[this.source]||(ku.stencils[this.source]=[]),ku.stencils[this.source].push(o)}}}return null}};let Wg=ku;u(Wg,"stencils",{});function yC(n){switch(n){case 0:return Pg;case 1:return SL;case 2:return CL;case 3:return EL;case 4:return ML;case 6:return TL;case 7:return IL;case 5:return RL}return 0}function jK(n){switch(n){case 1:return f1;case 2:return PL;case 3:return BL;case 4:return DL;case 5:return kL;case 6:return OL;case 7:return LL;case 8:return aT}return f1}const XK="NEEDLE_render_objects",Cb="NEEDLE_progressive",Rn=se("debugprogressive"),bC=Symbol("needle-progressive-texture"),nM=new Map;let _C=!1;Rn&&window.addEventListener("keyup",n=>{n.key==="p"&&(nM.forEach((e,t)=>{Object.entries(e).forEach(([i,s])=>{_C?t[i]=s.lod0:t[i]=s.original,t.needsUpdate=!0})}),_C=!_C)});const sA=class{constructor(e,t,i){u(this,"parser");u(this,"sourceId");u(this,"context");this.parser=e,this.sourceId=t,this.context=i}static assignTextureLOD(e,t,i,s=0){if(!i)return Promise.resolve(null);const r=[];for(let o of Object.keys(i)){const a=i[o];if(a!=null&&a.isTexture){const l=this.assignTextureLODForSlot(e,t,i,s,o,a);r.push(l)}}if(i instanceof xx)for(let o of Object.keys(i.uniforms)){const a=i.uniforms[o].value;if(a!=null&&a.isTexture){const l=this.assignTextureLODForSlot(e,t,i,s,o,a);r.push(l)}}return r}static assignTextureLODForSlot(e,t,i,s,r,o){return(o==null?void 0:o.isTexture)!==!0?Promise.resolve(null):(Rn&&console.log(`-----------
4410
4410
  `,"FIND",i.name,r,o==null?void 0:o.name,o==null?void 0:o.userData,o,i),sA.getOrLoadTexture(e,t,i,r,o,s).then(a=>{if((a==null?void 0:a.isTexture)===!0){if(Rn&&console.log("Assign LOD",i.name,r,a.name,a.guid,i,"Prev:",o,"Now:",a,`
4411
- --------------`),i[r]=a,a.needsUpdate=!0,i.needsUpdate=!0,Rn){let l=nM.get(i);l||(l={},nM.set(i,l));let c=l[r];c||(c=l[r]={original:o,lod0:a}),c.lod0=a}return a}return null}))}get name(){return Cb}afterRoot(e){var t;return Rn&&console.log("AFTER",this.sourceId,e),(t=this.parser.json.textures)==null||t.forEach((i,s)=>{if(i!=null&&i.extensions){const r=i==null?void 0:i.extensions[Cb];r&&this.parser.getDependency("texture",s).then(a=>{Rn&&console.log("> Progressive: register",a.name,a.uuid,r),a.source&&(a.source[bC]=r),sA.cache.set(a.uuid,r)})}}),null}static async getOrLoadTexture(e,t,i,s,r,o){const a=r.uuid;let l;if(r.source&&r.source[bC]&&(l=r.source[bC]),l||(l=sA.cache.get(a)),l){Rn&&console.log(a,l.uri,l.guid);const c=Bh(t,l.uri);if(c.endsWith(".glb")||c.endsWith(".gltf")){if(!l.guid)return console.warn("missing pointer for glb/gltf texture",l),null;const h=c+"_"+l.guid;if(this.resolved[h]){let f=this.resolved[h];if(f.image&&f.image.data)return Rn&&console.log("Texture has already been loaded: "+h,i.name,s,r.name,f),f=this.copySettings(r,f),f;f&&Rn&&console.log("Texture has been disposed, will load again: "+h,i.name,s,r.name,f)}const d=this.onProgressiveLoadStart(e,t,c,i,s);try{if(this.currentlyLoading[h]!==void 0){Rn&&console.log("Already loading:",i.name+"."+s,h);let A=await this.currentlyLoading[h];return A&&(A=this.copySettings(r,A)),A}const f=l,p=new Promise(async(A,v)=>{var I;const g=new Wp;vv(g,e),Rn&&console.log("Load "+c,i.name,s,f.guid),Rn&&await ZA(Math.random()*1e3);const b=await g.loadAsync(c),y=b.parser;Rn&&console.log("Loading finished "+c,i.name,s,f.guid);let _=-1,x=!1;if(!((I=b.parser.json)!=null&&I.textures))return Rn&&console.warn("No textures in glTF "+c+" - may be a bug",i.name,s,f.guid),A(null);for(const R of b.parser.json.textures)if(_++,R!=null&&R.extensions){const E=R==null?void 0:R.extensions[Cb];if(E!=null&&E.guid&&E.guid===f.guid){x=!0;break}}if(!x)return A(null);let S=await y.getDependency("texture",_);S=this.copySettings(r,S),S&&(S.guid=f.guid),this.resolved[h]=S,Rn&&console.log(i.name,s,'change "'+r.name+'" → "'+S.name+'"',c,_,S,i,h),A(S)});return this.currentlyLoading[h]=p,await p}finally{delete this.currentlyLoading[h],this.onProgressiveLoadEnd(d)}}else{const h=this.onProgressiveLoadStart(e,t,c,i,s);try{Rn&&console.log("Load texture from uri: "+c);const f=await new vh().loadAsync(c);return f?(f.guid=l.guid,f.flipY=!1,f.needsUpdate=!0,f.encoding=r.encoding,Rn&&console.log(l,f)):Rn&&console.warn("failed loading",c),f}finally{this.onProgressiveLoadEnd(h)}}}else Rn&&console.warn("unknown texture",r.name,r.uuid,r);return null}static copySettings(e,t){const i=e.clone(),s=t.source,r=t.mipmaps;return i.copy(e),i.source=s,i.mipmaps=r,i}static beginListenStart(e,t){this._progressiveEventListeners.has(e)||this._progressiveEventListeners.set(e,new w2),this._progressiveEventListeners.get(e).start.push(t)}static stopListenStart(e,t){if(!this._progressiveEventListeners.has(e))return;const i=this._progressiveEventListeners.get(e).start,s=i.indexOf(t);s>=0&&i.splice(s,1)}static beginListenEnd(e,t){this._progressiveEventListeners.has(e)||this._progressiveEventListeners.set(e,new w2),this._progressiveEventListeners.get(e).end.push(t)}static stopListenEnd(e,t){if(!this._progressiveEventListeners.has(e))return;const i=this._progressiveEventListeners.get(e).end,s=i.indexOf(t);s>=0&&i.splice(s,1)}static onProgressiveLoadStart(e,t,i,s,r){this._currentProgressiveLoadingInfo.has(e)||this._currentProgressiveLoadingInfo.set(e,[]);const o=new W3(e,t,i,s,r),a=this._currentProgressiveLoadingInfo.get(e),l=this._progressiveEventListeners.get(e);return l&&l.onStart(o),a.push(o),o}static onProgressiveLoadEnd(e){if(!e)return;const t=e.context;if(!this._currentProgressiveLoadingInfo.has(t))return;const i=this._currentProgressiveLoadingInfo.get(t),s=i.indexOf(e);if(s<0)return;i.splice(s,1);const r=this._progressiveEventListeners.get(t);r&&r.onEnd(e)}};let Fr=sA;u(Fr,"cache",new Map),u(Fr,"resolved",{}),u(Fr,"currentlyLoading",{}),u(Fr,"_progressiveEventListeners",new Map),u(Fr,"_currentProgressiveLoadingInfo",new Map);class W3{constructor(e,t,i,s,r){u(this,"context");u(this,"source");u(this,"uri");u(this,"material");u(this,"slot");this.context=e,this.source=t,this.uri=i,this.material=s,this.slot=r}}class w2{constructor(){u(this,"start",[]);u(this,"end",[])}onStart(e){for(const t of this.start)t(e)}onEnd(e){for(const t of this.end)t(e)}}let w_;Promise.resolve().then(()=>She).then(n=>(w_=n.GLTFAnimationPointerExtension,w_)).catch(n=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three for full KHR_animation support",n)});const IA=new Array;function qK(n){IA.includes(n)||IA.push(n)}function YK(n){const e=IA.indexOf(n);e>=0&&IA.splice(e,1)}function xI(n){const e=new U3;return n.register(t=>(e.parser=t,e)),e}class KK{resolvePath(e){return e.includes("/extensions/builtin_components/")?e.replace("/extensions/builtin_components/","/userData/components/"):e.includes("extensions/builtin_components/")?e.replace("extensions/builtin_components/","/userData/components/"):e}}function j3(n,e,t){const i=t.lastIndexOf("?");i>=0&&(t=t.substring(0,i)),n.register(s=>new HK(s)),n.register(s=>new j9(s)),n.register(s=>new rY(s,e.lightmaps,t)),n.register(s=>new QK(s,t,e)),n.register(s=>new bK(s,t)),n.register(s=>new Wg(s,t)),n.register(s=>new Fr(s,t,e)),n.register(s=>new GK(s)),MN()&&n.register(s=>new Ab(s));for(const s of IA)n.register(r=>new s(r));n.register(s=>{if(w_){const r=new w_(s);return r.setAnimationPointerResolver.bind(r)(new KK),r}})}const xC=se("debuglightmaps");class RA{constructor(e,t){u(this,"lightmapIndex",-1);u(this,"lightmapScaleOffset",new At(1,1,0,0));u(this,"context");u(this,"gameObject");u(this,"lightmapTexture",null);u(this,"lightmapScaleOffsetUniform",{value:new At(1,1,0,0)});u(this,"lightmapUniform",{value:null});u(this,"onBeforeCompile",(e,t)=>{xC&&console.log("Lightmaps, before compile"),e.lightMapUv="uv1",this.lightmapScaleOffsetUniform.value=this.lightmapScaleOffset,this.lightmapUniform.value=this.lightmapTexture,e.uniforms.lightmap=this.lightmapUniform,e.uniforms.lightmapScaleOffset=this.lightmapScaleOffsetUniform});this.gameObject=e,this.context=t}get lightmap(){return this.lightmapTexture}set lightmap(e){e!==this.lightmapTexture&&(this.lightmapTexture=e,this.applyLightmap())}init(e,t,i){console.assert(this.gameObject!==void 0&&this.gameObject!==null,"Missing gameobject",this),this.lightmapIndex=e,!(this.lightmapIndex<0)&&(this.lightmapScaleOffset=t,this.lightmapTexture=i,xC&&this.setLightmapDebugMaterial(),this.applyLightmap())}updateLightmapUniforms(e){const t=e.uniforms;t&&t.lightmap&&(this.lightmapScaleOffsetUniform.value=this.lightmapScaleOffset,this.lightmapUniform.value=this.lightmapTexture,t.lightmap=this.lightmapUniform,t.lightmapScaleOffset=this.lightmapScaleOffsetUniform)}applyLightmap(){if(this.gameObject.type==="Object3D"){xC&&console.warn("Can not add lightmap. Is this object missing a renderer?",this.gameObject.name);return}if(this.gameObject.type==="Group"){console.warn("Lightmap on multimaterial object is not supported yet... please open a feature request on https://github.com/needle-tools/needle-engine-support if your project requires it");return}console.assert(this.gameObject.type==="Mesh","Lightmap only works on meshes",this);const e=this.gameObject;if(e.geometry.getAttribute("uv1")||e.geometry.setAttribute("uv1",e.geometry.getAttribute("uv")),Array.isArray(this.gameObject.material)){const t=this.gameObject.material;for(let i=0;i<t.length;i++){const r=t[i].clone();t[i]=r,r.onBeforeCompile=this.onBeforeCompile}}else{const t=this.gameObject.material.clone();this.gameObject.material=t,this.gameObject.material.onBeforeCompile=this.onBeforeCompile}if(this.lightmapIndex>=0){const t=this.lightmapTexture,i=this.gameObject.material;i&&t&&(i.uniforms||(i.uniforms={}),i.lightMap=t,i.uniforms.lightmap={value:t})}}setLightmapDebugMaterial(){this.gameObject.material=new Ot({vertexShader:`
4411
+ --------------`),i[r]=a,a.needsUpdate=!0,i.needsUpdate=!0,Rn){let l=nM.get(i);l||(l={},nM.set(i,l));let c=l[r];c||(c=l[r]={original:o,lod0:a}),c.lod0=a}return a}return null}))}get name(){return Cb}afterRoot(e){var t;return Rn&&console.log("AFTER",this.sourceId,e),(t=this.parser.json.textures)==null||t.forEach((i,s)=>{if(i!=null&&i.extensions){const r=i==null?void 0:i.extensions[Cb];r&&this.parser.getDependency("texture",s).then(a=>{Rn&&console.log("> Progressive: register",a.name,a.uuid,r),a.source&&(a.source[bC]=r),sA.cache.set(a.uuid,r)})}}),null}static async getOrLoadTexture(e,t,i,s,r,o){const a=r.uuid;let l;if(r.source&&r.source[bC]&&(l=r.source[bC]),l||(l=sA.cache.get(a)),l){Rn&&console.log(a,l.uri,l.guid);const c=Bh(t,l.uri);if(c.endsWith(".glb")||c.endsWith(".gltf")){if(!l.guid)return console.warn("missing pointer for glb/gltf texture",l),null;const h=c+"_"+l.guid;if(this.resolved[h]){let f=this.resolved[h];if(f.image&&f.image.data)return Rn&&console.log("Texture has already been loaded: "+h,i.name,s,r.name,f),f=this.copySettings(r,f),f;f&&Rn&&console.log("Texture has been disposed, will load again: "+h,i.name,s,r.name,f)}const d=this.onProgressiveLoadStart(e,t,c,i,s);try{if(this.currentlyLoading[h]!==void 0){Rn&&console.log("Already loading:",i.name+"."+s,h);let A=await this.currentlyLoading[h];return A&&(A=this.copySettings(r,A)),A}const f=l,p=new Promise(async(A,v)=>{var I;const g=new Wp;vv(g,e),Rn&&console.log("Load "+c,i.name,s,f.guid),Rn&&await ZA(Math.random()*1e3);const b=await g.loadAsync(c),y=b.parser;Rn&&console.log("Loading finished "+c,i.name,s,f.guid);let _=-1,x=!1;if(!((I=b.parser.json)!=null&&I.textures))return Rn&&console.warn("No textures in glTF "+c+" - may be a bug",i.name,s,f.guid),A(null);for(const R of b.parser.json.textures)if(_++,R!=null&&R.extensions){const E=R==null?void 0:R.extensions[Cb];if(E!=null&&E.guid&&E.guid===f.guid){x=!0;break}}if(!x)return A(null);let S=await y.getDependency("texture",_);S=this.copySettings(r,S),S&&(S.guid=f.guid),this.resolved[h]=S,Rn&&console.log(i.name,s,'change "'+r.name+'" → "'+S.name+'"',c,_,S,i,h),A(S)});return this.currentlyLoading[h]=p,await p}finally{delete this.currentlyLoading[h],this.onProgressiveLoadEnd(d)}}else{const h=this.onProgressiveLoadStart(e,t,c,i,s);try{Rn&&console.log("Load texture from uri: "+c);const f=await new vh().loadAsync(c);return f?(f.guid=l.guid,f.flipY=!1,f.needsUpdate=!0,f.encoding=r.encoding,Rn&&console.log(l,f)):Rn&&console.warn("failed loading",c),f}finally{this.onProgressiveLoadEnd(h)}}}else Rn&&console.warn("unknown texture",r.name,r.uuid,r);return null}static copySettings(e,t){const i=e.clone(),s=t.source,r=t.mipmaps;return i.copy(e),i.source=s,i.mipmaps=r,i}static beginListenStart(e,t){this._progressiveEventListeners.has(e)||this._progressiveEventListeners.set(e,new w2),this._progressiveEventListeners.get(e).start.push(t)}static stopListenStart(e,t){if(!this._progressiveEventListeners.has(e))return;const i=this._progressiveEventListeners.get(e).start,s=i.indexOf(t);s>=0&&i.splice(s,1)}static beginListenEnd(e,t){this._progressiveEventListeners.has(e)||this._progressiveEventListeners.set(e,new w2),this._progressiveEventListeners.get(e).end.push(t)}static stopListenEnd(e,t){if(!this._progressiveEventListeners.has(e))return;const i=this._progressiveEventListeners.get(e).end,s=i.indexOf(t);s>=0&&i.splice(s,1)}static onProgressiveLoadStart(e,t,i,s,r){this._currentProgressiveLoadingInfo.has(e)||this._currentProgressiveLoadingInfo.set(e,[]);const o=new W3(e,t,i,s,r),a=this._currentProgressiveLoadingInfo.get(e),l=this._progressiveEventListeners.get(e);return l&&l.onStart(o),a.push(o),o}static onProgressiveLoadEnd(e){if(!e)return;const t=e.context;if(!this._currentProgressiveLoadingInfo.has(t))return;const i=this._currentProgressiveLoadingInfo.get(t),s=i.indexOf(e);if(s<0)return;i.splice(s,1);const r=this._progressiveEventListeners.get(t);r&&r.onEnd(e)}};let Fr=sA;u(Fr,"cache",new Map),u(Fr,"resolved",{}),u(Fr,"currentlyLoading",{}),u(Fr,"_progressiveEventListeners",new Map),u(Fr,"_currentProgressiveLoadingInfo",new Map);class W3{constructor(e,t,i,s,r){u(this,"context");u(this,"source");u(this,"uri");u(this,"material");u(this,"slot");this.context=e,this.source=t,this.uri=i,this.material=s,this.slot=r}}class w2{constructor(){u(this,"start",[]);u(this,"end",[])}onStart(e){for(const t of this.start)t(e)}onEnd(e){for(const t of this.end)t(e)}}let w_;Promise.resolve().then(()=>She).then(n=>(w_=n.GLTFAnimationPointerExtension,w_)).catch(n=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three for full KHR_animation support",n)});const IA=new Array;function qK(n){IA.includes(n)||IA.push(n)}function YK(n){const e=IA.indexOf(n);e>=0&&IA.splice(e,1)}function xI(n){const e=new U3;return n.register(t=>(e.parser=t,e)),e}class KK{resolvePath(e){return e.includes("/extensions/builtin_components/")?e.replace("/extensions/builtin_components/","/userData/components/"):e.includes("extensions/builtin_components/")?e.replace("extensions/builtin_components/","/userData/components/"):e}}function j3(n,e,t){const i=t.lastIndexOf("?");i>=0&&(t=t.substring(0,i)),n.register(s=>new HK(s)),n.register(s=>new j9(s)),n.register(s=>new rY(s,e.lightmaps,t)),n.register(s=>new QK(s,t,e)),n.register(s=>new bK(s,t)),n.register(s=>new Wg(s,t)),n.register(s=>new Fr(s,t,e)),n.register(s=>new GK(s)),MN()&&n.register(s=>new Ab(s));for(const s of IA)n.register(r=>new s(r));n.register(s=>{if(w_){const r=new w_(s);return r.setAnimationPointerResolver.bind(r)(new KK),r}})}const xC=se("debuglightmaps");class RA{constructor(e,t){u(this,"lightmapIndex",-1);u(this,"lightmapScaleOffset",new At(1,1,0,0));u(this,"context");u(this,"gameObject");u(this,"lightmapTexture",null);u(this,"lightmapScaleOffsetUniform",{value:new At(1,1,0,0)});u(this,"lightmapUniform",{value:null});u(this,"onBeforeCompile",(e,t)=>{xC&&console.log("Lightmaps, before compile",e),e.lightMapUv="uv1",this.lightmapScaleOffsetUniform.value=this.lightmapScaleOffset,this.lightmapUniform.value=this.lightmapTexture,e.uniforms.lightmapScaleOffset=this.lightmapScaleOffsetUniform});this.gameObject=e,this.context=t}get lightmap(){return this.lightmapTexture}set lightmap(e){e!==this.lightmapTexture&&(this.lightmapTexture=e,this.applyLightmap())}init(e,t,i){console.assert(this.gameObject!==void 0&&this.gameObject!==null,"Missing gameobject",this),this.lightmapIndex=e,!(this.lightmapIndex<0)&&(this.lightmapScaleOffset=t,this.lightmapTexture=i,xC&&this.setLightmapDebugMaterial(),this.applyLightmap())}updateLightmapUniforms(e){const t=e.uniforms;t&&t.lightmap&&(this.lightmapScaleOffsetUniform.value=this.lightmapScaleOffset,t.lightmapScaleOffset=this.lightmapScaleOffsetUniform)}applyLightmap(){if(this.gameObject.type==="Object3D"){xC&&console.warn("Can not add lightmap. Is this object missing a renderer?",this.gameObject.name);return}if(this.gameObject.type==="Group"){console.warn("Lightmap on multimaterial object is not supported yet... please open a feature request on https://github.com/needle-tools/needle-engine-support if your project requires it");return}console.assert(this.gameObject.type==="Mesh","Lightmap only works on meshes",this);const e=this.gameObject;if(e.geometry.getAttribute("uv1")||e.geometry.setAttribute("uv1",e.geometry.getAttribute("uv")),Array.isArray(this.gameObject.material)){const t=this.gameObject.material;for(let i=0;i<t.length;i++){const r=t[i].clone();t[i]=r,r.onBeforeCompile=this.onBeforeCompile}}else{const t=this.gameObject.material.clone();this.gameObject.material=t,this.gameObject.material.onBeforeCompile=this.onBeforeCompile}if(this.lightmapIndex>=0&&this.lightmapTexture){const t=this.gameObject.material;t&&(t.lightMap=this.lightmapTexture,t.needsUpdate=!0)}}setLightmapDebugMaterial(){this.gameObject.material=new Ot({vertexShader:`
4412
4412
  varying vec2 vUv1;
4413
4413
  void main()
4414
4414
  {
@@ -4416,7 +4416,7 @@ version 0.6.9
4416
4416
  gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
4417
4417
  }
4418
4418
  `,fragmentShader:`
4419
- uniform sampler2D lightmap;
4419
+ uniform sampler2D lightMap;
4420
4420
  uniform float lightMapIntensity;
4421
4421
  uniform vec4 lightmapScaleOffset;
4422
4422
  varying vec2 vUv1;
@@ -4429,11 +4429,11 @@ version 0.6.9
4429
4429
  void main() {
4430
4430
  vec2 lUv = vUv1.xy * lightmapScaleOffset.xy + vec2(lightmapScaleOffset.z, (1. - (lightmapScaleOffset.y + lightmapScaleOffset.w)));
4431
4431
 
4432
- vec4 lightMapTexel = texture2D( lightmap, lUv);
4432
+ vec4 lightMapTexel = texture2D( lightMap, lUv);
4433
4433
  // The range of RGBM lightmaps goes from 0 to 34.49 (5^2.2) in linear space, and from 0 to 5 in gamma space.
4434
- //lightMapTexel.rgb *= lightMapTexel.a * 8.; // no idea where that "8" comes from... heuristically derived
4435
- //lightMapTexel.a = 1.;
4436
- //lightMapTexel = conv_sRGBToLinear(lightMapTexel);
4434
+ // lightMapTexel.rgb *= lightMapTexel.a * 8.; // no idea where that "8" comes from... heuristically derived
4435
+ // lightMapTexel.a = 1.;
4436
+ // lightMapTexel = conv_sRGBToLinear(lightMapTexel);
4437
4437
  // lightMapTexel.rgb = vec3(1.);
4438
4438
 
4439
4439
  // gl_FragColor = vec4(vUv1.xy, 0, 1);
@@ -5006,7 +5006,7 @@ void main() {
5006
5006
  `){super("lineBreak",e,!0),this._newLineBreakability=null}update(e,t){this._needsProcess=!0}process(e){const t=e._whiteSpace._newLineBreakability;if(e._inlines._value)for(let i=0;i<e._inlines._value.length;i++){const s=e._inlines._value[i],r=s.char;let o=null;r!==void 0&&(t!=="nowrap"&&(this._value.includes(r)||r.match(/\s/g))&&(o="possible"),r.match(/\n/g)&&(o=t)),s.lineBreak=o}}get value(){return this._value}}class bG extends mi{constructor(){super("layouter",null,!1),this._value=null}update(e,t){this._value=e._parent.find(i=>i.isUI&&i.isText),this._needsProcess=!0}process(e){this._value&&(this._value._layouter._needsProcess=!0)}}class Jte extends DA{constructor(e){super("backgroundColor",e,!1),this._allowsInherit=!1,this._input=0}computeOutputValue(e){this._input==="inherit"?this._value.set(this.getInheritedInput(e)):this._value.set(this._input)}}class _G extends xz{constructor(){super(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}}class xG extends wz{constructor(){super()}computeOutputValue(e){this._value=BI(this.getInheritedInput(e))}}class wG extends Rz{constructor(){super("fontFamily","inherit",!0),this._input="inherit",this._needsUpdate=!0,this._allowsInherit=!1}computeOutputValue(e){let t=this._inheritedInput;if(t==="inherit"&&(t=this.getInheritedInput(e)),t instanceof mw)this._value=t,e._font._needsUpdate=!0;else if(typeof t=="string"){const i=od.getFontFamily(t);i?(this._value=i,e._font._needsUpdate=!0):console.warn(`(.style) fontFamily, the font '${t}' is not registered. Aborted.`)}else console.warn("(.style) fontFamily requires a registered fontFamily instance, or the id of a registered fontFamily."),console.warn("If you want to set a specific font, please use .font property instead.")}get value(){return this._value}}class rR extends Bz{constructor(){super(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited,this._whiteSpacedContent="",this._stringCollapser=this.emptyStrategyLogic,this._inlineCollapser=this.emptyStrategyLogic,this._inlineWrapper=this.emptyStrategyLogic}_computeFromInherited(e){switch(super._computeFromInherited(e),this._newLineBreakability=Zte(this._value),this._value){case"nowrap":case"normal":this._stringCollapser=$te;break;case"pre-line":this._stringCollapser=SG;break;default:this._stringCollapser=eie}switch(this._value){case"pre-line":case"nowrap":case"normal":this._inlineCollapser=rie;break;case"pre-wrap":this._inlineCollapser=sie;break;default:this._inlineCollapser=oie}switch(this._value){case"pre-line":case"pre-wrap":case"normal":this._inlineWrapper=tie;break;case"pre":this._inlineWrapper=iie;break;default:this._inlineWrapper=nie}this._needsProcess=!0}process(e){e.isInline&&!e.isInlineBlock&&(this._whiteSpacedContent=this._stringCollapser(e._textContent._value),e._glyphs._needsProcess=!0)}}const tk={" ":" ","\n":`
5007
5007
  `,"\r":"\r"," ":" "},Zte=function(n){switch(n){case"pre":case"pre-wrap":case"pre-line":return"mandatory"}return null};function $te(n){return SG(n.replace(/\n/g," "))}function SG(n){return n.replace(/[ ]{2,}/g," ")}function eie(n){return n}function tie(n,e,t,i){const s=n[e];if(s.lineBreak==="mandatory"||t+s.xadvance+s.xoffset+s.kerning>i.INNER_WIDTH)return!0;const r=MG(n,e,i);return aie(n[e-1],t,r,i)}function iie(n,e,t,i){return n[e].lineBreak==="mandatory"}function nie(){return!1}function sie(n){if(!n[0])return 0;const e=n[0],t=n[n.length-1];return e.char&&e.char===`
5008
5008
  `&&n.length>1&&EG([e],n[1]),t.char&&t.char===`
5009
- `&&n.length>1&&CG([t],n[n.length-2]),e.offsetX}function rie(n){if(!n[0])return 0;let e=[],t;for(let i=0;i<n.length;i++){const s=n[i];if(s.char&&tk[s.char]&&n.length>i){e.push(s),t=n[i+1];continue}break}EG(e,t),e=[],t=null;for(let i=n.length-1;i>0;i--){const s=n[i];if(s.char&&tk[s.char]&&i>0){e.push(s),t=n[i-1];continue}break}return CG(e,t),n[0].offsetX}function oie(n){return n[0]?n[0].offsetX:0}function CG(n,e){if(e)for(let t=0;t<n.length;t++){const i=n[t];i.fontFactor=0,i.offsetX=e.offsetX+e.cumulativeWidth,i.cumulativeWidth=0}}function EG(n,e){if(e)for(let t=0;t<n.length;t++){const i=n[t];i.fontFactor=0,i.offsetX=e.offsetX,i.cumulativeWidth=0}}function MG(n,e,t,i){if(i=i||0,!n[e])return i;const s=n[e];return s.lineBreak?i+s.xadvance:MG(n,e+1,t,i+s.xadvance+s.xoffset+s.kerning+t.LETTERSPACING)}function aie(n,e,t,i){return!n||!n.char||e+t<i.INNER_WIDTH?!1:i.BREAKON.indexOf(n.char)>-1}class TG extends Dz{constructor(){super(),this._input="inherit",this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}_computeFromInherited(e){super._computeFromInherited(e),e._fontSize._needsProcess=!0,e._layouter._needsProcess=!0}}class IG extends zi{constructor(){super("fontSize","inherit",!0),this._allowsInherit=!1}computeOutputValue(e){this._value=this._inheritedInput,e._font._fontVariant&&(e._bounds._needsProcess=!0,e._layouter._needsProcess=!0)}process(e){if(!e._font._fontVariant||!e._font._fontVariant.isReady)return;const t=this._value/e._font._fontVariant.typographic.size,i=e._inlines._value;for(let s=0;s<i.length;s++){const r=i[s];r.resetOffsets(),r.fontSize=this._value,r.fontFactor=t}}get value(){return this._value}}class RG extends kz{constructor(){super("segments",1,!1),this._notInheritedValue=void 0}update(e,t){this._notInheritedValue=this._value,this._notInheritedValue==="inherit"&&(this._notInheritedValue=this.getInheritedInput(e)),e._layouter._needsUpdate=!0}set value(e){this._value!==e&&(this._value=e,this._needsUpdate=!0)}get value(){return this._value==="inherit"?this._notInheritedValue:this._value}}class lie extends RG{constructor(){super(),this._value="inherit"}}class cie extends gw{constructor(){super(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}_computeFromInherited(e){super._computeFromInherited(e),e._parent._value._layouter._needsProcess=!1}process(e){if(this._value!=="none"){const t=e._whiteSpace._whiteSpacedContent,i=e._inlines._value;for(let s=1;s<i.length;s++){const r=t[s-1]+t[s];i[s].kerning=e._font._fontVariant.getKerningAmount(r)}}}}class PG extends mi{constructor(){super("children",null,!1),this._uis=[]}update(e,t){}process(e){}_compute(e){}dispose(){}}function hie(n,e=!1){const t=n[0].index!==null,i=new Set(Object.keys(n[0].attributes)),s=new Set(Object.keys(n[0].morphAttributes)),r={},o={},a=n[0].morphTargetsRelative,l=new ze.BufferGeometry;let c=0;for(let h=0;h<n.length;++h){const d=n[h];let f=0;if(t!==(d.index!==null))return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+h+". All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them."),null;for(const p in d.attributes){if(!i.has(p))return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+h+'. All geometries must have compatible attributes; make sure "'+p+'" attribute exists among all geometries, or in none of them.'),null;r[p]===void 0&&(r[p]=[]),r[p].push(d.attributes[p]),f++}if(f!==i.size)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+h+". Make sure all geometries have the same number of attributes."),null;if(a!==d.morphTargetsRelative)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+h+". .morphTargetsRelative must be consistent throughout all geometries."),null;for(const p in d.morphAttributes){if(!s.has(p))return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+h+". .morphAttributes must be consistent throughout all geometries."),null;o[p]===void 0&&(o[p]=[]),o[p].push(d.morphAttributes[p])}if(l.userData.mergedUserData=l.userData.mergedUserData||[],l.userData.mergedUserData.push(d.userData),e){let p;if(t)p=d.index.count;else if(d.attributes.position!==void 0)p=d.attributes.position.count;else return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+h+". The geometry must have either an index or a position attribute"),null;l.addGroup(c,p,h),c+=p}}if(t){let h=0;const d=[];for(let f=0;f<n.length;++f){const p=n[f].index;for(let m=0;m<p.count;++m)d.push(p.getX(m)+h);h+=n[f].attributes.position.count}l.setIndex(d)}for(const h in r){const d=ik(r[h]);if(!d)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the "+h+" attribute."),null;l.setAttribute(h,d)}for(const h in o){const d=o[h][0].length;if(d===0)break;l.morphAttributes=l.morphAttributes||{},l.morphAttributes[h]=[];for(let f=0;f<d;++f){const p=[];for(let A=0;A<o[h].length;++A)p.push(o[h][A][f]);const m=ik(p);if(!m)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the "+h+" morphAttribute."),null;l.morphAttributes[h].push(m)}}return l}function ik(n){let e,t,i,s=0;for(let a=0;a<n.length;++a){const l=n[a];if(l.isInterleavedBufferAttribute)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. InterleavedBufferAttributes are not supported."),null;if(e===void 0&&(e=l.array.constructor),e!==l.array.constructor)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes."),null;if(t===void 0&&(t=l.itemSize),t!==l.itemSize)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes."),null;if(i===void 0&&(i=l.normalized),i!==l.normalized)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes."),null;s+=l.array.length}const r=new e(s);let o=0;for(let a=0;a<n.length;++a)r.set(n[a].array,o),o+=n[a].array.length;return new ze.BufferAttribute(r,t,i)}class uie extends mi{constructor(){super("renderer")}render(e){if(!e._inlines._value||!e._inlines._value.length)return;const t=e._inlines._value.map(s=>e._font._fontVariant.getGeometricGlyph(s,e).translate(s.offsetX,s.offsetY,0)),i=hie(t);e.setFontMesh(new ze.Mesh(i,e.fontMaterial)),e._fontMesh.renderOrder=1/0}}class die extends kI{constructor(){super(),this._allowsInherit=!1,this._needsUpdate=!1}computeOutputValue(e){this._value=this._inheritedInput,e._layouter._needsProcess=!0}}class Mp extends Ev{constructor(t={}){const i={};Mp.definePropertiesValues(i,t);super(i,t);u(this,"_rebuildParentUI",()=>{super._rebuildParentUI(),this._layouter._needsUpdate=!0});Mp.init(this)}add(t){const i=[];for(let s=0;s<arguments.length;s++){const r=arguments[s];!r.isUI||r.isInline?(i.push(r),r.position.z=.005):console.warn("Block element can only contain Box elements.",r)}return super.add(...i)}set textContent(t){this._textContent.value=t}get textContent(){return this._textContent._value}set invertAlpha(t){this._invertAlpha.value=t}get invertAlpha(){return this._invertAlpha._value}static definePropertiesValues(t,i){t.children||(t.children=PG),t.textContent||(t.textContent=Xte),t.glyphs||(t.glyphs=Yte),t.inlines||(t.inlines=qte),t.layouter||(t.layouter=bG),t.renderer||(t.renderer=uie),t.fontFamily||(t.fontFamily=wG),t.fontWeight||(t.fontWeight=xG),t.fontStyle||(t.fontStyle=_G),t.fontSize||(t.fontSize=IG),t.color||(t.color=Kte),t.backgroundColor||(t.backgroundColor=Jte),t.lineBreak||(t.lineBreak=yG),t.letterSpacing||(t.letterSpacing=TG),t.whiteSpace||(t.whiteSpace=rR),t.segments||(t.segments=lie),t.textAlign||(t.textAlign=die),t.fontKerning||(t.fontKerning=cie)}static init(t){Object.defineProperties(t,{isInline:{configurable:!1,enumerable:!0,value:!0}})}}class fie extends _z{constructor(){super("textContent",null,!1),this._needsUpdate=!1}set value(e){this._value!==e&&(this._value=e,this._needsUpdate=!0)}update(e,t){this._needsUpdate=!1;for(let i=e.children.length-1;i>=0;i--){const s=e.children[i];s.isUI&&(e.remove(s),s.clear())}e._children._uis=[],this._value&&e.add(new Mp({name:"anonymousInline",textContent:this._value}))}}class pie extends Array{constructor(...e){super(...e),this.width=0,this.height=0}}class mie extends mi{constructor(){super("layouter",null,!1),this._value=null}update(e,t){}process(e){let t=e._width._value;e._width._auto?t=1/0:t=e._bounds._innerWidth;const i=e._lineHeight._value,s=new pie(new ek);let r=0;e._children._inlines.forEach(d=>{if(!d._inlines.value)return;this._resetInlines(d);const f=d._fontSize._value,p=d._letterSpacing._value*f,m=d._whiteSpace._value,A=d._lineBreak._value,v={WHITESPACE:m,LETTERSPACING:p,BREAKON:A,INNER_WIDTH:t},g=d._whiteSpace._inlineWrapper;r+=d._margin._value.w+d._padding._value.w,d._inlines.value.forEach((b,y,_)=>{const x=s[s.length-1];if(g(_,y,r,v)){if(s.push(new ek(b)),b.offsetX=b.xoffset,b.width===0){r=0;return}b.cumulativeWidth=b.xadvance+p,r=b.cumulativeWidth;return}s[s.length-1].push(b),b.offsetX=r+b.xoffset+b.kerning,b.cumulativeWidth=b.xadvance+b.kerning+p,r+=b.cumulativeWidth,x.length-1===1&&x[x.length-2].width===0&&(b.offsetX-=b.xoffset,r-=b.xoffset)}),r+=d._margin._value.y+d._padding._value.y});const o=e._whiteSpace._inlineCollapser;let a=0,l=0,c=0;s.forEach((d,f)=>{const p=o(d);let m=0,A=0;if(d.forEach(v=>{m=Math.max(m,v.lineHeight),A=Math.max(A,v.lineBase),v.offsetX-=p}),d.lineHeight=m,d.lineBase=A,f===0?c=-(m*i-m)*.5:c-=s[f-1].lineHeight*i,d.y=c,d.x=0,d.forEach(v=>{v.offsetY=c-v.anchor,v.lineHeight<d.lineHeight&&(v.offsetY-=d.lineBase-v.lineBase)}),l+=d.lineHeight*i,d.width=0,d[0]){const v=d[d.length-1];d.width=v.offsetX+v.cumulativeWidth+v.paddingRight+v.marginRight+d[0].offsetX,a=Math.max(a,d.width)}}),s.height=l,s.width=a,this._value=s,t===1/0&&e._bounds.setChildrenWidth(e,s.width),e._height._auto&&e._bounds.setChildrenHeight(e,s.height);const h=e._parent._value;h&&(h._autoSize._needsProcess=!0,h._flexDirection._needsProcess=!0),e._inlineJustificator._needsProcess=!0,e._textAlign._needsProcess=!0,e._overflow._needsUpdate=!0}_resetInlines(e){e._fontSize.process(e)}}class gie extends kI{constructor(){super(),this._allowsInherit=!1,this._needsUpdate=!0}computeOutputValue(e){this._value=this._inheritedInput,this._needsProcess=!0}process(e){Aie(e),e._renderer._needsRender=!0}}function Aie(n){const e=n._layouter._value,t=n._textAlign._value,i=n._bounds._innerWidth;for(let s=0;s<e.length;s++){const r=e[s],o=vie(n,r,s===e.length-1),a=n._padding._value,l=n._borderWidth._value,c=(-a.w+a.y)/2+(-l.w+l.y)/2;r.x+=o;for(let h=0;h<r.length;h++)r[h].offsetX+=o-c}if(t.indexOf("justify")===0)for(let s=0;s<e.length;s++){const r=e[s];if(t.indexOf("-")!==-1&&s===e.length-1)return;const o=i-r.width;if(o<=0)return;let a=0;for(let d=1;d<r.length-1;d++)a+=r[d].char===" "?1:0;const l=o/a;let c=1;t==="justify-right"&&(r.reverse(),c=-1);let h=0;for(let d=1;d<=r.length-1;d++){const f=r[d];f.offsetX+=h*c,h+=f.char===" "?l:0}t==="justify-right"&&r.reverse()}}function vie(n,e,t){switch(n._textAlign._value){case"justify-left":case"justify":case"left":return-n._bounds._innerWidth/2;case"justify-right":case"right":return-e.width+n._bounds._innerWidth/2;case"center":return-e.width/2;case"justify-center":return t?-e.width/2:-n._bounds._innerWidth/2;default:console.warn(`textAlign: '${n._textAlign._value}' is not valid`)}}class yie extends OI{constructor(){super(),this._value=this._input="column",this._allowsInherit=!1,this._needsUpdate=!0}computeOutputValue(e){this._value=this._inheritedInput}}class bie extends Pz{constructor(){super(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}}class _ie extends gw{constructor(){super(),this._value=this._input=this.getDefaultValue(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}_computeFromInherited(e){super._computeFromInherited(e)}}class xie extends gG{constructor(){super(),this._innerWidth=1/0,this._innerHeight=0}}class wie extends mi{constructor(){super("children",null,!1);u(this,"_sortOrder",(t,i)=>t._order._value<i._order._value?-1:t._order._value>i._order._value?1:this._uis.indexOf(t)<this._uis.indexOf(i)?-1:1);this._uis=[],this._inlines=[],this._boxes=[]}update(t,i){this._compute(t),this._needsProcess=!0}process(t){this._compute(t),t._overflow._needsRender=!0}_compute(t){this._uis=t.children.filter(i=>i.visible&&i.isUI),this._inlines=this._uis.filter(i=>i.isInline).sort(this._sortOrder)}dispose(){this._inlines=null}}class Sie extends mi{constructor(){super("autosize")}process(e){if(e._layouter._value&&e._layouter._value.length){const t=e._layouter._value,i=e._padding._value,s=e._borderWidth._value;e._width._auto&&e._bounds.setOffsetWidth(e,t.width+i.w+i.y+s.w+s.y),e._height._auto&&e._bounds.setOffsetHeight(e,t.height+i.x+i.z+s.x+s.z)}}}class Cie extends vG{constructor(){super("renderer"),this._needsUpdate=!1}render(e){super.render(e);for(const t of e._children._inlines)t._renderer.render(t);e.performAfterUpdate()}}class UA extends LA{constructor(e={},t={}){UA.definePropertiesValues(t,e),super(t,e),UA.init(this)}add(e){const t=[];let i=!1;for(let s=0;s<arguments.length;s++){const r=arguments[s];!r.isUI||r.isInline?(r.isInline&&(i=!0),t.push(r)):console.warn("Block element can only contain Box elements.",r)}return t.length>0&&super.add(...t),i&&(this._children._needsUpdate=!0,this._layouter._needsProcess=!0),this}set textContent(e){this._textContent.value=e}get textContent(){return super.textContent}set invertAlpha(e){this._invertAlpha.value=e}get invertAlpha(){return this._invertAlpha._value}get lines(){return this._layouter._value}static definePropertiesValues(e,t){e.flexDirection=yie,e.justifyContent=LI,e.alignItems=DI,e.bounds=xie,e.autoSize=Sie,e.renderer=Cie,e.children||(e.children=wie),e.textContent||(e.textContent=fie),e.layouter||(e.layouter=mie),e.lineHeight||(e.lineHeight=bie),e.textAlign||(e.textAlign=gie),e.whiteSpace||(e.whiteSpace=rR),e.fontKerning||(e.fontKerning=_ie),e.segments||(e.segments=RG),t.width||(t.width="100%"),t.fontSide||(t.fontSide=0)}static init(e){Object.defineProperties(e,{isText:{configurable:!1,enumerable:!0,value:!0}})}}class Eie extends mi{constructor(){super("inlines",null,!1),this._value=[]}process(e){this._value[0].paddingLeft=e._padding._value.w,this._value[0].marginLeft=e._margin._value.w;const t=this._value.length-1;this._value[t].paddingRight=e._padding._value.y,this._value[t].marginRight=e._margin._value.y}}class Mie extends mi{constructor(){super("renderer")}render(e){e._backgroundMesh||e.setBackgroundMesh(new AG(e)),e._backgroundMesh.position.x=e._inlines._value[0].offsetX+e._inlines._value[0].width/2,e._backgroundMesh.position.y=e._inlines._value[0].offsetY+e._inlines._value[0].lineBase/2,e._bounds.render(e)}}class Tie extends mi{constructor(){super("bounds",null,!1),this._size=new ze.Vector3(1,1,1),this._offsetWidth=0,this._offsetHeight=0,this._innerWidth=0,this._innerHeight=0}update(e,t){this.output(t),this._needsProcess=!0}process(e){this._offsetWidth=this._innerWidth=e._inlines._value[0].width,this._offsetHeight=this._innerHeight=e._inlines._value[0].height,this._needsRender=!0,e._borderWidth._needsRender=!0,e._borderRadius._needsRender=!0}render(e){this._size.x=this._offsetWidth,this._size.y=this._offsetHeight}output(e){e.size=this._size}}class NA extends Ev{constructor(e={}){const t={};NA.definePropertiesValues(t,e),super(t,e),NA.init(this)}clear(){for(const e of this._inlines._value)e.clear();return super.clear()}bindBackgroundMeshProperties(){this._backgroundMesh.raycast=()=>{},this._bounds._size=this._backgroundMesh.scale,this._bounds._needsUpdate=!0}unbindBackgroundMeshProperties(){this._bounds._size=new ze.Vector3(1,1,1),this._bounds._needsUpdate=!0}add(e){const t=[];for(let i=0;i<arguments.length;i++){const s=arguments[i];s.isUI?console.warn("ThreeMeshUI::InlineBlockElement cannot contains UI Elements.",s):(t.push(s),s.position.z=.005)}return super.add(...t)}static definePropertiesValues(e,t){e.children||(e.children=PG),e.bounds||(e.bounds=Tie),e.inlines||(e.inlines=Eie),e.layouter||(e.layouter=bG),e.renderer||(e.renderer=Mie),e.fontFamily||(e.fontFamily=wG),e.fontWeight||(e.fontWeight=xG),e.fontStyle||(e.fontStyle=_G),e.fontSize||(e.fontSize=IG),e.backgroundColor||(e.backgroundColor=vz),e.lineBreak||(e.lineBreak=yG),e.letterSpacing||(e.letterSpacing=TG),e.whiteSpace||(e.whiteSpace=rR),e.fontKerning||(e.fontKerning=gw),t.backgroundSize||(t.backgroundSize="cover"),t.width||(t.width="100%"),t.height||(t.height="100%"),t.boxSizing||(t.boxSizing="border-box")}static init(e){Object.defineProperties(e,{isInline:{configurable:!1,enumerable:!0,value:!0},isInlineBlock:{configurable:!1,enumerable:!0,value:!0}}),e._inlines._value=[new Iie(e)],e.backgroundMaterial=new mG,e._renderer.render(e)}}class Iie extends Ez{constructor(e){super(),this._uiElement=e}get xadvance(){const e=this._uiElement._padding._value,t=this._uiElement._width;return t._relative?t._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):e.w+e.y+t.value}get width(){const e=this._uiElement._width;return e._relative?e._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):e.value}get height(){const e=this._uiElement._height;return e._relative?e._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):e.value}get anchor(){return this.height}get lineHeight(){const e=this._uiElement._height;return e._relative?e._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):e.value}get lineBase(){const e=this._uiElement._height;return e._relative?e._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):e.value}clear(){this._uiElement=null}}class BG{constructor(e){this._subject=e}attach(){console.error(`Behavior::attach() - Is abstract and therefore should be overridden in ${this.constructor.name}`)}act(){throw new Error(`Behavior::act() - Is abstract and therefore should be overridden in ${this.constructor.name}`)}detach(){console.error(`Behavior::detach() - Is abstract and therefore should be overridden in ${this.constructor.name}`)}clear(){}}const DG=()=>R_.update(),kG={BaseProperty:mi,Block:FA,Text:UA,Inline:Mp,InlineBlock:NA,MeshUIBaseElement:Ev,FontLibrary:od,update:DG,MSDFFontMaterialUtils:wo,ShaderChunkUI:pG,Behavior:BG,FontVariant:xv};typeof global<"u"&&(global.ThreeMeshUI=kG);const Rie=kG;var Pie=Cn.w8,OG=Cn.cg,oR=Cn.gO,Bie=Cn.wb,fM=Cn.zV,Die=Cn.HS,kie=Cn.Ec,Bb=Cn.gF,Oie=Cn.ol,Lie=Cn.pz,Fie=Cn.tx,Uie=Cn.hj,Nie=Cn.FV,zie=Cn.sV,LG=Cn.xv,Gie=Cn.mx,Hie=Cn.gE,Qie=Cn.ZP,FG=Cn.Vx;const OC=Object.freeze(Object.defineProperty({__proto__:null,BaseProperty:Pie,Behavior:OG,Block:oR,DefaultValues:Bie,FontLibrary:fM,FontVariant:Die,InheritableProperty:kie,Inline:Bb,InlineBlock:Oie,InlineGlyph:Lie,MSDFFontMaterialUtils:Fie,MaterialTransformers:Uie,MeshUIBaseElement:Nie,ShaderChunkUI:zie,Text:LG,TypographicFont:Gie,TypographicGlyph:Hie,default:Qie,update:FG},Symbol.toStringTag,{value:"Module"})),Vie=se("debugshadowcomponents");oR.prototype.interactable={get(){return this.interactive},set(n){this.interactable=n}};const Ga=Symbol("shadowDomOwner");class pa extends we{constructor(){super(...arguments);u(this,"shadowComponent",null);u(this,"_controlsChildLayout",!0);u(this,"_root");u(this,"_parentComponent")}isRoot(){var t;return((t=this.Root)==null?void 0:t.gameObject)===this.gameObject}get canvas(){const t=this.Root;return t!=null&&t.isCanvas?t:null}markDirty(){qs.markUIDirty(this.context)}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(t){this._controlsChildLayout=t,this.shadowComponent&&(this.shadowComponent.autoLayout=t)}get Root(){return this._root===void 0&&(this._root=$.getComponentInParent(this.gameObject,Mv)),this._root}get Canvas(){return this.canvas}__internalNewInstanceCreated(){super.__internalNewInstanceCreated(),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0}onEnable(){super.onEnable()}addShadowComponent(t,i){var o;this.removeShadowComponent();const s=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=$.getComponentInParent(s,pa),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}t.name=this.name+" ("+(this.constructor.name??"UI")+")",t.autoLayout=this._parentComponent.controlsChildLayout,t[Ga]=this,this.setShadowComponentOwner(t);let r=!1;if(((o=this.Root)==null?void 0:o.gameObject)===this.gameObject)this.gameObject.add(t);else{let a=this._parentComponent.shadowComponent;a&&(a==null||a.add(t),r=!0)}this.shadowComponent=t,i&&i.shadowComponent&&this.shadowComponent&&i.shadowComponent.add(this.shadowComponent),lv&&t.add(new Up(.5)),this.onAfterAddedToScene(),r&&FG(),Vie&&console.log(this.shadowComponent)}set(t){}setShadowComponentOwner(t){if(t&&(t[Ga]===void 0||t[Ga]===this)&&(t[Ga]=this,t.children))for(const i of t.children)this.setShadowComponentOwner(i)}traverseOwnedShadowComponents(t,i,s){if(t&&t[Ga]===i){s(t);for(const r of t.children)this.traverseOwnedShadowComponents(r,i,s)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(t){this.shadowComponent&&(this.shadowComponent.interactable=t)}}class Mv extends pa{awake(){super.awake()}}class Tp{static getObject(e){const t=e[Ga];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const i=this.tryFindCanvasGroup(e);if((i==null?void 0:i.isCanvasGroup)===!0&&(t&&(t.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const s=sd(e,r=>{if(r.isGraphic===!0)return r},!1);return t&&(s==null?void 0:s.isGraphic)===!0&&(t.graphic=s),!((s==null?void 0:s.raycastTarget)===!1||(s==null?void 0:s.layer)===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=sd(e,i=>{const s=i;if(s.blocksRaycasts!==void 0&&s.interactable!==void 0)return s},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}const gg=se("debugwebxrcontroller");var rp=(n=>(n[n.PhysicalDevice=0]="PhysicalDevice",n[n.Touch=1]="Touch",n))(rp||{}),Nl=(n=>(n.SelectStart="select-start",n.SelectEnd="select-end",n.Update="update",n))(Nl||{});class _w extends we{}const Wn=class extends we{constructor(){super(...arguments);u(this,"webXR");u(this,"index",-1);u(this,"controllerModel");u(this,"controller");u(this,"controllerGrip");u(this,"hand");u(this,"handPointerModel");u(this,"grabbed",null);u(this,"input",null);u(this,"type",0);u(this,"showRaycastLine",!0);u(this,"_wristQuaternion",null);u(this,"movementVector",new M);u(this,"worldRot",new Le);u(this,"joystick",new K);u(this,"didRotate",!1);u(this,"didTeleport",!1);u(this,"didChangeScale",!1);u(this,"lastHit",null);u(this,"raycastLine",null);u(this,"_raycastHitPoint",null);u(this,"_connnectedCallback",null);u(this,"_disconnectedCallback",null);u(this,"_selectStartEvt",null);u(this,"_selectEndEvt",null);u(this,"_selectionPressed",!1);u(this,"_selectionPressedLastFrame",!1);u(this,"_selectionStartTime",0);u(this,"_selectionEndTime",0);u(this,"_useSmoothing",!0);u(this,"_isConnected",!1);u(this,"rayRotation",new Le);u(this,"_pinchStartTime");u(this,"selectStartCallback",null);u(this,"lastSelectStartObject",null);u(this,"_didNotEndSelection",!1);u(this,"closeGrabBoundingBoxHelper")}static CreateRaycastLine(){const t=new an(this.geometry),i=t.material;return i.color=this.raycastColor,t.layers.set(2),t.name="line",t.scale.z=1,t}static CreateRaycastHitPoint(){const t=new No(.5,22,22),i=new fi({color:this.raycastColor}),s=new ye(t,i);return s.visible=!1,s.layers.set(2),s}static Create(t,i,s,r){const o=s?$.addNewComponent(s,Wn,!1):new Wn;o.webXR=t,o.index=i,o.type=r;const a=t.context;o.controller=a.renderer.xr.getController(i),o.controllerGrip=a.renderer.xr.getControllerGrip(i),o.controllerModel=this.Factory.createControllerModel(o.controller),o.controllerGrip.add(o.controllerModel),o.hand=a.renderer.xr.getHand(i);const l=new Wp;vv(l,a),o.webXR.handModelPath&&o.webXR.handModelPath!==""?l.setPath(Bh(t.sourceId,o.webXR.handModelPath)):l.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/");const c=new fZ(o.hand,l);return o.hand.add(c),o.hand.traverse(h=>h.layers.set(2)),o.handPointerModel=new bZ(o.hand,o.controller),o.controller.addEventListener("connected",h=>{o.setControllerLayers(o.controllerModel,2),o.setControllerLayers(o.controllerGrip,2),o.setControllerLayers(o.hand,2),setTimeout(()=>{o.setControllerLayers(o.controllerModel,2),o.setControllerLayers(o.controllerGrip,2),o.setControllerLayers(o.hand,2)},1e3)}),o.hand.addEventListener("connected",h=>{var f;if(h.data.hand){t.Rig&&t.Rig.add(o.hand),o.type=0,o.handPointerModel.traverse(m=>m.layers.set(2)),(f=o.handPointerModel.pointerObject)==null||f.traverse(m=>m.layers.set(2));const p=o.hand.joints;if(p)for(const m of Object.keys(p)){const A=p[m];A.parent||o.hand.add(A)}}}),o}static addEventListener(t,i){const s=this.eventSubs[t]??[];s.push(i),this.eventSubs[t]=s}static removeEventListener(t,i){if(!i)return;const s=this.eventSubs[t]??[],r=s.indexOf(i);r>=0&&s.splice(r,1),this.eventSubs[t]=s}get isUsingHands(){var i;const t=(i=this.input)==null?void 0:i.hand;return t!=null}get wrist(){if(!this.hand)return null;const t=this.hand.joints;return t?t.wrist:null}getWristQuaternion(){const t=this.wrist;return t?(this._wristQuaternion||(this._wristQuaternion=new Le),On(t).multiply(this._wristQuaternion.setFromEuler(new cs(-Math.PI/4,0,0)))):null}get selectionDown(){return this._selectionPressed&&!this._selectionPressedLastFrame}get selectionUp(){return!this._selectionPressed&&this._selectionPressedLastFrame}get selectionPressed(){return this._selectionPressed}get selectionClick(){return this._selectionEndTime-this._selectionStartTime<.3}get raycastHitPoint(){return this._raycastHitPoint}get useSmoothing(){return this._useSmoothing}awake(){if(!this.controller){console.warn("Missing Controller!!!",this);return}this._connnectedCallback=this.onSourceConnected.bind(this),this._disconnectedCallback=this.onSourceDisconnected.bind(this),this._selectStartEvt=this.onSelectStart.bind(this),this._selectEndEvt=this.onSelectEnd.bind(this),this.type===1&&(this.controllerGrip.addEventListener("connected",this._connnectedCallback),this.controllerGrip.addEventListener("disconnected",this._disconnectedCallback),this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt))}onDestroy(){var t,i,s;this.type===1&&(this.controllerGrip.removeEventListener("connected",this._connnectedCallback),this.controllerGrip.removeEventListener("disconnected",this._disconnectedCallback),this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),(t=this.hand)==null||t.clear(),(i=this.controllerGrip)==null||i.clear(),(s=this.controller)==null||s.clear()}onEnable(){var t,i,s,r,o;this.hand&&(this.hand.name="Hand"),this.controllerGrip&&(this.controllerGrip.name="ControllerGrip"),this.controller&&(this.controller.name="Controller"),this.raycastLine&&(this.raycastLine.name="RaycastLine;"),this.webXR.Controllers.indexOf(this)<0&&this.webXR.Controllers.push(this),this.raycastLine||(this.raycastLine=Wn.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=Wn.CreateRaycastHitPoint()),(t=this.webXR.Rig)==null||t.add(this.hand),(i=this.webXR.Rig)==null||i.add(this.controllerGrip),(s=this.webXR.Rig)==null||s.add(this.controller),(r=this.webXR.Rig)==null||r.add(this.raycastLine),(o=this.raycastLine)==null||o.add(this._raycastHitPoint),this._raycastHitPoint.visible=!1,this.hand.add(this.handPointerModel),gg&&console.log("ADDED TO RIG",this.webXR.Rig)}onDisable(){var i,s,r,o,a;(i=this.hand)==null||i.removeFromParent(),(s=this.controllerGrip)==null||s.removeFromParent(),(r=this.controller)==null||r.removeFromParent(),(o=this.raycastLine)==null||o.removeFromParent(),(a=this._raycastHitPoint)==null||a.removeFromParent();const t=this.webXR.Controllers.indexOf(this);t>=0&&this.webXR.Controllers.splice(t,1)}onSourceConnected(t){if(this._isConnected){console.warn("Received connected event for controller that is already connected",this.index,t);return}this._isConnected=!0,this.input=t.data,this.type===1&&(this.onSelectStart(),this.createPointerEvent("down"))}onSourceDisconnected(t){if(!this._isConnected){console.warn("Received discnnected event for controller that is not connected",t);return}this._isConnected=!1,this.type===1&&(this.onSelectEnd(),this.createPointerEvent("up")),this.input=null}createPointerEvent(t){switch(t){case"down":this.context.input.createPointerDown({clientX:0,clientY:0,button:this.index,pointerType:"touch"});break;case"move":break;case"up":this.context.input.createPointerUp({clientX:0,clientY:0,button:this.index,pointerType:"touch"});break}}update(){this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));const t=Wn.eventSubs.update;if(t&&t.length>0)for(const r of t)r(this);let i=1;this.type===0?i=this.context.time.deltaTime/.1:this.isUsingHands&&this.handPointerModel.pinched&&(i=this.context.time.deltaTime/.3),this.rayRotation.slerp(On(this.controller),this.useSmoothing?i:1);const s=xt(this.controller);if(this.isUsingHands&&this.handPointerModel.cursorObject&&(this.handPointerModel.cursorObject.visible=!1),this.raycastLine){const r=this.showRaycastLine&&this.type!==1;if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed&&r,cn(this.raycastLine,s);const o=this.hand.joints;if(o&&o.wrist&&this.grabbed&&this.grabbed.isCloseGrab){const l=this.getWristQuaternion();l&&this.rayRotation.copy(l)}xr(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=r,xr(this.raycastLine,this.rayRotation),cn(this.raycastLine,s)}this.lastHit=this.updateLastHit(),this.grabbed&&this.grabbed.update(),this._selectionPressedLastFrame=this._selectionPressed,this.selectStartCallback&&this.selectStartCallback()}onUpdate(t){var r,o;if(this.lastHit=null,!t||t.inputSources.length<=this.index){this.input=null;return}if(this.type===0&&(this.input=t.inputSources[this.index]),!this.input)return;const i=this.webXR.Rig;if(!i)return;this._didNotEndSelection&&!this.handPointerModel.pinched&&(this._didNotEndSelection=!1,this.onSelectEnd()),this.updateStick(this.input);const s=(o=(r=this.input)==null?void 0:r.gamepad)==null?void 0:o.buttons;switch(this.input.handedness){case"left":const a=3*Wn.MovementSpeedFactor,l=2,c=et.clamp01(this.joystick.length()*2),h=this.joystick.x>0?1:-1;let d=Math.pow(this.joystick.x,l);d*=h,d*=c;const f=this.joystick.y>0?1:-1;let p=Math.pow(this.joystick.y,l);p*=f,d*=c,i.getWorldQuaternion(this.worldRot),this.movementVector.set(d,0,p),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),this.movementVector.multiplyScalar(a*this.context.time.deltaTime),i.position.add(this.movementVector),this.isUsingHands&&this.runTeleport(i,s);break;case"right":const m=this.joystick.x,A=Math.abs(m);if(A<.4)this.didRotate=!1;else if(A>.5&&!this.didRotate){const v=m>0?-1:1;i.rotateY(et.toRadians(30*v)),this.didRotate=!0}this.runTeleport(i,s);break}}runTeleport(t,i){var l,c,h;let s=-this.joystick.y;if((l=this.hand)!=null&&l.visible&&!this.grabbed){const d=this.handPointerModel.isPinched();d&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),d&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(s=this.handPointerModel.isPinched()?1:0),d||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;let r=s>.5&&this.webXR.IsInVR,o=this.webXR.Rig?((h=(c=this.webXR.Rig)==null?void 0:c.scale)==null?void 0:h.x)<.999:!1,a=null;if(i&&this.input&&!this.input.hand)for(let d=0;d<i.length;d++){const f=i[d];if(d===4)if(f.pressed&&!this.didChangeScale&&this.webXR.IsInVR){this.didChangeScale=!0;const p=this.webXR.Rig;if(p)if(o){o=!1,p.scale.set(1,1,1),a=1,Wn.MovementSpeedFactor=1;const m=this.context.mainCamera;Wn.PreviousCameraFarDistance&&(m.far=Wn.PreviousCameraFarDistance)}else{o=!0,r=!0,a=.1,Wn.MovementSpeedFactor=a*2;const m=this.context.mainCamera;Wn.PreviousCameraFarDistance=m.far,m.far/=a}}else f.pressed||(this.didChangeScale=!1)}if(r){if(!this.didTeleport){const d=this.raycast();if(this.didTeleport=!0,d&&d.length>0){const f=d[0];if(o||this.isValidTeleportTarget(f.object)){const p=f.point;cn(t,p)}}}}else s<.1&&(this.didTeleport=!1);a!==null&&(t.scale.set(a,a,a),t.updateMatrixWorld())}isValidTeleportTarget(t){return $.getComponentInParent(t,_w)!=null}updateStick(t){var i;!t||!t.gamepad||((i=t.gamepad.axes)==null?void 0:i.length)<4||(this.joystick.x=t.gamepad.axes[2],this.joystick.y=t.gamepad.axes[3])}updateLastHit(){var r;const t=this.raycast(),i=t?t[0]:null;this.lastHit=i;let s=1;if(this.webXR.Rig&&(s/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=s*(((r=this.lastHit)==null?void 0:r.distance)??9999);const o=this.raycastLine.material;i!=null?o.color=Wn.raycastColor:o.color=Wn.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;const o=et.clamp(this.lastHit.distance*.01*s,.015,.1);this._raycastHitPoint.scale.set(o,o,o)}this._raycastHitPoint.visible=this.lastHit!==null&&this.lastHit!==void 0}return i}onSelectStart(){this.context.connection.allowEditing&&(this.selectStartCallback=()=>this.onHandleSelectStart())}onHandleSelectStart(){this.selectStartCallback=null,this._selectionPressed=!0,this._selectionStartTime=this.context.time.time,this._selectionEndTime=1e3;let t=null,i=!1;if(this.isUsingHands?(t=this.overlap(),t.length<=0?(t=this.raycast(),i=!1):i=!0):t=this.raycast(),gg&&console.log("onHandleSelectStart","close grab? "+i,"intersections",t),t&&t.length>0)for(const s of t){const r=s.object;this.lastSelectStartObject=r;const o={selected:r,grab:r},a=Wn.eventSubs["select-start"];if(a&&a.length>0)for(const l of a)l(this,o);o.grab!==r&&gg&&console.log("Grabbed object changed","original",r,"new",o.grab),o.grab&&(this.grabbed=Po.TryTake(this,o.grab,s,i));break}else{const s=Wn.eventSubs["select-start"],r={selected:null,grab:null};if(s&&s.length>0)for(const o of s)o(this,r)}}onSelectEnd(){var s;if(this.isUsingHands&&this.handPointerModel.pinched){this._didNotEndSelection=!0;return}if(!this._selectionPressed)return;this.selectStartCallback=null,this._selectionPressed=!1,this._selectionEndTime=this.context.time.time;const t={grab:((s=this.grabbed)==null?void 0:s.selected)??this.lastSelectStartObject},i=Wn.eventSubs["select-end"];if(i&&i.length>0)for(const r of i)r(this,t);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(t){return!(!t||$.isActiveInHierarchy(t)===!1||Tp.isInteractable(t)===!1)}setControllerLayers(t,i){var s,r;if(t&&(t.layers.set(i),t.children))for(const o of t.children)((s=this.grabbed)==null?void 0:s.selected)===o||((r=this.grabbed)==null?void 0:r.selectedMesh)===o||this.setControllerLayers(o,i)}getRay(){const t=new ol;return t.origin.copy(xt(this.controller)),t.direction.set(0,0,-1).applyQuaternion(this.rayRotation),t}overlap(){const t=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(gg&&(!this.closeGrabBoundingBoxHelper&&t&&(this.closeGrabBoundingBoxHelper=new Bx(t,16776960),this.scene.add(this.closeGrabBoundingBoxHelper)),this.closeGrabBoundingBoxHelper&&t&&this.closeGrabBoundingBoxHelper.setFromObject(t)),!t)return new Array;const i=xt(t).clone();return this.context.physics.sphereOverlap(i,.02)}raycast(){const t=new Aa;t.layerMask=new Lo,t.layerMask.enableAll(),t.layerMask.disable(2),t.ray=this.getRay();const i=this.context.physics.raycast(t);for(let s=0;s<i.length;s++){const r=i[s],o=r.object;if(!this.testIsVisible(o)){i.splice(s,1),s--;continue}r.object=Tp.getObject(o);break}return i}};let Ji=Wn;u(Ji,"Factory",new BZ),u(Ji,"raycastColor",new ve(.9,.3,.3)),u(Ji,"raycastNoHitColor",new ve(.6,.6,.6)),u(Ji,"geometry",new wt().setFromPoints([new M(0,0,0),new M(0,0,-1)])),u(Ji,"handModels",{}),u(Ji,"eventSubs",{}),u(Ji,"PreviousCameraFarDistance"),u(Ji,"MovementSpeedFactor",1);var B_=(n=>(n.WillTake="WillTake",n.DidTake="DidTake",n.WillFree="WillFree",n.DidFree="DidFree",n))(B_||{});const Ns=class{constructor(){u(this,"sync",null);u(this,"selected",null);u(this,"selectedParent",null);u(this,"selectedMesh",null);u(this,"controller",null);u(this,"grabTime",0);u(this,"grabUUID","");u(this,"isCloseGrab",!1);u(this,"originalMaterial",null);u(this,"usageMarker",null);u(this,"rigidbodies",null);u(this,"didReparent",!1);u(this,"grabDistance",0);u(this,"interactable",null);u(this,"positionSource",null);u(this,"grabPoint",new M);u(this,"localPositionOffsetToGrab",null);u(this,"localPositionOffsetToGrab_worldSpace",new M);u(this,"localQuaternionToGrab",new Le(0,0,0,1));u(this,"targetDir",null);u(this,"quaternionLerp",null);u(this,"controllerDir",new M);u(this,"controllerWorldPos",new M);u(this,"lastControllerWorldPos",new M);u(this,"controllerPosDelta",new M);u(this,"totalChangeAlongDirection",0);u(this,"rigPositionLastFrame",new M)}static AddEventListener(e,t){return Ns.Events[e]||(Ns.Events[e]=[]),Ns.Events[e].push(t),t}static RemoveEventListener(e,t){if(!t||!Ns.Events[e])return;const i=Ns.Events[e].indexOf(t);i>=0&&Ns.Events[e].splice(i,1)}static Register(e){this.Current.find(t=>t===e)||this.Current.push(e)}static Remove(e){const t=this.Current.indexOf(e);t>=0&&this.Current.splice(t,1)}static TryTake(e,t,i,s){const r=$.getComponentInParent(t,qp);if(r)t=r.gameObject;else return gg&&console.warn("Prevented taking object that is not interactable",t),null;let o=t;const a=$.getComponentInParent(t,Th);a&&(a.requestOwnership(),o=a.gameObject);for(const c of this.Current)if(c.selected===o)return c.controller===e||(c.free(),c.Take(e,o,t,a,r,i,s)),c;const l=new Ns;return l.Take(e,o,t,a,r,i,s),l}Take(e,t,i,s,r,o,a){var p,m;if(console.assert(t!==null,"Expected object to be taken but was",t),e.isUsingHands?this.positionSource=a?e.wrist:e.controller:this.positionSource=e.controller,!this.positionSource)return console.warn("No position source"),this;const l={controller:e,take:t,hit:i,sync:s,interactable:r};(p=Ns.Events.WillTake)==null||p.forEach(A=>A(this,l));const c=i;c!=null&&c.material&&(this.originalMaterial=c.material,Array.isArray(c.material)||(c.material=c.material.clone(),c.material&&c.material.emissive&&(c.material.emissive.b=.2))),this.selected=t,this.selectedParent||(this.selectedParent=t.parent),this.selectedMesh=c,this.controller=e,this.interactable=r,this.isCloseGrab=a,this.didReparent=!1,this.sync=s,this.grabTime=e.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=$.addNewComponent(this.selected,Yp),this.rigidbodies=$.getComponentsInChildren(this.selected,ji),xt(this.positionSource,this.lastControllerWorldPos);const h=()=>a?this.lastControllerWorldPos.clone():o.point.clone();this.grabDistance=h().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(h());const d=e.isUsingHands&&a?this.controller.getWristQuaternion().clone():e.rayRotation.clone();On(this.selected,this.localQuaternionToGrab).premultiply(d.invert());const f=this.controller.webXR.Rig;return f&&this.rigPositionLastFrame.copy(xt(f)),Js.Add(e.context,this.selected),Ns.Register(this),this.sync&&(this.sync.fastMode=!0),(m=Ns.Events.DidTake)==null||m.forEach(A=>A(this,l)),this}free(){var s,r,o,a;if(!this.selected)return;const e={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};(s=Ns.Events.WillFree)==null||s.forEach(l=>l(this,e)),Js.Remove(this.controller.context,this.selected),Ns.Remove(this),this.sync&&(this.sync.fastMode=!1);const t=this.selectedMesh;t&&this.originalMaterial&&t.material&&(t.material=this.originalMaterial);const i=this.selected;if(this.didReparent&&i.parent){const l=this.selectedParent;l?l.attach(i):(r=this.controller)==null||r.context.scene.attach(i)}if((o=this.usageMarker)==null||o.destroy(),this.controller&&(this.controller.grabbed=null),this.selected=null,this.selectedParent=null,this.selectedMesh=null,this.sync=null,this.rigidbodies)for(const l of this.rigidbodies)l.wakeUp(),l.setVelocity(l.smoothedVelocity);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,(a=Ns.Events.DidFree)==null||a.forEach(l=>l(this,e))}controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),xt(this.positionSource,this.controllerWorldPos),this.controllerPosDelta.copy(this.controllerWorldPos),this.controllerPosDelta.sub(this.lastControllerWorldPos),this.lastControllerWorldPos.copy(this.controllerWorldPos);const e=this.controller.webXR.Rig;if(e){const i=xt(e),s=this.rigPositionLastFrame.sub(i);this.controllerPosDelta.add(s),this.rigPositionLastFrame.copy(i)}return this.controllerDir.dot(this.controllerPosDelta)}update(){var e;if(this.rigidbodies)for(const t of this.rigidbodies)t.resetVelocities();if(this.sync&&this.controller&&this.controller.context.connection.isInRoom&&this.controller.context.time.time-this.grabTime>3&&this.sync.hasOwnership()===!1&&(console.log("no ownership, will leave",this.sync.guid),this.free()),!(this.interactable&&!this.interactable.canGrab)){if(!this.didReparent&&this.selected&&this.controller){const t=((e=this.controller.webXR.Rig)==null?void 0:e.scale.x)??1;this.totalChangeAlongDirection+=this.controllerMovementSinceLastFrame();let i=1;this.controller.type===0&&(i=Math.max(0,1+this.totalChangeAlongDirection*2/t),i=i*i*i),this.grabDistance/t<.8&&(i=1),this.targetDir||(this.targetDir=new M),this.targetDir.set(0,0,-this.grabDistance*i);const s=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),r=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=r.clone()),this.quaternionLerp.slerp(r,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),xr(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(s),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(xt(this.selected)),s.sub(this.localPositionOffsetToGrab_worldSpace)),cn(this.selected,s)}if(this.rigidbodies!=null)for(const t of this.rigidbodies)t.wakeUp();Ar.markDirty(this.selected,!0)}}};let Po=Ns;u(Po,"Events",{}),u(Po,"Current",[]);var Wie=Object.defineProperty,jie=Object.getOwnPropertyDescriptor,aR=(n,e,t,i)=>{for(var s=i>1?void 0:i?jie(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&&Wie(e,t,s),s};class md extends we{constructor(){super(...arguments);u(this,"objectBounds",!1);u(this,"color");u(this,"isGizmo",!0);u(this,"_gizmoObject",null);u(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!lv||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new Bx(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=K3(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),Yr.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){var t;for(;this._boxHelper;)(t=this._boxHelper)==null||t.update(),yield}}aR([w()],md.prototype,"objectBounds",2);aR([w(ve)],md.prototype,"color",2);aR([w()],md.prototype,"isGizmo",2);const Xie=se("debugrig");class xw extends we{awake(){if(Xie){const e=new ke;e.position.y+=.5,this.gameObject.add(e);const t=e.addNewComponent(md);t&&(t.isGizmo=!1)}}}class op{constructor(){u(this,"bb",null);u(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)}w(){return this.bb.readFloat32(this.bb_pos+12)}static sizeOf(){return 16}static createVec4(e,t,i,s,r){return e.prep(4,16),e.writeFloat32(r),e.writeFloat32(s),e.writeFloat32(i),e.writeFloat32(t),e.offset()}}class Ts{constructor(){u(this,"bb",null);u(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsVrUserStateBuffer(e,t){return(t||new Ts).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+Hx),(t||new Ts).__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}time(){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}avatarId(e){const t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__string(this.bb_pos+t,e):null}position(e){const t=this.bb.__offset(this.bb_pos,10);return t?(e||new jr).__init(this.bb_pos+t,this.bb):null}rotation(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new op).__init(this.bb_pos+t,this.bb):null}scale(){const e=this.bb.__offset(this.bb_pos,14);return e?this.bb.readFloat32(this.bb_pos+e):0}posLeftHand(e){const t=this.bb.__offset(this.bb_pos,16);return t?(e||new jr).__init(this.bb_pos+t,this.bb):null}posRightHand(e){const t=this.bb.__offset(this.bb_pos,18);return t?(e||new jr).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){const t=this.bb.__offset(this.bb_pos,20);return t?(e||new op).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){const t=this.bb.__offset(this.bb_pos,22);return t?(e||new op).__init(this.bb_pos+t,this.bb):null}static startVrUserStateBuffer(e){e.startObject(10)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addTime(e,t){e.addFieldInt64(1,t,e.createLong(0,0))}static addAvatarId(e,t){e.addFieldOffset(2,t,0)}static addPosition(e,t){e.addFieldStruct(3,t,0)}static addRotation(e,t){e.addFieldStruct(4,t,0)}static addScale(e,t){e.addFieldFloat32(5,t,0)}static addPosLeftHand(e,t){e.addFieldStruct(6,t,0)}static addPosRightHand(e,t){e.addFieldStruct(7,t,0)}static addRotLeftHand(e,t){e.addFieldStruct(8,t,0)}static addRotRightHand(e,t){e.addFieldStruct(9,t,0)}static endVrUserStateBuffer(e){return e.endObject()}static finishVrUserStateBufferBuffer(e,t){e.finish(t)}static finishSizePrefixedVrUserStateBufferBuffer(e,t){e.finish(t,void 0,!0)}}const nk=se("debugxr"),jm=se("debugavatar"),lR="VRUS";jT(lR,Ts.getRootAsVrUserStateBuffer);function pM(){return new Date().getTime()}function qie(n){let e=n&4294967295,t=n/Math.pow(2,32)&1048575;return Ka.create(e,t)}const oA=class{constructor(e){u(this,"guid");u(this,"time");u(this,"avatarId");u(this,"position",new M);u(this,"rotation",new At);u(this,"scale",1);u(this,"posLeftHand",new M);u(this,"posRightHand",new M);u(this,"rotLeftHand",new Le);u(this,"rotRightHand",new Le);this.guid=e}update(e,t,i,s,r){var h,d,f,p,m,A;this.time=pM(),this.avatarId=r,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let o=oA.quat0;const a=oA.quat1;o.set(i.x,i.y,i.z,i.w),o=o.multiplyQuaternions(o,oA.invertRotation),e&&(e.getWorldQuaternion(a),o.multiplyQuaternions(a,o)),this.rotation.set(o.x,o.y,o.z,o.w),this.scale=e.scale.x;const l=(h=s.LeftController)==null?void 0:h.controllerGrip;l&&(l.getWorldPosition(this.posLeftHand),l.getWorldQuaternion(this.rotLeftHand));const c=(d=s.RightController)==null?void 0:d.controllerGrip;if(c&&(c.getWorldPosition(this.posRightHand),c.getWorldQuaternion(this.rotRightHand)),(p=(f=s.LeftController)==null?void 0:f.hand)!=null&&p.visible){const v=s.LeftController.wrist;v&&(v.getWorldPosition(this.posLeftHand),v.getWorldQuaternion(this.rotLeftHand))}if((A=(m=s.RightController)==null?void 0:m.hand)!=null&&A.visible){const v=s.RightController.wrist;v&&(v.getWorldPosition(this.posRightHand),v.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(e,t){e.clear();const i=e.createString(this.guid),s=e.createString(this.avatarId);Ts.startVrUserStateBuffer(e),Ts.addGuid(e,i),Ts.addTime(e,qie(this.time)),Ts.addAvatarId(e,s),Ts.addPosition(e,jr.createVec3(e,this.position.x,this.position.y,this.position.z)),Ts.addRotation(e,op.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),Ts.addScale(e,this.scale),Ts.addPosLeftHand(e,jr.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),Ts.addPosRightHand(e,jr.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),Ts.addRotLeftHand(e,op.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),Ts.addRotRightHand(e,op.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));const r=Ts.endVrUserStateBuffer(e);e.finish(r,lR);const o=e.asUint8Array();t.sendBinary(o)}setFromBuffer(e,t){if(!e)return;this.guid=e,this.time=t.time().toFloat64();const i=t.avatarId();i&&(this.avatarId=i);const s=t.position();s&&this.position.set(s.x(),s.y(),s.z());const r=t.rotation();r&&this.rotation.set(r.x(),r.y(),r.z(),r.w());const o=t.posLeftHand();o&&this.posLeftHand.set(o.x(),o.y(),o.z());const a=t.posRightHand();a&&this.posRightHand.set(a.x(),a.y(),a.z());const l=t.rotLeftHand();l&&this.rotLeftHand.set(l.x(),l.y(),l.z(),l.w());const c=t.rotRightHand();c&&this.rotRightHand.set(c.x(),c.y(),c.z(),c.w()),this.scale=t.scale()}};let aa=oA;u(aa,"invertRotation",new Le().setFromAxisAngle(new M(0,1,0),Math.PI)),u(aa,"quat0",new Le),u(aa,"quat1",new Le);class zA extends we{constructor(){super(...arguments);u(this,"webXR",null);u(this,"debugAvatarUser",null);u(this,"voip",null);u(this,"tempState",new aa(""));u(this,"_removeAvatarsList",[]);u(this,"eventSub_ConnectionEvent",null);u(this,"eventSub_WebXRStartEvent",null);u(this,"eventSub_WebXREndEvent",null);u(this,"eventSub_WebXRUpdateEvent",null);u(this,"avatars",{});u(this,"localAvatar",null);u(this,"k_LocalAvatarNoNetworkingGuid","local");u(this,"ownership",null);u(this,"xrState",null);u(this,"builder",new Np(1024))}async awake(){if(this.webXR||(this.webXR=$.getComponent(this.gameObject,St)),this.webXR||(this.webXR=$.findObjectOfType(St,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=$.findObjectOfType(St,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=$.findObjectOfType(yc,this.context)),jm){const t="debug-avatar-"+jm,i=new qa(this.context,t,this.webXR);if(this.debugAvatarUser=i,typeof jm=="string"&&jm.length>0)if(await i.setAvatarOverride(jm)){const s=new aa(t);s.position.y+=1;const r=.5;s.posLeftHand.y+=r,s.posLeftHand.x+=r,s.posRightHand.y+=r,s.posRightHand.x-=r,i.tryUpdate(s,0)}else i.destroy()}}onEnable(){if(!this.webXR&&(this.webXR=$.getComponent(this.gameObject,St),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),St.addEventListener(xi.XRStarted,this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),St.addEventListener(xi.XRUpdate,this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),St.addEventListener(xi.XRStopped,this.eventSub_WebXREndEvent),this.eventSub_ConnectionEvent=this.onConnected.bind(this),this.context.connection.beginListen($i.JoinedRoom,this.eventSub_ConnectionEvent),this.context.connection.beginListen("webxr-user-joined",t=>{console.log("webxr user joined evt")}),this.context.connection.beginListen("webxr-user-left",t=>{const i=t.id!==null&&t.id!==void 0;if(i&&(console.log("webxr user left evt"),i)){const s=this.avatars[t.id];s==null||s.destroy(),this.avatars[t.id]=void 0}}),this.context.connection.beginListenBinary(lR,t=>{const i=t.guid();if(!i)return;const s=t.time().toFloat64(),r=this.tempState;r.setFromBuffer(i,t);const o=this.onTryGetAvatar(i,s);o==null||o.tryUpdate(r,s)}),this.context.connection.beginListen("vr-session-update",t=>{const i=t.guid,s=t.time,r=this.onTryGetAvatar(i,s);r==null||r.tryUpdate(t,s)})}onTryGetAvatar(t,i){if(t===this.context.connection.connectionId)return null;const s=new Date().getTime()-i;if(s>5e3)return nk&&console.log("old data",s,t),null;let r=this.avatars[t];if(r===void 0)try{console.log("create new avatar");const o=new qa(this.context,t,this.webXR);r=o,this.avatars[t]=o}catch(o){this.avatars[t]=null,console.error(o)}return r}onDisable(){this.eventSub_ConnectionEvent&&this.context.connection.stopListen($i.JoinedRoom,this.eventSub_ConnectionEvent),St.removeEventListener(xi.XRStarted,this.eventSub_WebXRStartEvent),St.removeEventListener(xi.XRUpdate,this.eventSub_WebXRUpdateEvent),St.removeEventListener(xi.XRStopped,this.eventSub_WebXREndEvent)}update(){const t=pM();this.debugAvatarUser&&(this.debugAvatarUser.lastUpdate=t),this.detectPotentiallyDisconnectedAvatarsAndRemove();for(const i in this.avatars){const s=this.avatars[i];s&&s.update()}}detectPotentiallyDisconnectedAvatarsAndRemove(){const t=pM();for(const i in this.avatars){const s=this.avatars[i];if(!s){this._removeAvatarsList.push(i);continue}t-s.lastUpdate>1e4&&(console.log("avatar timed out (didnt receive any updates in a while) - destroying it now"),s.destroy(),this.avatars[i]=void 0)}for(const i of this._removeAvatarsList)delete this.avatars[i];this._removeAvatarsList.length=0}buildLocalAvatar(){var i;if(this.localAvatar)return;const t=((i=this.context.connection)==null?void 0:i.connectionId)??this.k_LocalAvatarNoNetworkingGuid;this.localAvatar=new qa(this.context,t,this.webXR),this.localAvatar.isLocalAvatar=!0,this.localAvatar.setAvatarOverride(this.getAvatarId()),this.avatars[this.localAvatar.guid]=this.localAvatar}onConnected(){var t,i,s;nk&&console.log("Hey you are connected as "+this.context.connection.connectionId),((t=this.localAvatar)==null?void 0:t.guid)===this.k_LocalAvatarNoNetworkingGuid&&(this.localAvatar&&((i=this.localAvatar)==null||i.destroy(),this.avatars[this.localAvatar.guid]=void 0),this.localAvatar=null,this.xrState=null,(s=this.ownership)==null||s.freeOwnership(),this.ownership=null)}onXRSessionStart(t){var i,s,r;if(console.log("XR session started"),this.context.connection.send("webxr-user-joined",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&((i=this.localAvatar)==null||i.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null),this.xrState=null,(s=this.ownership)==null||s.freeOwnership(),this.ownership=null,this.avatars)for(const o in this.avatars)(r=this.avatars[o])==null||r.updateFlags()}onXRSessionEnded(t){var i;console.log("XR session ended"),this.context.connection.send("webxr-user-left",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&((i=this.localAvatar)==null||i.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null)}onXRSessionUpdate(t){this.xrState??(this.xrState=new aa(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid)),this.ownership??(this.ownership=new Vx(this.context.connection,this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid)),this.ownership.guid=this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid,this.buildLocalAvatar();const{frame:i,xr:s,rig:r}=t,o=i.getViewerPose(s.getReferenceSpace());if(!o)return;const a=o==null?void 0:o.transform,l=a.position,c=a.orientation;this.xrState.update(r,l,c,this.webXR,this.getAvatarId()),this.localAvatar&&(this.context.connection.connectionId&&(this.localAvatar.guid=this.context.connection.connectionId),this.localAvatar.tryUpdate(this.xrState,0)),!(this.ownership&&!this.ownership.hasOwnership&&this.context.connection.isConnected&&(this.context.time.frameCount%120===0&&this.ownership.requestOwnership(),!this.ownership.hasOwnership))&&(!this.context.connection.isConnected||!this.context.connection.connectionId||this.xrState.sendAsBuffer(this.builder,this.context.connection))}getAvatarId(){return se("avatar")??null}}var Yie=Object.defineProperty,Kie=Object.getOwnPropertyDescriptor,$p=(n,e,t,i)=>{for(var s=i>1?void 0:i?Kie(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&&Yie(e,t,s),s};const LC=se("debugwebxr");async function UG(){return Yb()?!0:"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function NG(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}let Ag=!1,vg=!1;UG().then(n=>Ag=n);NG().then(n=>vg=n);var xi=(n=>(n.XRStarted="xrStarted",n.XRStopped="xrStopped",n.XRUpdate="xrUpdate",n.RequestVRSession="requestVRSession",n.ModifyAROptions="modify-ar-options",n))(xi||{}),Tf;const Pn=(Tf=class extends we{constructor(){super(...arguments);u(this,"enableVR",!0);u(this,"enableAR",!0);u(this,"defaultAvatar");u(this,"handModelPath","");u(this,"createVRButton",!0);u(this,"createARButton",!0);u(this,"controllers",[]);u(this,"rig");u(this,"isInit",!1);u(this,"_requestedAR",!1);u(this,"_requestedVR",!1);u(this,"_isInAR",!1);u(this,"_isInVR",!1);u(this,"_arButton");u(this,"_vrButton");u(this,"webAR",null);u(this,"_transformOrientation",new Le);u(this,"_currentHeadPose",null);u(this,"_originalCameraParent",null);u(this,"_originalCameraPosition",new M);u(this,"_originalCameraRotation",new Le);u(this,"_originalXRRigParent",null);u(this,"_originalXRRigPosition",new M);u(this,"_originalXRRigRotation",new Le);u(this,"xrMirrorWindow",null)}static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(Ag||vg)}static get IsARSupported(){return Ag}static get IsVRSupported(){return vg}static get OptionalFeatures_VR(){return this._optionalFeatures_VR}static get OptionalFeatures_AR(){return this._optionalFeatures_AR}static addEventListener(e,t){return this.events.addEventListener(e,t),t}static removeEventListener(e,t){return this.events.removeEventListener(e,t),t}static dispatchEvent(e,t){this.events.dispatchEvent({type:e,detail:t})}static createVRButton(e,t){Pn.XRSupported?e.__internalAwake():console.warn("WebXR is not supported on this device");const i={optionalFeatures:Pn.OptionalFeatures_VR},s=jg.createButton(e.context.renderer,i);return s.classList.add("webxr-ar-button"),s.classList.add("webxr-button"),this.resetButtonStyles(s),((t==null?void 0:t.registerClick)??!0)&&s.addEventListener("click",e.onClickedVRButton.bind(e)),s}static createARButton(e,t){var o;e.__internalAwake();const i=(o=e.webAR)==null?void 0:o.getAROverlayContainer(),s={optionalFeatures:[...this.OptionalFeatures_AR]};i?(s.domOverlay={root:i},s.optionalFeatures.push("dom-overlay"),s.optionalFeatures.push("hit-test")):console.warn("No dom overlay root found, HTML overlays on top of screen-based AR will not work.");const r=iZ.createButton(e.context.renderer,s,this.onModifyAROptions.bind(this));return r.classList.add("webxr-ar-button"),r.classList.add("webxr-button"),Pn.resetButtonStyles(r),((t==null?void 0:t.registerClick)??!0)&&r.addEventListener("click",e.onClickedARButton.bind(e)),r}static onModifyAROptions(e){Pn.dispatchEvent("modify-ar-options",e)}static resetButtonStyles(e){e&&(e.style.position="",e.style.bottom="",e.style.left="")}endSession(){const e=this.context.renderer.xr.getSession();e&&e.end()}get Rig(){return this.rig||this.ensureRig(),this.rig}get Controllers(){return this.controllers}get LeftController(){var e,t;return this.controllers.length>0&&((e=this.controllers[0].input)==null?void 0:e.handedness)==="left"?this.controllers[0]:this.controllers.length>1&&((t=this.controllers[1].input)==null?void 0:t.handedness)==="left"?this.controllers[1]:null}get RightController(){var e,t;return this.controllers.length>0&&((e=this.controllers[0].input)==null?void 0:e.handedness)==="right"?this.controllers[0]:this.controllers.length>1&&((t=this.controllers[1].input)==null?void 0:t.handedness)==="right"?this.controllers[1]:null}get ARButton(){return this._arButton}get VRButton(){return this._vrButton}get IsInVR(){return this._isInVR}get IsInAR(){return this._isInAR}awake(){if(this.defaultAvatar&&typeof this.defaultAvatar=="string"&&(this.defaultAvatar=Kn.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!$.findObjectOfType(zA,this.context)){const e=$.addNewComponent(this.gameObject,zA,!1);e.webXR=this}this.webAR=new Ku(this)}start(){location.protocol=="http:"&&location.host.indexOf("localhost")<0&&(Fo("WebXR only works on https"),console.warn("WebXR only works on https. https://engine.needle.tools/docs/xr.html"))}onEnable(){if(this.isInit||!this.enableAR&&!this.enableVR)return;this.isInit=!0,this.context.renderer.xr.enabled=!0,Pn.XRSupported;let e,t;const i=document.createElement("div");i.classList.add("webxr-buttons"),i.style.cssText=`
5009
+ `&&n.length>1&&CG([t],n[n.length-2]),e.offsetX}function rie(n){if(!n[0])return 0;let e=[],t;for(let i=0;i<n.length;i++){const s=n[i];if(s.char&&tk[s.char]&&n.length>i){e.push(s),t=n[i+1];continue}break}EG(e,t),e=[],t=null;for(let i=n.length-1;i>0;i--){const s=n[i];if(s.char&&tk[s.char]&&i>0){e.push(s),t=n[i-1];continue}break}return CG(e,t),n[0].offsetX}function oie(n){return n[0]?n[0].offsetX:0}function CG(n,e){if(e)for(let t=0;t<n.length;t++){const i=n[t];i.fontFactor=0,i.offsetX=e.offsetX+e.cumulativeWidth,i.cumulativeWidth=0}}function EG(n,e){if(e)for(let t=0;t<n.length;t++){const i=n[t];i.fontFactor=0,i.offsetX=e.offsetX,i.cumulativeWidth=0}}function MG(n,e,t,i){if(i=i||0,!n[e])return i;const s=n[e];return s.lineBreak?i+s.xadvance:MG(n,e+1,t,i+s.xadvance+s.xoffset+s.kerning+t.LETTERSPACING)}function aie(n,e,t,i){return!n||!n.char||e+t<i.INNER_WIDTH?!1:i.BREAKON.indexOf(n.char)>-1}class TG extends Dz{constructor(){super(),this._input="inherit",this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}_computeFromInherited(e){super._computeFromInherited(e),e._fontSize._needsProcess=!0,e._layouter._needsProcess=!0}}class IG extends zi{constructor(){super("fontSize","inherit",!0),this._allowsInherit=!1}computeOutputValue(e){this._value=this._inheritedInput,e._font._fontVariant&&(e._bounds._needsProcess=!0,e._layouter._needsProcess=!0)}process(e){if(!e._font._fontVariant||!e._font._fontVariant.isReady)return;const t=this._value/e._font._fontVariant.typographic.size,i=e._inlines._value;for(let s=0;s<i.length;s++){const r=i[s];r.resetOffsets(),r.fontSize=this._value,r.fontFactor=t}}get value(){return this._value}}class RG extends kz{constructor(){super("segments",1,!1),this._notInheritedValue=void 0}update(e,t){this._notInheritedValue=this._value,this._notInheritedValue==="inherit"&&(this._notInheritedValue=this.getInheritedInput(e)),e._layouter._needsUpdate=!0}set value(e){this._value!==e&&(this._value=e,this._needsUpdate=!0)}get value(){return this._value==="inherit"?this._notInheritedValue:this._value}}class lie extends RG{constructor(){super(),this._value="inherit"}}class cie extends gw{constructor(){super(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}_computeFromInherited(e){super._computeFromInherited(e),e._parent._value._layouter._needsProcess=!1}process(e){if(this._value!=="none"){const t=e._whiteSpace._whiteSpacedContent,i=e._inlines._value;for(let s=1;s<i.length;s++){const r=t[s-1]+t[s];i[s].kerning=e._font._fontVariant.getKerningAmount(r)}}}}class PG extends mi{constructor(){super("children",null,!1),this._uis=[]}update(e,t){}process(e){}_compute(e){}dispose(){}}function hie(n,e=!1){const t=n[0].index!==null,i=new Set(Object.keys(n[0].attributes)),s=new Set(Object.keys(n[0].morphAttributes)),r={},o={},a=n[0].morphTargetsRelative,l=new ze.BufferGeometry;let c=0;for(let h=0;h<n.length;++h){const d=n[h];let f=0;if(t!==(d.index!==null))return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+h+". All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them."),null;for(const p in d.attributes){if(!i.has(p))return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+h+'. All geometries must have compatible attributes; make sure "'+p+'" attribute exists among all geometries, or in none of them.'),null;r[p]===void 0&&(r[p]=[]),r[p].push(d.attributes[p]),f++}if(f!==i.size)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+h+". Make sure all geometries have the same number of attributes."),null;if(a!==d.morphTargetsRelative)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+h+". .morphTargetsRelative must be consistent throughout all geometries."),null;for(const p in d.morphAttributes){if(!s.has(p))return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+h+". .morphAttributes must be consistent throughout all geometries."),null;o[p]===void 0&&(o[p]=[]),o[p].push(d.morphAttributes[p])}if(l.userData.mergedUserData=l.userData.mergedUserData||[],l.userData.mergedUserData.push(d.userData),e){let p;if(t)p=d.index.count;else if(d.attributes.position!==void 0)p=d.attributes.position.count;else return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+h+". The geometry must have either an index or a position attribute"),null;l.addGroup(c,p,h),c+=p}}if(t){let h=0;const d=[];for(let f=0;f<n.length;++f){const p=n[f].index;for(let m=0;m<p.count;++m)d.push(p.getX(m)+h);h+=n[f].attributes.position.count}l.setIndex(d)}for(const h in r){const d=ik(r[h]);if(!d)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the "+h+" attribute."),null;l.setAttribute(h,d)}for(const h in o){const d=o[h][0].length;if(d===0)break;l.morphAttributes=l.morphAttributes||{},l.morphAttributes[h]=[];for(let f=0;f<d;++f){const p=[];for(let A=0;A<o[h].length;++A)p.push(o[h][A][f]);const m=ik(p);if(!m)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the "+h+" morphAttribute."),null;l.morphAttributes[h].push(m)}}return l}function ik(n){let e,t,i,s=0;for(let a=0;a<n.length;++a){const l=n[a];if(l.isInterleavedBufferAttribute)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. InterleavedBufferAttributes are not supported."),null;if(e===void 0&&(e=l.array.constructor),e!==l.array.constructor)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes."),null;if(t===void 0&&(t=l.itemSize),t!==l.itemSize)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes."),null;if(i===void 0&&(i=l.normalized),i!==l.normalized)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes."),null;s+=l.array.length}const r=new e(s);let o=0;for(let a=0;a<n.length;++a)r.set(n[a].array,o),o+=n[a].array.length;return new ze.BufferAttribute(r,t,i)}class uie extends mi{constructor(){super("renderer")}render(e){if(!e._inlines._value||!e._inlines._value.length)return;const t=e._inlines._value.map(s=>e._font._fontVariant.getGeometricGlyph(s,e).translate(s.offsetX,s.offsetY,0)),i=hie(t);e.setFontMesh(new ze.Mesh(i,e.fontMaterial)),e._fontMesh.renderOrder=1/0}}class die extends kI{constructor(){super(),this._allowsInherit=!1,this._needsUpdate=!1}computeOutputValue(e){this._value=this._inheritedInput,e._layouter._needsProcess=!0}}class Mp extends Ev{constructor(t={}){const i={};Mp.definePropertiesValues(i,t);super(i,t);u(this,"_rebuildParentUI",()=>{super._rebuildParentUI(),this._layouter._needsUpdate=!0});Mp.init(this)}add(t){const i=[];for(let s=0;s<arguments.length;s++){const r=arguments[s];!r.isUI||r.isInline?(i.push(r),r.position.z=.005):console.warn("Block element can only contain Box elements.",r)}return super.add(...i)}set textContent(t){this._textContent.value=t}get textContent(){return this._textContent._value}set invertAlpha(t){this._invertAlpha.value=t}get invertAlpha(){return this._invertAlpha._value}static definePropertiesValues(t,i){t.children||(t.children=PG),t.textContent||(t.textContent=Xte),t.glyphs||(t.glyphs=Yte),t.inlines||(t.inlines=qte),t.layouter||(t.layouter=bG),t.renderer||(t.renderer=uie),t.fontFamily||(t.fontFamily=wG),t.fontWeight||(t.fontWeight=xG),t.fontStyle||(t.fontStyle=_G),t.fontSize||(t.fontSize=IG),t.color||(t.color=Kte),t.backgroundColor||(t.backgroundColor=Jte),t.lineBreak||(t.lineBreak=yG),t.letterSpacing||(t.letterSpacing=TG),t.whiteSpace||(t.whiteSpace=rR),t.segments||(t.segments=lie),t.textAlign||(t.textAlign=die),t.fontKerning||(t.fontKerning=cie)}static init(t){Object.defineProperties(t,{isInline:{configurable:!1,enumerable:!0,value:!0}})}}class fie extends _z{constructor(){super("textContent",null,!1),this._needsUpdate=!1}set value(e){this._value!==e&&(this._value=e,this._needsUpdate=!0)}update(e,t){this._needsUpdate=!1;for(let i=e.children.length-1;i>=0;i--){const s=e.children[i];s.isUI&&(e.remove(s),s.clear())}e._children._uis=[],this._value&&e.add(new Mp({name:"anonymousInline",textContent:this._value}))}}class pie extends Array{constructor(...e){super(...e),this.width=0,this.height=0}}class mie extends mi{constructor(){super("layouter",null,!1),this._value=null}update(e,t){}process(e){let t=e._width._value;e._width._auto?t=1/0:t=e._bounds._innerWidth;const i=e._lineHeight._value,s=new pie(new ek);let r=0;e._children._inlines.forEach(d=>{if(!d._inlines.value)return;this._resetInlines(d);const f=d._fontSize._value,p=d._letterSpacing._value*f,m=d._whiteSpace._value,A=d._lineBreak._value,v={WHITESPACE:m,LETTERSPACING:p,BREAKON:A,INNER_WIDTH:t},g=d._whiteSpace._inlineWrapper;r+=d._margin._value.w+d._padding._value.w,d._inlines.value.forEach((b,y,_)=>{const x=s[s.length-1];if(g(_,y,r,v)){if(s.push(new ek(b)),b.offsetX=b.xoffset,b.width===0){r=0;return}b.cumulativeWidth=b.xadvance+p,r=b.cumulativeWidth;return}s[s.length-1].push(b),b.offsetX=r+b.xoffset+b.kerning,b.cumulativeWidth=b.xadvance+b.kerning+p,r+=b.cumulativeWidth,x.length-1===1&&x[x.length-2].width===0&&(b.offsetX-=b.xoffset,r-=b.xoffset)}),r+=d._margin._value.y+d._padding._value.y});const o=e._whiteSpace._inlineCollapser;let a=0,l=0,c=0;s.forEach((d,f)=>{const p=o(d);let m=0,A=0;if(d.forEach(v=>{m=Math.max(m,v.lineHeight),A=Math.max(A,v.lineBase),v.offsetX-=p}),d.lineHeight=m,d.lineBase=A,f===0?c=-(m*i-m)*.5:c-=s[f-1].lineHeight*i,d.y=c,d.x=0,d.forEach(v=>{v.offsetY=c-v.anchor,v.lineHeight<d.lineHeight&&(v.offsetY-=d.lineBase-v.lineBase)}),l+=d.lineHeight*i,d.width=0,d[0]){const v=d[d.length-1];d.width=v.offsetX+v.cumulativeWidth+v.paddingRight+v.marginRight+d[0].offsetX,a=Math.max(a,d.width)}}),s.height=l,s.width=a,this._value=s,t===1/0&&e._bounds.setChildrenWidth(e,s.width),e._height._auto&&e._bounds.setChildrenHeight(e,s.height);const h=e._parent._value;h&&(h._autoSize._needsProcess=!0,h._flexDirection._needsProcess=!0),e._inlineJustificator._needsProcess=!0,e._textAlign._needsProcess=!0,e._overflow._needsUpdate=!0}_resetInlines(e){e._fontSize.process(e)}}class gie extends kI{constructor(){super(),this._allowsInherit=!1,this._needsUpdate=!0}computeOutputValue(e){this._value=this._inheritedInput,this._needsProcess=!0}process(e){Aie(e),e._renderer._needsRender=!0}}function Aie(n){const e=n._layouter._value,t=n._textAlign._value,i=n._bounds._innerWidth;for(let s=0;s<e.length;s++){const r=e[s],o=vie(n,r,s===e.length-1),a=n._padding._value,l=n._borderWidth._value,c=(-a.w+a.y)/2+(-l.w+l.y)/2;r.x+=o;for(let h=0;h<r.length;h++)r[h].offsetX+=o-c}if(t.indexOf("justify")===0)for(let s=0;s<e.length;s++){const r=e[s];if(t.indexOf("-")!==-1&&s===e.length-1)return;const o=i-r.width;if(o<=0)return;let a=0;for(let d=1;d<r.length-1;d++)a+=r[d].char===" "?1:0;const l=o/a;let c=1;t==="justify-right"&&(r.reverse(),c=-1);let h=0;for(let d=1;d<=r.length-1;d++){const f=r[d];f.offsetX+=h*c,h+=f.char===" "?l:0}t==="justify-right"&&r.reverse()}}function vie(n,e,t){switch(n._textAlign._value){case"justify-left":case"justify":case"left":return-n._bounds._innerWidth/2;case"justify-right":case"right":return-e.width+n._bounds._innerWidth/2;case"center":return-e.width/2;case"justify-center":return t?-e.width/2:-n._bounds._innerWidth/2;default:console.warn(`textAlign: '${n._textAlign._value}' is not valid`)}}class yie extends OI{constructor(){super(),this._value=this._input="column",this._allowsInherit=!1,this._needsUpdate=!0}computeOutputValue(e){this._value=this._inheritedInput}}class bie extends Pz{constructor(){super(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}}class _ie extends gw{constructor(){super(),this._value=this._input=this.getDefaultValue(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}_computeFromInherited(e){super._computeFromInherited(e)}}class xie extends gG{constructor(){super(),this._innerWidth=1/0,this._innerHeight=0}}class wie extends mi{constructor(){super("children",null,!1);u(this,"_sortOrder",(t,i)=>t._order._value<i._order._value?-1:t._order._value>i._order._value?1:this._uis.indexOf(t)<this._uis.indexOf(i)?-1:1);this._uis=[],this._inlines=[],this._boxes=[]}update(t,i){this._compute(t),this._needsProcess=!0}process(t){this._compute(t),t._overflow._needsRender=!0}_compute(t){this._uis=t.children.filter(i=>i.visible&&i.isUI),this._inlines=this._uis.filter(i=>i.isInline).sort(this._sortOrder)}dispose(){this._inlines=null}}class Sie extends mi{constructor(){super("autosize")}process(e){if(e._layouter._value&&e._layouter._value.length){const t=e._layouter._value,i=e._padding._value,s=e._borderWidth._value;e._width._auto&&e._bounds.setOffsetWidth(e,t.width+i.w+i.y+s.w+s.y),e._height._auto&&e._bounds.setOffsetHeight(e,t.height+i.x+i.z+s.x+s.z)}}}class Cie extends vG{constructor(){super("renderer"),this._needsUpdate=!1}render(e){super.render(e);for(const t of e._children._inlines)t._renderer.render(t);e.performAfterUpdate()}}class UA extends LA{constructor(e={},t={}){UA.definePropertiesValues(t,e),super(t,e),UA.init(this)}add(e){const t=[];let i=!1;for(let s=0;s<arguments.length;s++){const r=arguments[s];!r.isUI||r.isInline?(r.isInline&&(i=!0),t.push(r)):console.warn("Block element can only contain Box elements.",r)}return t.length>0&&super.add(...t),i&&(this._children._needsUpdate=!0,this._layouter._needsProcess=!0),this}set textContent(e){this._textContent.value=e}get textContent(){return super.textContent}set invertAlpha(e){this._invertAlpha.value=e}get invertAlpha(){return this._invertAlpha._value}get lines(){return this._layouter._value}static definePropertiesValues(e,t){e.flexDirection=yie,e.justifyContent=LI,e.alignItems=DI,e.bounds=xie,e.autoSize=Sie,e.renderer=Cie,e.children||(e.children=wie),e.textContent||(e.textContent=fie),e.layouter||(e.layouter=mie),e.lineHeight||(e.lineHeight=bie),e.textAlign||(e.textAlign=gie),e.whiteSpace||(e.whiteSpace=rR),e.fontKerning||(e.fontKerning=_ie),e.segments||(e.segments=RG),t.width||(t.width="100%"),t.fontSide||(t.fontSide=0)}static init(e){Object.defineProperties(e,{isText:{configurable:!1,enumerable:!0,value:!0}})}}class Eie extends mi{constructor(){super("inlines",null,!1),this._value=[]}process(e){this._value[0].paddingLeft=e._padding._value.w,this._value[0].marginLeft=e._margin._value.w;const t=this._value.length-1;this._value[t].paddingRight=e._padding._value.y,this._value[t].marginRight=e._margin._value.y}}class Mie extends mi{constructor(){super("renderer")}render(e){e._backgroundMesh||e.setBackgroundMesh(new AG(e)),e._backgroundMesh.position.x=e._inlines._value[0].offsetX+e._inlines._value[0].width/2,e._backgroundMesh.position.y=e._inlines._value[0].offsetY+e._inlines._value[0].lineBase/2,e._bounds.render(e)}}class Tie extends mi{constructor(){super("bounds",null,!1),this._size=new ze.Vector3(1,1,1),this._offsetWidth=0,this._offsetHeight=0,this._innerWidth=0,this._innerHeight=0}update(e,t){this.output(t),this._needsProcess=!0}process(e){this._offsetWidth=this._innerWidth=e._inlines._value[0].width,this._offsetHeight=this._innerHeight=e._inlines._value[0].height,this._needsRender=!0,e._borderWidth._needsRender=!0,e._borderRadius._needsRender=!0}render(e){this._size.x=this._offsetWidth,this._size.y=this._offsetHeight}output(e){e.size=this._size}}class NA extends Ev{constructor(e={}){const t={};NA.definePropertiesValues(t,e),super(t,e),NA.init(this)}clear(){for(const e of this._inlines._value)e.clear();return super.clear()}bindBackgroundMeshProperties(){this._backgroundMesh.raycast=()=>{},this._bounds._size=this._backgroundMesh.scale,this._bounds._needsUpdate=!0}unbindBackgroundMeshProperties(){this._bounds._size=new ze.Vector3(1,1,1),this._bounds._needsUpdate=!0}add(e){const t=[];for(let i=0;i<arguments.length;i++){const s=arguments[i];s.isUI?console.warn("ThreeMeshUI::InlineBlockElement cannot contains UI Elements.",s):(t.push(s),s.position.z=.005)}return super.add(...t)}static definePropertiesValues(e,t){e.children||(e.children=PG),e.bounds||(e.bounds=Tie),e.inlines||(e.inlines=Eie),e.layouter||(e.layouter=bG),e.renderer||(e.renderer=Mie),e.fontFamily||(e.fontFamily=wG),e.fontWeight||(e.fontWeight=xG),e.fontStyle||(e.fontStyle=_G),e.fontSize||(e.fontSize=IG),e.backgroundColor||(e.backgroundColor=vz),e.lineBreak||(e.lineBreak=yG),e.letterSpacing||(e.letterSpacing=TG),e.whiteSpace||(e.whiteSpace=rR),e.fontKerning||(e.fontKerning=gw),t.backgroundSize||(t.backgroundSize="cover"),t.width||(t.width="100%"),t.height||(t.height="100%"),t.boxSizing||(t.boxSizing="border-box")}static init(e){Object.defineProperties(e,{isInline:{configurable:!1,enumerable:!0,value:!0},isInlineBlock:{configurable:!1,enumerable:!0,value:!0}}),e._inlines._value=[new Iie(e)],e.backgroundMaterial=new mG,e._renderer.render(e)}}class Iie extends Ez{constructor(e){super(),this._uiElement=e}get xadvance(){const e=this._uiElement._padding._value,t=this._uiElement._width;return t._relative?t._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):e.w+e.y+t.value}get width(){const e=this._uiElement._width;return e._relative?e._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):e.value}get height(){const e=this._uiElement._height;return e._relative?e._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):e.value}get anchor(){return this.height}get lineHeight(){const e=this._uiElement._height;return e._relative?e._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):e.value}get lineBase(){const e=this._uiElement._height;return e._relative?e._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):e.value}clear(){this._uiElement=null}}class BG{constructor(e){this._subject=e}attach(){console.error(`Behavior::attach() - Is abstract and therefore should be overridden in ${this.constructor.name}`)}act(){throw new Error(`Behavior::act() - Is abstract and therefore should be overridden in ${this.constructor.name}`)}detach(){console.error(`Behavior::detach() - Is abstract and therefore should be overridden in ${this.constructor.name}`)}clear(){}}const DG=()=>R_.update(),kG={BaseProperty:mi,Block:FA,Text:UA,Inline:Mp,InlineBlock:NA,MeshUIBaseElement:Ev,FontLibrary:od,update:DG,MSDFFontMaterialUtils:wo,ShaderChunkUI:pG,Behavior:BG,FontVariant:xv};typeof global<"u"&&(global.ThreeMeshUI=kG);const Rie=kG;var Pie=Cn.w8,OG=Cn.cg,oR=Cn.gO,Bie=Cn.wb,fM=Cn.zV,Die=Cn.HS,kie=Cn.Ec,Bb=Cn.gF,Oie=Cn.ol,Lie=Cn.pz,Fie=Cn.tx,Uie=Cn.hj,Nie=Cn.FV,zie=Cn.sV,LG=Cn.xv,Gie=Cn.mx,Hie=Cn.gE,Qie=Cn.ZP,FG=Cn.Vx;const OC=Object.freeze(Object.defineProperty({__proto__:null,BaseProperty:Pie,Behavior:OG,Block:oR,DefaultValues:Bie,FontLibrary:fM,FontVariant:Die,InheritableProperty:kie,Inline:Bb,InlineBlock:Oie,InlineGlyph:Lie,MSDFFontMaterialUtils:Fie,MaterialTransformers:Uie,MeshUIBaseElement:Nie,ShaderChunkUI:zie,Text:LG,TypographicFont:Gie,TypographicGlyph:Hie,default:Qie,update:FG},Symbol.toStringTag,{value:"Module"})),Vie=se("debugshadowcomponents");oR.prototype.interactable={get(){return this.interactive},set(n){this.interactable=n}};const Ga=Symbol("shadowDomOwner");class pa extends we{constructor(){super(...arguments);u(this,"shadowComponent",null);u(this,"_controlsChildLayout",!0);u(this,"_root");u(this,"_parentComponent")}isRoot(){var t;return((t=this.Root)==null?void 0:t.gameObject)===this.gameObject}get canvas(){const t=this.Root;return t!=null&&t.isCanvas?t:null}markDirty(){qs.markUIDirty(this.context)}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(t){this._controlsChildLayout=t,this.shadowComponent&&(this.shadowComponent.autoLayout=t)}get Root(){return this._root===void 0&&(this._root=$.getComponentInParent(this.gameObject,Mv)),this._root}get Canvas(){return this.canvas}__internalNewInstanceCreated(){super.__internalNewInstanceCreated(),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0}onEnable(){super.onEnable()}addShadowComponent(t,i){var o;this.removeShadowComponent();const s=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=$.getComponentInParent(s,pa),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}t.name=this.name+" ("+(this.constructor.name??"UI")+")",t.autoLayout=this._parentComponent.controlsChildLayout,t[Ga]=this,this.setShadowComponentOwner(t);let r=!1;if(((o=this.Root)==null?void 0:o.gameObject)===this.gameObject)this.gameObject.add(t);else{let a=this._parentComponent.shadowComponent;a&&(a==null||a.add(t),r=!0)}this.shadowComponent=t,i&&i.shadowComponent&&this.shadowComponent&&i.shadowComponent.add(this.shadowComponent),lv&&t.add(new Up(.5)),this.onAfterAddedToScene(),r&&FG(),Vie&&console.log(this.shadowComponent)}set(t){}setShadowComponentOwner(t){if(t&&(t[Ga]===void 0||t[Ga]===this)&&(t[Ga]=this,t.children))for(const i of t.children)this.setShadowComponentOwner(i)}traverseOwnedShadowComponents(t,i,s){if(t&&t[Ga]===i){s(t);for(const r of t.children)this.traverseOwnedShadowComponents(r,i,s)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(t){this.shadowComponent&&(this.shadowComponent.interactable=t)}}class Mv extends pa{awake(){super.awake()}}class Tp{static getObject(e){const t=e[Ga];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const i=this.tryFindCanvasGroup(e);if((i==null?void 0:i.isCanvasGroup)===!0&&(t&&(t.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const s=sd(e,r=>{if(r.isGraphic===!0)return r},!1);return t&&(s==null?void 0:s.isGraphic)===!0&&(t.graphic=s),!((s==null?void 0:s.raycastTarget)===!1||(s==null?void 0:s.layer)===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=sd(e,i=>{const s=i;if(s.blocksRaycasts!==void 0&&s.interactable!==void 0)return s},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}const gg=se("debugwebxrcontroller");var rp=(n=>(n[n.PhysicalDevice=0]="PhysicalDevice",n[n.Touch=1]="Touch",n))(rp||{}),Nl=(n=>(n.SelectStart="select-start",n.SelectEnd="select-end",n.Update="update",n))(Nl||{});class _w extends we{}const Wn=class extends we{constructor(){super(...arguments);u(this,"webXR");u(this,"index",-1);u(this,"controllerModel");u(this,"controller");u(this,"controllerGrip");u(this,"hand");u(this,"handPointerModel");u(this,"grabbed",null);u(this,"input",null);u(this,"type",0);u(this,"showRaycastLine",!0);u(this,"_wristQuaternion",null);u(this,"movementVector",new M);u(this,"worldRot",new Le);u(this,"joystick",new K);u(this,"didRotate",!1);u(this,"didTeleport",!1);u(this,"didChangeScale",!1);u(this,"lastHit",null);u(this,"raycastLine",null);u(this,"_raycastHitPoint",null);u(this,"_connnectedCallback",null);u(this,"_disconnectedCallback",null);u(this,"_selectStartEvt",null);u(this,"_selectEndEvt",null);u(this,"_selectionPressed",!1);u(this,"_selectionPressedLastFrame",!1);u(this,"_selectionStartTime",0);u(this,"_selectionEndTime",0);u(this,"_useSmoothing",!0);u(this,"_isConnected",!1);u(this,"rayRotation",new Le);u(this,"_pinchStartTime");u(this,"selectStartCallback",null);u(this,"lastSelectStartObject",null);u(this,"_didNotEndSelection",!1);u(this,"closeGrabBoundingBoxHelper")}static CreateRaycastLine(){const t=new an(this.geometry),i=t.material;return i.color=this.raycastColor,t.layers.set(2),t.name="line",t.scale.z=1,t}static CreateRaycastHitPoint(){const t=new No(.5,22,22),i=new fi({color:this.raycastColor}),s=new ye(t,i);return s.visible=!1,s.layers.set(2),s}static Create(t,i,s,r){const o=s?$.addNewComponent(s,Wn,!1):new Wn;o.webXR=t,o.index=i,o.type=r;const a=t.context;o.controller=a.renderer.xr.getController(i),o.controllerGrip=a.renderer.xr.getControllerGrip(i),o.controllerModel=this.Factory.createControllerModel(o.controller),o.controllerGrip.add(o.controllerModel),o.hand=a.renderer.xr.getHand(i);const l=new Wp;vv(l,a),o.webXR.handModelPath&&o.webXR.handModelPath!==""?l.setPath(Bh(t.sourceId,o.webXR.handModelPath)):l.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/");const c=new fZ(o.hand,l);return o.hand.add(c),o.hand.traverse(h=>h.layers.set(2)),o.handPointerModel=new bZ(o.hand,o.controller),o.controller.addEventListener("connected",h=>{o.setControllerLayers(o.controllerModel,2),o.setControllerLayers(o.controllerGrip,2),o.setControllerLayers(o.hand,2),setTimeout(()=>{o.setControllerLayers(o.controllerModel,2),o.setControllerLayers(o.controllerGrip,2),o.setControllerLayers(o.hand,2)},1e3)}),o.hand.addEventListener("connected",h=>{var f;if(h.data.hand){t.Rig&&t.Rig.add(o.hand),o.type=0,o.handPointerModel.traverse(m=>m.layers.set(2)),(f=o.handPointerModel.pointerObject)==null||f.traverse(m=>m.layers.set(2));const p=o.hand.joints;if(p)for(const m of Object.keys(p)){const A=p[m];A.parent||o.hand.add(A)}}}),o}static addEventListener(t,i){const s=this.eventSubs[t]??[];s.push(i),this.eventSubs[t]=s}static removeEventListener(t,i){if(!i)return;const s=this.eventSubs[t]??[],r=s.indexOf(i);r>=0&&s.splice(r,1),this.eventSubs[t]=s}get isUsingHands(){var i;const t=(i=this.input)==null?void 0:i.hand;return t!=null}get wrist(){if(!this.hand)return null;const t=this.hand.joints;return t?t.wrist:null}getWristQuaternion(){const t=this.wrist;return t?(this._wristQuaternion||(this._wristQuaternion=new Le),On(t).multiply(this._wristQuaternion.setFromEuler(new cs(-Math.PI/4,0,0)))):null}get selectionDown(){return this._selectionPressed&&!this._selectionPressedLastFrame}get selectionUp(){return!this._selectionPressed&&this._selectionPressedLastFrame}get selectionPressed(){return this._selectionPressed}get selectionClick(){return this._selectionEndTime-this._selectionStartTime<.3}get raycastHitPoint(){return this._raycastHitPoint}get useSmoothing(){return this._useSmoothing}awake(){if(!this.controller){console.warn("Missing Controller!!!",this);return}this._connnectedCallback=this.onSourceConnected.bind(this),this._disconnectedCallback=this.onSourceDisconnected.bind(this),this._selectStartEvt=this.onSelectStart.bind(this),this._selectEndEvt=this.onSelectEnd.bind(this),this.type===1&&(this.controllerGrip.addEventListener("connected",this._connnectedCallback),this.controllerGrip.addEventListener("disconnected",this._disconnectedCallback),this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt))}onDestroy(){var t,i,s;this.type===1&&(this.controllerGrip.removeEventListener("connected",this._connnectedCallback),this.controllerGrip.removeEventListener("disconnected",this._disconnectedCallback),this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),(t=this.hand)==null||t.clear(),(i=this.controllerGrip)==null||i.clear(),(s=this.controller)==null||s.clear()}onEnable(){var t,i,s,r,o;this.hand&&(this.hand.name="Hand"),this.controllerGrip&&(this.controllerGrip.name="ControllerGrip"),this.controller&&(this.controller.name="Controller"),this.raycastLine&&(this.raycastLine.name="RaycastLine;"),this.webXR.Controllers.indexOf(this)<0&&this.webXR.Controllers.push(this),this.raycastLine||(this.raycastLine=Wn.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=Wn.CreateRaycastHitPoint()),(t=this.webXR.Rig)==null||t.add(this.hand),(i=this.webXR.Rig)==null||i.add(this.controllerGrip),(s=this.webXR.Rig)==null||s.add(this.controller),(r=this.webXR.Rig)==null||r.add(this.raycastLine),(o=this.raycastLine)==null||o.add(this._raycastHitPoint),this._raycastHitPoint.visible=!1,this.hand.add(this.handPointerModel),gg&&console.log("ADDED TO RIG",this.webXR.Rig)}onDisable(){var i,s,r,o,a;(i=this.hand)==null||i.removeFromParent(),(s=this.controllerGrip)==null||s.removeFromParent(),(r=this.controller)==null||r.removeFromParent(),(o=this.raycastLine)==null||o.removeFromParent(),(a=this._raycastHitPoint)==null||a.removeFromParent();const t=this.webXR.Controllers.indexOf(this);t>=0&&this.webXR.Controllers.splice(t,1)}onSourceConnected(t){if(this._isConnected){console.warn("Received connected event for controller that is already connected",this.index,t);return}this._isConnected=!0,this.input=t.data,this.type===1&&(this.onSelectStart(),this.createPointerEvent("down"))}onSourceDisconnected(t){if(!this._isConnected){console.warn("Received discnnected event for controller that is not connected",t);return}this._isConnected=!1,this.type===1&&(this.onSelectEnd(),this.createPointerEvent("up")),this.input=null}createPointerEvent(t){switch(t){case"down":this.context.input.createPointerDown({clientX:0,clientY:0,button:this.index,pointerType:"touch"});break;case"move":break;case"up":this.context.input.createPointerUp({clientX:0,clientY:0,button:this.index,pointerType:"touch"});break}}raycastUpdate(t,i){const s=this.showRaycastLine&&this.type!==1;if(this.type===1)t.visible=!1;else if(this.isUsingHands){t.visible=!this.grabbed&&s,cn(t,i);const r=this.hand.joints;if(r&&r.wrist&&this.grabbed&&this.grabbed.isCloseGrab){const a=this.getWristQuaternion();a&&this.rayRotation.copy(a)}xr(t,this.rayRotation)}else t.visible=s,xr(t,this.rayRotation),cn(t,i)}update(){this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));const t=Wn.eventSubs.update;if(t&&t.length>0)for(const r of t)r(this);let i=1;this.type===0?i=this.context.time.deltaTime/.1:this.isUsingHands&&this.handPointerModel.pinched&&(i=this.context.time.deltaTime/.3),this.rayRotation.slerp(On(this.controller),this.useSmoothing?i:1);const s=xt(this.controller);this.isUsingHands&&this.handPointerModel.cursorObject&&(this.handPointerModel.cursorObject.visible=!1),this.raycastLine&&this.raycastUpdate(this.raycastLine,s),this.lastHit=this.updateLastHit(),this.grabbed&&this.grabbed.update(),this._selectionPressedLastFrame=this._selectionPressed,this.selectStartCallback&&this.selectStartCallback()}onUpdate(t){var r,o;if(this.lastHit=null,!t||t.inputSources.length<=this.index){this.input=null;return}if(this.type===0&&(this.input=t.inputSources[this.index]),!this.input)return;const i=this.webXR.Rig;if(!i)return;this._didNotEndSelection&&!this.handPointerModel.pinched&&(this._didNotEndSelection=!1,this.onSelectEnd()),this.updateStick(this.input);const s=(o=(r=this.input)==null?void 0:r.gamepad)==null?void 0:o.buttons;switch(this.input.handedness){case"left":this.movementUpdate(i,s);break;case"right":this.rotationUpdate(i,s);break}}movementUpdate(t,i){const s=3*Wn.MovementSpeedFactor,r=2,o=et.clamp01(this.joystick.length()*2),a=this.joystick.x>0?1:-1;let l=Math.pow(this.joystick.x,r);l*=a,l*=o;const c=this.joystick.y>0?1:-1;let h=Math.pow(this.joystick.y,r);h*=c,l*=o,t.getWorldQuaternion(this.worldRot),this.movementVector.set(l,0,h),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),this.movementVector.multiplyScalar(s*this.context.time.deltaTime),t.position.add(this.movementVector),this.isUsingHands&&this.runTeleport(t,i)}rotationUpdate(t,i){const s=this.joystick.x,r=Math.abs(s);if(r<.4)this.didRotate=!1;else if(r>.5&&!this.didRotate){const o=s>0?-1:1;t.rotateY(et.toRadians(30*o)),this.didRotate=!0}this.runTeleport(t,i)}runTeleport(t,i){var l,c,h;let s=-this.joystick.y;if((l=this.hand)!=null&&l.visible&&!this.grabbed){const d=this.handPointerModel.isPinched();d&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),d&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(s=this.handPointerModel.isPinched()?1:0),d||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;let r=s>.5&&this.webXR.IsInVR,o=this.webXR.Rig?((h=(c=this.webXR.Rig)==null?void 0:c.scale)==null?void 0:h.x)<.999:!1,a=null;if(i&&this.input&&!this.input.hand)for(let d=0;d<i.length;d++){const f=i[d];if(d===4)if(f.pressed&&!this.didChangeScale&&this.webXR.IsInVR){this.didChangeScale=!0;const p=this.webXR.Rig;if(p){let m=this.switchScale(p,r,o,a);r=m.doTeleport,o=m.isInMiniatureMode,a=m.newRigScale}}else f.pressed||(this.didChangeScale=!1)}if(r){if(!this.didTeleport){const d=this.raycast();if(this.didTeleport=!0,d&&d.length>0){const f=d[0];if(o||this.isValidTeleportTarget(f.object)){const p=f.point;cn(t,p)}}}}else s<.1&&(this.didTeleport=!1);a!==null&&(t.scale.set(a,a,a),t.updateMatrixWorld())}isValidTeleportTarget(t){return $.getComponentInParent(t,_w)!=null}switchScale(t,i,s,r){if(s){s=!1,t.scale.set(1,1,1),r=1,Wn.MovementSpeedFactor=1;const o=this.context.mainCamera;Wn.PreviousCameraFarDistance&&(o.far=Wn.PreviousCameraFarDistance)}else{s=!0,i=!0,r=.1,Wn.MovementSpeedFactor=r*2;const o=this.context.mainCamera;Wn.PreviousCameraFarDistance=o.far,o.far/=r}return{doTeleport:i,isInMiniatureMode:s,newRigScale:r}}updateStick(t){var i;!t||!t.gamepad||((i=t.gamepad.axes)==null?void 0:i.length)<4||(this.joystick.x=t.gamepad.axes[2],this.joystick.y=t.gamepad.axes[3])}updateLastHit(){var r;const t=this.raycast(),i=t?t[0]:null;this.lastHit=i;let s=1;if(this.webXR.Rig&&(s/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=s*(((r=this.lastHit)==null?void 0:r.distance)??9999);const o=this.raycastLine.material;i!=null?o.color=Wn.raycastColor:o.color=Wn.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;const o=et.clamp(this.lastHit.distance*.01*s,.015,.1);this._raycastHitPoint.scale.set(o,o,o)}this._raycastHitPoint.visible=this.lastHit!==null&&this.lastHit!==void 0}return i}onSelectStart(){this.context.connection.allowEditing&&(this.selectStartCallback=()=>this.onHandleSelectStart())}onHandleSelectStart(){this.selectStartCallback=null,this._selectionPressed=!0,this._selectionStartTime=this.context.time.time,this._selectionEndTime=1e3;let t=null,i=!1;if(this.isUsingHands?(t=this.overlap(),t.length<=0?(t=this.raycast(),i=!1):i=!0):t=this.raycast(),gg&&console.log("onHandleSelectStart","close grab? "+i,"intersections",t),t&&t.length>0)for(const s of t){const r=s.object;this.lastSelectStartObject=r;const o={selected:r,grab:r},a=Wn.eventSubs["select-start"];if(a&&a.length>0)for(const l of a)l(this,o);o.grab!==r&&gg&&console.log("Grabbed object changed","original",r,"new",o.grab),o.grab&&(this.grabbed=Po.TryTake(this,o.grab,s,i));break}else{const s=Wn.eventSubs["select-start"],r={selected:null,grab:null};if(s&&s.length>0)for(const o of s)o(this,r)}}onSelectEnd(){var s;if(this.isUsingHands&&this.handPointerModel.pinched){this._didNotEndSelection=!0;return}if(!this._selectionPressed)return;this.selectStartCallback=null,this._selectionPressed=!1,this._selectionEndTime=this.context.time.time;const t={grab:((s=this.grabbed)==null?void 0:s.selected)??this.lastSelectStartObject},i=Wn.eventSubs["select-end"];if(i&&i.length>0)for(const r of i)r(this,t);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(t){return!(!t||$.isActiveInHierarchy(t)===!1||Tp.isInteractable(t)===!1)}setControllerLayers(t,i){var s,r;if(t&&(t.layers.set(i),t.children))for(const o of t.children)((s=this.grabbed)==null?void 0:s.selected)===o||((r=this.grabbed)==null?void 0:r.selectedMesh)===o||this.setControllerLayers(o,i)}getRay(){const t=new ol;return t.origin.copy(xt(this.controller)),t.direction.set(0,0,-1).applyQuaternion(this.rayRotation),t}overlap(){const t=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(gg&&(!this.closeGrabBoundingBoxHelper&&t&&(this.closeGrabBoundingBoxHelper=new Bx(t,16776960),this.scene.add(this.closeGrabBoundingBoxHelper)),this.closeGrabBoundingBoxHelper&&t&&this.closeGrabBoundingBoxHelper.setFromObject(t)),!t)return new Array;const i=xt(t).clone();return this.context.physics.sphereOverlap(i,.02)}raycast(){const t=new Aa;t.layerMask=new Lo,t.layerMask.enableAll(),t.layerMask.disable(2),t.ray=this.getRay();const i=this.context.physics.raycast(t);for(let s=0;s<i.length;s++){const r=i[s],o=r.object;if(!this.testIsVisible(o)){i.splice(s,1),s--;continue}r.object=Tp.getObject(o);break}return i}};let Ji=Wn;u(Ji,"Factory",new BZ),u(Ji,"raycastColor",new ve(.9,.3,.3)),u(Ji,"raycastNoHitColor",new ve(.6,.6,.6)),u(Ji,"geometry",new wt().setFromPoints([new M(0,0,0),new M(0,0,-1)])),u(Ji,"handModels",{}),u(Ji,"eventSubs",{}),u(Ji,"PreviousCameraFarDistance"),u(Ji,"MovementSpeedFactor",1);var B_=(n=>(n.WillTake="WillTake",n.DidTake="DidTake",n.WillFree="WillFree",n.DidFree="DidFree",n))(B_||{});const Ns=class{constructor(){u(this,"sync",null);u(this,"selected",null);u(this,"selectedParent",null);u(this,"selectedMesh",null);u(this,"controller",null);u(this,"grabTime",0);u(this,"grabUUID","");u(this,"isCloseGrab",!1);u(this,"originalMaterial",null);u(this,"usageMarker",null);u(this,"rigidbodies",null);u(this,"didReparent",!1);u(this,"grabDistance",0);u(this,"interactable",null);u(this,"positionSource",null);u(this,"grabPoint",new M);u(this,"localPositionOffsetToGrab",null);u(this,"localPositionOffsetToGrab_worldSpace",new M);u(this,"localQuaternionToGrab",new Le(0,0,0,1));u(this,"targetDir",null);u(this,"quaternionLerp",null);u(this,"controllerDir",new M);u(this,"controllerWorldPos",new M);u(this,"lastControllerWorldPos",new M);u(this,"controllerPosDelta",new M);u(this,"totalChangeAlongDirection",0);u(this,"rigPositionLastFrame",new M)}static AddEventListener(e,t){return Ns.Events[e]||(Ns.Events[e]=[]),Ns.Events[e].push(t),t}static RemoveEventListener(e,t){if(!t||!Ns.Events[e])return;const i=Ns.Events[e].indexOf(t);i>=0&&Ns.Events[e].splice(i,1)}static Register(e){this.Current.find(t=>t===e)||this.Current.push(e)}static Remove(e){const t=this.Current.indexOf(e);t>=0&&this.Current.splice(t,1)}static TryTake(e,t,i,s){const r=$.getComponentInParent(t,qp);if(r)t=r.gameObject;else return gg&&console.warn("Prevented taking object that is not interactable",t),null;let o=t;const a=$.getComponentInParent(t,Th);a&&(a.requestOwnership(),o=a.gameObject);for(const c of this.Current)if(c.selected===o)return c.controller===e||(c.free(),c.Take(e,o,t,a,r,i,s)),c;const l=new Ns;return l.Take(e,o,t,a,r,i,s),l}Take(e,t,i,s,r,o,a){var p,m;if(console.assert(t!==null,"Expected object to be taken but was",t),e.isUsingHands?this.positionSource=a?e.wrist:e.controller:this.positionSource=e.controller,!this.positionSource)return console.warn("No position source"),this;const l={controller:e,take:t,hit:i,sync:s,interactable:r};(p=Ns.Events.WillTake)==null||p.forEach(A=>A(this,l));const c=i;c!=null&&c.material&&(this.originalMaterial=c.material,Array.isArray(c.material)||(c.material=c.material.clone(),c.material&&c.material.emissive&&(c.material.emissive.b=.2))),this.selected=t,this.selectedParent||(this.selectedParent=t.parent),this.selectedMesh=c,this.controller=e,this.interactable=r,this.isCloseGrab=a,this.didReparent=!1,this.sync=s,this.grabTime=e.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=$.addNewComponent(this.selected,Yp),this.rigidbodies=$.getComponentsInChildren(this.selected,ji),xt(this.positionSource,this.lastControllerWorldPos);const h=()=>a?this.lastControllerWorldPos.clone():o.point.clone();this.grabDistance=h().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(h());const d=e.isUsingHands&&a?this.controller.getWristQuaternion().clone():e.rayRotation.clone();On(this.selected,this.localQuaternionToGrab).premultiply(d.invert());const f=this.controller.webXR.Rig;return f&&this.rigPositionLastFrame.copy(xt(f)),Js.Add(e.context,this.selected),Ns.Register(this),this.sync&&(this.sync.fastMode=!0),(m=Ns.Events.DidTake)==null||m.forEach(A=>A(this,l)),this}free(){var s,r,o,a;if(!this.selected)return;const e={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};(s=Ns.Events.WillFree)==null||s.forEach(l=>l(this,e)),Js.Remove(this.controller.context,this.selected),Ns.Remove(this),this.sync&&(this.sync.fastMode=!1);const t=this.selectedMesh;t&&this.originalMaterial&&t.material&&(t.material=this.originalMaterial);const i=this.selected;if(this.didReparent&&i.parent){const l=this.selectedParent;l?l.attach(i):(r=this.controller)==null||r.context.scene.attach(i)}if((o=this.usageMarker)==null||o.destroy(),this.controller&&(this.controller.grabbed=null),this.selected=null,this.selectedParent=null,this.selectedMesh=null,this.sync=null,this.rigidbodies)for(const l of this.rigidbodies)l.wakeUp(),l.setVelocity(l.smoothedVelocity);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,(a=Ns.Events.DidFree)==null||a.forEach(l=>l(this,e))}controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),xt(this.positionSource,this.controllerWorldPos),this.controllerPosDelta.copy(this.controllerWorldPos),this.controllerPosDelta.sub(this.lastControllerWorldPos),this.lastControllerWorldPos.copy(this.controllerWorldPos);const e=this.controller.webXR.Rig;if(e){const i=xt(e),s=this.rigPositionLastFrame.sub(i);this.controllerPosDelta.add(s),this.rigPositionLastFrame.copy(i)}return this.controllerDir.dot(this.controllerPosDelta)}update(){var e;if(this.rigidbodies)for(const t of this.rigidbodies)t.resetVelocities();if(this.sync&&this.controller&&this.controller.context.connection.isInRoom&&this.controller.context.time.time-this.grabTime>3&&this.sync.hasOwnership()===!1&&(console.log("no ownership, will leave",this.sync.guid),this.free()),!(this.interactable&&!this.interactable.canGrab)){if(!this.didReparent&&this.selected&&this.controller){const t=((e=this.controller.webXR.Rig)==null?void 0:e.scale.x)??1;this.totalChangeAlongDirection+=this.controllerMovementSinceLastFrame();let i=1;this.controller.type===0&&(i=Math.max(0,1+this.totalChangeAlongDirection*2/t),i=i*i*i),this.grabDistance/t<.8&&(i=1),this.targetDir||(this.targetDir=new M),this.targetDir.set(0,0,-this.grabDistance*i);const s=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),r=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=r.clone()),this.quaternionLerp.slerp(r,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),xr(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(s),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(xt(this.selected)),s.sub(this.localPositionOffsetToGrab_worldSpace)),cn(this.selected,s)}if(this.rigidbodies!=null)for(const t of this.rigidbodies)t.wakeUp();Ar.markDirty(this.selected,!0)}}};let Po=Ns;u(Po,"Events",{}),u(Po,"Current",[]);var Wie=Object.defineProperty,jie=Object.getOwnPropertyDescriptor,aR=(n,e,t,i)=>{for(var s=i>1?void 0:i?jie(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&&Wie(e,t,s),s};class md extends we{constructor(){super(...arguments);u(this,"objectBounds",!1);u(this,"color");u(this,"isGizmo",!0);u(this,"_gizmoObject",null);u(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!lv||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new Bx(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=K3(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),Yr.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){var t;for(;this._boxHelper;)(t=this._boxHelper)==null||t.update(),yield}}aR([w()],md.prototype,"objectBounds",2);aR([w(ve)],md.prototype,"color",2);aR([w()],md.prototype,"isGizmo",2);const Xie=se("debugrig");class xw extends we{awake(){if(Xie){const e=new ke;e.position.y+=.5,this.gameObject.add(e);const t=e.addNewComponent(md);t&&(t.isGizmo=!1)}}}class op{constructor(){u(this,"bb",null);u(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)}w(){return this.bb.readFloat32(this.bb_pos+12)}static sizeOf(){return 16}static createVec4(e,t,i,s,r){return e.prep(4,16),e.writeFloat32(r),e.writeFloat32(s),e.writeFloat32(i),e.writeFloat32(t),e.offset()}}class Ts{constructor(){u(this,"bb",null);u(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsVrUserStateBuffer(e,t){return(t||new Ts).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+Hx),(t||new Ts).__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}time(){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}avatarId(e){const t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__string(this.bb_pos+t,e):null}position(e){const t=this.bb.__offset(this.bb_pos,10);return t?(e||new jr).__init(this.bb_pos+t,this.bb):null}rotation(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new op).__init(this.bb_pos+t,this.bb):null}scale(){const e=this.bb.__offset(this.bb_pos,14);return e?this.bb.readFloat32(this.bb_pos+e):0}posLeftHand(e){const t=this.bb.__offset(this.bb_pos,16);return t?(e||new jr).__init(this.bb_pos+t,this.bb):null}posRightHand(e){const t=this.bb.__offset(this.bb_pos,18);return t?(e||new jr).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){const t=this.bb.__offset(this.bb_pos,20);return t?(e||new op).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){const t=this.bb.__offset(this.bb_pos,22);return t?(e||new op).__init(this.bb_pos+t,this.bb):null}static startVrUserStateBuffer(e){e.startObject(10)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addTime(e,t){e.addFieldInt64(1,t,e.createLong(0,0))}static addAvatarId(e,t){e.addFieldOffset(2,t,0)}static addPosition(e,t){e.addFieldStruct(3,t,0)}static addRotation(e,t){e.addFieldStruct(4,t,0)}static addScale(e,t){e.addFieldFloat32(5,t,0)}static addPosLeftHand(e,t){e.addFieldStruct(6,t,0)}static addPosRightHand(e,t){e.addFieldStruct(7,t,0)}static addRotLeftHand(e,t){e.addFieldStruct(8,t,0)}static addRotRightHand(e,t){e.addFieldStruct(9,t,0)}static endVrUserStateBuffer(e){return e.endObject()}static finishVrUserStateBufferBuffer(e,t){e.finish(t)}static finishSizePrefixedVrUserStateBufferBuffer(e,t){e.finish(t,void 0,!0)}}const nk=se("debugxr"),jm=se("debugavatar"),lR="VRUS";jT(lR,Ts.getRootAsVrUserStateBuffer);function pM(){return new Date().getTime()}function qie(n){let e=n&4294967295,t=n/Math.pow(2,32)&1048575;return Ka.create(e,t)}const oA=class{constructor(e){u(this,"guid");u(this,"time");u(this,"avatarId");u(this,"position",new M);u(this,"rotation",new At);u(this,"scale",1);u(this,"posLeftHand",new M);u(this,"posRightHand",new M);u(this,"rotLeftHand",new Le);u(this,"rotRightHand",new Le);this.guid=e}update(e,t,i,s,r){var h,d,f,p,m,A;this.time=pM(),this.avatarId=r,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let o=oA.quat0;const a=oA.quat1;o.set(i.x,i.y,i.z,i.w),o=o.multiplyQuaternions(o,oA.invertRotation),e&&(e.getWorldQuaternion(a),o.multiplyQuaternions(a,o)),this.rotation.set(o.x,o.y,o.z,o.w),this.scale=e.scale.x;const l=(h=s.LeftController)==null?void 0:h.controllerGrip;l&&(l.getWorldPosition(this.posLeftHand),l.getWorldQuaternion(this.rotLeftHand));const c=(d=s.RightController)==null?void 0:d.controllerGrip;if(c&&(c.getWorldPosition(this.posRightHand),c.getWorldQuaternion(this.rotRightHand)),(p=(f=s.LeftController)==null?void 0:f.hand)!=null&&p.visible){const v=s.LeftController.wrist;v&&(v.getWorldPosition(this.posLeftHand),v.getWorldQuaternion(this.rotLeftHand))}if((A=(m=s.RightController)==null?void 0:m.hand)!=null&&A.visible){const v=s.RightController.wrist;v&&(v.getWorldPosition(this.posRightHand),v.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(e,t){e.clear();const i=e.createString(this.guid),s=e.createString(this.avatarId);Ts.startVrUserStateBuffer(e),Ts.addGuid(e,i),Ts.addTime(e,qie(this.time)),Ts.addAvatarId(e,s),Ts.addPosition(e,jr.createVec3(e,this.position.x,this.position.y,this.position.z)),Ts.addRotation(e,op.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),Ts.addScale(e,this.scale),Ts.addPosLeftHand(e,jr.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),Ts.addPosRightHand(e,jr.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),Ts.addRotLeftHand(e,op.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),Ts.addRotRightHand(e,op.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));const r=Ts.endVrUserStateBuffer(e);e.finish(r,lR);const o=e.asUint8Array();t.sendBinary(o)}setFromBuffer(e,t){if(!e)return;this.guid=e,this.time=t.time().toFloat64();const i=t.avatarId();i&&(this.avatarId=i);const s=t.position();s&&this.position.set(s.x(),s.y(),s.z());const r=t.rotation();r&&this.rotation.set(r.x(),r.y(),r.z(),r.w());const o=t.posLeftHand();o&&this.posLeftHand.set(o.x(),o.y(),o.z());const a=t.posRightHand();a&&this.posRightHand.set(a.x(),a.y(),a.z());const l=t.rotLeftHand();l&&this.rotLeftHand.set(l.x(),l.y(),l.z(),l.w());const c=t.rotRightHand();c&&this.rotRightHand.set(c.x(),c.y(),c.z(),c.w()),this.scale=t.scale()}};let aa=oA;u(aa,"invertRotation",new Le().setFromAxisAngle(new M(0,1,0),Math.PI)),u(aa,"quat0",new Le),u(aa,"quat1",new Le);class zA extends we{constructor(){super(...arguments);u(this,"webXR",null);u(this,"debugAvatarUser",null);u(this,"voip",null);u(this,"tempState",new aa(""));u(this,"_removeAvatarsList",[]);u(this,"eventSub_ConnectionEvent",null);u(this,"eventSub_WebXRStartEvent",null);u(this,"eventSub_WebXREndEvent",null);u(this,"eventSub_WebXRUpdateEvent",null);u(this,"avatars",{});u(this,"localAvatar",null);u(this,"k_LocalAvatarNoNetworkingGuid","local");u(this,"ownership",null);u(this,"xrState",null);u(this,"builder",new Np(1024))}async awake(){if(this.webXR||(this.webXR=$.getComponent(this.gameObject,St)),this.webXR||(this.webXR=$.findObjectOfType(St,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=$.findObjectOfType(St,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=$.findObjectOfType(yc,this.context)),jm){const t="debug-avatar-"+jm,i=new qa(this.context,t,this.webXR);if(this.debugAvatarUser=i,typeof jm=="string"&&jm.length>0)if(await i.setAvatarOverride(jm)){const s=new aa(t);s.position.y+=1;const r=.5;s.posLeftHand.y+=r,s.posLeftHand.x+=r,s.posRightHand.y+=r,s.posRightHand.x-=r,i.tryUpdate(s,0)}else i.destroy()}}onEnable(){if(!this.webXR&&(this.webXR=$.getComponent(this.gameObject,St),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),St.addEventListener(xi.XRStarted,this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),St.addEventListener(xi.XRUpdate,this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),St.addEventListener(xi.XRStopped,this.eventSub_WebXREndEvent),this.eventSub_ConnectionEvent=this.onConnected.bind(this),this.context.connection.beginListen($i.JoinedRoom,this.eventSub_ConnectionEvent),this.context.connection.beginListen("webxr-user-joined",t=>{console.log("webxr user joined evt")}),this.context.connection.beginListen("webxr-user-left",t=>{const i=t.id!==null&&t.id!==void 0;if(i&&(console.log("webxr user left evt"),i)){const s=this.avatars[t.id];s==null||s.destroy(),this.avatars[t.id]=void 0}}),this.context.connection.beginListenBinary(lR,t=>{const i=t.guid();if(!i)return;const s=t.time().toFloat64(),r=this.tempState;r.setFromBuffer(i,t);const o=this.onTryGetAvatar(i,s);o==null||o.tryUpdate(r,s)}),this.context.connection.beginListen("vr-session-update",t=>{const i=t.guid,s=t.time,r=this.onTryGetAvatar(i,s);r==null||r.tryUpdate(t,s)})}onTryGetAvatar(t,i){if(t===this.context.connection.connectionId)return null;const s=new Date().getTime()-i;if(s>5e3)return nk&&console.log("old data",s,t),null;let r=this.avatars[t];if(r===void 0)try{console.log("create new avatar");const o=new qa(this.context,t,this.webXR);r=o,this.avatars[t]=o}catch(o){this.avatars[t]=null,console.error(o)}return r}onDisable(){this.eventSub_ConnectionEvent&&this.context.connection.stopListen($i.JoinedRoom,this.eventSub_ConnectionEvent),St.removeEventListener(xi.XRStarted,this.eventSub_WebXRStartEvent),St.removeEventListener(xi.XRUpdate,this.eventSub_WebXRUpdateEvent),St.removeEventListener(xi.XRStopped,this.eventSub_WebXREndEvent)}update(){const t=pM();this.debugAvatarUser&&(this.debugAvatarUser.lastUpdate=t),this.detectPotentiallyDisconnectedAvatarsAndRemove();for(const i in this.avatars){const s=this.avatars[i];s&&s.update()}}detectPotentiallyDisconnectedAvatarsAndRemove(){const t=pM();for(const i in this.avatars){const s=this.avatars[i];if(!s){this._removeAvatarsList.push(i);continue}t-s.lastUpdate>1e4&&(console.log("avatar timed out (didnt receive any updates in a while) - destroying it now"),s.destroy(),this.avatars[i]=void 0)}for(const i of this._removeAvatarsList)delete this.avatars[i];this._removeAvatarsList.length=0}buildLocalAvatar(){var i;if(this.localAvatar)return;const t=((i=this.context.connection)==null?void 0:i.connectionId)??this.k_LocalAvatarNoNetworkingGuid;this.localAvatar=new qa(this.context,t,this.webXR),this.localAvatar.isLocalAvatar=!0,this.localAvatar.setAvatarOverride(this.getAvatarId()),this.avatars[this.localAvatar.guid]=this.localAvatar}onConnected(){var t,i,s;nk&&console.log("Hey you are connected as "+this.context.connection.connectionId),((t=this.localAvatar)==null?void 0:t.guid)===this.k_LocalAvatarNoNetworkingGuid&&(this.localAvatar&&((i=this.localAvatar)==null||i.destroy(),this.avatars[this.localAvatar.guid]=void 0),this.localAvatar=null,this.xrState=null,(s=this.ownership)==null||s.freeOwnership(),this.ownership=null)}onXRSessionStart(t){var i,s,r;if(console.log("XR session started"),this.context.connection.send("webxr-user-joined",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&((i=this.localAvatar)==null||i.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null),this.xrState=null,(s=this.ownership)==null||s.freeOwnership(),this.ownership=null,this.avatars)for(const o in this.avatars)(r=this.avatars[o])==null||r.updateFlags()}onXRSessionEnded(t){var i;console.log("XR session ended"),this.context.connection.send("webxr-user-left",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&((i=this.localAvatar)==null||i.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null)}onXRSessionUpdate(t){this.xrState??(this.xrState=new aa(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid)),this.ownership??(this.ownership=new Vx(this.context.connection,this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid)),this.ownership.guid=this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid,this.buildLocalAvatar();const{frame:i,xr:s,rig:r}=t,o=i.getViewerPose(s.getReferenceSpace());if(!o)return;const a=o==null?void 0:o.transform,l=a.position,c=a.orientation;this.xrState.update(r,l,c,this.webXR,this.getAvatarId()),this.localAvatar&&(this.context.connection.connectionId&&(this.localAvatar.guid=this.context.connection.connectionId),this.localAvatar.tryUpdate(this.xrState,0)),!(this.ownership&&!this.ownership.hasOwnership&&this.context.connection.isConnected&&(this.context.time.frameCount%120===0&&this.ownership.requestOwnership(),!this.ownership.hasOwnership))&&(!this.context.connection.isConnected||!this.context.connection.connectionId||this.xrState.sendAsBuffer(this.builder,this.context.connection))}getAvatarId(){return se("avatar")??null}}var Yie=Object.defineProperty,Kie=Object.getOwnPropertyDescriptor,$p=(n,e,t,i)=>{for(var s=i>1?void 0:i?Kie(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&&Yie(e,t,s),s};const LC=se("debugwebxr");async function UG(){return Yb()?!0:"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function NG(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}let Ag=!1,vg=!1;UG().then(n=>Ag=n);NG().then(n=>vg=n);var xi=(n=>(n.XRStarted="xrStarted",n.XRStopped="xrStopped",n.XRUpdate="xrUpdate",n.RequestVRSession="requestVRSession",n.ModifyAROptions="modify-ar-options",n))(xi||{}),Tf;const Pn=(Tf=class extends we{constructor(){super(...arguments);u(this,"enableVR",!0);u(this,"enableAR",!0);u(this,"defaultAvatar");u(this,"handModelPath","");u(this,"createVRButton",!0);u(this,"createARButton",!0);u(this,"controllers",[]);u(this,"rig");u(this,"isInit",!1);u(this,"_requestedAR",!1);u(this,"_requestedVR",!1);u(this,"_isInAR",!1);u(this,"_isInVR",!1);u(this,"_arButton");u(this,"_vrButton");u(this,"webAR",null);u(this,"_transformOrientation",new Le);u(this,"_currentHeadPose",null);u(this,"_originalCameraParent",null);u(this,"_originalCameraPosition",new M);u(this,"_originalCameraRotation",new Le);u(this,"_originalXRRigParent",null);u(this,"_originalXRRigPosition",new M);u(this,"_originalXRRigRotation",new Le);u(this,"xrMirrorWindow",null)}static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(Ag||vg)}static get IsARSupported(){return Ag}static get IsVRSupported(){return vg}static get OptionalFeatures_VR(){return this._optionalFeatures_VR}static get OptionalFeatures_AR(){return this._optionalFeatures_AR}static addEventListener(e,t){return this.events.addEventListener(e,t),t}static removeEventListener(e,t){return this.events.removeEventListener(e,t),t}static dispatchEvent(e,t){this.events.dispatchEvent({type:e,detail:t})}static createVRButton(e,t){Pn.XRSupported?e.__internalAwake():console.warn("WebXR is not supported on this device");const i={optionalFeatures:Pn.OptionalFeatures_VR},s=jg.createButton(e.context.renderer,i);return s.classList.add("webxr-ar-button"),s.classList.add("webxr-button"),this.resetButtonStyles(s),((t==null?void 0:t.registerClick)??!0)&&s.addEventListener("click",e.onClickedVRButton.bind(e)),s}static createARButton(e,t){var o;e.__internalAwake();const i=(o=e.webAR)==null?void 0:o.getAROverlayContainer(),s={optionalFeatures:[...this.OptionalFeatures_AR]};i?(s.domOverlay={root:i},s.optionalFeatures.push("dom-overlay"),s.optionalFeatures.push("hit-test")):console.warn("No dom overlay root found, HTML overlays on top of screen-based AR will not work.");const r=iZ.createButton(e.context.renderer,s,this.onModifyAROptions.bind(this));return r.classList.add("webxr-ar-button"),r.classList.add("webxr-button"),Pn.resetButtonStyles(r),((t==null?void 0:t.registerClick)??!0)&&r.addEventListener("click",e.onClickedARButton.bind(e)),r}static onModifyAROptions(e){Pn.dispatchEvent("modify-ar-options",e)}static resetButtonStyles(e){e&&(e.style.position="",e.style.bottom="",e.style.left="")}endSession(){const e=this.context.renderer.xr.getSession();e&&e.end()}get Rig(){return this.rig||this.ensureRig(),this.rig}get Controllers(){return this.controllers}get LeftController(){var e,t;return this.controllers.length>0&&((e=this.controllers[0].input)==null?void 0:e.handedness)==="left"?this.controllers[0]:this.controllers.length>1&&((t=this.controllers[1].input)==null?void 0:t.handedness)==="left"?this.controllers[1]:null}get RightController(){var e,t;return this.controllers.length>0&&((e=this.controllers[0].input)==null?void 0:e.handedness)==="right"?this.controllers[0]:this.controllers.length>1&&((t=this.controllers[1].input)==null?void 0:t.handedness)==="right"?this.controllers[1]:null}get ARButton(){return this._arButton}get VRButton(){return this._vrButton}get IsInVR(){return this._isInVR}get IsInAR(){return this._isInAR}awake(){if(this.defaultAvatar&&typeof this.defaultAvatar=="string"&&(this.defaultAvatar=Kn.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!$.findObjectOfType(zA,this.context)){const e=$.addNewComponent(this.gameObject,zA,!1);e.webXR=this}this.webAR=new Ku(this)}start(){location.protocol=="http:"&&location.host.indexOf("localhost")<0&&(Fo("WebXR only works on https"),console.warn("WebXR only works on https. https://engine.needle.tools/docs/xr.html"))}onEnable(){if(this.isInit||!this.enableAR&&!this.enableVR)return;this.isInit=!0,this.context.renderer.xr.enabled=!0,Pn.XRSupported;let e,t;const i=document.createElement("div");i.classList.add("webxr-buttons"),i.style.cssText=`
5010
5010
  position: fixed;
5011
5011
  bottom: 21px;
5012
5012
  left: 50%;