@needle-tools/engine 3.6.0-alpha → 3.6.0-alpha.2

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.
@@ -3333,11 +3333,11 @@ a=extmap-allow-mixed`)!==-1){const I=g.sdp.split(`
3333
3333
  isUnifiedPlanSupported:`).concat(this.isUnifiedPlanSupported())},i}()),JN={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:["turn:eu-0.turn.peerjs.com:3478","turn:us-0.turn.peerjs.com:3478"],username:"peerjs",credential:"peerjsp"}],sdpSemantics:"unified-plan"},jV=function(){function i(){this.CLOUD_HOST="0.peerjs.com",this.CLOUD_PORT=443,this.chunkedBrowsers={Chrome:1,chrome:1},this.chunkedMTU=16300,this.defaultConfig=JN,this.browser=dc.getBrowser(),this.browserVersion=dc.getVersion(),this.supports=function(){var A={browser:dc.isBrowserSupported(),webRTC:dc.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!A.webRTC)return A;var e;try{e=new RTCPeerConnection(JN),A.audioVideo=!0;var t=void 0;try{t=e.createDataChannel("_PEERJSTEST",{ordered:!0}),A.data=!0,A.reliable=!!t.ordered;try{t.binaryType="blob",A.binaryBlob=!dc.isIOS}catch{}}catch{}finally{t&&t.close()}}catch{}finally{e&&e.close()}return A}(),this.pack=yN.pack,this.unpack=yN.unpack,this._dataCount=1}return i.prototype.noop=function(){},i.prototype.validateId=function(A){return!A||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(A)},i.prototype.chunk=function(A){for(var e=[],t=A.size,g=Math.ceil(t/Qt.chunkedMTU),I=0,o=0;o<t;){var C=Math.min(t,o+Qt.chunkedMTU),s=A.slice(o,C),n={__peerData:this._dataCount,n:I,data:s,total:g};e.push(n),o=C,I++}return this._dataCount++,e},i.prototype.blobToArrayBuffer=function(A,e){var t=new FileReader;return t.onload=function(g){g.target&&e(g.target.result)},t.readAsArrayBuffer(A),t},i.prototype.binaryStringToArrayBuffer=function(A){for(var e=new Uint8Array(A.length),t=0;t<A.length;t++)e[t]=A.charCodeAt(t)&255;return e.buffer},i.prototype.randomToken=function(){return Math.random().toString(36).slice(2)},i.prototype.isSecure=function(){return location.protocol==="https:"},i}(),Qt=new jV,vv={};zC(vv,"Peer",()=>PN,i=>PN=i);var Wl={},zV=Object.prototype.hasOwnProperty,$g="~";function Ph(){}Object.create&&(Ph.prototype=Object.create(null),new Ph().__proto__||($g=!1));function ZV(i,A,e){this.fn=i,this.context=A,this.once=e||!1}function xv(i,A,e,t,g){if(typeof e!="function")throw new TypeError("The listener must be a function");var I=new ZV(e,t||i,g),o=$g?$g+A:A;return i._events[o]?i._events[o].fn?i._events[o]=[i._events[o],I]:i._events[o].push(I):(i._events[o]=I,i._eventsCount++),i}function FD(i,A){--i._eventsCount===0?i._events=new Ph:delete i._events[A]}function Rg(){this._events=new Ph,this._eventsCount=0}Rg.prototype.eventNames=function(){var A=[],e,t;if(this._eventsCount===0)return A;for(t in e=this._events)zV.call(e,t)&&A.push($g?t.slice(1):t);return Object.getOwnPropertySymbols?A.concat(Object.getOwnPropertySymbols(e)):A};Rg.prototype.listeners=function(A){var e=$g?$g+A:A,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var g=0,I=t.length,o=new Array(I);g<I;g++)o[g]=t[g].fn;return o};Rg.prototype.listenerCount=function(A){var e=$g?$g+A:A,t=this._events[e];return t?t.fn?1:t.length:0};Rg.prototype.emit=function(A,e,t,g,I,o){var C=$g?$g+A:A;if(!this._events[C])return!1;var s=this._events[C],n=arguments.length,a,B;if(s.fn){switch(s.once&&this.removeListener(A,s.fn,void 0,!0),n){case 1:return s.fn.call(s.context),!0;case 2:return s.fn.call(s.context,e),!0;case 3:return s.fn.call(s.context,e,t),!0;case 4:return s.fn.call(s.context,e,t,g),!0;case 5:return s.fn.call(s.context,e,t,g,I),!0;case 6:return s.fn.call(s.context,e,t,g,I,o),!0}for(B=1,a=new Array(n-1);B<n;B++)a[B-1]=arguments[B];s.fn.apply(s.context,a)}else{var Q=s.length,E;for(B=0;B<Q;B++)switch(s[B].once&&this.removeListener(A,s[B].fn,void 0,!0),n){case 1:s[B].fn.call(s[B].context);break;case 2:s[B].fn.call(s[B].context,e);break;case 3:s[B].fn.call(s[B].context,e,t);break;case 4:s[B].fn.call(s[B].context,e,t,g);break;default:if(!a)for(E=1,a=new Array(n-1);E<n;E++)a[E-1]=arguments[E];s[B].fn.apply(s[B].context,a)}}return!0};Rg.prototype.on=function(A,e,t){return xv(this,A,e,t,!1)};Rg.prototype.once=function(A,e,t){return xv(this,A,e,t,!0)};Rg.prototype.removeListener=function(A,e,t,g){var I=$g?$g+A:A;if(!this._events[I])return this;if(!e)return FD(this,I),this;var o=this._events[I];if(o.fn)o.fn===e&&(!g||o.once)&&(!t||o.context===t)&&FD(this,I);else{for(var C=0,s=[],n=o.length;C<n;C++)(o[C].fn!==e||g&&!o[C].once||t&&o[C].context!==t)&&s.push(o[C]);s.length?this._events[I]=s.length===1?s[0]:s:FD(this,I)}return this};Rg.prototype.removeAllListeners=function(A){var e;return A?(e=$g?$g+A:A,this._events[e]&&FD(this,e)):(this._events=new Ph,this._eventsCount=0),this};Rg.prototype.off=Rg.prototype.removeListener;Rg.prototype.addListener=Rg.prototype.on;Rg.prefixed=$g;Rg.EventEmitter=Rg;Wl=Rg;var ge={};zC(ge,"LogLevel",()=>rI,i=>rI=i);zC(ge,"default",()=>qN,i=>qN=i);var $a=function(i,A){var e=typeof Symbol=="function"&&i[Symbol.iterator];if(!e)return i;var t=e.call(i),g,I=[],o;try{for(;(A===void 0||A-- >0)&&!(g=t.next()).done;)I.push(g.value)}catch(C){o={error:C}}finally{try{g&&!g.done&&(e=t.return)&&e.call(t)}finally{if(o)throw o.error}}return I},Ar=function(i,A,e){if(e||arguments.length===2)for(var t=0,g=A.length,I;t<g;t++)(I||!(t in A))&&(I||(I=Array.prototype.slice.call(A,0,t)),I[t]=A[t]);return i.concat(I||Array.prototype.slice.call(A))},XV="PeerJS: ",rI;(function(i){i[i.Disabled=0]="Disabled",i[i.Errors=1]="Errors",i[i.Warnings=2]="Warnings",i[i.All=3]="All"})(rI||(rI={}));var $V=function(){function i(){this._logLevel=rI.Disabled}return Object.defineProperty(i.prototype,"logLevel",{get:function(){return this._logLevel},set:function(A){this._logLevel=A},enumerable:!1,configurable:!0}),i.prototype.log=function(){for(var A=[],e=0;e<arguments.length;e++)A[e]=arguments[e];this._logLevel>=rI.All&&this._print.apply(this,Ar([rI.All],$a(A),!1))},i.prototype.warn=function(){for(var A=[],e=0;e<arguments.length;e++)A[e]=arguments[e];this._logLevel>=rI.Warnings&&this._print.apply(this,Ar([rI.Warnings],$a(A),!1))},i.prototype.error=function(){for(var A=[],e=0;e<arguments.length;e++)A[e]=arguments[e];this._logLevel>=rI.Errors&&this._print.apply(this,Ar([rI.Errors],$a(A),!1))},i.prototype.setLogFunction=function(A){this._print=A},i.prototype._print=function(A){for(var e=[],t=1;t<arguments.length;t++)e[t-1]=arguments[t];var g=Ar([XV],$a(e),!1);for(var I in g)g[I]instanceof Error&&(g[I]="("+g[I].name+") "+g[I].message);A>=rI.All?console.log.apply(console,Ar([],$a(g),!1)):A>=rI.Warnings?console.warn.apply(console,Ar(["WARNING"],$a(g),!1)):A>=rI.Errors&&console.error.apply(console,Ar(["ERROR"],$a(g),!1))},i}(),qN=new $V,Yv={};zC(Yv,"Socket",()=>bN,i=>bN=i);var Wo;(function(i){i.Data="data",i.Media="media"})(Wo||(Wo={}));var ai;(function(i){i.BrowserIncompatible="browser-incompatible",i.Disconnected="disconnected",i.InvalidID="invalid-id",i.InvalidKey="invalid-key",i.Network="network",i.PeerUnavailable="peer-unavailable",i.SslUnavailable="ssl-unavailable",i.ServerError="server-error",i.SocketError="socket-error",i.SocketClosed="socket-closed",i.UnavailableID="unavailable-id",i.WebRTC="webrtc"})(ai||(ai={}));var ps;(function(i){i.Binary="binary",i.BinaryUTF8="binary-utf8",i.JSON="json"})(ps||(ps={}));var vs;(function(i){i.Message="message",i.Disconnected="disconnected",i.Error="error",i.Close="close"})(vs||(vs={}));var rg;(function(i){i.Heartbeat="HEARTBEAT",i.Candidate="CANDIDATE",i.Offer="OFFER",i.Answer="ANSWER",i.Open="OPEN",i.Error="ERROR",i.IdTaken="ID-TAKEN",i.InvalidKey="INVALID-KEY",i.Leave="LEAVE",i.Expire="EXPIRE"})(rg||(rg={}));var YM={};YM=JSON.parse('{"name":"peerjs","version":"1.4.7","keywords":["peerjs","webrtc","p2p","rtc"],"description":"PeerJS client","homepage":"https://peerjs.com","bugs":{"url":"https://github.com/peers/peerjs/issues"},"repository":{"type":"git","url":"https://github.com/peers/peerjs"},"license":"MIT","contributors":["Michelle Bu <michelle@michellebu.com>","afrokick <devbyru@gmail.com>","ericz <really.ez@gmail.com>","Jairo <kidandcat@gmail.com>","Jonas Gloning <34194370+jonasgloning@users.noreply.github.com>","Jairo Caro-Accino Viciana <jairo@galax.be>","Carlos Caballero <carlos.caballero.gonzalez@gmail.com>","hc <hheennrryy@gmail.com>","Muhammad Asif <capripio@gmail.com>","PrashoonB <prashoonbhattacharjee@gmail.com>","Harsh Bardhan Mishra <47351025+HarshCasper@users.noreply.github.com>","akotynski <aleksanderkotbury@gmail.com>","lmb <i@lmb.io>","Jairooo <jairocaro@msn.com>","Moritz Stückler <moritz.stueckler@gmail.com>","Simon <crydotsnakegithub@gmail.com>","Denis Lukov <denismassters@gmail.com>","Philipp Hancke <fippo@andyet.net>","Hans Oksendahl <hansoksendahl@gmail.com>","Jess <jessachandler@gmail.com>","khankuan <khankuan@gmail.com>","DUODVK <kurmanov.work@gmail.com>","XiZhao <kwang1imsa@gmail.com>","Matthias Lohr <matthias@lohr.me>","=frank tree <=frnktrb@googlemail.com>","Andre Eckardt <aeckardt@outlook.com>","Chris Cowan <agentme49@gmail.com>","Alex Chuev <alex@chuev.com>","alxnull <alxnull@e.mail.de>","Yemel Jardi <angel.jardi@gmail.com>","Ben Parnell <benjaminparnell.94@gmail.com>","Benny Lichtner <bennlich@gmail.com>","fresheneesz <bitetrudpublic@gmail.com>","bob.barstead@exaptive.com <bob.barstead@exaptive.com>","chandika <chandika@gmail.com>","emersion <contact@emersion.fr>","Christopher Van <cvan@users.noreply.github.com>","eddieherm <edhermoso@gmail.com>","Eduardo Pinho <enet4mikeenet@gmail.com>","Evandro Zanatta <ezanatta@tray.net.br>","Gardner Bickford <gardner@users.noreply.github.com>","Gian Luca <gianluca.cecchi@cynny.com>","PatrickJS <github@gdi2290.com>","jonnyf <github@jonathanfoss.co.uk>","Hizkia Felix <hizkifw@gmail.com>","Hristo Oskov <hristo.oskov@gmail.com>","Isaac Madwed <i.madwed@gmail.com>","Ilya Konanykhin <ilya.konanykhin@gmail.com>","jasonbarry <jasbarry@me.com>","Jonathan Burke <jonathan.burke.1311@googlemail.com>","Josh Hamit <josh.hamit@gmail.com>","Jordan Austin <jrax86@gmail.com>","Joel Wetzell <jwetzell@yahoo.com>","xizhao <kevin.wang@cloudera.com>","Alberto Torres <kungfoobar@gmail.com>","Jonathan Mayol <mayoljonathan@gmail.com>","Jefferson Felix <me@jsfelix.dev>","Rolf Erik Lekang <me@rolflekang.com>","Kevin Mai-Husan Chia <mhchia@users.noreply.github.com>","Pepijn de Vos <pepijndevos@gmail.com>","JooYoung <qkdlql@naver.com>","Tobias Speicher <rootcommander@gmail.com>","Steve Blaurock <sblaurock@gmail.com>","Kyrylo Shegeda <shegeda@ualberta.ca>","Diwank Singh Tomer <singh@diwank.name>","Sören Balko <Soeren.Balko@gmail.com>","Arpit Solanki <solankiarpit1997@gmail.com>","Yuki Ito <yuki@gnnk.net>","Artur Zayats <zag2art@gmail.com>"],"funding":{"type":"opencollective","url":"https://opencollective.com/peer"},"collective":{"type":"opencollective","url":"https://opencollective.com/peer"},"files":["dist/*"],"sideEffects":["lib/global.ts","lib/supports.ts"],"main":"dist/bundler.cjs","module":"dist/bundler.mjs","browser-minified":"dist/peerjs.min.js","browser-unminified":"dist/peerjs.js","types":"dist/types.d.ts","engines":{"node":">= 10"},"targets":{"types":{"source":"lib/exports.ts"},"main":{"source":"lib/exports.ts","sourceMap":{"inlineSources":true}},"module":{"source":"lib/exports.ts","includeNodeModules":["eventemitter3"],"sourceMap":{"inlineSources":true}},"browser-minified":{"context":"browser","outputFormat":"global","optimize":true,"engines":{"browsers":"cover 99%, not dead"},"source":"lib/global.ts"},"browser-unminified":{"context":"browser","outputFormat":"global","optimize":false,"engines":{"browsers":"cover 99%, not dead"},"source":"lib/global.ts"}},"scripts":{"contributors":"git-authors-cli --print=false && prettier --write package.json && git add package.json package-lock.json && git commit -m \\"chore(contributors): update and sort contributors list\\"","check":"tsc --noEmit","watch":"parcel watch","build":"rm -rf dist && parcel build","prepublishOnly":"npm run build","test":"mocha -r ts-node/register -r jsdom-global/register test/**/*.ts","format":"prettier --write .","semantic-release":"semantic-release"},"devDependencies":{"@parcel/config-default":"^2.5.0","@parcel/packager-ts":"^2.5.0","@parcel/transformer-typescript-tsc":"^2.5.0","@parcel/transformer-typescript-types":"^2.5.0","@semantic-release/changelog":"^6.0.1","@semantic-release/git":"^10.0.1","@types/chai":"^4.3.0","@types/mocha":"^9.1.0","@types/node":"^17.0.18","chai":"^4.3.6","git-authors-cli":"^1.0.40","jsdom":"^19.0.0","jsdom-global":"^3.0.2","mocha":"^9.2.0","mock-socket":"8.0.5","parcel":"^2.5.0","parcel-transformer-tsc-sourcemaps":"^1.0.2","prettier":"^2.6.2","semantic-release":"^19.0.2","standard":"^16.0.4","ts-node":"^10.5.0","typescript":"^4.5.5"},"dependencies":{"@swc/helpers":"^0.3.13","eventemitter3":"^4.0.7","peerjs-js-binarypack":"1.0.1","webrtc-adapter":"^7.7.1"}}');var Aj=function(){var i=function(A,e){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,g){t.__proto__=g}||function(t,g){for(var I in g)Object.prototype.hasOwnProperty.call(g,I)&&(t[I]=g[I])},i(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");i(A,e);function t(){this.constructor=A}A.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}}(),ej=function(i,A){var e=typeof Symbol=="function"&&i[Symbol.iterator];if(!e)return i;var t=e.call(i),g,I=[],o;try{for(;(A===void 0||A-- >0)&&!(g=t.next()).done;)I.push(g.value)}catch(C){o={error:C}}finally{try{g&&!g.done&&(e=t.return)&&e.call(t)}finally{if(o)throw o.error}}return I},tj=function(i,A,e){if(e||arguments.length===2)for(var t=0,g=A.length,I;t<g;t++)(I||!(t in A))&&(I||(I=Array.prototype.slice.call(A,0,t)),I[t]=A[t]);return i.concat(I||Array.prototype.slice.call(A))},ij=function(i){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&i[A],t=0;if(e)return e.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&t>=i.length&&(i=void 0),{value:i&&i[t++],done:!i}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")},bN=function(i){Aj(A,i);function A(e,t,g,I,o,C){C===void 0&&(C=5e3);var s=i.call(this)||this;s.pingInterval=C,s._disconnected=!0,s._messagesQueue=[];var n=e?"wss://":"ws://";return s._baseUrl=n+t+":"+g+I+"peerjs?key="+o,s}return A.prototype.start=function(e,t){var g=this;this._id=e;var I="".concat(this._baseUrl,"&id=").concat(e,"&token=").concat(t);this._socket||!this._disconnected||(this._socket=new WebSocket(I+"&version="+YM.version),this._disconnected=!1,this._socket.onmessage=function(o){var C;try{C=JSON.parse(o.data),ge.default.log("Server message received:",C)}catch{ge.default.log("Invalid server message",o.data);return}g.emit(vs.Message,C)},this._socket.onclose=function(o){g._disconnected||(ge.default.log("Socket closed.",o),g._cleanup(),g._disconnected=!0,g.emit(vs.Disconnected))},this._socket.onopen=function(){g._disconnected||(g._sendQueuedMessages(),ge.default.log("Socket open"),g._scheduleHeartbeat())})},A.prototype._scheduleHeartbeat=function(){var e=this;this._wsPingTimer=setTimeout(function(){e._sendHeartbeat()},this.pingInterval)},A.prototype._sendHeartbeat=function(){if(!this._wsOpen()){ge.default.log("Cannot send heartbeat, because socket closed");return}var e=JSON.stringify({type:rg.Heartbeat});this._socket.send(e),this._scheduleHeartbeat()},A.prototype._wsOpen=function(){return!!this._socket&&this._socket.readyState===1},A.prototype._sendQueuedMessages=function(){var e,t,g=tj([],ej(this._messagesQueue),!1);this._messagesQueue=[];try{for(var I=ij(g),o=I.next();!o.done;o=I.next()){var C=o.value;this.send(C)}}catch(s){e={error:s}}finally{try{o&&!o.done&&(t=I.return)&&t.call(I)}finally{if(e)throw e.error}}},A.prototype.send=function(e){if(!this._disconnected){if(!this._id){this._messagesQueue.push(e);return}if(!e.type){this.emit(vs.Error,"Invalid message");return}if(this._wsOpen()){var t=JSON.stringify(e);this._socket.send(t)}}},A.prototype.close=function(){this._disconnected||(this._cleanup(),this._disconnected=!0)},A.prototype._cleanup=function(){this._socket&&(this._socket.onopen=this._socket.onmessage=this._socket.onclose=null,this._socket.close(),this._socket=void 0),clearTimeout(this._wsPingTimer)},A}(Wl.EventEmitter),Wk={};zC(Wk,"MediaConnection",()=>xN,i=>xN=i);var TM={};zC(TM,"Negotiator",()=>LN,i=>LN=i);var Up=function(){return Up=Object.assign||function(i){for(var A,e=1,t=arguments.length;e<t;e++){A=arguments[e];for(var g in A)Object.prototype.hasOwnProperty.call(A,g)&&(i[g]=A[g])}return i},Up.apply(this,arguments)},Lu=function(i,A,e,t){function g(I){return I instanceof e?I:new e(function(o){o(I)})}return new(e||(e=Promise))(function(I,o){function C(a){try{n(t.next(a))}catch(B){o(B)}}function s(a){try{n(t.throw(a))}catch(B){o(B)}}function n(a){a.done?I(a.value):g(a.value).then(C,s)}n((t=t.apply(i,A||[])).next())})},vu=function(i,A){var e={label:0,sent:function(){if(I[0]&1)throw I[1];return I[1]},trys:[],ops:[]},t,g,I,o;return o={next:C(0),throw:C(1),return:C(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function C(n){return function(a){return s([n,a])}}function s(n){if(t)throw new TypeError("Generator is already executing.");for(;e;)try{if(t=1,g&&(I=n[0]&2?g.return:n[0]?g.throw||((I=g.return)&&I.call(g),0):g.next)&&!(I=I.call(g,n[1])).done)return I;switch(g=0,I&&(n=[n[0]&2,I.value]),n[0]){case 0:case 1:I=n;break;case 4:return e.label++,{value:n[1],done:!1};case 5:e.label++,g=n[1],n=[0];continue;case 7:n=e.ops.pop(),e.trys.pop();continue;default:if(I=e.trys,!(I=I.length>0&&I[I.length-1])&&(n[0]===6||n[0]===2)){e=0;continue}if(n[0]===3&&(!I||n[1]>I[0]&&n[1]<I[3])){e.label=n[1];break}if(n[0]===6&&e.label<I[1]){e.label=I[1],I=n;break}if(I&&e.label<I[2]){e.label=I[2],e.ops.push(n);break}I[2]&&e.ops.pop(),e.trys.pop();continue}n=A.call(i,e)}catch(a){n=[6,a],g=0}finally{t=I=0}if(n[0]&5)throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}},LN=function(){function i(A){this.connection=A}return i.prototype.startConnection=function(A){var e=this._startPeerConnection();if(this.connection.peerConnection=e,this.connection.type===Wo.Media&&A._stream&&this._addTracksToConnection(A._stream,e),A.originator){if(this.connection.type===Wo.Data){var t=this.connection,g={ordered:!!A.reliable},I=e.createDataChannel(t.label,g);t.initialize(I)}this._makeOffer()}else this.handleSDP("OFFER",A.sdp)},i.prototype._startPeerConnection=function(){ge.default.log("Creating RTCPeerConnection.");var A=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(A),A},i.prototype._setupListeners=function(A){var e=this,t=this.connection.peer,g=this.connection.connectionId,I=this.connection.type,o=this.connection.provider;ge.default.log("Listening for ICE candidates."),A.onicecandidate=function(C){!C.candidate||!C.candidate.candidate||(ge.default.log("Received ICE candidates for ".concat(t,":"),C.candidate),o.socket.send({type:rg.Candidate,payload:{candidate:C.candidate,type:I,connectionId:g},dst:t}))},A.oniceconnectionstatechange=function(){switch(A.iceConnectionState){case"failed":ge.default.log("iceConnectionState is failed, closing connections to "+t),e.connection.emit("error",new Error("Negotiation of connection to "+t+" failed.")),e.connection.close();break;case"closed":ge.default.log("iceConnectionState is closed, closing connections to "+t),e.connection.emit("error",new Error("Connection to "+t+" closed.")),e.connection.close();break;case"disconnected":ge.default.log("iceConnectionState changed to disconnected on the connection with "+t);break;case"completed":A.onicecandidate=Qt.noop;break}e.connection.emit("iceStateChanged",A.iceConnectionState)},ge.default.log("Listening for data channel"),A.ondatachannel=function(C){ge.default.log("Received data channel");var s=C.channel,n=o.getConnection(t,g);n.initialize(s)},ge.default.log("Listening for remote stream"),A.ontrack=function(C){ge.default.log("Received remote stream");var s=C.streams[0],n=o.getConnection(t,g);if(n.type===Wo.Media){var a=n;e._addStreamToMediaConnection(s,a)}}},i.prototype.cleanup=function(){ge.default.log("Cleaning up PeerConnection to "+this.connection.peer);var A=this.connection.peerConnection;if(A){this.connection.peerConnection=null,A.onicecandidate=A.oniceconnectionstatechange=A.ondatachannel=A.ontrack=function(){};var e=A.signalingState!=="closed",t=!1;if(this.connection.type===Wo.Data){var g=this.connection,I=g.dataChannel;I&&(t=!!I.readyState&&I.readyState!=="closed")}(e||t)&&A.close()}},i.prototype._makeOffer=function(){return Lu(this,void 0,Promise,function(){var A,e,t,g,I,o,C;return vu(this,function(s){switch(s.label){case 0:A=this.connection.peerConnection,e=this.connection.provider,s.label=1;case 1:return s.trys.push([1,7,,8]),[4,A.createOffer(this.connection.options.constraints)];case 2:t=s.sent(),ge.default.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(t.sdp=this.connection.options.sdpTransform(t.sdp)||t.sdp),s.label=3;case 3:return s.trys.push([3,5,,6]),[4,A.setLocalDescription(t)];case 4:return s.sent(),ge.default.log("Set localDescription:",t,"for:".concat(this.connection.peer)),g={sdp:t,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata,browser:Qt.browser},this.connection.type===Wo.Data&&(I=this.connection,g=Up(Up({},g),{label:I.label,reliable:I.reliable,serialization:I.serialization})),e.socket.send({type:rg.Offer,payload:g,dst:this.connection.peer}),[3,6];case 5:return o=s.sent(),o!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(e.emitError(ai.WebRTC,o),ge.default.log("Failed to setLocalDescription, ",o)),[3,6];case 6:return[3,8];case 7:return C=s.sent(),e.emitError(ai.WebRTC,C),ge.default.log("Failed to createOffer, ",C),[3,8];case 8:return[2]}})})},i.prototype._makeAnswer=function(){return Lu(this,void 0,Promise,function(){var A,e,t,g,I;return vu(this,function(o){switch(o.label){case 0:A=this.connection.peerConnection,e=this.connection.provider,o.label=1;case 1:return o.trys.push([1,7,,8]),[4,A.createAnswer()];case 2:t=o.sent(),ge.default.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(t.sdp=this.connection.options.sdpTransform(t.sdp)||t.sdp),o.label=3;case 3:return o.trys.push([3,5,,6]),[4,A.setLocalDescription(t)];case 4:return o.sent(),ge.default.log("Set localDescription:",t,"for:".concat(this.connection.peer)),e.socket.send({type:rg.Answer,payload:{sdp:t,type:this.connection.type,connectionId:this.connection.connectionId,browser:Qt.browser},dst:this.connection.peer}),[3,6];case 5:return g=o.sent(),e.emitError(ai.WebRTC,g),ge.default.log("Failed to setLocalDescription, ",g),[3,6];case 6:return[3,8];case 7:return I=o.sent(),e.emitError(ai.WebRTC,I),ge.default.log("Failed to create answer, ",I),[3,8];case 8:return[2]}})})},i.prototype.handleSDP=function(A,e){return Lu(this,void 0,Promise,function(){var t,g,I,o;return vu(this,function(C){switch(C.label){case 0:e=new RTCSessionDescription(e),t=this.connection.peerConnection,g=this.connection.provider,ge.default.log("Setting remote description",e),I=this,C.label=1;case 1:return C.trys.push([1,5,,6]),[4,t.setRemoteDescription(e)];case 2:return C.sent(),ge.default.log("Set remoteDescription:".concat(A," for:").concat(this.connection.peer)),A!=="OFFER"?[3,4]:[4,I._makeAnswer()];case 3:C.sent(),C.label=4;case 4:return[3,6];case 5:return o=C.sent(),g.emitError(ai.WebRTC,o),ge.default.log("Failed to setRemoteDescription, ",o),[3,6];case 6:return[2]}})})},i.prototype.handleCandidate=function(A){return Lu(this,void 0,Promise,function(){var e,t,g,I,o,C;return vu(this,function(s){switch(s.label){case 0:ge.default.log("handleCandidate:",A),e=A.candidate,t=A.sdpMLineIndex,g=A.sdpMid,I=this.connection.peerConnection,o=this.connection.provider,s.label=1;case 1:return s.trys.push([1,3,,4]),[4,I.addIceCandidate(new RTCIceCandidate({sdpMid:g,sdpMLineIndex:t,candidate:e}))];case 2:return s.sent(),ge.default.log("Added ICE candidate for:".concat(this.connection.peer)),[3,4];case 3:return C=s.sent(),o.emitError(ai.WebRTC,C),ge.default.log("Failed to handleCandidate, ",C),[3,4];case 4:return[2]}})})},i.prototype._addTracksToConnection=function(A,e){if(ge.default.log("add tracks from stream ".concat(A.id," to peer connection")),!e.addTrack)return ge.default.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");A.getTracks().forEach(function(t){e.addTrack(t,A)})},i.prototype._addStreamToMediaConnection=function(A,e){ge.default.log("add stream ".concat(A.id," to media connection ").concat(e.connectionId)),e.addStream(A)},i}(),HM={};zC(HM,"BaseConnection",()=>vN,i=>vN=i);var gj=function(){var i=function(A,e){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,g){t.__proto__=g}||function(t,g){for(var I in g)Object.prototype.hasOwnProperty.call(g,I)&&(t[I]=g[I])},i(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");i(A,e);function t(){this.constructor=A}A.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}}(),vN=function(i){gj(A,i);function A(e,t,g){var I=i.call(this)||this;return I.peer=e,I.provider=t,I.options=g,I._open=!1,I.metadata=g.metadata,I}return Object.defineProperty(A.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),A}(Wl.EventEmitter),Ij=function(){var i=function(A,e){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,g){t.__proto__=g}||function(t,g){for(var I in g)Object.prototype.hasOwnProperty.call(g,I)&&(t[I]=g[I])},i(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");i(A,e);function t(){this.constructor=A}A.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}}(),Fp=function(){return Fp=Object.assign||function(i){for(var A,e=1,t=arguments.length;e<t;e++){A=arguments[e];for(var g in A)Object.prototype.hasOwnProperty.call(A,g)&&(i[g]=A[g])}return i},Fp.apply(this,arguments)},oj=function(i){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&i[A],t=0;if(e)return e.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&t>=i.length&&(i=void 0),{value:i&&i[t++],done:!i}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")},xN=function(i){Ij(A,i);function A(e,t,g){var I=i.call(this,e,t,g)||this;return I._localStream=I.options._stream,I.connectionId=I.options.connectionId||A.ID_PREFIX+Qt.randomToken(),I._negotiator=new TM.Negotiator(I),I._localStream&&I._negotiator.startConnection({_stream:I._localStream,originator:!0}),I}return Object.defineProperty(A.prototype,"type",{get:function(){return Wo.Media},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"localStream",{get:function(){return this._localStream},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"remoteStream",{get:function(){return this._remoteStream},enumerable:!1,configurable:!0}),A.prototype.addStream=function(e){ge.default.log("Receiving stream",e),this._remoteStream=e,i.prototype.emit.call(this,"stream",e)},A.prototype.handleMessage=function(e){var t=e.type,g=e.payload;switch(e.type){case rg.Answer:this._negotiator.handleSDP(t,g.sdp),this._open=!0;break;case rg.Candidate:this._negotiator.handleCandidate(g.candidate);break;default:ge.default.warn("Unrecognized message type:".concat(t," from peer:").concat(this.peer));break}},A.prototype.answer=function(e,t){var g,I;if(t===void 0&&(t={}),this._localStream){ge.default.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");return}this._localStream=e,t&&t.sdpTransform&&(this.options.sdpTransform=t.sdpTransform),this._negotiator.startConnection(Fp(Fp({},this.options._payload),{_stream:e}));var o=this.provider._getMessages(this.connectionId);try{for(var C=oj(o),s=C.next();!s.done;s=C.next()){var n=s.value;this.handleMessage(n)}}catch(a){g={error:a}}finally{try{s&&!s.done&&(I=C.return)&&I.call(C)}finally{if(g)throw g.error}}this._open=!0},A.prototype.close=function(){this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this._localStream=null,this._remoteStream=null,this.provider&&(this.provider._removeConnection(this),this.provider=null),this.options&&this.options._stream&&(this.options._stream=null),this.open&&(this._open=!1,i.prototype.emit.call(this,"close"))},A.ID_PREFIX="mc_",A}(HM.BaseConnection),Vk={};zC(Vk,"DataConnection",()=>TN,i=>TN=i);var Tv={};zC(Tv,"EncodingQueue",()=>YN,i=>YN=i);var Cj=function(){var i=function(A,e){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,g){t.__proto__=g}||function(t,g){for(var I in g)Object.prototype.hasOwnProperty.call(g,I)&&(t[I]=g[I])},i(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");i(A,e);function t(){this.constructor=A}A.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}}(),YN=function(i){Cj(A,i);function A(){var e=i.call(this)||this;return e.fileReader=new FileReader,e._queue=[],e._processing=!1,e.fileReader.onload=function(t){e._processing=!1,t.target&&e.emit("done",t.target.result),e.doNextTask()},e.fileReader.onerror=function(t){ge.default.error("EncodingQueue error:",t),e._processing=!1,e.destroy(),e.emit("error",t)},e}return Object.defineProperty(A.prototype,"queue",{get:function(){return this._queue},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"size",{get:function(){return this.queue.length},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"processing",{get:function(){return this._processing},enumerable:!1,configurable:!0}),A.prototype.enque=function(e){this.queue.push(e),!this.processing&&this.doNextTask()},A.prototype.destroy=function(){this.fileReader.abort(),this._queue=[]},A.prototype.doNextTask=function(){this.size!==0&&(this.processing||(this._processing=!0,this.fileReader.readAsArrayBuffer(this.queue.shift())))},A}(Wl.EventEmitter),sj=function(){var i=function(A,e){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,g){t.__proto__=g}||function(t,g){for(var I in g)Object.prototype.hasOwnProperty.call(g,I)&&(t[I]=g[I])},i(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");i(A,e);function t(){this.constructor=A}A.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}}(),nj=function(i){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&i[A],t=0;if(e)return e.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&t>=i.length&&(i=void 0),{value:i&&i[t++],done:!i}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")},TN=function(i){sj(A,i);function A(e,t,g){var I=i.call(this,e,t,g)||this;return I.stringify=JSON.stringify,I.parse=JSON.parse,I._buffer=[],I._bufferSize=0,I._buffering=!1,I._chunkedData={},I._encodingQueue=new Tv.EncodingQueue,I.connectionId=I.options.connectionId||A.ID_PREFIX+Qt.randomToken(),I.label=I.options.label||I.connectionId,I.serialization=I.options.serialization||ps.Binary,I.reliable=!!I.options.reliable,I._encodingQueue.on("done",function(o){I._bufferedSend(o)}),I._encodingQueue.on("error",function(){ge.default.error("DC#".concat(I.connectionId,": Error occured in encoding from blob to arraybuffer, close DC")),I.close()}),I._negotiator=new TM.Negotiator(I),I._negotiator.startConnection(I.options._payload||{originator:!0}),I}return Object.defineProperty(A.prototype,"type",{get:function(){return Wo.Data},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"dataChannel",{get:function(){return this._dc},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"bufferSize",{get:function(){return this._bufferSize},enumerable:!1,configurable:!0}),A.prototype.initialize=function(e){this._dc=e,this._configureDataChannel()},A.prototype._configureDataChannel=function(){var e=this;(!Qt.supports.binaryBlob||Qt.supports.reliable)&&(this.dataChannel.binaryType="arraybuffer"),this.dataChannel.onopen=function(){ge.default.log("DC#".concat(e.connectionId," dc connection success")),e._open=!0,e.emit("open")},this.dataChannel.onmessage=function(t){ge.default.log("DC#".concat(e.connectionId," dc onmessage:"),t.data),e._handleDataMessage(t)},this.dataChannel.onclose=function(){ge.default.log("DC#".concat(e.connectionId," dc closed for:"),e.peer),e.close()}},A.prototype._handleDataMessage=function(e){var t=this,g=e.data,I=g.constructor,o=this.serialization===ps.Binary||this.serialization===ps.BinaryUTF8,C=g;if(o){if(I===Blob){Qt.blobToArrayBuffer(g,function(n){var a=Qt.unpack(n);t.emit("data",a)});return}else if(I===ArrayBuffer)C=Qt.unpack(g);else if(I===String){var s=Qt.binaryStringToArrayBuffer(g);C=Qt.unpack(s)}}else this.serialization===ps.JSON&&(C=this.parse(g));if(C.__peerData){this._handleChunk(C);return}i.prototype.emit.call(this,"data",C)},A.prototype._handleChunk=function(e){var t=e.__peerData,g=this._chunkedData[t]||{data:[],count:0,total:e.total};if(g.data[e.n]=e.data,g.count++,this._chunkedData[t]=g,g.total===g.count){delete this._chunkedData[t];var I=new Blob(g.data);this._handleDataMessage({data:I})}},A.prototype.close=function(){this._buffer=[],this._bufferSize=0,this._chunkedData={},this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this.provider&&(this.provider._removeConnection(this),this.provider=null),this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onmessage=null,this.dataChannel.onclose=null,this._dc=null),this._encodingQueue&&(this._encodingQueue.destroy(),this._encodingQueue.removeAllListeners(),this._encodingQueue=null),this.open&&(this._open=!1,i.prototype.emit.call(this,"close"))},A.prototype.send=function(e,t){if(!this.open){i.prototype.emit.call(this,"error",new Error("Connection is not open. You should listen for the `open` event before sending messages."));return}if(this.serialization===ps.JSON)this._bufferedSend(this.stringify(e));else if(this.serialization===ps.Binary||this.serialization===ps.BinaryUTF8){var g=Qt.pack(e);if(!t&&g.size>Qt.chunkedMTU){this._sendChunks(g);return}Qt.supports.binaryBlob?this._bufferedSend(g):this._encodingQueue.enque(g)}else this._bufferedSend(e)},A.prototype._bufferedSend=function(e){(this._buffering||!this._trySend(e))&&(this._buffer.push(e),this._bufferSize=this._buffer.length)},A.prototype._trySend=function(e){var t=this;if(!this.open)return!1;if(this.dataChannel.bufferedAmount>A.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(function(){t._buffering=!1,t._tryBuffer()},50),!1;try{this.dataChannel.send(e)}catch(g){return ge.default.error("DC#:".concat(this.connectionId," Error when sending:"),g),this._buffering=!0,this.close(),!1}return!0},A.prototype._tryBuffer=function(){if(this.open&&this._buffer.length!==0){var e=this._buffer[0];this._trySend(e)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}},A.prototype._sendChunks=function(e){var t,g,I=Qt.chunk(e);ge.default.log("DC#".concat(this.connectionId," Try to send ").concat(I.length," chunks..."));try{for(var o=nj(I),C=o.next();!C.done;C=o.next()){var s=C.value;this.send(s,!0)}}catch(n){t={error:n}}finally{try{C&&!C.done&&(g=o.return)&&g.call(o)}finally{if(t)throw t.error}}},A.prototype.handleMessage=function(e){var t=e.payload;switch(e.type){case rg.Answer:this._negotiator.handleSDP(e.type,t.sdp);break;case rg.Candidate:this._negotiator.handleCandidate(t.candidate);break;default:ge.default.warn("Unrecognized message type:",e.type,"from peer:",this.peer);break}},A.ID_PREFIX="dc_",A.MAX_BUFFERED_AMOUNT=8388608,A}(HM.BaseConnection),Hv={};zC(Hv,"API",()=>ON,i=>ON=i);var HN=function(i,A,e,t){function g(I){return I instanceof e?I:new e(function(o){o(I)})}return new(e||(e=Promise))(function(I,o){function C(a){try{n(t.next(a))}catch(B){o(B)}}function s(a){try{n(t.throw(a))}catch(B){o(B)}}function n(a){a.done?I(a.value):g(a.value).then(C,s)}n((t=t.apply(i,A||[])).next())})},_N=function(i,A){var e={label:0,sent:function(){if(I[0]&1)throw I[1];return I[1]},trys:[],ops:[]},t,g,I,o;return o={next:C(0),throw:C(1),return:C(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function C(n){return function(a){return s([n,a])}}function s(n){if(t)throw new TypeError("Generator is already executing.");for(;e;)try{if(t=1,g&&(I=n[0]&2?g.return:n[0]?g.throw||((I=g.return)&&I.call(g),0):g.next)&&!(I=I.call(g,n[1])).done)return I;switch(g=0,I&&(n=[n[0]&2,I.value]),n[0]){case 0:case 1:I=n;break;case 4:return e.label++,{value:n[1],done:!1};case 5:e.label++,g=n[1],n=[0];continue;case 7:n=e.ops.pop(),e.trys.pop();continue;default:if(I=e.trys,!(I=I.length>0&&I[I.length-1])&&(n[0]===6||n[0]===2)){e=0;continue}if(n[0]===3&&(!I||n[1]>I[0]&&n[1]<I[3])){e.label=n[1];break}if(n[0]===6&&e.label<I[1]){e.label=I[1],I=n;break}if(I&&e.label<I[2]){e.label=I[2],e.ops.push(n);break}I[2]&&e.ops.pop(),e.trys.pop();continue}n=A.call(i,e)}catch(a){n=[6,a],g=0}finally{t=I=0}if(n[0]&5)throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}},ON=function(){function i(A){this._options=A}return i.prototype._buildRequest=function(A){var e=this._options.secure?"https":"http",t=this._options,g=t.host,I=t.port,o=t.path,C=t.key,s=new URL("".concat(e,"://").concat(g,":").concat(I).concat(o).concat(C,"/").concat(A));return s.searchParams.set("ts","".concat(Date.now()).concat(Math.random())),s.searchParams.set("version",YM.version),fetch(s.href,{referrerPolicy:this._options.referrerPolicy})},i.prototype.retrieveId=function(){return HN(this,void 0,Promise,function(){var A,e,t;return _N(this,function(g){switch(g.label){case 0:return g.trys.push([0,2,,3]),[4,this._buildRequest("id")];case 1:if(A=g.sent(),A.status!==200)throw new Error("Error. Status:".concat(A.status));return[2,A.text()];case 2:throw e=g.sent(),ge.default.error("Error retrieving ID",e),t="",this._options.path==="/"&&this._options.host!==Qt.CLOUD_HOST&&(t=" If you passed in a `path` to your self-hosted PeerServer, you'll also need to pass in that same path when creating a new Peer."),new Error("Could not get an ID from the server."+t);case 3:return[2]}})})},i.prototype.listAllPeers=function(){return HN(this,void 0,Promise,function(){var A,e,t;return _N(this,function(g){switch(g.label){case 0:return g.trys.push([0,2,,3]),[4,this._buildRequest("peers")];case 1:if(A=g.sent(),A.status!==200)throw A.status===401?(e="",this._options.host===Qt.CLOUD_HOST?e="It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":e="You need to enable `allow_discovery` on your self-hosted PeerServer to use this feature.",new Error("It doesn't look like you have permission to list peers IDs. "+e)):new Error("Error. Status:".concat(A.status));return[2,A.json()];case 2:throw t=g.sent(),ge.default.error("Error retrieving list peers",t),new Error("Could not get list peers from the server."+t);case 3:return[2]}})})},i}(),aj=function(){var i=function(A,e){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,g){t.__proto__=g}||function(t,g){for(var I in g)Object.prototype.hasOwnProperty.call(g,I)&&(t[I]=g[I])},i(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");i(A,e);function t(){this.constructor=A}A.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}}(),oh=function(){return oh=Object.assign||function(i){for(var A,e=1,t=arguments.length;e<t;e++){A=arguments[e];for(var g in A)Object.prototype.hasOwnProperty.call(A,g)&&(i[g]=A[g])}return i},oh.apply(this,arguments)},uc=function(i){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&i[A],t=0;if(e)return e.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&t>=i.length&&(i=void 0),{value:i&&i[t++],done:!i}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")},rj=function(i,A){var e=typeof Symbol=="function"&&i[Symbol.iterator];if(!e)return i;var t=e.call(i),g,I=[],o;try{for(;(A===void 0||A-- >0)&&!(g=t.next()).done;)I.push(g.value)}catch(C){o={error:C}}finally{try{g&&!g.done&&(e=t.return)&&e.call(t)}finally{if(o)throw o.error}}return I},PN=function(i){aj(A,i);function A(e,t){var g=i.call(this)||this;g._id=null,g._lastServerId=null,g._destroyed=!1,g._disconnected=!1,g._open=!1,g._connections=new Map,g._lostMessages=new Map;var I;return e&&e.constructor==Object?t=e:e&&(I=e.toString()),t=oh({debug:0,host:Qt.CLOUD_HOST,port:Qt.CLOUD_PORT,path:"/",key:A.DEFAULT_KEY,token:Qt.randomToken(),config:Qt.defaultConfig,referrerPolicy:"strict-origin-when-cross-origin"},t),g._options=t,g._options.host==="/"&&(g._options.host=window.location.hostname),g._options.path&&(g._options.path[0]!=="/"&&(g._options.path="/"+g._options.path),g._options.path[g._options.path.length-1]!=="/"&&(g._options.path+="/")),g._options.secure===void 0&&g._options.host!==Qt.CLOUD_HOST?g._options.secure=Qt.isSecure():g._options.host==Qt.CLOUD_HOST&&(g._options.secure=!0),g._options.logFunction&&ge.default.setLogFunction(g._options.logFunction),ge.default.logLevel=g._options.debug||0,g._api=new Hv.API(t),g._socket=g._createServerConnection(),!Qt.supports.audioVideo&&!Qt.supports.data?(g._delayedAbort(ai.BrowserIncompatible,"The current browser does not support WebRTC"),g):I&&!Qt.validateId(I)?(g._delayedAbort(ai.InvalidID,'ID "'.concat(I,'" is invalid')),g):(I?g._initialize(I):g._api.retrieveId().then(function(o){return g._initialize(o)}).catch(function(o){return g._abort(ai.ServerError,o)}),g)}return Object.defineProperty(A.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"socket",{get:function(){return this._socket},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"connections",{get:function(){var e,t,g=Object.create(null);try{for(var I=uc(this._connections),o=I.next();!o.done;o=I.next()){var C=rj(o.value,2),s=C[0],n=C[1];g[s]=n}}catch(a){e={error:a}}finally{try{o&&!o.done&&(t=I.return)&&t.call(I)}finally{if(e)throw e.error}}return g},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"disconnected",{get:function(){return this._disconnected},enumerable:!1,configurable:!0}),A.prototype._createServerConnection=function(){var e=this,t=new Yv.Socket(this._options.secure,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval);return t.on(vs.Message,function(g){e._handleMessage(g)}),t.on(vs.Error,function(g){e._abort(ai.SocketError,g)}),t.on(vs.Disconnected,function(){e.disconnected||(e.emitError(ai.Network,"Lost connection to server."),e.disconnect())}),t.on(vs.Close,function(){e.disconnected||e._abort(ai.SocketClosed,"Underlying socket is already closed.")}),t},A.prototype._initialize=function(e){this._id=e,this.socket.start(e,this._options.token)},A.prototype._handleMessage=function(e){var t,g,I=e.type,o=e.payload,C=e.src;switch(I){case rg.Open:this._lastServerId=this.id,this._open=!0,this.emit("open",this.id);break;case rg.Error:this._abort(ai.ServerError,o.msg);break;case rg.IdTaken:this._abort(ai.UnavailableID,'ID "'.concat(this.id,'" is taken'));break;case rg.InvalidKey:this._abort(ai.InvalidKey,'API KEY "'.concat(this._options.key,'" is invalid'));break;case rg.Leave:ge.default.log("Received leave message from ".concat(C)),this._cleanupPeer(C),this._connections.delete(C);break;case rg.Expire:this.emitError(ai.PeerUnavailable,"Could not connect to peer ".concat(C));break;case rg.Offer:var c=o.connectionId,h=this.getConnection(C,c);if(h&&(h.close(),ge.default.warn("Offer received for existing Connection ID:".concat(c))),o.type===Wo.Media){var s=new Wk.MediaConnection(C,this,{connectionId:c,_payload:o,metadata:o.metadata});h=s,this._addConnection(C,h),this.emit("call",s)}else if(o.type===Wo.Data){var n=new Vk.DataConnection(C,this,{connectionId:c,_payload:o,metadata:o.metadata,label:o.label,serialization:o.serialization,reliable:o.reliable});h=n,this._addConnection(C,h),this.emit("connection",n)}else{ge.default.warn("Received malformed connection type:".concat(o.type));return}var a=this._getMessages(c);try{for(var B=uc(a),Q=B.next();!Q.done;Q=B.next()){var E=Q.value;h.handleMessage(E)}}catch(l){t={error:l}}finally{try{Q&&!Q.done&&(g=B.return)&&g.call(B)}finally{if(t)throw t.error}}break;default:if(!o){ge.default.warn("You received a malformed message from ".concat(C," of type ").concat(I));return}var c=o.connectionId,h=this.getConnection(C,c);h&&h.peerConnection?h.handleMessage(e):c?this._storeMessage(c,e):ge.default.warn("You received an unrecognized message:",e);break}},A.prototype._storeMessage=function(e,t){this._lostMessages.has(e)||this._lostMessages.set(e,[]),this._lostMessages.get(e).push(t)},A.prototype._getMessages=function(e){var t=this._lostMessages.get(e);return t?(this._lostMessages.delete(e),t):[]},A.prototype.connect=function(e,t){if(t===void 0&&(t={}),this.disconnected){ge.default.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect, or call reconnect on this peer if you believe its ID to still be available."),this.emitError(ai.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}var g=new Vk.DataConnection(e,this,t);return this._addConnection(e,g),g},A.prototype.call=function(e,t,g){if(g===void 0&&(g={}),this.disconnected){ge.default.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect."),this.emitError(ai.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}if(!t){ge.default.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.");return}var I=new Wk.MediaConnection(e,this,oh(oh({},g),{_stream:t}));return this._addConnection(e,I),I},A.prototype._addConnection=function(e,t){ge.default.log("add connection ".concat(t.type,":").concat(t.connectionId," to peerId:").concat(e)),this._connections.has(e)||this._connections.set(e,[]),this._connections.get(e).push(t)},A.prototype._removeConnection=function(e){var t=this._connections.get(e.peer);if(t){var g=t.indexOf(e);g!==-1&&t.splice(g,1)}this._lostMessages.delete(e.connectionId)},A.prototype.getConnection=function(e,t){var g,I,o=this._connections.get(e);if(!o)return null;try{for(var C=uc(o),s=C.next();!s.done;s=C.next()){var n=s.value;if(n.connectionId===t)return n}}catch(a){g={error:a}}finally{try{s&&!s.done&&(I=C.return)&&I.call(C)}finally{if(g)throw g.error}}return null},A.prototype._delayedAbort=function(e,t){var g=this;setTimeout(function(){g._abort(e,t)},0)},A.prototype._abort=function(e,t){ge.default.error("Aborting!"),this.emitError(e,t),this._lastServerId?this.disconnect():this.destroy()},A.prototype.emitError=function(e,t){ge.default.error("Error:",t);var g;typeof t=="string"?g=new Error(t):g=t,g.type=e,this.emit("error",g)},A.prototype.destroy=function(){this.destroyed||(ge.default.log("Destroy peer with ID:".concat(this.id)),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit("close"))},A.prototype._cleanup=function(){var e,t;try{for(var g=uc(this._connections.keys()),I=g.next();!I.done;I=g.next()){var o=I.value;this._cleanupPeer(o),this._connections.delete(o)}}catch(C){e={error:C}}finally{try{I&&!I.done&&(t=g.return)&&t.call(g)}finally{if(e)throw e.error}}this.socket.removeAllListeners()},A.prototype._cleanupPeer=function(e){var t,g,I=this._connections.get(e);if(I)try{for(var o=uc(I),C=o.next();!C.done;C=o.next()){var s=C.value;s.close()}}catch(n){t={error:n}}finally{try{C&&!C.done&&(g=o.return)&&g.call(o)}finally{if(t)throw t.error}}},A.prototype.disconnect=function(){if(!this.disconnected){var e=this.id;ge.default.log("Disconnect peer with ID:".concat(e)),this._disconnected=!0,this._open=!1,this.socket.close(),this._lastServerId=e,this._id=null,this.emit("disconnected",e)}},A.prototype.reconnect=function(){if(this.disconnected&&!this.destroyed)ge.default.log("Attempting reconnection to server with ID ".concat(this._lastServerId)),this._disconnected=!1,this._initialize(this._lastServerId);else{if(this.destroyed)throw new Error("This peer cannot reconnect to the server. It has already been destroyed.");if(!this.disconnected&&!this.open)ge.default.error("In a hurry? We're still trying to make the initial connection!");else throw new Error("Peer ".concat(this.id," cannot reconnect because it is not disconnected from the server!"))}},A.prototype.listAllPeers=function(e){var t=this;e===void 0&&(e=function(g){}),this._api.listAllPeers().then(function(g){return e(g)}).catch(function(g){return t._abort(ai.ServerError,g)})},A.DEFAULT_KEY="peerjs",A}(Wl.EventEmitter),Np=vv.Peer;class Bj{constructor(){r(this,"_host");r(this,"_client");r(this,"_clientData");this.onEnable()}get isHost(){return this._host!==void 0}onEnable(){const A="HOST-5980e65c-8438-453e-8b35-f13c736dcd81";this.trySetupHost(A)}trySetupHost(A){let e=new Np(A);e.on("error",t=>{console.error(t),this._host=void 0,this.trySetupClient(A)}),e.on("open",t=>{this._host=new Ej(e)})}trySetupClient(A){this._client=new Np,this._client.on("error",e=>{console.error("Client error",e)}),this._client.on("open",e=>{console.log("client connected",e),this._clientData=this._client.connect(A,{metadata:{id:e}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",t=>{console.log("<<",t)})})}}class Qj{constructor(A){r(this,"_peer");this._peer=A}}class Ej extends Qj{constructor(e){var t;super(e);r(this,"_connections",[]);console.log("I AM THE HOST"),(t=this._peer)==null||t.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}get isHost(){return!0}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){const t=this._connections.map(g=>{var I;return(I=g.metadata)==null?void 0:I.id}).filter(g=>g!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(const t in this._peer.connections){const g=this._peer.connections[t];if(g)if(Array.isArray(g))for(const I of g)I&&I.send(e);else console.warn(g)}}}}var EI=(i=>(i[i.OnConnection=0]="OnConnection",i[i.OnRoomJoin=1]="OnRoomJoin",i[i.Queued=2]="Queued",i[i.Immediate=3]="Immediate",i))(EI||{});const WN="https://urls.needle.tools/default-networking-backend/index";let mn="wss://needle-tiny-starter.glitch.me/socket";const vg=!!rA("debugnet"),_c=!!(vg||rA("debugowner"));var _v=(i=>(i.ConnectionInfo="connection-start-info",i))(_v||{}),gi=(i=>(i.Join="join-room",i.Leave="leave-room",i.JoinedRoom="joined-room",i.LeftRoom="left-room",i.UserJoinedRoom="user-joined-room",i.UserLeftRoom="user-left-room",i))(gi||{});class cj{constructor(){r(this,"room");r(this,"viewId");r(this,"allowEditing");r(this,"inRoom")}}class hj{constructor(){r(this,"room")}}class lj{constructor(){r(this,"userId")}}var Ov=(i=>(i.RequestHasOwner="request-has-owner",i.ResponseHasOwner="response-has-owner",i.RequestIsOwner="request-is-owner",i.ResponseIsOwner="response-is-owner",i.RequestOwnership="request-ownership",i.GainedOwnership="gained-ownership",i.RemoveOwnership="remove-ownership",i.LostOwnership="lost-ownership",i.GainedOwnershipBroadcast="gained-ownership-broadcast",i.LostOwnershipBroadcast="lost-ownership-broadcast",i))(Ov||{});class rw{constructor(A,e){r(this,"guid");r(this,"connection");r(this,"_hasOwnership",!1);r(this,"_isOwned");r(this,"_gainSubscription");r(this,"_lostSubscription");r(this,"_hasOwnerResponse");r(this,"_isWaitingForOwnershipResponseCallback",null);this.connection=A,this.guid=e,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),A.beginListen("lost-ownership",this._lostSubscription),A.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),A.beginListen("response-has-owner",this._hasOwnerResponse)}get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(A){A.guid===this.guid&&(this._isOwned=A.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(A){A.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=A.value,A.value||(_c&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((A,e)=>{this.requestOwnership();let t=0;const g=()=>{if(t++>10)return e("Timeout");setTimeout(()=>{this.hasOwnership?A(this):g()},100)};g()})}requestOwnership(){return _c&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(A){A.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===A.owner?(_c&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(A){A===this.guid&&(_c&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class Pv{constructor(A){r(this,"context");r(this,"_peer",null);r(this,"_usersInRoomCopy",[]);r(this,"_defaultMessagesBuffer",[]);r(this,"_defaultMessagesBufferArray",[]);r(this,"netWebSocketUrlProvider");r(this,"_listeners",{});r(this,"_listenersBinary",{});r(this,"connected",!1);r(this,"channelId");r(this,"_connectionId",null);r(this,"_ws");r(this,"_waitingForSocket",{});r(this,"_isInRoom",!1);r(this,"_currentRoomName",null);r(this,"_currentRoomViewId",null);r(this,"_currentRoomAllowEditing",!0);r(this,"_currentInRoom",[]);r(this,"_state",{});r(this,"_currentDelay",-1);r(this,"_connectingToWebsocketPromise",null);this.context=A}get peer(){return this._peer||(this._peer=new Bj),this._peer}tryGetState(A){return A==="invalid"?null:this._state[A]}get connectionId(){return this._connectionId}get isDebugEnabled(){return vg}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(A){return this._currentInRoom.indexOf(A)!==-1}usersInRoom(A=null){A||(A=this._usersInRoomCopy),A.length=0;for(const e of this._currentInRoom)A.push(e);return A}joinRoom(A,e=!1){this.connect(),vg&&console.log("join: "+A),this.send("join-room",{room:A,viewOnly:e},EI.OnConnection)}leaveRoom(A=null){if(A||(A=this.currentRoomName),!A){console.error("Can not leave unknown room");return}this.send("leave-room",{room:A})}send(A,e=null,t=EI.Queued){if(e===null&&(e={}),t===EI.Queued){this._defaultMessagesBuffer.push({key:A,value:e});return}return this.sendWithWebsocket(A,e,t)}sendDeleteRemoteState(A){this.send("delete-state",{guid:A,dontSave:!0}),delete this._state[A]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(A){var e;vg&&console.log("<< bin",A.length),(e=this._ws)==null||e.send(A)}sendBufferedMessagesNow(){var t;if(!this._ws)return;this._defaultMessagesBufferArray.length=0;const A=Object.keys(this._defaultMessagesBuffer).length;for(const g in this._defaultMessagesBuffer){const I=this._defaultMessagesBuffer[g];if(A<=1){this.sendWithWebsocket(I.key,I.value,EI.Immediate);break}const o=this.toMessage(I.key,I.value);this._defaultMessagesBufferArray.push(o)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&vg&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const e=JSON.stringify(this._defaultMessagesBufferArray);(t=this._ws)==null||t.send(e)}beginListen(A,e){return this._listeners[A]||(this._listeners[A]=[]),this._listeners[A].push(e),e}stopListening(A,e){return this.stopListen(A,e)}stopListen(A,e){if(!e||!this._listeners[A])return;const t=this._listeners[A].indexOf(e);t>=0&&this._listeners[A].splice(t,1)}beginListenBinary(A,e){return this._listenersBinary[A]||(this._listenersBinary[A]=[]),this._listenersBinary[A].push(e),e}stopListenBinary(A,e){if(!this._listenersBinary[A])return;const t=this._listenersBinary[A].indexOf(e);t>=0&&this._listenersBinary[A].splice(t,1)}registerProvider(A){this.netWebSocketUrlProvider=A}async connect(){var e;if(this.connected)return Promise.resolve(!0);vg&&console.log("connecting");const A=(e=this.netWebSocketUrlProvider)==null?void 0:e.getWebsocketUrl();return A?mn=A:Yq()&&(mn="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){var A;(A=this._ws)==null||A.close(),this._ws=void 0}connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(A,e)=>{let t=!1;const g=o=>{t||(t=!0,A(o))};if(mn===void 0&&(console.log("Fetch default backend url: "+WN),mn=await(await fetch(WN)).text()),mn===void 0){g(!1);return}console.log(`⊡ Connecting to networking backend on
3334
3334
  `+mn);const I=new ZL.WebsocketBuilder(mn).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=I,this.connected=!0,console.log(`⊞ Connected to networking backend
3335
3335
  `+mn),g(!0),this.onSendQueued(EI.OnConnection)}).onClose(o=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,g(!1)}).onError((o,C)=>{console.error("⊠ Websocket error",o,C),g(!1)}).onMessage(this.onMessage.bind(this)).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build()})}onMessage(A,e){const t=e.data;try{if(typeof t!="string"){t.size&&this.handleIncomingBinaryMessage(t);return}const g=JSON.parse(t);if(Array.isArray(g))for(const I of g)this.handleIncomingStringMessage(I);else this.handleIncomingStringMessage(g);return}catch{vg&&t==="pong"&&console.log("<<",t)}}async handleIncomingBinaryMessage(A){const e=await A.arrayBuffer();var t=new Uint8Array(e);const g=new Oh(t),I=g.getBufferIdentifier(),o=this._listenersBinary[I],C=RV(g),s=UV(C);if(s&&typeof s=="string"&&(this._state[s]=C),!o)return;const n=C??g;for(const a of o)a(n)}handleIncomingStringMessage(A){var g,I;if(vg&&console.log("<<",A.key??A),A.key)switch(A.key){case"connection-start-info":if(A.data){const s=A.data;s&&(console.assert(s.id!==void 0&&s.id!==null&&s.id.length>0,"server did not send connection id",s.id),console.log("Your id is: "+s.id,this.context.alias??""),this._connectionId=s.id)}else console.warn("Expected connection id in "+A.key);break;case"joined-room":if(vg&&console.log(A),A){this._isInRoom=!0;const s=A;this._currentRoomName=s.room,this._currentRoomViewId=s.viewId,this._currentRoomAllowEditing=s.allowEditing??!0,console.log("Room view id",this._currentRoomViewId),this._currentInRoom.length=0,this._currentInRoom.push(...s.inRoom),vg&&console.log("joined room with",this._currentInRoom,this.context.alias??"")}this.onSendQueued(EI.OnRoomJoin);break;case"left-room":A.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(A.data){const s=A.data;this._currentInRoom.push(s.userId),vg&&console.log(s.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(A.data){const s=A.data,n=this._currentInRoom.indexOf(s.userId);n>=0&&(console.log(s.userId+" left",this.context.alias??""),this._currentInRoom.splice(n,1)),s.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":vg&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const C=(g=A.data)==null?void 0:g.time;C&&(this._currentDelay=this.context.time.time-C),vg&&console.log("Current latency: "+this._currentDelay.toFixed(1)+" sec","Clients in room: "+((I=this._currentInRoom)==null?void 0:I.length));break}const e=this._listeners[A.key];if(e)for(const o of e)o(A.data);const t=A.data;t&&(this._state[t.guid]=t)}toMessage(A,e){return{key:A,data:e}}sendWithWebsocket(A,e,t=EI.OnRoomJoin){if(!this._ws){const I=this._waitingForSocket[t]||[];I.push(()=>this.sendWithWebsocket(A,e,t)),this._waitingForSocket[t]=I;return}const g=JSON.stringify(this.toMessage(A,e));vg&&console.log(">>",A),this._ws.send(g)}onSendQueued(A){const e=this._waitingForSocket[A];if(e){for(const t of e)t();e.length=0}}}function wQ(i,A){try{A?i(A):i()}catch(e){return console.error(e),!1}return!0}(0,eval)(`
3336
- if(!globalThis[""null""])
3337
- globalThis[""null""] = "0.0.0";
3336
+ if(!globalThis["NEEDLE_ENGINE_VERSION"])
3337
+ globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";
3338
3338
  if(!globalThis[""undefined""])
3339
3339
  globalThis[""undefined""] = "unknown";
3340
- `);const Wv="null",dj="undefined",Hs="needle_isActiveInHierarchy",rr="builtin_components",Ch="needle_editor_guid",uj=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function Dj(i){return typeof i=="string"&&uj.test(i)}const ng=[];for(let i=0;i<256;++i)ng.push((i+256).toString(16).slice(1));function pj(i,A=0){return(ng[i[A+0]]+ng[i[A+1]]+ng[i[A+2]]+ng[i[A+3]]+"-"+ng[i[A+4]]+ng[i[A+5]]+"-"+ng[i[A+6]]+ng[i[A+7]]+"-"+ng[i[A+8]]+ng[i[A+9]]+"-"+ng[i[A+10]]+ng[i[A+11]]+ng[i[A+12]]+ng[i[A+13]]+ng[i[A+14]]+ng[i[A+15]]).toLowerCase()}function fj(i){if(!Dj(i))throw TypeError("Invalid UUID");let A;const e=new Uint8Array(16);return e[0]=(A=parseInt(i.slice(0,8),16))>>>24,e[1]=A>>>16&255,e[2]=A>>>8&255,e[3]=A&255,e[4]=(A=parseInt(i.slice(9,13),16))>>>8,e[5]=A&255,e[6]=(A=parseInt(i.slice(14,18),16))>>>8,e[7]=A&255,e[8]=(A=parseInt(i.slice(19,23),16))>>>8,e[9]=A&255,e[10]=(A=parseInt(i.slice(24,36),16))/1099511627776&255,e[11]=A/4294967296&255,e[12]=A>>>24&255,e[13]=A>>>16&255,e[14]=A>>>8&255,e[15]=A&255,e}function wj(i){i=unescape(encodeURIComponent(i));const A=[];for(let e=0;e<i.length;++e)A.push(i.charCodeAt(e));return A}const yj="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Sj="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function kj(i,A,e){function t(g,I,o,C){var s;if(typeof g=="string"&&(g=wj(g)),typeof I=="string"&&(I=fj(I)),((s=I)===null||s===void 0?void 0:s.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let n=new Uint8Array(16+g.length);if(n.set(I),n.set(g,I.length),n=e(n),n[6]=n[6]&15|A,n[8]=n[8]&63|128,o){C=C||0;for(let a=0;a<16;++a)o[C+a]=n[a];return o}return pj(n)}try{t.name=i}catch{}return t.DNS=yj,t.URL=Sj,t}function Gj(i,A,e,t){switch(i){case 0:return A&e^~A&t;case 1:return A^e^t;case 2:return A&e^A&t^e&t;case 3:return A^e^t}}function JS(i,A){return i<<A|i>>>32-A}function Mj(i){const A=[1518500249,1859775393,2400959708,3395469782],e=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof i=="string"){const o=unescape(encodeURIComponent(i));i=[];for(let C=0;C<o.length;++C)i.push(o.charCodeAt(C))}else Array.isArray(i)||(i=Array.prototype.slice.call(i));i.push(128);const t=i.length/4+2,g=Math.ceil(t/16),I=new Array(g);for(let o=0;o<g;++o){const C=new Uint32Array(16);for(let s=0;s<16;++s)C[s]=i[o*64+s*4]<<24|i[o*64+s*4+1]<<16|i[o*64+s*4+2]<<8|i[o*64+s*4+3];I[o]=C}I[g-1][14]=(i.length-1)*8/Math.pow(2,32),I[g-1][14]=Math.floor(I[g-1][14]),I[g-1][15]=(i.length-1)*8&4294967295;for(let o=0;o<g;++o){const C=new Uint32Array(80);for(let E=0;E<16;++E)C[E]=I[o][E];for(let E=16;E<80;++E)C[E]=JS(C[E-3]^C[E-8]^C[E-14]^C[E-16],1);let s=e[0],n=e[1],a=e[2],B=e[3],Q=e[4];for(let E=0;E<80;++E){const c=Math.floor(E/20),h=JS(s,5)+Gj(c,n,a,B)+Q+A[c]+C[E]>>>0;Q=B,B=a,a=JS(n,30)>>>0,n=s,s=h}e[0]=e[0]+s>>>0,e[1]=e[1]+n>>>0,e[2]=e[2]+a>>>0,e[3]=e[3]+B>>>0,e[4]=e[4]+Q>>>0}return[e[0]>>24&255,e[0]>>16&255,e[0]>>8&255,e[0]&255,e[1]>>24&255,e[1]>>16&255,e[1]>>8&255,e[1]&255,e[2]>>24&255,e[2]>>16&255,e[2]>>8&255,e[2]&255,e[3]>>24&255,e[3]>>16&255,e[3]>>8&255,e[3]&255,e[4]>>24&255,e[4]>>16&255,e[4]>>8&255,e[4]&255]}const mj=kj("v5",80,Mj),VN=mj;ii.registerCallback(LI.ContextCreated,i=>{const A=i.context;Xv(A),Zv(A)});const Kp=rA("debugcomponents"),jN="eff8ba80-635d-11ec-90d6-0242ac120003";class Vg{constructor(A){r(this,"_originalSeed");r(this,"_seed");typeof A=="string"&&(A=Vg.hash(A)),this._originalSeed=A,this._seed=A}get seed(){return this._seed}set seed(A){this._seed=A}reset(){this._seed=this._originalSeed}generateUUID(A){if(typeof A=="string")return VN(A,jN);const e=this._seed;return this._seed-=1,VN(e.toString(),jN)}initialize(A){typeof A=="string"?this._seed=Vg.hash(A):this._seed=A}static createFromString(A){return new Vg(this.hash(A))}static hash(A){let e=0;for(let t=0;t<A.length;t++)e=A.charCodeAt(t)+((e<<5)-e);return e}}var Vv=(i=>(i.NewInstanceCreated="new-instance-created",i.InstanceDestroyed="instance-destroyed",i))(Vv||{});class jv{constructor(A){r(this,"guid");this.guid=A}}function Bw(i,A,e=!0){if(!i)return;const t=i;if(js(i,e),!A){console.warn("Can not send destroy: No networking connection provided",i.guid);return}if(!A.isConnected){console.warn("Can not send destroy: not connected",i.guid);return}let g=i.guid;if(!g&&t.uuid&&(g=t.uuid),!g){console.warn("Can not send destroy: failed to find guid",i);return}const I=new jv(g);A.send("instance-destroyed",I,EI.Queued)}function zv(i,A){const e=new jv(i);A.send("instance-destroyed",e,EI.Queued)}function Zv(i){i.connection.beginListen("instance-destroyed",A=>{Kp&&console.log("[Remote] Destroyed",i.scene,A);const e=Xl(A.guid,i.scene);e&&js(e)})}class Rj{constructor(A,e,t){r(this,"filename");r(this,"hash");r(this,"size");this.filename=A,this.hash=e,this.size=t}}class Uj{constructor(A,e){r(this,"guid");r(this,"originalGuid");r(this,"seed");r(this,"visible");r(this,"hostData");r(this,"dontSave");r(this,"parent");r(this,"position");r(this,"rotation");r(this,"scale");this.originalGuid=A,this.guid=e}}function _M(i,A,e,t){var s;const g=i;if(!g.guid)return console.warn("Can not instantiate: No guid",g),null;if(A.context||(A.context=pe.Current),!A.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const I=A?{...A}:null,{instance:o,seed:C}=Fj(g,A);if(o){const n=o;if(n.guid){Kp&&console.log("[Local] new instance","gameobject:",o==null?void 0:o.guid);const a=new Uj(g.guid,n.guid);a.seed=C,I&&(I.position&&(a.position={x:I.position.x,y:I.position.y,z:I.position.z}),I.rotation&&(a.rotation={x:I.rotation.x,y:I.rotation.y,z:I.rotation.z,w:I.rotation.w}),I.scale&&(a.scale={x:I.scale.x,y:I.scale.y,z:I.scale.z})),a.position||(a.position={x:n.position.x,y:n.position.y,z:n.position.z}),a.rotation||(a.rotation={x:n.quaternion.x,y:n.quaternion.y,z:n.quaternion.z,w:n.quaternion.w}),a.scale||(a.scale={x:n.scale.x,y:n.scale.y,z:n.scale.z}),a.visible=g.visible,I!=null&&I.parent&&(typeof I.parent=="string"?a.parent=I.parent:a.parent=I.parent.guid),a.hostData=e,t===!1&&(a.dontSave=!0),(s=A==null?void 0:A.context)==null||s.connection.send("new-instance-created",a)}else console.warn("Missing guid, can not send new instance event",n)}return o}function Qw(){return Math.random()*9999999}function Xv(i){i.connection.beginListen("new-instance-created",async A=>{const e=await Nj(A.originalGuid,i.scene);if(!e){console.warn("could not find object that was instantiated: "+A.guid);return}const t=new TC;A.position&&(t.position=new k(A.position.x,A.position.y,A.position.z)),A.rotation&&(t.rotation=new kA(A.rotation.x,A.rotation.y,A.rotation.z,A.rotation.w)),A.scale&&(t.scale=new k(A.scale.x,A.scale.y,A.scale.z)),t.parent=A.parent,A.seed&&(t.idProvider=new Vg(A.seed)),t.visible=A.visible,t.context=i,Kp&&i.alias&&console.log("[Remote] instantiate in: "+i.alias);const g=$l(e,t);g&&(A.parent==="scene"&&i.scene.add(g),Kp&&console.log("[Remote] new instance","gameobject:",g==null?void 0:g.guid,e))})}function Fj(i,A){const e=Qw(),t=A??new TC;t.idProvider=new Vg(e);const g=$l(i,t);return{seed:e,instance:g}}const $v={};function Ax(i,A){$v[i]=A}async function Nj(i,A){const e=$v[i];if(e!=null){const t=await e(i);if(t)return t}return ex(i,A)}function ex(i,A){if(A===null||!i)return null;if(A.guid===i)return A;if(A.children)for(const e of A.children){const t=ex(i,e);if(t)return t}return null}const tx=new Map;function Kj(i,A){if(!i)return;if(!A){console.warn("No prototype found",i,i.prototype,i.constructor);return}let e=tx.get(A);e&&e.apply(i)}function Jj(i){const A=qj(i.prototype);tx.set(i,A)}function qj(i){return new bj(i)}class bj{constructor(A){r(this,"$symbol");r(this,"extensions");r(this,"descriptors");this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(A),this.descriptors=new Array;for(let e=0;e<this.extensions.length;e++){const t=this.extensions[e],g=Object.getOwnPropertyDescriptor(A,t);g&&this.descriptors.push(g)}}apply(A){if(!A[this.$symbol]){A[this.$symbol]=!0;for(let e=0;e<this.extensions.length;e++){const t=this.extensions[e],g=this.descriptors[e];g&&Object.defineProperty(A,t,g)}}}}var Vl=(i=>(i.Added="component-added",i.Removing="removing-component",i))(Vl||{});const zN=rA("debugcomponentevents");class jl{static addComponentLifecylceEventListener(A,e){this.eventListeners.has(A)&&this.eventListeners.set(A,[]);let t=this.eventListeners.get(A);t||(t=[]),t.push(e),this.eventListeners.set(A,t),zN&&console.log("Added event listener for "+A,this.eventListeners)}static removeComponentLifecylceEventListener(A,e){const t=this.eventListeners.get(A);if(!t)return;const g=t.indexOf(e);g<0||t.splice(g,1)}static dispatchComponentLifecycleEvent(A,e){const t=this.eventListeners.get(A);if(zN&&console.log("Dispatching event "+A,t),!!t)for(const g of t)g(e)}}r(jl,"eventListeners",new Map);const qS=rA("debuggetcomponent");function Lj(i){return i==null||i.isObject3D?i:i.object&&i.object.isObject3D?i.object:i}function OM(i,A){if(!i||!i.userData.components)return;const e=i.userData.components.indexOf(A);e<0||(jl.dispatchComponentLifecycleEvent(Vl.Removing,A),A.gameObject=null,i.userData.components.splice(e,1))}function Ew(i,A){const e=hE(i,A);if(e)return e;const t=new A;return Xr(i,t)}const ix=new Vg("addComponentIdProvider");function Xr(i,A,e=!0){i.userData||(i.userData={}),i.userData.components||(i.userData.components=[]),i.userData.components.push(A),A.gameObject=i,(A.guid===void 0||A.guid==="invalid")&&(A.guid=ix.generateUUID()),hw(i),pw(A);try{e&&A.__internalAwake&&(ah(i),A.__internalAwake()),jl.dispatchComponentLifecycleEvent(Vl.Added,A)}catch(t){console.error(t)}return A}function PM(i,A){if(A.gameObject===i)return A;if(A.gameObject&&A.gameObject.userData.components){const e=A.gameObject.userData.components.indexOf(A);A.gameObject.userData.components.splice(e,1)}if(!i.userData.components)i.userData.components=[];else if(i.userData.components.includes(A))return A;return i.userData.components.push(A),A.gameObject=i,(A.guid===void 0||A.guid==="invalid")&&(A.guid=ix.generateUUID()),pw(A),A}function gx(i){if(i.gameObject&&i.gameObject.userData.components){const A=i.gameObject.userData.components.indexOf(i);i.gameObject.userData.components.splice(A,1)}i.__internalDisable&&i.__internalDisable(),i.onDestroy&&i.onDestroy(),Us(i,i.context??pe.Current),i.__internalDestroy(),i.gameObject=null}let ZN=!1;function Ix(i,A,e){var t;if(i!=null){if(!i.isObject3D){console.error("Object is not object3D");return}if(!((t=i==null?void 0:i.userData)!=null&&t.components))return null;if(typeof A=="string"&&(ZN||(ZN=!0,console.warn(`Accessing components by name is not supported.
3340
+ `);const Wv=NEEDLE_ENGINE_VERSION,dj="undefined",Hs="needle_isActiveInHierarchy",rr="builtin_components",Ch="needle_editor_guid",uj=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function Dj(i){return typeof i=="string"&&uj.test(i)}const ng=[];for(let i=0;i<256;++i)ng.push((i+256).toString(16).slice(1));function pj(i,A=0){return(ng[i[A+0]]+ng[i[A+1]]+ng[i[A+2]]+ng[i[A+3]]+"-"+ng[i[A+4]]+ng[i[A+5]]+"-"+ng[i[A+6]]+ng[i[A+7]]+"-"+ng[i[A+8]]+ng[i[A+9]]+"-"+ng[i[A+10]]+ng[i[A+11]]+ng[i[A+12]]+ng[i[A+13]]+ng[i[A+14]]+ng[i[A+15]]).toLowerCase()}function fj(i){if(!Dj(i))throw TypeError("Invalid UUID");let A;const e=new Uint8Array(16);return e[0]=(A=parseInt(i.slice(0,8),16))>>>24,e[1]=A>>>16&255,e[2]=A>>>8&255,e[3]=A&255,e[4]=(A=parseInt(i.slice(9,13),16))>>>8,e[5]=A&255,e[6]=(A=parseInt(i.slice(14,18),16))>>>8,e[7]=A&255,e[8]=(A=parseInt(i.slice(19,23),16))>>>8,e[9]=A&255,e[10]=(A=parseInt(i.slice(24,36),16))/1099511627776&255,e[11]=A/4294967296&255,e[12]=A>>>24&255,e[13]=A>>>16&255,e[14]=A>>>8&255,e[15]=A&255,e}function wj(i){i=unescape(encodeURIComponent(i));const A=[];for(let e=0;e<i.length;++e)A.push(i.charCodeAt(e));return A}const yj="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Sj="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function kj(i,A,e){function t(g,I,o,C){var s;if(typeof g=="string"&&(g=wj(g)),typeof I=="string"&&(I=fj(I)),((s=I)===null||s===void 0?void 0:s.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let n=new Uint8Array(16+g.length);if(n.set(I),n.set(g,I.length),n=e(n),n[6]=n[6]&15|A,n[8]=n[8]&63|128,o){C=C||0;for(let a=0;a<16;++a)o[C+a]=n[a];return o}return pj(n)}try{t.name=i}catch{}return t.DNS=yj,t.URL=Sj,t}function Gj(i,A,e,t){switch(i){case 0:return A&e^~A&t;case 1:return A^e^t;case 2:return A&e^A&t^e&t;case 3:return A^e^t}}function JS(i,A){return i<<A|i>>>32-A}function Mj(i){const A=[1518500249,1859775393,2400959708,3395469782],e=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof i=="string"){const o=unescape(encodeURIComponent(i));i=[];for(let C=0;C<o.length;++C)i.push(o.charCodeAt(C))}else Array.isArray(i)||(i=Array.prototype.slice.call(i));i.push(128);const t=i.length/4+2,g=Math.ceil(t/16),I=new Array(g);for(let o=0;o<g;++o){const C=new Uint32Array(16);for(let s=0;s<16;++s)C[s]=i[o*64+s*4]<<24|i[o*64+s*4+1]<<16|i[o*64+s*4+2]<<8|i[o*64+s*4+3];I[o]=C}I[g-1][14]=(i.length-1)*8/Math.pow(2,32),I[g-1][14]=Math.floor(I[g-1][14]),I[g-1][15]=(i.length-1)*8&4294967295;for(let o=0;o<g;++o){const C=new Uint32Array(80);for(let E=0;E<16;++E)C[E]=I[o][E];for(let E=16;E<80;++E)C[E]=JS(C[E-3]^C[E-8]^C[E-14]^C[E-16],1);let s=e[0],n=e[1],a=e[2],B=e[3],Q=e[4];for(let E=0;E<80;++E){const c=Math.floor(E/20),h=JS(s,5)+Gj(c,n,a,B)+Q+A[c]+C[E]>>>0;Q=B,B=a,a=JS(n,30)>>>0,n=s,s=h}e[0]=e[0]+s>>>0,e[1]=e[1]+n>>>0,e[2]=e[2]+a>>>0,e[3]=e[3]+B>>>0,e[4]=e[4]+Q>>>0}return[e[0]>>24&255,e[0]>>16&255,e[0]>>8&255,e[0]&255,e[1]>>24&255,e[1]>>16&255,e[1]>>8&255,e[1]&255,e[2]>>24&255,e[2]>>16&255,e[2]>>8&255,e[2]&255,e[3]>>24&255,e[3]>>16&255,e[3]>>8&255,e[3]&255,e[4]>>24&255,e[4]>>16&255,e[4]>>8&255,e[4]&255]}const mj=kj("v5",80,Mj),VN=mj;ii.registerCallback(LI.ContextCreated,i=>{const A=i.context;Xv(A),Zv(A)});const Kp=rA("debugcomponents"),jN="eff8ba80-635d-11ec-90d6-0242ac120003";class Vg{constructor(A){r(this,"_originalSeed");r(this,"_seed");typeof A=="string"&&(A=Vg.hash(A)),this._originalSeed=A,this._seed=A}get seed(){return this._seed}set seed(A){this._seed=A}reset(){this._seed=this._originalSeed}generateUUID(A){if(typeof A=="string")return VN(A,jN);const e=this._seed;return this._seed-=1,VN(e.toString(),jN)}initialize(A){typeof A=="string"?this._seed=Vg.hash(A):this._seed=A}static createFromString(A){return new Vg(this.hash(A))}static hash(A){let e=0;for(let t=0;t<A.length;t++)e=A.charCodeAt(t)+((e<<5)-e);return e}}var Vv=(i=>(i.NewInstanceCreated="new-instance-created",i.InstanceDestroyed="instance-destroyed",i))(Vv||{});class jv{constructor(A){r(this,"guid");this.guid=A}}function Bw(i,A,e=!0){if(!i)return;const t=i;if(js(i,e),!A){console.warn("Can not send destroy: No networking connection provided",i.guid);return}if(!A.isConnected){console.warn("Can not send destroy: not connected",i.guid);return}let g=i.guid;if(!g&&t.uuid&&(g=t.uuid),!g){console.warn("Can not send destroy: failed to find guid",i);return}const I=new jv(g);A.send("instance-destroyed",I,EI.Queued)}function zv(i,A){const e=new jv(i);A.send("instance-destroyed",e,EI.Queued)}function Zv(i){i.connection.beginListen("instance-destroyed",A=>{Kp&&console.log("[Remote] Destroyed",i.scene,A);const e=Xl(A.guid,i.scene);e&&js(e)})}class Rj{constructor(A,e,t){r(this,"filename");r(this,"hash");r(this,"size");this.filename=A,this.hash=e,this.size=t}}class Uj{constructor(A,e){r(this,"guid");r(this,"originalGuid");r(this,"seed");r(this,"visible");r(this,"hostData");r(this,"dontSave");r(this,"parent");r(this,"position");r(this,"rotation");r(this,"scale");this.originalGuid=A,this.guid=e}}function _M(i,A,e,t){var s;const g=i;if(!g.guid)return console.warn("Can not instantiate: No guid",g),null;if(A.context||(A.context=pe.Current),!A.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const I=A?{...A}:null,{instance:o,seed:C}=Fj(g,A);if(o){const n=o;if(n.guid){Kp&&console.log("[Local] new instance","gameobject:",o==null?void 0:o.guid);const a=new Uj(g.guid,n.guid);a.seed=C,I&&(I.position&&(a.position={x:I.position.x,y:I.position.y,z:I.position.z}),I.rotation&&(a.rotation={x:I.rotation.x,y:I.rotation.y,z:I.rotation.z,w:I.rotation.w}),I.scale&&(a.scale={x:I.scale.x,y:I.scale.y,z:I.scale.z})),a.position||(a.position={x:n.position.x,y:n.position.y,z:n.position.z}),a.rotation||(a.rotation={x:n.quaternion.x,y:n.quaternion.y,z:n.quaternion.z,w:n.quaternion.w}),a.scale||(a.scale={x:n.scale.x,y:n.scale.y,z:n.scale.z}),a.visible=g.visible,I!=null&&I.parent&&(typeof I.parent=="string"?a.parent=I.parent:a.parent=I.parent.guid),a.hostData=e,t===!1&&(a.dontSave=!0),(s=A==null?void 0:A.context)==null||s.connection.send("new-instance-created",a)}else console.warn("Missing guid, can not send new instance event",n)}return o}function Qw(){return Math.random()*9999999}function Xv(i){i.connection.beginListen("new-instance-created",async A=>{const e=await Nj(A.originalGuid,i.scene);if(!e){console.warn("could not find object that was instantiated: "+A.guid);return}const t=new TC;A.position&&(t.position=new k(A.position.x,A.position.y,A.position.z)),A.rotation&&(t.rotation=new kA(A.rotation.x,A.rotation.y,A.rotation.z,A.rotation.w)),A.scale&&(t.scale=new k(A.scale.x,A.scale.y,A.scale.z)),t.parent=A.parent,A.seed&&(t.idProvider=new Vg(A.seed)),t.visible=A.visible,t.context=i,Kp&&i.alias&&console.log("[Remote] instantiate in: "+i.alias);const g=$l(e,t);g&&(A.parent==="scene"&&i.scene.add(g),Kp&&console.log("[Remote] new instance","gameobject:",g==null?void 0:g.guid,e))})}function Fj(i,A){const e=Qw(),t=A??new TC;t.idProvider=new Vg(e);const g=$l(i,t);return{seed:e,instance:g}}const $v={};function Ax(i,A){$v[i]=A}async function Nj(i,A){const e=$v[i];if(e!=null){const t=await e(i);if(t)return t}return ex(i,A)}function ex(i,A){if(A===null||!i)return null;if(A.guid===i)return A;if(A.children)for(const e of A.children){const t=ex(i,e);if(t)return t}return null}const tx=new Map;function Kj(i,A){if(!i)return;if(!A){console.warn("No prototype found",i,i.prototype,i.constructor);return}let e=tx.get(A);e&&e.apply(i)}function Jj(i){const A=qj(i.prototype);tx.set(i,A)}function qj(i){return new bj(i)}class bj{constructor(A){r(this,"$symbol");r(this,"extensions");r(this,"descriptors");this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(A),this.descriptors=new Array;for(let e=0;e<this.extensions.length;e++){const t=this.extensions[e],g=Object.getOwnPropertyDescriptor(A,t);g&&this.descriptors.push(g)}}apply(A){if(!A[this.$symbol]){A[this.$symbol]=!0;for(let e=0;e<this.extensions.length;e++){const t=this.extensions[e],g=this.descriptors[e];g&&Object.defineProperty(A,t,g)}}}}var Vl=(i=>(i.Added="component-added",i.Removing="removing-component",i))(Vl||{});const zN=rA("debugcomponentevents");class jl{static addComponentLifecylceEventListener(A,e){this.eventListeners.has(A)&&this.eventListeners.set(A,[]);let t=this.eventListeners.get(A);t||(t=[]),t.push(e),this.eventListeners.set(A,t),zN&&console.log("Added event listener for "+A,this.eventListeners)}static removeComponentLifecylceEventListener(A,e){const t=this.eventListeners.get(A);if(!t)return;const g=t.indexOf(e);g<0||t.splice(g,1)}static dispatchComponentLifecycleEvent(A,e){const t=this.eventListeners.get(A);if(zN&&console.log("Dispatching event "+A,t),!!t)for(const g of t)g(e)}}r(jl,"eventListeners",new Map);const qS=rA("debuggetcomponent");function Lj(i){return i==null||i.isObject3D?i:i.object&&i.object.isObject3D?i.object:i}function OM(i,A){if(!i||!i.userData.components)return;const e=i.userData.components.indexOf(A);e<0||(jl.dispatchComponentLifecycleEvent(Vl.Removing,A),A.gameObject=null,i.userData.components.splice(e,1))}function Ew(i,A){const e=hE(i,A);if(e)return e;const t=new A;return Xr(i,t)}const ix=new Vg("addComponentIdProvider");function Xr(i,A,e=!0){i.userData||(i.userData={}),i.userData.components||(i.userData.components=[]),i.userData.components.push(A),A.gameObject=i,(A.guid===void 0||A.guid==="invalid")&&(A.guid=ix.generateUUID()),hw(i),pw(A);try{e&&A.__internalAwake&&(ah(i),A.__internalAwake()),jl.dispatchComponentLifecycleEvent(Vl.Added,A)}catch(t){console.error(t)}return A}function PM(i,A){if(A.gameObject===i)return A;if(A.gameObject&&A.gameObject.userData.components){const e=A.gameObject.userData.components.indexOf(A);A.gameObject.userData.components.splice(e,1)}if(!i.userData.components)i.userData.components=[];else if(i.userData.components.includes(A))return A;return i.userData.components.push(A),A.gameObject=i,(A.guid===void 0||A.guid==="invalid")&&(A.guid=ix.generateUUID()),pw(A),A}function gx(i){if(i.gameObject&&i.gameObject.userData.components){const A=i.gameObject.userData.components.indexOf(i);i.gameObject.userData.components.splice(A,1)}i.__internalDisable&&i.__internalDisable(),i.onDestroy&&i.onDestroy(),Us(i,i.context??pe.Current),i.__internalDestroy(),i.gameObject=null}let ZN=!1;function Ix(i,A,e){var t;if(i!=null){if(!i.isObject3D){console.error("Object is not object3D");return}if(!((t=i==null?void 0:i.userData)!=null&&t.components))return null;if(typeof A=="string"&&(ZN||(ZN=!0,console.warn(`Accessing components by name is not supported.
3341
3341
  Please use the component type instead. This may keep working in local development but it will fail when bundling your application.
3342
3342
 
3343
3343
  You can import other modules your main module to get access to types
@@ -3833,7 +3833,7 @@ outputColor=vec4(color,inputColor.a);}`,vx=class extends sC{constructor({blendFu
3833
3833
  irradiance += 0.;
3834
3834
  #else
3835
3835
  irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
3836
- #endif`);ZA.lightmap.lightmapScaleOffset={value:new Ce(1,1,0,0)};const u5=rA("debugplayerview");var vC=(i=>(i.Browser="browser",i.Headset="headset",i.Handheld="handheld",i))(vC||{});class $x{constructor(A,e){r(this,"userId");r(this,"context");r(this,"viewDevice","browser");r(this,"removed",!1);r(this,"_object");this.userId=A,this.context=e}get currentObject(){return this._object}set currentObject(A){this._object=A}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class AY{constructor(A){r(this,"context");r(this,"playerViews",new Map);this.context=A}setPlayerView(A,e,t){let g=this.playerViews.get(A);g||(g=new $x(A,this.context),this.playerViews.set(A,g)),g.viewDevice=t,g.currentObject=e,g.removed=!1}getPlayerView(A){if(!A)return;if(!this.context.connection.userIsInRoom(A)){this.playerViews.delete(A);return}return this.playerViews.get(A)}removePlayerView(A,e){const t=this.playerViews.get(A);(t==null?void 0:t.viewDevice)===e&&(u5&&console.log("REMOVE",A),t.removed=!0,this.playerViews.delete(A))}}const xS=rA("debugSetup"),D5=rA("stats"),p5=rA("debugactive"),f5=rA("debugframerate"),w5=rA("debugcoroutine"),y5={};class S5{constructor(A){r(this,"name");r(this,"alias");r(this,"domElement");r(this,"renderer");r(this,"hash");this.domElement=A??document.body}}var OI=(i=>(i[i.EarlyUpdate=0]="EarlyUpdate",i[i.Update=1]="Update",i[i.LateUpdate=2]="LateUpdate",i[i.OnBeforeRender=3]="OnBeforeRender",i[i.OnAfterRender=4]="OnAfterRender",i[i.PrePhysicsStep=9]="PrePhysicsStep",i[i.PostPhysicsStep=10]="PostPhysicsStep",i[i.Undefined=-1]="Undefined",i))(OI||{}),jh=(i=>(i.ImmersiveVR="immersive-vr",i.ImmersiveAR="immersive-ar",i))(jh||{});function pw(i,A){if(!i)return;const e=(A==null?void 0:A.new_scripts)??pe.Current.new_scripts;e.includes(i)||e.push(i)}class pe{constructor(A){r(this,"name");r(this,"alias");r(this,"isManagedExternally",!1);r(this,"isPaused",!1);r(this,"runInBackground",!1);r(this,"targetFrameRate");r(this,"hash");r(this,"domElement");r(this,"_resolutionScaleFactor",1);r(this,"_boundingClientRectFrame",-1);r(this,"_boundingClientRect",null);r(this,"_domX");r(this,"_domY");r(this,"xrSessionMode");r(this,"_xrFrame",null);r(this,"_currentFrameEvent",-1);r(this,"scene");r(this,"renderer");r(this,"composer",null);r(this,"scripts",[]);r(this,"scripts_pausedChanged",[]);r(this,"scripts_earlyUpdate",[]);r(this,"scripts_update",[]);r(this,"scripts_lateUpdate",[]);r(this,"scripts_onBeforeRender",[]);r(this,"scripts_onAfterRender",[]);r(this,"scripts_WithCorroutines",[]);r(this,"coroutines",{});r(this,"mainCameraComponent");r(this,"post_setup_callbacks",[]);r(this,"pre_update_callbacks",[]);r(this,"pre_render_callbacks",[]);r(this,"post_render_callbacks",[]);r(this,"new_scripts",[]);r(this,"new_script_start",[]);r(this,"new_scripts_pre_setup_callbacks",[]);r(this,"new_scripts_post_setup_callbacks",[]);r(this,"application");r(this,"time");r(this,"input");r(this,"physics");r(this,"connection");r(this,"assets");r(this,"mainLight",null);r(this,"sceneLighting");r(this,"addressables");r(this,"lightmaps");r(this,"players");r(this,"_sizeChanged",!1);r(this,"_isCreated",!1);r(this,"_isCreating",!1);r(this,"_isVisible",!1);r(this,"_stats",D5?t5():null);r(this,"_intersectionObserver",null);r(this,"_disposeCallbacks",[]);r(this,"_cameraStack",[]);r(this,"_onBeforeRenderListeners",new Map);r(this,"_onAfterRenderListeners",new Map);r(this,"_requireDepthTexture",!1);r(this,"_requireColorTexture",!1);r(this,"_renderTarget");r(this,"_isRendering",!1);r(this,"_accumulatedTime",0);r(this,"_framerateClock",new zf);r(this,"_dispatchReadyAfterFrame",!1);r(this,"_wasPaused",!1);var g,I;if(this.name=(A==null?void 0:A.name)||"",this.alias=A==null?void 0:A.alias,this.domElement=(A==null?void 0:A.domElement)||document.body,this.hash=A==null?void 0:A.hash,A!=null&&A.renderer)this.renderer=A.renderer,this.isManagedExternally=!0;else{const o={antialias:!0},C=(I=(g=A==null?void 0:A.domElement)==null?void 0:g.shadowRoot)==null?void 0:I.querySelector("canvas");C&&(o.canvas=C),this.renderer=new IE(o),this.renderer.toneMappingExposure=1,this.renderer.toneMapping=Pg,this.renderer.setClearColor(new yA("lightgrey"),0),this.renderer.antialias=!0,this.renderer.alpha=!1,this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=HG,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputEncoding=De,this.renderer.physicallyCorrectLights=!0}this.scene=new HI,ii.register(this),this.application=new Xx(this),this.time=new zL,this.input=new xL(this),this.physics=new jL(this),this.connection=new Pv(this),this.assets=new nx,this.sceneLighting=new zx(this),this.addressables=new Vx(this),this.lightmaps=new d5(this),this.players=new AY(this);const e=()=>this._sizeChanged=!0;window.addEventListener("resize",e),this._disposeCallbacks.push(()=>window.removeEventListener("resize",e));const t=new ResizeObserver(o=>this._sizeChanged=!0);t.observe(this.domElement),this._disposeCallbacks.push(()=>t.disconnect()),this._intersectionObserver=new IntersectionObserver(o=>{this._isVisible=o[0].isIntersecting}),this._disposeCallbacks.push(()=>{var o;return(o=this._intersectionObserver)==null?void 0:o.disconnect()})}get version(){return Wv}static get Current(){return ii.Current}static set Current(A){ii.Current=A}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(A){if(A!==this._resolutionScaleFactor&&typeof A=="number"){if(A<=0){console.error("Invalid resolution scale factor",A);return}this._resolutionScaleFactor=A,this.updateSize()}}calculateBoundingClientRect(){if(this.isInAR){this._domX=0,this._domY=0;return}this._boundingClientRectFrame!==this.time.frame&&(this._boundingClientRectFrame=this.time.frame,this._boundingClientRect=this.domElement.getBoundingClientRect(),this._domX=this._boundingClientRect.x,this._domY=this._boundingClientRect.y)}get domWidth(){return this.isInAR?window.innerWidth:this.domElement.clientWidth}get domHeight(){return this.isInAR?window.innerHeight:this.domElement.clientHeight}get domX(){return this.calculateBoundingClientRect(),this._domX}get domY(){return this.calculateBoundingClientRect(),this._domY}get isInXR(){var A;return((A=this.renderer.xr)==null?void 0:A.isPresenting)||!1}get isInVR(){return this.xrSessionMode==="immersive-vr"}get isInAR(){return this.xrSessionMode==="immersive-ar"}get xrSession(){var A;return(A=this.renderer.xr)==null?void 0:A.getSession()}get xrFrame(){return this._xrFrame}get arOverlayElement(){const A=this.domElement;return typeof A.getAROverlayContainer=="function"?A.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}get mainCamera(){if(this.mainCameraComponent){const A=this.mainCameraComponent;return A.cam||A.buildCamera(),A.cam}return null}get rendererData(){return this.sceneLighting}get isCreated(){return this._isCreated}internalOnUpdateVisible(){var A,e;(A=this._intersectionObserver)==null||A.disconnect(),(e=this._intersectionObserver)==null||e.observe(this.domElement)}updateSize(){var A,e,t;if(!this.isManagedExternally&&((A=this.renderer.xr)==null?void 0:A.isPresenting)===!1){this._sizeChanged=!1;const g=this.resolutionScaleFactor,I=this.domWidth*g,o=this.domHeight*g,C=this.mainCamera;this.updateAspect(C),this.renderer.setSize(I,o),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.composer&&((e=this.composer.setSize)==null||e.call(this.composer,I,o),"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&((t=this.composer.setPixelRatio)==null||t.call(this.composer,window.devicePixelRatio)))}}updateAspect(A,e,t){if(!A)return;e===void 0&&(e=this.domWidth),t===void 0&&(t=this.domHeight);const g=A.aspect;A.aspect=e/t,g!==A.aspect&&A.updateProjectionMatrix()}async onCreate(A,e){try{return this._isCreating=!0,await this.internalOnCreate(A,e)}finally{this._isCreating=!1}}clear(){var A;(A=this.scene)!=null&&A.children.length&&(js(this.scene,!0,!0),this.scene=new HI),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear())}dispose(){this.internalOnDestroy()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){var A,e,t;this.clear(),(A=this.renderer)==null||A.setAnimationLoop(null),this.isManagedExternally||(e=this.renderer)==null||e.dispose();for(const g of this._disposeCallbacks)try{g()}catch(I){console.error("Error in on dispose callback:",I,g)}(t=this.domElement)!=null&&t.parentElement&&this.domElement.parentElement.removeChild(this.domElement),ii.dispatchCallback(LI.ContextDestroyed,this),ii.unregister(this)}registerCoroutineUpdate(A,e,t){return this.coroutines[t]||(this.coroutines[t]=[]),this.coroutines[t].push({comp:A,main:e}),e}unregisterCoroutineUpdate(A,e){if(!this.coroutines[e])return;const t=this.coroutines[e].findIndex(g=>g.main===A);t>=0&&this.coroutines[e].splice(t,1)}stopAllCoroutinesFrom(A){for(const e in this.coroutines){const t=this.coroutines[e];for(let g=t.length-1;g>=0;g--)t[g].comp===A&&t.splice(g,1)}}setCurrentCamera(A){var g;if(!A)return;if(A.cam||A.buildCamera(),!A.cam){console.warn("Camera component is missing camera",A);return}const e=this._cameraStack.indexOf(A);e>=0&&this._cameraStack.splice(e,1),this._cameraStack.push(A),this.mainCameraComponent=A;const t=A.cam;t.isPerspectiveCamera&&this.updateAspect(t),(g=this.mainCameraComponent)==null||g.applyClearFlagsIfIsActiveCamera()}removeCamera(A){if(!A)return;const e=this._cameraStack.indexOf(A);if(e>=0&&this._cameraStack.splice(e,1),this.mainCameraComponent===A&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){const t=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(t)}}addBeforeRenderListener(A,e){var t;this._onBeforeRenderListeners.has(A.uuid)||(this._onBeforeRenderListeners.set(A.uuid,[]),A.onBeforeRender=this._createRenderCallbackWrapper(A,this._onBeforeRenderListeners)),(t=this._onBeforeRenderListeners.get(A.uuid))==null||t.push(e)}removeBeforeRenderListener(A,e){if(this._onBeforeRenderListeners.has(A.uuid)){const t=this._onBeforeRenderListeners.get(A.uuid),g=t.indexOf(e);g>=0&&t.splice(g,1)}}addAfterRenderListener(A,e){var t;this._onAfterRenderListeners.has(A.uuid)||(this._onAfterRenderListeners.set(A.uuid,[]),A.onAfterRender=this._createRenderCallbackWrapper(A,this._onAfterRenderListeners)),(t=this._onAfterRenderListeners.get(A.uuid))==null||t.push(e)}removeAfterRenderListener(A,e){if(this._onAfterRenderListeners.has(A.uuid)){const t=this._onAfterRenderListeners.get(A.uuid),g=t.indexOf(e);g>=0&&t.splice(g,1)}}_createRenderCallbackWrapper(A,e){return(t,g,I,o,C,s)=>{const n=e.get(A.uuid);if(n)for(let a=0;a<n.length;a++){const B=n[a];B(t,g,I,o,C,s)}}}get isRendering(){return this._isRendering}setRequireDepth(A){this._requireDepthTexture=A}setRequireColor(A){this._requireColorTexture=A}get depthTexture(){var A;return((A=this._renderTarget)==null?void 0:A.depthTexture)||null}get opaqueColorTexture(){var A;return((A=this._renderTarget)==null?void 0:A.texture)||null}get isVisibleToUser(){if(this.isInXR)return!0;if(!this._isVisible)return!1;const A=getComputedStyle(this.domElement);return A.visibility!=="hidden"&&A.display!=="none"&&A.opacity!=="0"}async internalOnCreate(A,e){var g;this.clear(),(g=this.renderer)==null||g.setAnimationLoop(null),await Gl(1),pe.Current=this,await ii.dispatchCallback(LI.ContextCreationStart,this);let t=!0;try{pe.Current=this,A&&await A(this,e)}catch(I){console.error(I),t=!1}if(!t)return!1;this.internalOnUpdateVisible(),!this.isManagedExternally&&!this.domElement.shadowRoot&&this.domElement.prepend(this.renderer.domElement),pe.Current=this,pe.Current=this;for(let I=0;I<this.new_scripts.length;I++){const o=this.new_scripts[I];if(o.gameObject!==void 0&&o.gameObject!==null){o.gameObject.userData===void 0&&(o.gameObject.userData={}),o.gameObject.userData.components===void 0&&(o.gameObject.userData.components=[]);const C=o.gameObject.userData.components;C.includes(o)||C.push(o)}}if(this.post_setup_callbacks)for(let I=0;I<this.post_setup_callbacks.length;I++)pe.Current=this,await this.post_setup_callbacks[I](this);if(!this.mainCamera){pe.Current=this;let I=null;xr(this.scene,o=>{const C=o;if(C!=null&&C.isCamera){if(ah(C.gameObject),!C.activeAndEnabled)return;if(C.tag==="MainCamera")return I=C,!0;I=C}}),I?this.setCurrentCamera(I):(ii.dispatchCallback(LI.MissingCamera,this),!this.mainCamera&&!this.isManagedExternally&&console.warn("Missing camera in main scene",this))}if(pe.Current=this,Jp(this),!this.isManagedExternally&&this.composer&&this.mainCamera){const I=new Dw(this.scene,this.mainCamera);this.renderer.setSize(this.domWidth,this.domHeight),this.composer.addPass(I),this.composer.setSize(this.domWidth,this.domHeight)}return this._sizeChanged=!0,this._stats&&(this._stats.showPanel(1),this.domElement.appendChild(this._stats.dom)),xS&&Rp(this.scene,!0),this._isCreating=!1,this.restartRenderLoop(),this._dispatchReadyAfterFrame=!0,ii.dispatchCallback(LI.ContextCreated,this)}restartRenderLoop(){if(!this.renderer)return console.error("Can not start render loop without renderer"),!1;if(this._isCreating)return console.warn("Can not start render loop while creating context"),!1;const A=this.render.bind(this);return this.renderer.setAnimationLoop(A),!0}render(A,e){if(Xg()||xS||Az())try{this.internalRender(A,e)}catch(t){(Xg()||xS)&&t instanceof Error&&eg("Exception during render-loop.<br/>See console for details.",Zo.Error),console.error(t),console.warn("Stopping render loop due to error"),this.renderer.setAnimationLoop(null),this.domElement.dispatchEvent(new CustomEvent("error",{detail:t}))}else this.internalRender(A,e)}internalRender(A,e){var t,g;if(this._xrFrame=e,this._currentFrameEvent=-1,this.isInXR===!1&&this.targetFrameRate!==void 0){if(this._accumulatedTime+=this._framerateClock.getDelta(),this._accumulatedTime<1/this.targetFrameRate)return;this._accumulatedTime=0}if((t=this._stats)==null||t.begin(),pe.Current=this,!this.onHandlePaused()){for(pe.Current=this,this.time.update(),f5&&console.log("FPS",this.time.smoothedFps.toFixed(0)),Jp(this),bD(this.scene),fx(this);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const I=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(I)}if(this.pre_update_callbacks)for(const I in this.pre_update_callbacks)this.pre_update_callbacks[I]();this._currentFrameEvent=0;for(let I=0;I<this.scripts_earlyUpdate.length;I++){const o=this.scripts_earlyUpdate[I];o.activeAndEnabled&&o.earlyUpdate!==void 0&&(pe.Current=this,o.earlyUpdate())}if(this.executeCoroutines(0),!this.onHandlePaused()){this._currentFrameEvent=1;for(let I=0;I<this.scripts_update.length;I++){const o=this.scripts_update[I];o.activeAndEnabled&&o.update!==void 0&&(pe.Current=this,o.update())}if(this.executeCoroutines(1),!this.onHandlePaused()){this._currentFrameEvent=2;for(let I=0;I<this.scripts_lateUpdate.length;I++){const o=this.scripts_lateUpdate[I];o.activeAndEnabled&&o.lateUpdate!==void 0&&(pe.Current=this,o.lateUpdate())}if(this.executeCoroutines(2),!this.onHandlePaused()){if(this.physics.engine){const o=this.time.deltaTime/1;for(let C=0;C<1;C++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.engine.step(o),this._currentFrameEvent=10,this.executeCoroutines(10);this.physics.engine.postStep()}if(!this.onHandlePaused()){if(this.isVisibleToUser){this._currentFrameEvent=3;for(let I=0;I<this.scripts_onBeforeRender.length;I++){const o=this.scripts_onBeforeRender[I];o.activeAndEnabled&&o.onBeforeRender!==void 0&&(pe.Current=this,o.onBeforeRender(e))}if(this.executeCoroutines(3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(const I in this.pre_render_callbacks)this.pre_render_callbacks[I]();this.isManagedExternally||(iz(this),this._currentFrameEvent=-1,this.renderNow(),this._currentFrameEvent=4);for(let I=0;I<this.scripts_onAfterRender.length;I++){const o=this.scripts_onAfterRender[I];o.activeAndEnabled&&o.onAfterRender!==void 0&&(pe.Current=this,o.onAfterRender())}if(this.executeCoroutines(4),this.post_render_callbacks)for(const I in this.post_render_callbacks)this.post_render_callbacks[I]()}this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),(g=this._stats)==null||g.end(),this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")))}}}}}}renderNow(A){return!A&&(A=this.mainCamera,!A)?!1:(this._isRendering=!0,this.renderRequiredTextures(),this.composer&&!this.isInXR?this.composer.render(this.time.deltaTime):A&&this.renderer.render(this.scene,A),this._isRendering=!1,!0)}onHandlePaused(){const A=this.evaluatePaused();if(this._wasPaused!==A){p5&&console.log("Paused?",A,"context:"+this.alias);for(let e=0;e<this.scripts_pausedChanged.length;e++){const t=this.scripts_pausedChanged[e];t.activeAndEnabled&&t.onPausedChanged!==void 0&&(pe.Current=this,t.onPausedChanged(A,this._wasPaused))}}return this._wasPaused=A,A}evaluatePaused(){return this.isInXR?!1:this.isPaused?!0:this.runInBackground?!1:!this.isVisibleToUser}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new rt(this.domWidth,this.domHeight),this._requireDepthTexture){const t=new bf(this.domWidth,this.domHeight);this._renderTarget.depthTexture=t}this._requireColorTexture&&(this._renderTarget.texture=new He,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=gt,this._renderTarget.texture.magFilter=gt,this._renderTarget.texture.format=qt)}const A=this._renderTarget;A.texture&&(A.texture.encoding=this.renderer.outputEncoding);const e=this.renderer.getRenderTarget();this.renderer.setRenderTarget(A),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(e)}executeCoroutines(A){if(this.coroutines[A]){const t=this.coroutines[A];for(let g=0;g<t.length;g++)try{const I=t[g];if(!I.comp||I.comp.destroyed||!I.main||I.comp.enabled===!1){w5&&console.log("Removing coroutine",I.comp,I.comp.enabled),t.splice(g,1),--g;continue}const C=I.chained;if(C&&C.length>0){const B=C[C.length-1].next();if(B.done&&C.pop(),e(B)&&(I.chained||(I.chained=[]),I.chained.push(B.value)),!B.done)continue}const s=I.main.next();if(s.done===!0){t.splice(g,1),--g;continue}const n=s.value;if(e(n)){if(n.next().done)continue;I.chained||(I.chained=[]),I.chained.push(n)}}catch(I){console.error(I)}}function e(t){return!!(t&&t.next&&t.return)}}}const k5=rA("debugaroverlay"),Br="ar",hK="quit-ar";class G5{constructor(){r(this,"arContainer",null);r(this,"closeARCallback");r(this,"currentSession",null);r(this,"registeredCloseEventElements",[]);r(this,"_createdAROnlyElements",[]);r(this,"_reparentedObjects",[]);this.closeARCallback=this.onRequestedEndAR.bind(this)}get ARContainer(){return this.arContainer}requestEndAR(){this.onRequestedEndAR()}onBegin(A,e,t){this.currentSession=t,this.arContainer=e,A.domElement.querySelectorAll(`.${Br}`).forEach(o=>{var C;o&&o!==this.arContainer&&(this._reparentedObjects.push({el:o,previousParent:o.parentElement}),(C=this.arContainer)==null||C.appendChild(o))});const I=e.getElementsByClassName(hK);if(!I||I.length<=0)console.warn(`Missing quit AR elements, creating fallback X button. Use class name '${hK}' to override.`),this.createFallbackCloseARButton(this.arContainer);else for(let o=0;o<I.length;o++){const C=I[o];C&&(C.addEventListener("click",this.closeARCallback),this.registeredCloseEventElements.push(C))}}onEnd(A){var e;for(const t of this._createdAROnlyElements)t.remove&&t.remove();for(const t of this._reparentedObjects){const g=t.el;(e=t.previousParent)==null||e.appendChild(g)}this._reparentedObjects.length=0,YG()&&setTimeout(()=>{const t=A.renderer.domElement;t&&A.domElement.insertBefore(t,A.domElement.firstChild);const g=document.querySelectorAll("*");for(var I=0;I<g.length;I++){const o=g[I];o&&o._displayChanged!==void 0&&o._displayWas!==void 0&&(o.style.display=o._displayWas)}},10)}findOrCreateARContainer(A){if(A.classList.contains(Br))return A;if(A.children)for(let g=0;g<A.children.length;g++){const I=A.children[g];if(!(!I||!I.classList)&&I.classList.contains(Br))return I}const e=document.getElementsByClassName(Br);if(e&&e.length>0)return e[0];k5&&console.log("No overlay container found in document - generating new ony");const t=document.createElement("div");return t.classList.add(Br),t.style.position="absolute",t.style.width="100%",t.style.height="100%",t.style.display="flex",t.style.visibility="visible",A.appendChild(t)}onRequestedEndAR(){if(this.currentSession){this.currentSession.end(),this.currentSession=null;for(const A of this.registeredCloseEventElements)A.removeEventListener("click",this.closeARCallback);this.registeredCloseEventElements.length=0}}createFallbackCloseARButton(A){var e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("width","38px"),e.setAttribute("height","38px"),e.style.position="absolute",e.style.right="20px",e.style.top="40px",e.style.zIndex="9999",e.style.pointerEvents="auto",e.addEventListener("click",this.closeARCallback),A.appendChild(e),this._createdAROnlyElements.push(e);var t=document.createElementNS("http://www.w3.org/2000/svg","path");t.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),t.setAttribute("stroke","#ddd"),t.setAttribute("stroke-width","3px"),e.appendChild(t),this._createdAROnlyElements.push(t)}}class eA extends UA{constructor(){super(...arguments);r(this,"guid")}static isDestroyed(e){return VM(e)}static setActive(e,t,g=!0){e&&(nh(e,t),bD(e),t&&g&&fx(pe.Current,e))}static isActiveSelf(e){return dE(e)}static isActiveInHierarchy(e){return cx(e)}static markAsInstancedRendered(e,t){hx(e,t)}static isUsingInstancing(e){return lw(e)}static foreachComponent(e,t,g=!0){return xr(e,t,g)}static instantiateSynced(e,t){return e?_M(e,t):null}static instantiate(e,t=null){return $l(e,t)}static destroySynced(e,t,g=!0){if(!e)return;const I=e;t=t??pe.Current,Bw(I,t.connection,g)}static destroy(e,t=!0,g=!0){return js(e,t,g)}static add(e,t,g){if(!(!e||!t)){if(e===t){console.warn("Can not add object to self",e);return}g||(g=pe.Current),t.add(e),nh(e,!0),bD(e),g?eA.foreachComponent(e,I=>{zM(I,g),!I.__internalDidAwakeAndStart&&g.new_script_start.includes(I)===!1&&g.new_script_start.push(I)},!0):console.warn("Missing context")}}static remove(e){var t;e&&((t=e.parent)==null||t.remove(e),nh(e,!1),bD(e),eA.foreachComponent(e,g=>{ez(g)},!0))}static invokeOnChildren(e,t,...g){this.invoke(e,t,!0,g)}static invoke(e,t,g=!1,...I){e&&this.foreachComponent(e,o=>{const C=o[t];C&&typeof C=="function"&&(C==null||C.call(o,...I))},g)}static addNewComponent(e,t,g=!0){const I=new t;return Xr(e,I,g),I}static addComponent(e,t){return this.moveComponent(e,t)}static moveComponent(e,t){return PM(e,t)}static removeComponent(e){return OM(e.gameObject,e),e}static getOrAddComponent(e,t){return Ew(e,t)}static getComponent(e,t){return e===null?null:hE(e,t)}static getComponents(e,t,g=null){return e===null?g??[]:zl(e,t,g)}static findByGuid(e,t){return Xl(e,t)}static findObjectOfType(e,t,g=!0){return ox(e,t??pe.Current,g)}static findObjectsOfType(e,t){const g=[];return Cx(e,g,t),g}static getComponentInChildren(e,t){return lE(e,t)}static getComponentsInChildren(e,t,g=null){return Zl(e,t,g??void 0)}static getComponentInParent(e,t){return Wh(e,t)}static getComponentsInParent(e,t,g=null){return cw(e,t,g)}static getAllComponents(e){var I;return[...(I=e.userData)==null?void 0:I.components]}static*iterateComponents(e){var g;const t=(g=e==null?void 0:e.userData)==null?void 0:g.components;if(t&&Array.isArray(t))for(let I=0;I<t.length;I++)yield t[I]}}var ei;let Ma=(ei=class{constructor(){r(this,"__context");r(this,"__name");r(this,"gameObject");r(this,"guid","invalid");r(this,"sourceId");r(this,"__didAwake",!1);r(this,"__didStart",!1);r(this,"__didEnable",!1);r(this,"__isEnabled");r(this,"__destroyed",!1);r(this,"_worldPosition");r(this,"_worldQuaternion");r(this,"_worldEuler");r(this,"_worldRotation");r(this,"_eventListeners",new Map);this.__internalNewInstanceCreated()}get isComponent(){return!0}get context(){return this.__context??pe.Current}set context(A){this.__context=A}get scene(){return this.context.scene}get layer(){var A,e;return(e=(A=this.gameObject)==null?void 0:A.userData)==null?void 0:e.layer}get name(){var A,e;return(A=this.gameObject)!=null&&A.name?this.gameObject.name:(e=this.gameObject)==null?void 0:e.userData.name}set name(A){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=A,this.__name=A):this.__name=A}get tag(){var A;return(A=this.gameObject)==null?void 0:A.userData.tag}set tag(A){this.gameObject&&(this.gameObject.userData.tag=A)}get static(){var A;return(A=this.gameObject)==null?void 0:A.userData.static}get hideFlags(){var A;return(A=this.gameObject)==null?void 0:A.userData.hideFlags}get activeAndEnabled(){return!(this.destroyed||this.__isEnabled===!1||!this.__isActiveInHierarchy)}get __isActive(){return this.gameObject.visible}get __isActiveInHierarchy(){if(!this.gameObject)return!1;const A=this.gameObject[Hs];return A===void 0?!0:A}set __isActiveInHierarchy(A){this.gameObject&&(this.gameObject[Hs]=A)}awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(A,e=OI.Update){return this.context.registerCoroutineUpdate(this,A,e)}stopCoroutine(A,e=OI.Update){this.context.unregisterCoroutineUpdate(A,e)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}__internalNewInstanceCreated(){this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(A){return this.__destroyed?(Xg()&&console.warn("[Needle Engine Dev] Trying to enable destroyed component"),!1):this.__didAwake?this.__didEnable?(A!==!0&&(this.__isEnabled=!0),!1):(this.__didEnable=!0,this.__isEnabled=!0,this.onEnable(),!0):!1}__internalDisable(A){if(this.__didAwake){if(!this.__didEnable){A!==!0&&(this.__isEnabled=!1);return}this.__didEnable=!1,this.__isEnabled=!1,this.onDisable()}}__internalDestroy(){var A;this.__destroyed||(this.__destroyed=!0,(A=this.destroy)==null||A.call(this),this.dispatchEvent(new CustomEvent("destroyed",{detail:this})),gx(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(A){if(this.__destroyed){Xg()&&console.warn(`[Needle Engine Dev] Trying to ${A?"enable":"disable"} destroyed component`);return}if(typeof A=="number"&&(A>=.5?A=!0:A=!1),!this.__didAwake){this.__isEnabled=A;return}A?this.__internalEnable():this.__internalDisable()}get worldPosition(){return this._worldPosition||(this._worldPosition=new k),ye(this.gameObject,this._worldPosition),this._worldPosition}set worldPosition(A){hi(this.gameObject,A)}setWorldPosition(A,e,t){ei._worldPositionBuffer.set(A,e,t),this.worldPosition=ei._worldPositionBuffer}get worldQuaternion(){return this._worldQuaternion||(this._worldQuaternion=new kA),Hi(this.gameObject,this._worldQuaternion)}set worldQuaternion(A){fI(this.gameObject,A)}setWorldQuaternion(A,e,t,g){ei._worldQuaternionBuffer.set(A,e,t,g),this.worldQuaternion=ei._worldQuaternionBuffer}get worldEuler(){return this._worldEuler||(this._worldEuler=new Ui),this._worldEuler.setFromQuaternion(this.worldQuaternion),this._worldEuler}set worldEuler(A){var e;this._worldQuaternion||(this._worldQuaternion=new kA),(e=this._worldQuaternion)==null||e.setFromEuler(A),this.worldQuaternion=this._worldQuaternion}get worldRotation(){const A=this.worldEuler;this._worldRotation||(this._worldRotation=new k);const e=this._worldRotation;return e.set(A.x,A.y,A.z),e.x=Ae.toDegrees(e.x),e.y=Ae.toDegrees(e.y),e.z=Ae.toDegrees(e.z),e}set worldRotation(A){this.setWorldRotation(A.x,A.y,A.z,!0)}setWorldRotation(A,e,t,g=!0){g&&(A=Ae.toRadians(A),e=Ae.toRadians(e),t=Ae.toRadians(t)),ei._worldEulerBuffer.set(A,e,t),ei._worldQuaternionBuffer.setFromEuler(ei._worldEulerBuffer),this.worldQuaternion=ei._worldQuaternionBuffer}get forward(){return ei._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}get right(){return ei._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}get up(){return ei._up.set(0,1,0).applyQuaternion(this.worldQuaternion)}addEventListener(A,e){this._eventListeners[A]=this._eventListeners[A]||[],this._eventListeners[A].push(e)}removeEventListener(A,e){if(!this._eventListeners[A])return;const t=this._eventListeners[A].indexOf(e);t>=0&&this._eventListeners[A].splice(t,1)}dispatchEvent(A){if(!this._eventListeners[A.type])return!1;const e=this._eventListeners[A.type];for(let t=0;t<e.length;t++)e[t](A);return!1}},r(ei,"_worldPositionBuffer",new k),r(ei,"_worldQuaternionBuffer",new kA),r(ei,"_worldEulerBuffer",new Ui),r(ei,"_tempQuaternionBuffer2",new kA),r(ei,"_forward",new k),r(ei,"_right",new k),r(ei,"_up",new k),ei);class MA extends Ma{}const M5=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:MA,Component:Ma,GameObject:eA},Symbol.toStringTag,{value:"Module"})),m5='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 160 187.74"><defs><linearGradient id="a" x1="89.64" y1="184.81" x2="90.48" y2="21.85" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#62d399"/><stop offset=".51" stop-color="#acd842"/><stop offset=".9" stop-color="#d7db0a"/></linearGradient><linearGradient id="b" x1="69.68" y1="178.9" x2="68.08" y2="16.77" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#0ba398"/><stop offset=".5" stop-color="#4ca352"/><stop offset="1" stop-color="#76a30a"/></linearGradient><linearGradient id="c" x1="36.6" y1="152.17" x2="34.7" y2="84.19" gradientUnits="userSpaceOnUse"><stop offset=".19" stop-color="#36a382"/><stop offset=".54" stop-color="#49a459"/><stop offset="1" stop-color="#76a30b"/></linearGradient><linearGradient id="d" x1="15.82" y1="153.24" x2="18" y2="90.86" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#267880"/><stop offset=".51" stop-color="#457a5c"/><stop offset="1" stop-color="#717516"/></linearGradient><linearGradient id="e" x1="135.08" y1="135.43" x2="148.93" y2="63.47" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#b0d939"/><stop offset="1" stop-color="#eadb04"/></linearGradient><linearGradient id="f" x1="-4163.25" y1="2285.12" x2="-4160.81" y2="2215.34" gradientTransform="rotate(20 4088.49 13316.712)" gradientUnits="userSpaceOnUse"><stop offset=".17" stop-color="#74af52"/><stop offset=".48" stop-color="#99be32"/><stop offset="1" stop-color="#c0c40a"/></linearGradient><symbol id="g" viewBox="0 0 160 187.74"><path style="fill:url(#a)" d="M79.32 36.98v150.76L95 174.54l6.59-156.31-22.27 18.75z"/><path style="fill:url(#b)" d="M79.32 36.98 57.05 18.23l6.59 156.31 15.68 13.2V36.98z"/><path style="fill:url(#c)" d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33z"/><path style="fill:url(#d)" d="M25.19 104.83 0 90.24l16.97 53.86 16.85 9.77-8.63-49.04z"/><path style="fill:#9c3" d="M43.86 82.5 18.69 67.98 0 90.24l25.18 14.59L43.86 82.5z"/><path style="fill:url(#e)" d="m134.82 78.69-9.97 56.5 15.58-9.04L160 64.1l-25.18 14.59z"/><path style="fill:url(#f)" d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5z"/><path style="fill:#ffe113" d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33L160 64.1z"/><path style="fill:#f3e600" d="M101.59 18.23 79.32 0 57.05 18.23l22.27 18.75 22.27-18.75z"/></symbol></defs><use width="160" height="187.74" xlink:href="#g"/></svg>',R5=new Blob([m5],{type:"image/svg+xml;charset=utf-8"}),U5=URL.createObjectURL(R5),eY=U5,wr=rA("debuglicense"),Im="basic";wr&&console.log("License Type: "+Im);function na(){switch(Im){case"pro":case"enterprise":return!0}return!1}function tY(){switch(Im){case"indie":return!0}return!1}function iY(){return na()||tY()}ii.registerCallback(LI.ContextRegistered,i=>{F5(i.context)});async function F5(i){try{if(na()!==!0)return YS(i)}catch(A){return wr&&console.log("License check failed",A),YS(i)}wr&&YS(i)}const gY="needle-license-element",$k=5e3,AG=200;function YS(i){K5(),i.domElement.addEventListener("ready",()=>{setTimeout(()=>{N5(i)},1e3)}),b5()}function N5(i){const A=J5(),e=q5(),t=setInterval(()=>{if(!A)return;const s=i.domElement.shadowRoot||i.domElement;A.parentNode!==s&&(s.appendChild(A),e&&s.appendChild(e))},100);let g=`<img class="logo" src="${eY}" style="width: 40px; height: 40px; margin-right: 2px; vertical-align: middle; margin-bottom: 2px;"/>`;const I=document.createElement("div");I.innerHTML=g,I.classList.add("logo"),A.appendChild(I);const o=document.createElement("div");o.classList.add("text"),A.appendChild(o),A.title="Needle Engine",iY()||(A.title+=" non commercial version"),A.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")});const C=$k+AG;setTimeout(()=>{clearInterval(t),A==null||A.remove(),e==null||e.remove()},C)}let lK=0;async function K5(i){const A=Date.now();if(A-lK<2e3)return;lK=A;const t=`
3836
+ #endif`);ZA.lightmap.lightmapScaleOffset={value:new Ce(1,1,0,0)};const u5=rA("debugplayerview");var vC=(i=>(i.Browser="browser",i.Headset="headset",i.Handheld="handheld",i))(vC||{});class $x{constructor(A,e){r(this,"userId");r(this,"context");r(this,"viewDevice","browser");r(this,"removed",!1);r(this,"_object");this.userId=A,this.context=e}get currentObject(){return this._object}set currentObject(A){this._object=A}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class AY{constructor(A){r(this,"context");r(this,"playerViews",new Map);this.context=A}setPlayerView(A,e,t){let g=this.playerViews.get(A);g||(g=new $x(A,this.context),this.playerViews.set(A,g)),g.viewDevice=t,g.currentObject=e,g.removed=!1}getPlayerView(A){if(!A)return;if(!this.context.connection.userIsInRoom(A)){this.playerViews.delete(A);return}return this.playerViews.get(A)}removePlayerView(A,e){const t=this.playerViews.get(A);(t==null?void 0:t.viewDevice)===e&&(u5&&console.log("REMOVE",A),t.removed=!0,this.playerViews.delete(A))}}const xS=rA("debugSetup"),D5=rA("stats"),p5=rA("debugactive"),f5=rA("debugframerate"),w5=rA("debugcoroutine"),y5={};class S5{constructor(A){r(this,"name");r(this,"alias");r(this,"domElement");r(this,"renderer");r(this,"hash");this.domElement=A??document.body}}var OI=(i=>(i[i.EarlyUpdate=0]="EarlyUpdate",i[i.Update=1]="Update",i[i.LateUpdate=2]="LateUpdate",i[i.OnBeforeRender=3]="OnBeforeRender",i[i.OnAfterRender=4]="OnAfterRender",i[i.PrePhysicsStep=9]="PrePhysicsStep",i[i.PostPhysicsStep=10]="PostPhysicsStep",i[i.Undefined=-1]="Undefined",i))(OI||{}),jh=(i=>(i.ImmersiveVR="immersive-vr",i.ImmersiveAR="immersive-ar",i))(jh||{});function pw(i,A){if(!i)return;const e=(A==null?void 0:A.new_scripts)??pe.Current.new_scripts;e.includes(i)||e.push(i)}class pe{constructor(A){r(this,"name");r(this,"alias");r(this,"isManagedExternally",!1);r(this,"isPaused",!1);r(this,"runInBackground",!1);r(this,"targetFrameRate");r(this,"hash");r(this,"domElement");r(this,"_resolutionScaleFactor",1);r(this,"_boundingClientRectFrame",-1);r(this,"_boundingClientRect",null);r(this,"_domX");r(this,"_domY");r(this,"xrSessionMode");r(this,"_xrFrame",null);r(this,"_currentFrameEvent",-1);r(this,"scene");r(this,"renderer");r(this,"composer",null);r(this,"scripts",[]);r(this,"scripts_pausedChanged",[]);r(this,"scripts_earlyUpdate",[]);r(this,"scripts_update",[]);r(this,"scripts_lateUpdate",[]);r(this,"scripts_onBeforeRender",[]);r(this,"scripts_onAfterRender",[]);r(this,"scripts_WithCorroutines",[]);r(this,"coroutines",{});r(this,"mainCameraComponent");r(this,"post_setup_callbacks",[]);r(this,"pre_update_callbacks",[]);r(this,"pre_render_callbacks",[]);r(this,"post_render_callbacks",[]);r(this,"new_scripts",[]);r(this,"new_script_start",[]);r(this,"new_scripts_pre_setup_callbacks",[]);r(this,"new_scripts_post_setup_callbacks",[]);r(this,"application");r(this,"time");r(this,"input");r(this,"physics");r(this,"connection");r(this,"assets");r(this,"mainLight",null);r(this,"sceneLighting");r(this,"addressables");r(this,"lightmaps");r(this,"players");r(this,"_sizeChanged",!1);r(this,"_isCreated",!1);r(this,"_isCreating",!1);r(this,"_isVisible",!1);r(this,"_stats",D5?t5():null);r(this,"_intersectionObserver",null);r(this,"_disposeCallbacks",[]);r(this,"_cameraStack",[]);r(this,"_onBeforeRenderListeners",new Map);r(this,"_onAfterRenderListeners",new Map);r(this,"_requireDepthTexture",!1);r(this,"_requireColorTexture",!1);r(this,"_renderTarget");r(this,"_isRendering",!1);r(this,"_accumulatedTime",0);r(this,"_framerateClock",new zf);r(this,"_dispatchReadyAfterFrame",!1);r(this,"_wasPaused",!1);var g,I;if(this.name=(A==null?void 0:A.name)||"",this.alias=A==null?void 0:A.alias,this.domElement=(A==null?void 0:A.domElement)||document.body,this.hash=A==null?void 0:A.hash,A!=null&&A.renderer)this.renderer=A.renderer,this.isManagedExternally=!0;else{const o={antialias:!0},C=(I=(g=A==null?void 0:A.domElement)==null?void 0:g.shadowRoot)==null?void 0:I.querySelector("canvas");C&&(o.canvas=C),this.renderer=new IE(o),this.renderer.toneMappingExposure=1,this.renderer.toneMapping=Pg,this.renderer.setClearColor(new yA("lightgrey"),0),this.renderer.antialias=!0,this.renderer.alpha=!1,this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=HG,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputEncoding=De,this.renderer.physicallyCorrectLights=!0}this.scene=new HI,ii.register(this),this.application=new Xx(this),this.time=new zL,this.input=new xL(this),this.physics=new jL(this),this.connection=new Pv(this),this.assets=new nx,this.sceneLighting=new zx(this),this.addressables=new Vx(this),this.lightmaps=new d5(this),this.players=new AY(this);const e=()=>this._sizeChanged=!0;window.addEventListener("resize",e),this._disposeCallbacks.push(()=>window.removeEventListener("resize",e));const t=new ResizeObserver(o=>this._sizeChanged=!0);t.observe(this.domElement),this._disposeCallbacks.push(()=>t.disconnect()),this._intersectionObserver=new IntersectionObserver(o=>{this._isVisible=o[0].isIntersecting}),this._disposeCallbacks.push(()=>{var o;return(o=this._intersectionObserver)==null?void 0:o.disconnect()})}get version(){return Wv}static get Current(){return ii.Current}static set Current(A){ii.Current=A}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(A){if(A!==this._resolutionScaleFactor&&typeof A=="number"){if(A<=0){console.error("Invalid resolution scale factor",A);return}this._resolutionScaleFactor=A,this.updateSize()}}calculateBoundingClientRect(){if(this.isInAR){this._domX=0,this._domY=0;return}this._boundingClientRectFrame!==this.time.frame&&(this._boundingClientRectFrame=this.time.frame,this._boundingClientRect=this.domElement.getBoundingClientRect(),this._domX=this._boundingClientRect.x,this._domY=this._boundingClientRect.y)}get domWidth(){return this.isInAR?window.innerWidth:this.domElement.clientWidth}get domHeight(){return this.isInAR?window.innerHeight:this.domElement.clientHeight}get domX(){return this.calculateBoundingClientRect(),this._domX}get domY(){return this.calculateBoundingClientRect(),this._domY}get isInXR(){var A;return((A=this.renderer.xr)==null?void 0:A.isPresenting)||!1}get isInVR(){return this.xrSessionMode==="immersive-vr"}get isInAR(){return this.xrSessionMode==="immersive-ar"}get xrSession(){var A;return(A=this.renderer.xr)==null?void 0:A.getSession()}get xrFrame(){return this._xrFrame}get arOverlayElement(){const A=this.domElement;return typeof A.getAROverlayContainer=="function"?A.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}get mainCamera(){if(this.mainCameraComponent){const A=this.mainCameraComponent;return A.cam||A.buildCamera(),A.cam}return null}get rendererData(){return this.sceneLighting}get isCreated(){return this._isCreated}internalOnUpdateVisible(){var A,e;(A=this._intersectionObserver)==null||A.disconnect(),(e=this._intersectionObserver)==null||e.observe(this.domElement)}updateSize(){var A,e,t;if(!this.isManagedExternally&&((A=this.renderer.xr)==null?void 0:A.isPresenting)===!1){this._sizeChanged=!1;const g=this.resolutionScaleFactor,I=this.domWidth*g,o=this.domHeight*g,C=this.mainCamera;this.updateAspect(C),this.renderer.setSize(I,o),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.composer&&((e=this.composer.setSize)==null||e.call(this.composer,I,o),"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&((t=this.composer.setPixelRatio)==null||t.call(this.composer,window.devicePixelRatio)))}}updateAspect(A,e,t){if(!A)return;e===void 0&&(e=this.domWidth),t===void 0&&(t=this.domHeight);const g=A.aspect;A.aspect=e/t,g!==A.aspect&&A.updateProjectionMatrix()}async onCreate(A,e){try{return this._isCreating=!0,await this.internalOnCreate(A,e)}finally{this._isCreating=!1}}clear(){var A;(A=this.scene)!=null&&A.children.length&&(js(this.scene,!0,!0),this.scene=new HI),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear())}dispose(){this.internalOnDestroy()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){var A,e,t;this.clear(),(A=this.renderer)==null||A.setAnimationLoop(null),this.isManagedExternally||(e=this.renderer)==null||e.dispose();for(const g of this._disposeCallbacks)try{g()}catch(I){console.error("Error in on dispose callback:",I,g)}(t=this.domElement)!=null&&t.parentElement&&this.domElement.parentElement.removeChild(this.domElement),ii.dispatchCallback(LI.ContextDestroyed,this),ii.unregister(this)}registerCoroutineUpdate(A,e,t){return this.coroutines[t]||(this.coroutines[t]=[]),this.coroutines[t].push({comp:A,main:e}),e}unregisterCoroutineUpdate(A,e){if(!this.coroutines[e])return;const t=this.coroutines[e].findIndex(g=>g.main===A);t>=0&&this.coroutines[e].splice(t,1)}stopAllCoroutinesFrom(A){for(const e in this.coroutines){const t=this.coroutines[e];for(let g=t.length-1;g>=0;g--)t[g].comp===A&&t.splice(g,1)}}setCurrentCamera(A){var g;if(!A)return;if(A.cam||A.buildCamera(),!A.cam){console.warn("Camera component is missing camera",A);return}const e=this._cameraStack.indexOf(A);e>=0&&this._cameraStack.splice(e,1),this._cameraStack.push(A),this.mainCameraComponent=A;const t=A.cam;t.isPerspectiveCamera&&this.updateAspect(t),(g=this.mainCameraComponent)==null||g.applyClearFlagsIfIsActiveCamera()}removeCamera(A){if(!A)return;const e=this._cameraStack.indexOf(A);if(e>=0&&this._cameraStack.splice(e,1),this.mainCameraComponent===A&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){const t=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(t)}}addBeforeRenderListener(A,e){var t;this._onBeforeRenderListeners.has(A.uuid)||(this._onBeforeRenderListeners.set(A.uuid,[]),A.onBeforeRender=this._createRenderCallbackWrapper(A,this._onBeforeRenderListeners)),(t=this._onBeforeRenderListeners.get(A.uuid))==null||t.push(e)}removeBeforeRenderListener(A,e){if(this._onBeforeRenderListeners.has(A.uuid)){const t=this._onBeforeRenderListeners.get(A.uuid),g=t.indexOf(e);g>=0&&t.splice(g,1)}}addAfterRenderListener(A,e){var t;this._onAfterRenderListeners.has(A.uuid)||(this._onAfterRenderListeners.set(A.uuid,[]),A.onAfterRender=this._createRenderCallbackWrapper(A,this._onAfterRenderListeners)),(t=this._onAfterRenderListeners.get(A.uuid))==null||t.push(e)}removeAfterRenderListener(A,e){if(this._onAfterRenderListeners.has(A.uuid)){const t=this._onAfterRenderListeners.get(A.uuid),g=t.indexOf(e);g>=0&&t.splice(g,1)}}_createRenderCallbackWrapper(A,e){return(t,g,I,o,C,s)=>{const n=e.get(A.uuid);if(n)for(let a=0;a<n.length;a++){const B=n[a];B(t,g,I,o,C,s)}}}get isRendering(){return this._isRendering}setRequireDepth(A){this._requireDepthTexture=A}setRequireColor(A){this._requireColorTexture=A}get depthTexture(){var A;return((A=this._renderTarget)==null?void 0:A.depthTexture)||null}get opaqueColorTexture(){var A;return((A=this._renderTarget)==null?void 0:A.texture)||null}get isVisibleToUser(){if(this.isInXR)return!0;if(!this._isVisible)return!1;const A=getComputedStyle(this.domElement);return A.visibility!=="hidden"&&A.display!=="none"&&A.opacity!=="0"}async internalOnCreate(A,e){var g;this.clear(),(g=this.renderer)==null||g.setAnimationLoop(null),await Gl(1),pe.Current=this,await ii.dispatchCallback(LI.ContextCreationStart,this);let t=!0;try{pe.Current=this,A&&await A(this,e)}catch(I){console.error(I),t=!1}if(!t)return!1;this.internalOnUpdateVisible(),!this.isManagedExternally&&!this.domElement.shadowRoot&&this.domElement.prepend(this.renderer.domElement),pe.Current=this,pe.Current=this;for(let I=0;I<this.new_scripts.length;I++){const o=this.new_scripts[I];if(o.gameObject!==void 0&&o.gameObject!==null){o.gameObject.userData===void 0&&(o.gameObject.userData={}),o.gameObject.userData.components===void 0&&(o.gameObject.userData.components=[]);const C=o.gameObject.userData.components;C.includes(o)||C.push(o)}}if(this.post_setup_callbacks)for(let I=0;I<this.post_setup_callbacks.length;I++)pe.Current=this,await this.post_setup_callbacks[I](this);if(!this.mainCamera){pe.Current=this;let I=null;xr(this.scene,o=>{const C=o;if(C!=null&&C.isCamera){if(ah(C.gameObject),!C.activeAndEnabled)return;if(C.tag==="MainCamera")return I=C,!0;I=C}}),I?this.setCurrentCamera(I):!ii.dispatchCallback(LI.MissingCamera,this)&&!this.mainCamera&&!this.isManagedExternally&&console.warn("Missing camera in main scene",this)}if(pe.Current=this,Jp(this),!this.isManagedExternally&&this.composer&&this.mainCamera){const I=new Dw(this.scene,this.mainCamera);this.renderer.setSize(this.domWidth,this.domHeight),this.composer.addPass(I),this.composer.setSize(this.domWidth,this.domHeight)}return this._sizeChanged=!0,this._stats&&(this._stats.showPanel(1),this.domElement.appendChild(this._stats.dom)),xS&&Rp(this.scene,!0),this._isCreating=!1,this.restartRenderLoop(),this._dispatchReadyAfterFrame=!0,ii.dispatchCallback(LI.ContextCreated,this)}restartRenderLoop(){if(!this.renderer)return console.error("Can not start render loop without renderer"),!1;if(this._isCreating)return console.warn("Can not start render loop while creating context"),!1;const A=this.render.bind(this);return this.renderer.setAnimationLoop(A),!0}render(A,e){if(Xg()||xS||Az())try{this.internalRender(A,e)}catch(t){(Xg()||xS)&&t instanceof Error&&eg("Exception during render-loop.<br/>See console for details.",Zo.Error),console.error(t),console.warn("Stopping render loop due to error"),this.renderer.setAnimationLoop(null),this.domElement.dispatchEvent(new CustomEvent("error",{detail:t}))}else this.internalRender(A,e)}internalRender(A,e){var t,g;if(this._xrFrame=e,this._currentFrameEvent=-1,this.isInXR===!1&&this.targetFrameRate!==void 0){if(this._accumulatedTime+=this._framerateClock.getDelta(),this._accumulatedTime<1/this.targetFrameRate)return;this._accumulatedTime=0}if((t=this._stats)==null||t.begin(),pe.Current=this,!this.onHandlePaused()){for(pe.Current=this,this.time.update(),f5&&console.log("FPS",this.time.smoothedFps.toFixed(0)),Jp(this),bD(this.scene),fx(this);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const I=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(I)}if(this.pre_update_callbacks)for(const I in this.pre_update_callbacks)this.pre_update_callbacks[I]();this._currentFrameEvent=0;for(let I=0;I<this.scripts_earlyUpdate.length;I++){const o=this.scripts_earlyUpdate[I];o.activeAndEnabled&&o.earlyUpdate!==void 0&&(pe.Current=this,o.earlyUpdate())}if(this.executeCoroutines(0),!this.onHandlePaused()){this._currentFrameEvent=1;for(let I=0;I<this.scripts_update.length;I++){const o=this.scripts_update[I];o.activeAndEnabled&&o.update!==void 0&&(pe.Current=this,o.update())}if(this.executeCoroutines(1),!this.onHandlePaused()){this._currentFrameEvent=2;for(let I=0;I<this.scripts_lateUpdate.length;I++){const o=this.scripts_lateUpdate[I];o.activeAndEnabled&&o.lateUpdate!==void 0&&(pe.Current=this,o.lateUpdate())}if(this.executeCoroutines(2),!this.onHandlePaused()){if(this.physics.engine){const o=this.time.deltaTime/1;for(let C=0;C<1;C++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.engine.step(o),this._currentFrameEvent=10,this.executeCoroutines(10);this.physics.engine.postStep()}if(!this.onHandlePaused()){if(this.isVisibleToUser){this._currentFrameEvent=3;for(let I=0;I<this.scripts_onBeforeRender.length;I++){const o=this.scripts_onBeforeRender[I];o.activeAndEnabled&&o.onBeforeRender!==void 0&&(pe.Current=this,o.onBeforeRender(e))}if(this.executeCoroutines(3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(const I in this.pre_render_callbacks)this.pre_render_callbacks[I]();this.isManagedExternally||(iz(this),this._currentFrameEvent=-1,this.renderNow(),this._currentFrameEvent=4);for(let I=0;I<this.scripts_onAfterRender.length;I++){const o=this.scripts_onAfterRender[I];o.activeAndEnabled&&o.onAfterRender!==void 0&&(pe.Current=this,o.onAfterRender())}if(this.executeCoroutines(4),this.post_render_callbacks)for(const I in this.post_render_callbacks)this.post_render_callbacks[I]()}this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),(g=this._stats)==null||g.end(),this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")))}}}}}}renderNow(A){return!A&&(A=this.mainCamera,!A)?!1:(this._isRendering=!0,this.renderRequiredTextures(),this.composer&&!this.isInXR?this.composer.render(this.time.deltaTime):A&&this.renderer.render(this.scene,A),this._isRendering=!1,!0)}onHandlePaused(){const A=this.evaluatePaused();if(this._wasPaused!==A){p5&&console.log("Paused?",A,"context:"+this.alias);for(let e=0;e<this.scripts_pausedChanged.length;e++){const t=this.scripts_pausedChanged[e];t.activeAndEnabled&&t.onPausedChanged!==void 0&&(pe.Current=this,t.onPausedChanged(A,this._wasPaused))}}return this._wasPaused=A,A}evaluatePaused(){return this.isInXR?!1:this.isPaused?!0:this.runInBackground?!1:!this.isVisibleToUser}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new rt(this.domWidth,this.domHeight),this._requireDepthTexture){const t=new bf(this.domWidth,this.domHeight);this._renderTarget.depthTexture=t}this._requireColorTexture&&(this._renderTarget.texture=new He,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=gt,this._renderTarget.texture.magFilter=gt,this._renderTarget.texture.format=qt)}const A=this._renderTarget;A.texture&&(A.texture.encoding=this.renderer.outputEncoding);const e=this.renderer.getRenderTarget();this.renderer.setRenderTarget(A),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(e)}executeCoroutines(A){if(this.coroutines[A]){const t=this.coroutines[A];for(let g=0;g<t.length;g++)try{const I=t[g];if(!I.comp||I.comp.destroyed||!I.main||I.comp.enabled===!1){w5&&console.log("Removing coroutine",I.comp,I.comp.enabled),t.splice(g,1),--g;continue}const C=I.chained;if(C&&C.length>0){const B=C[C.length-1].next();if(B.done&&C.pop(),e(B)&&(I.chained||(I.chained=[]),I.chained.push(B.value)),!B.done)continue}const s=I.main.next();if(s.done===!0){t.splice(g,1),--g;continue}const n=s.value;if(e(n)){if(n.next().done)continue;I.chained||(I.chained=[]),I.chained.push(n)}}catch(I){console.error(I)}}function e(t){return!!(t&&t.next&&t.return)}}}const k5=rA("debugaroverlay"),Br="ar",hK="quit-ar";class G5{constructor(){r(this,"arContainer",null);r(this,"closeARCallback");r(this,"currentSession",null);r(this,"registeredCloseEventElements",[]);r(this,"_createdAROnlyElements",[]);r(this,"_reparentedObjects",[]);this.closeARCallback=this.onRequestedEndAR.bind(this)}get ARContainer(){return this.arContainer}requestEndAR(){this.onRequestedEndAR()}onBegin(A,e,t){this.currentSession=t,this.arContainer=e,A.domElement.querySelectorAll(`.${Br}`).forEach(o=>{var C;o&&o!==this.arContainer&&(this._reparentedObjects.push({el:o,previousParent:o.parentElement}),(C=this.arContainer)==null||C.appendChild(o))});const I=e.getElementsByClassName(hK);if(!I||I.length<=0)console.warn(`Missing quit AR elements, creating fallback X button. Use class name '${hK}' to override.`),this.createFallbackCloseARButton(this.arContainer);else for(let o=0;o<I.length;o++){const C=I[o];C&&(C.addEventListener("click",this.closeARCallback),this.registeredCloseEventElements.push(C))}}onEnd(A){var e;for(const t of this._createdAROnlyElements)t.remove&&t.remove();for(const t of this._reparentedObjects){const g=t.el;(e=t.previousParent)==null||e.appendChild(g)}this._reparentedObjects.length=0,YG()&&setTimeout(()=>{const t=A.renderer.domElement;t&&A.domElement.insertBefore(t,A.domElement.firstChild);const g=document.querySelectorAll("*");for(var I=0;I<g.length;I++){const o=g[I];o&&o._displayChanged!==void 0&&o._displayWas!==void 0&&(o.style.display=o._displayWas)}},10)}findOrCreateARContainer(A){if(A.classList.contains(Br))return A;if(A.children)for(let g=0;g<A.children.length;g++){const I=A.children[g];if(!(!I||!I.classList)&&I.classList.contains(Br))return I}const e=document.getElementsByClassName(Br);if(e&&e.length>0)return e[0];k5&&console.log("No overlay container found in document - generating new ony");const t=document.createElement("div");return t.classList.add(Br),t.style.position="absolute",t.style.width="100%",t.style.height="100%",t.style.display="flex",t.style.visibility="visible",A.appendChild(t)}onRequestedEndAR(){if(this.currentSession){this.currentSession.end(),this.currentSession=null;for(const A of this.registeredCloseEventElements)A.removeEventListener("click",this.closeARCallback);this.registeredCloseEventElements.length=0}}createFallbackCloseARButton(A){var e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("width","38px"),e.setAttribute("height","38px"),e.style.position="absolute",e.style.right="20px",e.style.top="40px",e.style.zIndex="9999",e.style.pointerEvents="auto",e.addEventListener("click",this.closeARCallback),A.appendChild(e),this._createdAROnlyElements.push(e);var t=document.createElementNS("http://www.w3.org/2000/svg","path");t.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),t.setAttribute("stroke","#ddd"),t.setAttribute("stroke-width","3px"),e.appendChild(t),this._createdAROnlyElements.push(t)}}class eA extends UA{constructor(){super(...arguments);r(this,"guid")}static isDestroyed(e){return VM(e)}static setActive(e,t,g=!0){e&&(nh(e,t),bD(e),t&&g&&fx(pe.Current,e))}static isActiveSelf(e){return dE(e)}static isActiveInHierarchy(e){return cx(e)}static markAsInstancedRendered(e,t){hx(e,t)}static isUsingInstancing(e){return lw(e)}static foreachComponent(e,t,g=!0){return xr(e,t,g)}static instantiateSynced(e,t){return e?_M(e,t):null}static instantiate(e,t=null){return $l(e,t)}static destroySynced(e,t,g=!0){if(!e)return;const I=e;t=t??pe.Current,Bw(I,t.connection,g)}static destroy(e,t=!0,g=!0){return js(e,t,g)}static add(e,t,g){if(!(!e||!t)){if(e===t){console.warn("Can not add object to self",e);return}g||(g=pe.Current),t.add(e),nh(e,!0),bD(e),g?eA.foreachComponent(e,I=>{zM(I,g),!I.__internalDidAwakeAndStart&&g.new_script_start.includes(I)===!1&&g.new_script_start.push(I)},!0):console.warn("Missing context")}}static remove(e){var t;e&&((t=e.parent)==null||t.remove(e),nh(e,!1),bD(e),eA.foreachComponent(e,g=>{ez(g)},!0))}static invokeOnChildren(e,t,...g){this.invoke(e,t,!0,g)}static invoke(e,t,g=!1,...I){e&&this.foreachComponent(e,o=>{const C=o[t];C&&typeof C=="function"&&(C==null||C.call(o,...I))},g)}static addNewComponent(e,t,g=!0){const I=new t;return Xr(e,I,g),I}static addComponent(e,t){return this.moveComponent(e,t)}static moveComponent(e,t){return PM(e,t)}static removeComponent(e){return OM(e.gameObject,e),e}static getOrAddComponent(e,t){return Ew(e,t)}static getComponent(e,t){return e===null?null:hE(e,t)}static getComponents(e,t,g=null){return e===null?g??[]:zl(e,t,g)}static findByGuid(e,t){return Xl(e,t)}static findObjectOfType(e,t,g=!0){return ox(e,t??pe.Current,g)}static findObjectsOfType(e,t){const g=[];return Cx(e,g,t),g}static getComponentInChildren(e,t){return lE(e,t)}static getComponentsInChildren(e,t,g=null){return Zl(e,t,g??void 0)}static getComponentInParent(e,t){return Wh(e,t)}static getComponentsInParent(e,t,g=null){return cw(e,t,g)}static getAllComponents(e){var I;return[...(I=e.userData)==null?void 0:I.components]}static*iterateComponents(e){var g;const t=(g=e==null?void 0:e.userData)==null?void 0:g.components;if(t&&Array.isArray(t))for(let I=0;I<t.length;I++)yield t[I]}}var ei;let Ma=(ei=class{constructor(){r(this,"__context");r(this,"__name");r(this,"gameObject");r(this,"guid","invalid");r(this,"sourceId");r(this,"__didAwake",!1);r(this,"__didStart",!1);r(this,"__didEnable",!1);r(this,"__isEnabled");r(this,"__destroyed",!1);r(this,"_worldPosition");r(this,"_worldQuaternion");r(this,"_worldEuler");r(this,"_worldRotation");r(this,"_eventListeners",new Map);this.__internalNewInstanceCreated()}get isComponent(){return!0}get context(){return this.__context??pe.Current}set context(A){this.__context=A}get scene(){return this.context.scene}get layer(){var A,e;return(e=(A=this.gameObject)==null?void 0:A.userData)==null?void 0:e.layer}get name(){var A,e;return(A=this.gameObject)!=null&&A.name?this.gameObject.name:(e=this.gameObject)==null?void 0:e.userData.name}set name(A){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=A,this.__name=A):this.__name=A}get tag(){var A;return(A=this.gameObject)==null?void 0:A.userData.tag}set tag(A){this.gameObject&&(this.gameObject.userData.tag=A)}get static(){var A;return(A=this.gameObject)==null?void 0:A.userData.static}get hideFlags(){var A;return(A=this.gameObject)==null?void 0:A.userData.hideFlags}get activeAndEnabled(){return!(this.destroyed||this.__isEnabled===!1||!this.__isActiveInHierarchy)}get __isActive(){return this.gameObject.visible}get __isActiveInHierarchy(){if(!this.gameObject)return!1;const A=this.gameObject[Hs];return A===void 0?!0:A}set __isActiveInHierarchy(A){this.gameObject&&(this.gameObject[Hs]=A)}awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(A,e=OI.Update){return this.context.registerCoroutineUpdate(this,A,e)}stopCoroutine(A,e=OI.Update){this.context.unregisterCoroutineUpdate(A,e)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}__internalNewInstanceCreated(){this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(A){return this.__destroyed?(Xg()&&console.warn("[Needle Engine Dev] Trying to enable destroyed component"),!1):this.__didAwake?this.__didEnable?(A!==!0&&(this.__isEnabled=!0),!1):(this.__didEnable=!0,this.__isEnabled=!0,this.onEnable(),!0):!1}__internalDisable(A){if(this.__didAwake){if(!this.__didEnable){A!==!0&&(this.__isEnabled=!1);return}this.__didEnable=!1,this.__isEnabled=!1,this.onDisable()}}__internalDestroy(){var A;this.__destroyed||(this.__destroyed=!0,(A=this.destroy)==null||A.call(this),this.dispatchEvent(new CustomEvent("destroyed",{detail:this})),gx(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(A){if(this.__destroyed){Xg()&&console.warn(`[Needle Engine Dev] Trying to ${A?"enable":"disable"} destroyed component`);return}if(typeof A=="number"&&(A>=.5?A=!0:A=!1),!this.__didAwake){this.__isEnabled=A;return}A?this.__internalEnable():this.__internalDisable()}get worldPosition(){return this._worldPosition||(this._worldPosition=new k),ye(this.gameObject,this._worldPosition),this._worldPosition}set worldPosition(A){hi(this.gameObject,A)}setWorldPosition(A,e,t){ei._worldPositionBuffer.set(A,e,t),this.worldPosition=ei._worldPositionBuffer}get worldQuaternion(){return this._worldQuaternion||(this._worldQuaternion=new kA),Hi(this.gameObject,this._worldQuaternion)}set worldQuaternion(A){fI(this.gameObject,A)}setWorldQuaternion(A,e,t,g){ei._worldQuaternionBuffer.set(A,e,t,g),this.worldQuaternion=ei._worldQuaternionBuffer}get worldEuler(){return this._worldEuler||(this._worldEuler=new Ui),this._worldEuler.setFromQuaternion(this.worldQuaternion),this._worldEuler}set worldEuler(A){var e;this._worldQuaternion||(this._worldQuaternion=new kA),(e=this._worldQuaternion)==null||e.setFromEuler(A),this.worldQuaternion=this._worldQuaternion}get worldRotation(){const A=this.worldEuler;this._worldRotation||(this._worldRotation=new k);const e=this._worldRotation;return e.set(A.x,A.y,A.z),e.x=Ae.toDegrees(e.x),e.y=Ae.toDegrees(e.y),e.z=Ae.toDegrees(e.z),e}set worldRotation(A){this.setWorldRotation(A.x,A.y,A.z,!0)}setWorldRotation(A,e,t,g=!0){g&&(A=Ae.toRadians(A),e=Ae.toRadians(e),t=Ae.toRadians(t)),ei._worldEulerBuffer.set(A,e,t),ei._worldQuaternionBuffer.setFromEuler(ei._worldEulerBuffer),this.worldQuaternion=ei._worldQuaternionBuffer}get forward(){return ei._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}get right(){return ei._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}get up(){return ei._up.set(0,1,0).applyQuaternion(this.worldQuaternion)}addEventListener(A,e){this._eventListeners[A]=this._eventListeners[A]||[],this._eventListeners[A].push(e)}removeEventListener(A,e){if(!this._eventListeners[A])return;const t=this._eventListeners[A].indexOf(e);t>=0&&this._eventListeners[A].splice(t,1)}dispatchEvent(A){if(!this._eventListeners[A.type])return!1;const e=this._eventListeners[A.type];for(let t=0;t<e.length;t++)e[t](A);return!1}},r(ei,"_worldPositionBuffer",new k),r(ei,"_worldQuaternionBuffer",new kA),r(ei,"_worldEulerBuffer",new Ui),r(ei,"_tempQuaternionBuffer2",new kA),r(ei,"_forward",new k),r(ei,"_right",new k),r(ei,"_up",new k),ei);class MA extends Ma{}const M5=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:MA,Component:Ma,GameObject:eA},Symbol.toStringTag,{value:"Module"})),m5='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 160 187.74"><defs><linearGradient id="a" x1="89.64" y1="184.81" x2="90.48" y2="21.85" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#62d399"/><stop offset=".51" stop-color="#acd842"/><stop offset=".9" stop-color="#d7db0a"/></linearGradient><linearGradient id="b" x1="69.68" y1="178.9" x2="68.08" y2="16.77" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#0ba398"/><stop offset=".5" stop-color="#4ca352"/><stop offset="1" stop-color="#76a30a"/></linearGradient><linearGradient id="c" x1="36.6" y1="152.17" x2="34.7" y2="84.19" gradientUnits="userSpaceOnUse"><stop offset=".19" stop-color="#36a382"/><stop offset=".54" stop-color="#49a459"/><stop offset="1" stop-color="#76a30b"/></linearGradient><linearGradient id="d" x1="15.82" y1="153.24" x2="18" y2="90.86" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#267880"/><stop offset=".51" stop-color="#457a5c"/><stop offset="1" stop-color="#717516"/></linearGradient><linearGradient id="e" x1="135.08" y1="135.43" x2="148.93" y2="63.47" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#b0d939"/><stop offset="1" stop-color="#eadb04"/></linearGradient><linearGradient id="f" x1="-4163.25" y1="2285.12" x2="-4160.81" y2="2215.34" gradientTransform="rotate(20 4088.49 13316.712)" gradientUnits="userSpaceOnUse"><stop offset=".17" stop-color="#74af52"/><stop offset=".48" stop-color="#99be32"/><stop offset="1" stop-color="#c0c40a"/></linearGradient><symbol id="g" viewBox="0 0 160 187.74"><path style="fill:url(#a)" d="M79.32 36.98v150.76L95 174.54l6.59-156.31-22.27 18.75z"/><path style="fill:url(#b)" d="M79.32 36.98 57.05 18.23l6.59 156.31 15.68 13.2V36.98z"/><path style="fill:url(#c)" d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33z"/><path style="fill:url(#d)" d="M25.19 104.83 0 90.24l16.97 53.86 16.85 9.77-8.63-49.04z"/><path style="fill:#9c3" d="M43.86 82.5 18.69 67.98 0 90.24l25.18 14.59L43.86 82.5z"/><path style="fill:url(#e)" d="m134.82 78.69-9.97 56.5 15.58-9.04L160 64.1l-25.18 14.59z"/><path style="fill:url(#f)" d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5z"/><path style="fill:#ffe113" d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33L160 64.1z"/><path style="fill:#f3e600" d="M101.59 18.23 79.32 0 57.05 18.23l22.27 18.75 22.27-18.75z"/></symbol></defs><use width="160" height="187.74" xlink:href="#g"/></svg>',R5=new Blob([m5],{type:"image/svg+xml;charset=utf-8"}),U5=URL.createObjectURL(R5),eY=U5,wr=rA("debuglicense"),Im="basic";wr&&console.log("License Type: "+Im);function na(){switch(Im){case"pro":case"enterprise":return!0}return!1}function tY(){switch(Im){case"indie":return!0}return!1}function iY(){return na()||tY()}ii.registerCallback(LI.ContextRegistered,i=>{F5(i.context)});async function F5(i){try{if(na()!==!0)return YS(i)}catch(A){return wr&&console.log("License check failed",A),YS(i)}wr&&YS(i)}const gY="needle-license-element",$k=5e3,AG=200;function YS(i){K5(),i.domElement.addEventListener("ready",()=>{setTimeout(()=>{N5(i)},1e3)}),b5()}function N5(i){const A=J5(),e=q5(),t=setInterval(()=>{if(!A)return;const s=i.domElement.shadowRoot||i.domElement;A.parentNode!==s&&(s.appendChild(A),e&&s.appendChild(e))},100);let g=`<img class="logo" src="${eY}" style="width: 40px; height: 40px; margin-right: 2px; vertical-align: middle; margin-bottom: 2px;"/>`;const I=document.createElement("div");I.innerHTML=g,I.classList.add("logo"),A.appendChild(I);const o=document.createElement("div");o.classList.add("text"),A.appendChild(o),A.title="Needle Engine",iY()||(A.title+=" non commercial version"),A.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")});const C=$k+AG;setTimeout(()=>{clearInterval(t),A==null||A.remove(),e==null||e.remove()},C)}let lK=0;async function K5(i){const A=Date.now();if(A-lK<2e3)return;lK=A;const t=`
3837
3837
  font-size: 18px;
3838
3838
  background-size: 20px;
3839
3839
  background-position: left top;
@@ -4558,7 +4558,7 @@ void main() {
4558
4558
  `){super("lineBreak",A,!0),this._newLineBreakability=null}update(A,e){this._needsProcess=!0}process(A){const e=A._whiteSpace._newLineBreakability;if(A._inlines._value)for(let t=0;t<A._inlines._value.length;t++){const g=A._inlines._value[t],I=g.char;let o=null;I!==void 0&&(e!=="nowrap"&&(this._value.includes(I)||I.match(/\s/g))&&(o="possible"),I.match(/\n/g)&&(o=e)),g.lineBreak=o}}get value(){return this._value}}class UH extends ht{constructor(){super("layouter",null,!1),this._value=null}update(A,e){this._value=A._parent.find(t=>t.isUI&&t.isText),this._needsProcess=!0}process(A){this._value&&(this._value._layouter._needsProcess=!0)}}class teA extends il{constructor(A){super("backgroundColor",A,!1),this._allowsInherit=!1,this._input=0}computeOutputValue(A){this._input==="inherit"?this._value.set(this.getInheritedInput(A)):this._value.set(this._input)}}class FH extends NT{constructor(){super(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}}class NH extends KT{constructor(){super()}computeOutputValue(A){const e=this.getInheritedInput(A),t=ieA[e];t?this._value=t:this._value=e}}const ieA={light:"100",normal:"400",bold:"700",bolder:"900"};class KH extends YT{constructor(){super("fontFamily","inherit",!0),this._input="inherit",this._needsUpdate=!0,this._allowsInherit=!1}computeOutputValue(A){let e=this._inheritedInput;if(e==="inherit"&&(e=this.getInheritedInput(A)),e instanceof Nw)this._value=e,A._font._needsUpdate=!0;else if(typeof e=="string"){const t=Tr.getFontFamily(e);t?(this._value=t,A._font._needsUpdate=!0):console.warn(`(.style) fontFamily, the font '${e}' 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 oR extends HT{constructor(){super(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited,this._whiteSpacedContent="",this._stringCollapser=this.emptyStrategyLogic,this._inlineCollapser=this.emptyStrategyLogic,this._inlineWrapper=this.emptyStrategyLogic}_computeFromInherited(A){switch(super._computeFromInherited(A),this._newLineBreakability=geA(this._value),this._value){case"nowrap":case"normal":this._stringCollapser=IeA;break;case"pre-line":this._stringCollapser=JH;break;default:this._stringCollapser=oeA}switch(this._value){case"pre-line":case"nowrap":case"normal":this._inlineCollapser=reA;break;case"pre-wrap":this._inlineCollapser=aeA;break;default:this._inlineCollapser=BeA}switch(this._value){case"pre-line":case"pre-wrap":case"normal":this._inlineWrapper=CeA;break;case"pre":this._inlineWrapper=seA;break;default:this._inlineWrapper=neA}this._needsProcess=!0}process(A){A.isInline&&!A.isInlineBlock&&(this._whiteSpacedContent=this._stringCollapser(A._textContent._value),A._glyphs._needsProcess=!0)}}const DJ={" ":" ","\n":`
4559
4559
  `,"\r":"\r"," ":" "},geA=function(i){switch(i){case"pre":case"pre-wrap":case"pre-line":return"mandatory"}return null};function IeA(i){return JH(i.replace(/\n/g," "))}function JH(i){return i.replace(/[ ]{2,}/g," ")}function oeA(i){return i}function CeA(i,A,e,t){const g=i[A];if(g.lineBreak==="mandatory"||e+g.xadvance+g.xoffset+g.kerning>t.INNER_WIDTH)return!0;const I=LH(i,A,t);return QeA(i[A-1],e,I,t)}function seA(i,A,e,t){return i[A].lineBreak==="mandatory"}function neA(){return!1}function aeA(i){if(!i[0])return 0;const A=i[0],e=i[i.length-1];return A.char&&A.char===`
4560
4560
  `&&i.length>1&&bH([A],i[1]),e.char&&e.char===`
4561
- `&&i.length>1&&qH([e],i[i.length-2]),A.offsetX}function reA(i){if(!i[0])return 0;let A=[],e;for(let t=0;t<i.length;t++){const g=i[t];if(g.char&&DJ[g.char]&&i.length>t){A.push(g),e=i[t+1];continue}break}bH(A,e),A=[],e=null;for(let t=i.length-1;t>0;t--){const g=i[t];if(g.char&&DJ[g.char]&&t>0){A.push(g),e=i[t-1];continue}break}return qH(A,e),i[0].offsetX}function BeA(i){return i[0]?i[0].offsetX:0}function qH(i,A){if(A)for(let e=0;e<i.length;e++){const t=i[e];t.fontFactor=0,t.offsetX=A.offsetX+A.cumulativeWidth,t.cumulativeWidth=0}}function bH(i,A){if(A)for(let e=0;e<i.length;e++){const t=i[e];t.fontFactor=0,t.offsetX=A.offsetX,t.cumulativeWidth=0}}function LH(i,A,e,t){if(t=t||0,!i[A])return t;const g=i[A];return g.lineBreak?t+g.xadvance:LH(i,A+1,e,t+g.xadvance+g.xoffset+g.kerning+e.LETTERSPACING)}function QeA(i,A,e,t){return!i||!i.char||A+e<t.INNER_WIDTH?!1:t.BREAKON.indexOf(i.char)>-1}class vH extends _T{constructor(){super(),this._input="inherit",this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}_computeFromInherited(A){super._computeFromInherited(A),A._fontSize._needsProcess=!0,A._layouter._needsProcess=!0}}class xH extends Tt{constructor(){super("fontSize","inherit",!0),this._allowsInherit=!1}computeOutputValue(A){this._value=this._inheritedInput,A._font._fontVariant&&(A._bounds._needsProcess=!0,A._layouter._needsProcess=!0)}process(A){if(!A._font._fontVariant||!A._font._fontVariant.isReady)return;const e=this._value/A._font._fontVariant.typographic.size,t=A._inlines._value;for(let g=0;g<t.length;g++){const I=t[g];I.resetOffsets(),I.fontSize=this._value,I.fontFactor=e}}get value(){return this._value}}class YH extends OT{constructor(){super("segments",1,!1),this._notInheritedValue=void 0}update(A,e){this._notInheritedValue=this._value,this._notInheritedValue==="inherit"&&(this._notInheritedValue=this.getInheritedInput(A)),A._layouter._needsUpdate=!0}set value(A){this._value!==A&&(this._value=A,this._needsUpdate=!0)}get value(){return this._value==="inherit"?this._notInheritedValue:this._value}}class EeA extends YH{constructor(){super(),this._value="inherit"}}class ceA extends Kw{constructor(){super(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}_computeFromInherited(A){super._computeFromInherited(A),A._parent._value._layouter._needsProcess=!1}process(A){if(this._value!=="none"){const e=A._whiteSpace._whiteSpacedContent,t=A._inlines._value;for(let g=1;g<t.length;g++){const I=e[g-1]+e[g];t[g].kerning=A._font._fontVariant.getKerningAmount(I)}}}}class TH extends ht{constructor(){super("children",null,!1),this._uis=[]}update(A,e){}process(A){}_compute(A){}dispose(){}}function heA(i,A=!1){const e=i[0].index!==null,t=new Set(Object.keys(i[0].attributes)),g=new Set(Object.keys(i[0].morphAttributes)),I={},o={},C=i[0].morphTargetsRelative,s=new $A.BufferGeometry;let n=0;for(let a=0;a<i.length;++a){const B=i[a];let Q=0;if(e!==(B.index!==null))return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+a+". All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them."),null;for(const E in B.attributes){if(!t.has(E))return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+a+'. All geometries must have compatible attributes; make sure "'+E+'" attribute exists among all geometries, or in none of them.'),null;I[E]===void 0&&(I[E]=[]),I[E].push(B.attributes[E]),Q++}if(Q!==t.size)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+a+". Make sure all geometries have the same number of attributes."),null;if(C!==B.morphTargetsRelative)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+a+". .morphTargetsRelative must be consistent throughout all geometries."),null;for(const E in B.morphAttributes){if(!g.has(E))return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+a+". .morphAttributes must be consistent throughout all geometries."),null;o[E]===void 0&&(o[E]=[]),o[E].push(B.morphAttributes[E])}if(s.userData.mergedUserData=s.userData.mergedUserData||[],s.userData.mergedUserData.push(B.userData),A){let E;if(e)E=B.index.count;else if(B.attributes.position!==void 0)E=B.attributes.position.count;else return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+a+". The geometry must have either an index or a position attribute"),null;s.addGroup(n,E,a),n+=E}}if(e){let a=0;const B=[];for(let Q=0;Q<i.length;++Q){const E=i[Q].index;for(let c=0;c<E.count;++c)B.push(E.getX(c)+a);a+=i[Q].attributes.position.count}s.setIndex(B)}for(const a in I){const B=pJ(I[a]);if(!B)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the "+a+" attribute."),null;s.setAttribute(a,B)}for(const a in o){const B=o[a][0].length;if(B===0)break;s.morphAttributes=s.morphAttributes||{},s.morphAttributes[a]=[];for(let Q=0;Q<B;++Q){const E=[];for(let h=0;h<o[a].length;++h)E.push(o[a][h][Q]);const c=pJ(E);if(!c)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the "+a+" morphAttribute."),null;s.morphAttributes[a].push(c)}}return s}function pJ(i){let A,e,t,g=0;for(let C=0;C<i.length;++C){const s=i[C];if(s.isInterleavedBufferAttribute)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. InterleavedBufferAttributes are not supported."),null;if(A===void 0&&(A=s.array.constructor),A!==s.array.constructor)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes."),null;if(e===void 0&&(e=s.itemSize),e!==s.itemSize)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes."),null;if(t===void 0&&(t=s.normalized),t!==s.normalized)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes."),null;g+=s.array.length}const I=new A(g);let o=0;for(let C=0;C<i.length;++C)I.set(i[C].array,o),o+=i[C].array.length;return new $A.BufferAttribute(I,e,t)}class leA extends ht{constructor(){super("renderer")}render(A){if(!A._inlines._value||!A._inlines._value.length)return;const e=A._inlines._value.map(g=>A._font._fontVariant.getGeometricGlyph(g,A).translate(g.offsetX,g.offsetY,0)),t=heA(e);A.setFontMesh(new $A.Mesh(t,A.fontMaterial)),A._fontMesh.renderOrder=1/0}}class deA extends Jm{constructor(){super(),this._allowsInherit=!1,this._needsUpdate=!1}computeOutputValue(A){this._value=this._inheritedInput,A._layouter._needsProcess=!0}}class jQ extends Qd{constructor(e={}){const t={};jQ.definePropertiesValues(t,e);super(t,e);r(this,"_rebuildParentUI",()=>{super._rebuildParentUI(),this._layouter._needsUpdate=!0});jQ.init(this)}add(e){const t=[];for(let g=0;g<arguments.length;g++){const I=arguments[g];!I.isUI||I.isInline?(t.push(I),I.position.z=.005):console.warn("Block element can only contain Box elements.",I)}return super.add(...t)}set textContent(e){this._textContent.value=e}get textContent(){return this._textContent._value}set invertAlpha(e){this._invertAlpha.value=e}get invertAlpha(){return this._invertAlpha._value}static definePropertiesValues(e,t){e.children||(e.children=TH),e.textContent||(e.textContent=XAA),e.glyphs||(e.glyphs=AeA),e.inlines||(e.inlines=$AA),e.layouter||(e.layouter=UH),e.renderer||(e.renderer=leA),e.fontFamily||(e.fontFamily=KH),e.fontWeight||(e.fontWeight=NH),e.fontStyle||(e.fontStyle=FH),e.fontSize||(e.fontSize=xH),e.color||(e.color=eeA),e.backgroundColor||(e.backgroundColor=teA),e.lineBreak||(e.lineBreak=RH),e.letterSpacing||(e.letterSpacing=vH),e.whiteSpace||(e.whiteSpace=oR),e.segments||(e.segments=EeA),e.textAlign||(e.textAlign=deA),e.fontKerning||(e.fontKerning=ceA)}static init(e){Object.defineProperties(e,{isInline:{configurable:!1,enumerable:!0,value:!0}})}}class ueA extends FT{constructor(){super("textContent",null,!1),this._needsUpdate=!1}set value(A){this._value!==A&&(this._value=A,this._needsUpdate=!0)}update(A,e){this._needsUpdate=!1;for(let t=A.children.length-1;t>=0;t--){const g=A.children[t];g.isUI&&(A.remove(g),g.clear())}A._children._uis=[],this._value&&A.add(new jQ({name:"anonymousInline",textContent:this._value}))}}class DeA extends Array{constructor(...A){super(...A),this.width=0,this.height=0}}class peA extends ht{constructor(){super("layouter",null,!1),this._value=null}update(A,e){}process(A){let e=A._width._value;A._width._auto?e=1/0:e=A._bounds._innerWidth;const t=A._lineHeight._value,g=new DeA(new uJ);let I=0;A._children._inlines.forEach(B=>{if(!B._inlines.value)return;this._resetInlines(B);const Q=B._fontSize._value,E=B._letterSpacing._value*Q,c=B._whiteSpace._value,h=B._lineBreak._value,l={WHITESPACE:c,LETTERSPACING:E,BREAKON:h,INNER_WIDTH:e},d=B._whiteSpace._inlineWrapper;I+=B._margin._value.w+B._padding._value.w,B._inlines.value.forEach((p,u,D)=>{const y=g[g.length-1];if(d(D,u,I,l)){if(g.push(new uJ(p)),p.offsetX=p.xoffset,p.width===0){I=0;return}p.cumulativeWidth=p.xadvance+E,I=p.cumulativeWidth;return}g[g.length-1].push(p),p.offsetX=I+p.xoffset+p.kerning,p.cumulativeWidth=p.xadvance+p.kerning+E,I+=p.cumulativeWidth,y.length-1===1&&y[y.length-2].width===0&&(p.offsetX-=p.xoffset,I-=p.xoffset)}),I+=B._margin._value.y+B._padding._value.y});const o=A._whiteSpace._inlineCollapser;let C=0,s=0,n=0;g.forEach((B,Q)=>{const E=o(B);let c=0,h=0;if(B.forEach(l=>{c=Math.max(c,l.lineHeight),h=Math.max(h,l.lineBase),l.offsetX-=E}),B.lineHeight=c,B.lineBase=h,Q===0?n=-(c*t-c)*.5:n-=g[Q-1].lineHeight*t,B.y=n,B.x=0,B.forEach(l=>{l.offsetY=n-l.anchor,l.lineHeight<B.lineHeight&&(l.offsetY-=B.lineBase-l.lineBase)}),s+=B.lineHeight*t,B.width=0,B[0]){const l=B[B.length-1];B.width=l.offsetX+l.cumulativeWidth+l.paddingRight+l.marginRight+B[0].offsetX,C=Math.max(C,B.width)}}),g.height=s,g.width=C,this._value=g,e===1/0&&A._bounds.setChildrenWidth(A,g.width),A._height._auto&&A._bounds.setChildrenHeight(A,g.height);const a=A._parent._value;a&&(a._autoSize._needsProcess=!0,a._flexDirection._needsProcess=!0),A._inlineJustificator._needsProcess=!0,A._textAlign._needsProcess=!0,A._overflow._needsUpdate=!0}_resetInlines(A){A._fontSize.process(A)}}class feA extends Jm{constructor(){super(),this._allowsInherit=!1,this._needsUpdate=!0}computeOutputValue(A){this._value=this._inheritedInput,this._needsProcess=!0}process(A){weA(A),A._renderer._needsRender=!0}}function weA(i){const A=i._layouter._value,e=i._textAlign._value,t=i._bounds._innerWidth;for(let g=0;g<A.length;g++){const I=A[g],o=yeA(i,I,g===A.length-1),C=i._padding._value,s=i._borderWidth._value,n=(-C.w+C.y)/2+(-s.w+s.y)/2;I.x+=o;for(let a=0;a<I.length;a++)I[a].offsetX+=o-n}if(e.indexOf("justify")===0)for(let g=0;g<A.length;g++){const I=A[g];if(e.indexOf("-")!==-1&&g===A.length-1)return;const o=t-I.width;if(o<=0)return;let C=0;for(let B=1;B<I.length-1;B++)C+=I[B].char===" "?1:0;const s=o/C;let n=1;e==="justify-right"&&(I.reverse(),n=-1);let a=0;for(let B=1;B<=I.length-1;B++){const Q=I[B];Q.offsetX+=a*n,a+=Q.char===" "?s:0}e==="justify-right"&&I.reverse()}}function yeA(i,A,e){switch(i._textAlign._value){case"justify-left":case"justify":case"left":return-i._bounds._innerWidth/2;case"justify-right":case"right":return-A.width+i._bounds._innerWidth/2;case"center":return-A.width/2;case"justify-center":return e?-A.width/2:-i._bounds._innerWidth/2;default:console.warn(`textAlign: '${i._textAlign._value}' is not valid`)}}class SeA extends qm{constructor(){super(),this._value=this._input="column",this._allowsInherit=!1,this._needsUpdate=!0}computeOutputValue(A){this._value=this._inheritedInput}}class keA extends TT{constructor(){super(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}}class GeA extends Kw{constructor(){super(),this._value=this._input=this.getDefaultValue(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}_computeFromInherited(A){super._computeFromInherited(A)}}class MeA extends GH{constructor(){super(),this._innerWidth=1/0,this._innerHeight=0}}class meA extends ht{constructor(){super("children",null,!1);r(this,"_sortOrder",(e,t)=>e._order._value<t._order._value?-1:e._order._value>t._order._value?1:this._uis.indexOf(e)<this._uis.indexOf(t)?-1:1);this._uis=[],this._inlines=[],this._boxes=[]}update(e,t){this._compute(e),this._needsProcess=!0}process(e){this._compute(e),e._overflow._needsRender=!0}_compute(e){this._uis=e.children.filter(t=>t.visible&&t.isUI),this._inlines=this._uis.filter(t=>t.isInline).sort(this._sortOrder)}dispose(){this._inlines=null}}class ReA extends ht{constructor(){super("autosize")}process(A){if(A._layouter._value&&A._layouter._value.length){const e=A._layouter._value,t=A._padding._value,g=A._borderWidth._value;A._width._auto&&A._bounds.setOffsetWidth(A,e.width+t.w+t.y+g.w+g.y),A._height._auto&&A._bounds.setOffsetHeight(A,e.height+t.x+t.z+g.x+g.z)}}}class UeA extends mH{constructor(){super("renderer"),this._needsUpdate=!1}render(A){super.render(A);for(const e of A._children._inlines)e._renderer.render(e);A.performAfterUpdate()}}class sl extends ol{constructor(A={},e={}){sl.definePropertiesValues(e,A),super(e,A),sl.init(this)}add(A){const e=[];let t=!1;for(let g=0;g<arguments.length;g++){const I=arguments[g];!I.isUI||I.isInline?(I.isInline&&(t=!0),e.push(I)):console.warn("Block element can only contain Box elements.",I)}return e.length>0&&super.add(...e),t&&(this._children._needsUpdate=!0,this._layouter._needsProcess=!0),this}set textContent(A){this._textContent.value=A}get textContent(){return super.textContent}set invertAlpha(A){this._invertAlpha.value=A}get invertAlpha(){return this._invertAlpha._value}get lines(){return this._layouter._value}static definePropertiesValues(A,e){A.flexDirection=SeA,A.justifyContent=bm,A.alignItems=Km,A.bounds=MeA,A.autoSize=ReA,A.renderer=UeA,A.children||(A.children=meA),A.textContent||(A.textContent=ueA),A.layouter||(A.layouter=peA),A.lineHeight||(A.lineHeight=keA),A.textAlign||(A.textAlign=feA),A.whiteSpace||(A.whiteSpace=oR),A.fontKerning||(A.fontKerning=GeA),A.segments||(A.segments=YH),e.width||(e.width="100%"),e.fontSide||(e.fontSide=0)}static init(A){Object.defineProperties(A,{isText:{configurable:!1,enumerable:!0,value:!0}})}}class FeA extends ht{constructor(){super("inlines",null,!1),this._value=[]}process(A){this._value[0].paddingLeft=A._padding._value.w,this._value[0].marginLeft=A._margin._value.w;const e=this._value.length-1;this._value[e].paddingRight=A._padding._value.y,this._value[e].marginRight=A._margin._value.y}}class NeA extends ht{constructor(){super("renderer")}render(A){A._backgroundMesh||A.setBackgroundMesh(new MH(A)),A._backgroundMesh.position.x=A._inlines._value[0].offsetX+A._inlines._value[0].width/2,A._backgroundMesh.position.y=A._inlines._value[0].offsetY+A._inlines._value[0].lineBase/2,A._bounds.render(A)}}class KeA extends ht{constructor(){super("bounds",null,!1),this._size=new $A.Vector3(1,1,1),this._offsetWidth=0,this._offsetHeight=0,this._innerWidth=0,this._innerHeight=0}update(A,e){this.output(e),this._needsProcess=!0}process(A){this._offsetWidth=this._innerWidth=A._inlines._value[0].width,this._offsetHeight=this._innerHeight=A._inlines._value[0].height,this._needsRender=!0,A._borderWidth._needsRender=!0,A._borderRadius._needsRender=!0}render(A){this._size.x=this._offsetWidth,this._size.y=this._offsetHeight}output(A){A.size=this._size}}class nl extends Qd{constructor(A={}){const e={};nl.definePropertiesValues(e,A),super(e,A),nl.init(this)}clear(){for(const A of this._inlines._value)A.clear();return super.clear()}bindBackgroundMeshProperties(){this._backgroundMesh.raycast=()=>{},this._bounds._size=this._backgroundMesh.scale,this._bounds._needsUpdate=!0}unbindBackgroundMeshProperties(){this._bounds._size=new $A.Vector3(1,1,1),this._bounds._needsUpdate=!0}add(A){const e=[];for(let t=0;t<arguments.length;t++){const g=arguments[t];g.isUI?console.warn("ThreeMeshUI::InlineBlockElement cannot contains UI Elements.",g):(e.push(g),g.position.z=.005)}return super.add(...e)}static definePropertiesValues(A,e){A.children||(A.children=TH),A.bounds||(A.bounds=KeA),A.inlines||(A.inlines=FeA),A.layouter||(A.layouter=UH),A.renderer||(A.renderer=NeA),A.fontFamily||(A.fontFamily=KH),A.fontWeight||(A.fontWeight=NH),A.fontStyle||(A.fontStyle=FH),A.fontSize||(A.fontSize=xH),A.backgroundColor||(A.backgroundColor=mT),A.lineBreak||(A.lineBreak=RH),A.letterSpacing||(A.letterSpacing=vH),A.whiteSpace||(A.whiteSpace=oR),A.fontKerning||(A.fontKerning=Kw),e.backgroundSize||(e.backgroundSize="cover"),e.width||(e.width="100%"),e.height||(e.height="100%"),e.boxSizing||(e.boxSizing="border-box")}static init(A){Object.defineProperties(A,{isInline:{configurable:!1,enumerable:!0,value:!0},isInlineBlock:{configurable:!1,enumerable:!0,value:!0}}),A._inlines._value=[new JeA(A)],A.backgroundMaterial=new kH,A._renderer.render(A)}}class JeA extends bT{constructor(A){super(),this._uiElement=A}get xadvance(){const A=this._uiElement._padding._value,e=this._uiElement._width;return e._relative?e._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):A.w+A.y+e.value}get width(){const A=this._uiElement._width;return A._relative?A._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):A.value}get height(){const A=this._uiElement._height;return A._relative?A._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):A.value}get anchor(){return this.height}get lineHeight(){const A=this._uiElement._height;return A._relative?A._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):A.value}get lineBase(){const A=this._uiElement._height;return A._relative?A._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):A.value}clear(){this._uiElement=null}}class HH{constructor(A){this._subject=A}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 _H=()=>$p.update(),OH={BaseProperty:ht,Block:Cl,Text:sl,Inline:jQ,InlineBlock:nl,MeshUIBaseElement:Qd,FontLibrary:Tr,update:_H,MSDFFontMaterialUtils:ao,ShaderChunkUI:SH,Behavior:HH,FontVariant:nd};typeof global<"u"&&(global.ThreeMeshUI=OH);const qeA=OH;var beA=Ni.w8,PH=Ni.cg,CR=Ni.gO,LeA=Ni.wb,wG=Ni.zV,veA=Ni.HS,xeA=Ni.Ec,jD=Ni.gF,YeA=Ni.ol,TeA=Ni.pz,HeA=Ni.tx,_eA=Ni.hj,OeA=Ni.FV,PeA=Ni.sV,WH=Ni.xv,WeA=Ni.mx,VeA=Ni.gE,jeA=Ni.ZP,VH=Ni.Vx;const fJ=Object.freeze(Object.defineProperty({__proto__:null,BaseProperty:beA,Behavior:PH,Block:CR,DefaultValues:LeA,FontLibrary:wG,FontVariant:veA,InheritableProperty:xeA,Inline:jD,InlineBlock:YeA,InlineGlyph:TeA,MSDFFontMaterialUtils:HeA,MaterialTransformers:_eA,MeshUIBaseElement:OeA,ShaderChunkUI:PeA,Text:WH,TypographicFont:WeA,TypographicGlyph:VeA,default:jeA,update:VH},Symbol.toStringTag,{value:"Module"}));CR.prototype.interactable={get(){return this.interactive},set(i){this.interactable=i}};const Ns=Symbol("shadowDomOwner");class tC extends MA{constructor(){super(...arguments);r(this,"shadowComponent",null);r(this,"_controlsChildLayout",!0);r(this,"_root");r(this,"_parentComponent")}isRoot(){var e;return((e=this.Root)==null?void 0:e.gameObject)===this.gameObject}get canvas(){const e=this.Root;return e!=null&&e.isCanvas?e:null}markDirty(){lI.markUIDirty(this.context)}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}get Root(){return this._root===void 0&&(this._root=eA.getComponentInParent(this.gameObject,Ed)),this._root}get Canvas(){return this.canvas}__internalNewInstanceCreated(){super.__internalNewInstanceCreated(),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0}onEnable(){super.onEnable()}addShadowComponent(e,t){var o;this.removeShadowComponent();const g=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=eA.getComponentInParent(g,tC),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[Ns]=this,this.setShadowComponentOwner(e);let I=!1;if(((o=this.Root)==null?void 0:o.gameObject)===this.gameObject)this.gameObject.add(e);else{let C=this._parentComponent.shadowComponent;C&&(C==null||C.add(e),I=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),Pl&&e.add(new QE(.5)),this.onAfterAddedToScene(),I&&VH()}set(e){}setShadowComponentOwner(e){if(e&&(e[Ns]===void 0||e[Ns]===this)&&(e[Ns]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,g){if(e&&e[Ns]===t){g(e);for(const I of e.children)this.traverseOwnedShadowComponents(I,t,g)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class Ed extends tC{awake(){super.awake()}}class zQ{static getObject(A){const e=A[Ns];return e&&(e.isComponent===!0?A=e.gameObject:A=e),A}static isInteractable(A,e){if(e&&(e.canvasGroup=void 0,e.graphic=void 0),A==null||!A.visible||(A=this.getObject(A),!A.visible))return!1;const t=this.tryFindCanvasGroup(A);if((t==null?void 0:t.isCanvasGroup)===!0&&(e&&(e.canvasGroup=t),t.blocksRaycasts===!1||t.interactable===!1))return!1;const g=xr(A,I=>{if(I.isGraphic===!0)return I},!1);return e&&(g==null?void 0:g.isGraphic)===!0&&(e.graphic=g),!((g==null?void 0:g.raycastTarget)===!1||(g==null?void 0:g.layer)===2)}static tryFindCanvasGroup(A){if(!A)return null;const e=xr(A,t=>{const g=t;if(g.blocksRaycasts!==void 0&&g.interactable!==void 0)return g},!1);return e!==void 0?e:this.tryFindCanvasGroup(A.parent)}}const Oc=rA("debugwebxrcontroller");var MQ=(i=>(i[i.PhysicalDevice=0]="PhysicalDevice",i[i.Touch=1]="Touch",i))(MQ||{}),Ss=(i=>(i.SelectStart="select-start",i.SelectEnd="select-end",i.Update="update",i))(Ss||{});class vw extends MA{}const Xi=class extends MA{constructor(){super(...arguments);r(this,"webXR");r(this,"index",-1);r(this,"controllerModel");r(this,"controller");r(this,"controllerGrip");r(this,"hand");r(this,"handPointerModel");r(this,"grabbed",null);r(this,"input",null);r(this,"type",0);r(this,"showRaycastLine",!0);r(this,"_wristQuaternion",null);r(this,"movementVector",new k);r(this,"worldRot",new kA);r(this,"joystick",new j);r(this,"didRotate",!1);r(this,"didTeleport",!1);r(this,"didChangeScale",!1);r(this,"lastHit",null);r(this,"raycastLine",null);r(this,"_raycastHitPoint",null);r(this,"_connnectedCallback",null);r(this,"_disconnectedCallback",null);r(this,"_selectStartEvt",null);r(this,"_selectEndEvt",null);r(this,"_selectionPressed",!1);r(this,"_selectionPressedLastFrame",!1);r(this,"_selectionStartTime",0);r(this,"_selectionEndTime",0);r(this,"_useSmoothing",!0);r(this,"_isConnected",!1);r(this,"rayRotation",new kA);r(this,"_pinchStartTime");r(this,"selectStartCallback",null);r(this,"lastSelectStartObject",null);r(this,"_didNotEndSelection",!1);r(this,"closeGrabBoundingBoxHelper")}static CreateRaycastLine(){const e=new Qi(this.geometry),t=e.material;return t.color=this.raycastColor,e.layers.set(2),e.name="line",e.scale.z=1,e}static CreateRaycastHitPoint(){const e=new Go(.5,22,22),t=new wt({color:this.raycastColor}),g=new fA(e,t);return g.visible=!1,g.layers.set(2),g}static Create(e,t,g,I){const o=g?eA.addNewComponent(g,Xi,!1):new Xi;o.webXR=e,o.index=t,o.type=I;const C=e.context;o.controller=C.renderer.xr.getController(t),o.controllerGrip=C.renderer.xr.getControllerGrip(t),o.controllerModel=this.Factory.createControllerModel(o.controller),o.controllerGrip.add(o.controllerModel),o.hand=C.renderer.xr.getHand(t);const s=new pE;ed(s,C),o.webXR.handModelPath&&o.webXR.handModelPath!==""?s.setPath(wa(e.sourceId,o.webXR.handModelPath)):s.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/");const n=new f6(o.hand,s);return o.hand.add(n),o.hand.traverse(a=>a.layers.set(2)),o.handPointerModel=new m6(o.hand,o.controller),o.controller.addEventListener("connected",a=>{o.setControllerLayers(o.controllerModel,2),o.setControllerLayers(o.controllerGrip,2),o.setControllerLayers(o.hand,2),setTimeout(()=>{o.setControllerLayers(o.controllerModel,2),o.setControllerLayers(o.controllerGrip,2),o.setControllerLayers(o.hand,2)},1e3)}),o.hand.addEventListener("connected",a=>{var Q;if(a.data.hand){e.Rig&&e.Rig.add(o.hand),o.type=0,o.handPointerModel.traverse(c=>c.layers.set(2)),(Q=o.handPointerModel.pointerObject)==null||Q.traverse(c=>c.layers.set(2));const E=o.hand.joints;if(E)for(const c of Object.keys(E)){const h=E[c];h.parent||o.hand.add(h)}}}),o}static addEventListener(e,t){const g=this.eventSubs[e]??[];g.push(t),this.eventSubs[e]=g}static removeEventListener(e,t){if(!t)return;const g=this.eventSubs[e]??[],I=g.indexOf(t);I>=0&&g.splice(I,1),this.eventSubs[e]=g}get isUsingHands(){var t;const e=(t=this.input)==null?void 0:t.hand;return e!=null}get wrist(){if(!this.hand)return null;const e=this.hand.joints;return e?e.wrist:null}getWristQuaternion(){const e=this.wrist;return e?(this._wristQuaternion||(this._wristQuaternion=new kA),Hi(e).multiply(this._wristQuaternion.setFromEuler(new Ui(-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 e,t,g;this.type===1&&(this.controllerGrip.removeEventListener("connected",this._connnectedCallback),this.controllerGrip.removeEventListener("disconnected",this._disconnectedCallback),this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),(e=this.hand)==null||e.clear(),(t=this.controllerGrip)==null||t.clear(),(g=this.controller)==null||g.clear()}onEnable(){var e,t,g,I,o;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=Xi.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=Xi.CreateRaycastHitPoint()),(e=this.webXR.Rig)==null||e.add(this.hand),(t=this.webXR.Rig)==null||t.add(this.controllerGrip),(g=this.webXR.Rig)==null||g.add(this.controller),(I=this.webXR.Rig)==null||I.add(this.raycastLine),(o=this.raycastLine)==null||o.add(this._raycastHitPoint),this._raycastHitPoint.visible=!1,this.hand.add(this.handPointerModel),Oc&&console.log("ADDED TO RIG",this.webXR.Rig)}onDisable(){var t,g,I,o,C;(t=this.hand)==null||t.removeFromParent(),(g=this.controllerGrip)==null||g.removeFromParent(),(I=this.controller)==null||I.removeFromParent(),(o=this.raycastLine)==null||o.removeFromParent(),(C=this._raycastHitPoint)==null||C.removeFromParent();const e=this.webXR.Controllers.indexOf(this);e>=0&&this.webXR.Controllers.splice(e,1)}onSourceConnected(e){if(this._isConnected){console.warn("Received connected event for controller that is already connected",this.index,e);return}this._isConnected=!0,this.input=e.data,this.type===1&&(this.onSelectStart(),this.createPointerEvent("down"))}onSourceDisconnected(e){if(!this._isConnected){console.warn("Received discnnected event for controller that is not connected",e);return}this._isConnected=!1,this.type===1&&(this.onSelectEnd(),this.createPointerEvent("up")),this.input=null}createPointerEvent(e){switch(e){case"down":this.context.input.createPointerDown({clientX:0,clientY:0,button:this.index,pointerType:"touch"});break;case"move":break;case"up":this.context.input.createPointerUp({clientX:0,clientY:0,button:this.index,pointerType:"touch"});break}}update(){this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));const e=Xi.eventSubs.update;if(e&&e.length>0)for(const I of e)I(this);let t=1;this.type===0?t=this.context.time.deltaTime/.1:this.isUsingHands&&this.handPointerModel.pinched&&(t=this.context.time.deltaTime/.3),this.rayRotation.slerp(Hi(this.controller),this.useSmoothing?t:1);const g=ye(this.controller);if(this.isUsingHands&&this.handPointerModel.cursorObject&&(this.handPointerModel.cursorObject.visible=!1),this.raycastLine){const I=this.showRaycastLine&&this.type!==1;if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed&&I,hi(this.raycastLine,g);const o=this.hand.joints;if(o&&o.wrist&&this.grabbed&&this.grabbed.isCloseGrab){const s=this.getWristQuaternion();s&&this.rayRotation.copy(s)}fI(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=I,fI(this.raycastLine,this.rayRotation),hi(this.raycastLine,g)}this.lastHit=this.updateLastHit(),this.grabbed&&this.grabbed.update(),this._selectionPressedLastFrame=this._selectionPressed,this.selectStartCallback&&this.selectStartCallback()}onUpdate(e){var I,o;if(this.lastHit=null,!e||e.inputSources.length<=this.index){this.input=null;return}if(this.type===0&&(this.input=e.inputSources[this.index]),!this.input)return;const t=this.webXR.Rig;if(!t)return;this._didNotEndSelection&&!this.handPointerModel.pinched&&(this._didNotEndSelection=!1,this.onSelectEnd()),this.updateStick(this.input);const g=(o=(I=this.input)==null?void 0:I.gamepad)==null?void 0:o.buttons;switch(this.input.handedness){case"left":const C=3*Xi.MovementSpeedFactor,s=2,n=Ae.clamp01(this.joystick.length()*2),a=this.joystick.x>0?1:-1;let B=Math.pow(this.joystick.x,s);B*=a,B*=n;const Q=this.joystick.y>0?1:-1;let E=Math.pow(this.joystick.y,s);E*=Q,B*=n,t.getWorldQuaternion(this.worldRot),this.movementVector.set(B,0,E),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),this.movementVector.multiplyScalar(C*this.context.time.deltaTime),t.position.add(this.movementVector),this.isUsingHands&&this.runTeleport(t,g);break;case"right":const c=this.joystick.x,h=Math.abs(c);if(h<.4)this.didRotate=!1;else if(h>.5&&!this.didRotate){const l=c>0?-1:1;t.rotateY(Ae.toRadians(30*l)),this.didRotate=!0}this.runTeleport(t,g);break}}runTeleport(e,t){var s,n,a;let g=-this.joystick.y;if((s=this.hand)!=null&&s.visible&&!this.grabbed){const B=this.handPointerModel.isPinched();B&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),B&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(g=this.handPointerModel.isPinched()?1:0),B||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;let I=g>.5&&this.webXR.IsInVR,o=this.webXR.Rig?((a=(n=this.webXR.Rig)==null?void 0:n.scale)==null?void 0:a.x)<.999:!1,C=null;if(t&&this.input&&!this.input.hand)for(let B=0;B<t.length;B++){const Q=t[B];if(B===4)if(Q.pressed&&!this.didChangeScale&&this.webXR.IsInVR){this.didChangeScale=!0;const E=this.webXR.Rig;if(E)if(o){o=!1,E.scale.set(1,1,1),C=1,Xi.MovementSpeedFactor=1;const c=this.context.mainCamera;Xi.PreviousCameraFarDistance&&(c.far=Xi.PreviousCameraFarDistance)}else{o=!0,I=!0,C=.1,Xi.MovementSpeedFactor=C*2;const c=this.context.mainCamera;Xi.PreviousCameraFarDistance=c.far,c.far/=C}}else Q.pressed||(this.didChangeScale=!1)}if(I){if(!this.didTeleport){const B=this.raycast();if(this.didTeleport=!0,B&&B.length>0){const Q=B[0];if(o||this.isValidTeleportTarget(Q.object)){const E=Q.point;hi(e,E)}}}}else g<.1&&(this.didTeleport=!1);C!==null&&(e.scale.set(C,C,C),e.updateMatrixWorld())}isValidTeleportTarget(e){return eA.getComponentInParent(e,vw)!=null}updateStick(e){var t;!e||!e.gamepad||((t=e.gamepad.axes)==null?void 0:t.length)<4||(this.joystick.x=e.gamepad.axes[2],this.joystick.y=e.gamepad.axes[3])}updateLastHit(){var I;const e=this.raycast(),t=e?e[0]:null;this.lastHit=t;let g=1;if(this.webXR.Rig&&(g/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=g*(((I=this.lastHit)==null?void 0:I.distance)??9999);const o=this.raycastLine.material;t!=null?o.color=Xi.raycastColor:o.color=Xi.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;const o=Ae.clamp(this.lastHit.distance*.01*g,.015,.1);this._raycastHitPoint.scale.set(o,o,o)}this._raycastHitPoint.visible=this.lastHit!==null&&this.lastHit!==void 0}return t}onSelectStart(){this.context.connection.allowEditing&&(this.selectStartCallback=()=>this.onHandleSelectStart())}onHandleSelectStart(){this.selectStartCallback=null,this._selectionPressed=!0,this._selectionStartTime=this.context.time.time,this._selectionEndTime=1e3;let e=null,t=!1;if(this.isUsingHands?(e=this.overlap(),e.length<=0?(e=this.raycast(),t=!1):t=!0):e=this.raycast(),Oc&&console.log("onHandleSelectStart","close grab? "+t,"intersections",e),e&&e.length>0)for(const g of e){const I=g.object;this.lastSelectStartObject=I;const o={selected:I,grab:I},C=Xi.eventSubs["select-start"];if(C&&C.length>0)for(const s of C)s(this,o);o.grab!==I&&Oc&&console.log("Grabbed object changed","original",I,"new",o.grab),o.grab&&(this.grabbed=uo.TryTake(this,o.grab,g,t));break}else{const g=Xi.eventSubs["select-start"],I={selected:null,grab:null};if(g&&g.length>0)for(const o of g)o(this,I)}}onSelectEnd(){var g;if(this.isUsingHands&&this.handPointerModel.pinched){this._didNotEndSelection=!0;return}if(!this._selectionPressed)return;this.selectStartCallback=null,this._selectionPressed=!1,this._selectionEndTime=this.context.time.time;const e={grab:((g=this.grabbed)==null?void 0:g.selected)??this.lastSelectStartObject},t=Xi.eventSubs["select-end"];if(t&&t.length>0)for(const I of t)I(this,e);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(e){return!(!e||eA.isActiveInHierarchy(e)===!1||zQ.isInteractable(e)===!1)}setControllerLayers(e,t){var g,I;if(e&&(e.layers.set(t),e.children))for(const o of e.children)((g=this.grabbed)==null?void 0:g.selected)===o||((I=this.grabbed)==null?void 0:I.selectedMesh)===o||this.setControllerLayers(o,t)}getRay(){const e=new on;return e.origin.copy(ye(this.controller)),e.direction.set(0,0,-1).applyQuaternion(this.rayRotation),e}overlap(){const e=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(Oc&&(!this.closeGrabBoundingBoxHelper&&e&&(this.closeGrabBoundingBoxHelper=new $f(e,16776960),this.scene.add(this.closeGrabBoundingBoxHelper)),this.closeGrabBoundingBoxHelper&&e&&this.closeGrabBoundingBoxHelper.setFromObject(e)),!e)return new Array;const t=ye(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){const e=new CC;e.layerMask=new yo,e.layerMask.enableAll(),e.layerMask.disable(2),e.ray=this.getRay();const t=this.context.physics.raycast(e);for(let g=0;g<t.length;g++){const I=t[g],o=I.object;if(!this.testIsVisible(o)){t.splice(g,1),g--;continue}I.object=zQ.getObject(o);break}return t}};let ti=Xi;r(ti,"Factory",new Y6),r(ti,"raycastColor",new yA(.9,.3,.3)),r(ti,"raycastNoHitColor",new yA(.6,.6,.6)),r(ti,"geometry",new ue().setFromPoints([new k(0,0,0),new k(0,0,-1)])),r(ti,"handModels",{}),r(ti,"eventSubs",{}),r(ti,"PreviousCameraFarDistance"),r(ti,"MovementSpeedFactor",1);var ef=(i=>(i.WillTake="WillTake",i.DidTake="DidTake",i.WillFree="WillFree",i.DidFree="DidFree",i))(ef||{});const xg=class{constructor(){r(this,"sync",null);r(this,"selected",null);r(this,"selectedParent",null);r(this,"selectedMesh",null);r(this,"controller",null);r(this,"grabTime",0);r(this,"grabUUID","");r(this,"isCloseGrab",!1);r(this,"originalMaterial",null);r(this,"usageMarker",null);r(this,"rigidbodies",null);r(this,"didReparent",!1);r(this,"grabDistance",0);r(this,"interactable",null);r(this,"positionSource",null);r(this,"grabPoint",new k);r(this,"localPositionOffsetToGrab",null);r(this,"localPositionOffsetToGrab_worldSpace",new k);r(this,"localQuaternionToGrab",new kA(0,0,0,1));r(this,"targetDir",null);r(this,"quaternionLerp",null);r(this,"controllerDir",new k);r(this,"controllerWorldPos",new k);r(this,"lastControllerWorldPos",new k);r(this,"controllerPosDelta",new k);r(this,"totalChangeAlongDirection",0);r(this,"rigPositionLastFrame",new k)}static AddEventListener(A,e){return xg.Events[A]||(xg.Events[A]=[]),xg.Events[A].push(e),e}static RemoveEventListener(A,e){if(!e||!xg.Events[A])return;const t=xg.Events[A].indexOf(e);t>=0&&xg.Events[A].splice(t,1)}static Register(A){this.Current.find(e=>e===A)||this.Current.push(A)}static Remove(A){const e=this.Current.indexOf(A);e>=0&&this.Current.splice(e,1)}static TryTake(A,e,t,g){const I=eA.getComponentInParent(e,UE);if(I)e=I.gameObject;else return Oc&&console.warn("Prevented taking object that is not interactable",e),null;let o=e;const C=eA.getComponentInParent(e,da);C&&(C.requestOwnership(),o=C.gameObject);for(const n of this.Current)if(n.selected===o)return n.controller===A||(n.free(),n.Take(A,o,e,C,I,t,g)),n;const s=new xg;return s.Take(A,o,e,C,I,t,g),s}Take(A,e,t,g,I,o,C){var E,c;if(console.assert(e!==null,"Expected object to be taken but was",e),A.isUsingHands?this.positionSource=C?A.wrist:A.controller:this.positionSource=A.controller,!this.positionSource)return console.warn("No position source"),this;const s={controller:A,take:e,hit:t,sync:g,interactable:I};(E=xg.Events.WillTake)==null||E.forEach(h=>h(this,s));const n=t;n!=null&&n.material&&(this.originalMaterial=n.material,Array.isArray(n.material)||(n.material=n.material.clone(),n.material&&n.material.emissive&&(n.material.emissive.b=.2))),this.selected=e,this.selectedParent||(this.selectedParent=e.parent),this.selectedMesh=n,this.controller=A,this.interactable=I,this.isCloseGrab=C,this.didReparent=!1,this.sync=g,this.grabTime=A.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=eA.addNewComponent(this.selected,FE),this.rigidbodies=eA.getComponentsInChildren(this.selected,jt),ye(this.positionSource,this.lastControllerWorldPos);const a=()=>C?this.lastControllerWorldPos.clone():o.point.clone();this.grabDistance=a().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(a());const B=A.isUsingHands&&C?this.controller.getWristQuaternion().clone():A.rayRotation.clone();Hi(this.selected,this.localQuaternionToGrab).premultiply(B.invert());const Q=this.controller.webXR.Rig;return Q&&this.rigPositionLastFrame.copy(ye(Q)),jg.Add(A.context,this.selected),xg.Register(this),this.sync&&(this.sync.fastMode=!0),(c=xg.Events.DidTake)==null||c.forEach(h=>h(this,s)),this}free(){var g,I,o,C;if(!this.selected)return;const A={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};(g=xg.Events.WillFree)==null||g.forEach(s=>s(this,A)),jg.Remove(this.controller.context,this.selected),xg.Remove(this),this.sync&&(this.sync.fastMode=!1);const e=this.selectedMesh;e&&this.originalMaterial&&e.material&&(e.material=this.originalMaterial);const t=this.selected;if(this.didReparent&&t.parent){const s=this.selectedParent;s?s.attach(t):(I=this.controller)==null||I.context.scene.attach(t)}if((o=this.usageMarker)==null||o.destroy(),this.controller&&(this.controller.grabbed=null),this.selected=null,this.selectedParent=null,this.selectedMesh=null,this.sync=null,this.rigidbodies)for(const s of this.rigidbodies)s.wakeUp(),s.setVelocity(s.smoothedVelocity);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,(C=xg.Events.DidFree)==null||C.forEach(s=>s(this,A))}controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),ye(this.positionSource,this.controllerWorldPos),this.controllerPosDelta.copy(this.controllerWorldPos),this.controllerPosDelta.sub(this.lastControllerWorldPos),this.lastControllerWorldPos.copy(this.controllerWorldPos);const A=this.controller.webXR.Rig;if(A){const t=ye(A),g=this.rigPositionLastFrame.sub(t);this.controllerPosDelta.add(g),this.rigPositionLastFrame.copy(t)}return this.controllerDir.dot(this.controllerPosDelta)}update(){var A;if(this.rigidbodies)for(const e of this.rigidbodies)e.resetVelocities();if(this.sync&&this.controller&&this.controller.context.connection.isInRoom&&this.controller.context.time.time-this.grabTime>3&&this.sync.hasOwnership()===!1&&(console.log("no ownership, will leave",this.sync.guid),this.free()),!(this.interactable&&!this.interactable.canGrab)){if(!this.didReparent&&this.selected&&this.controller){const e=((A=this.controller.webXR.Rig)==null?void 0:A.scale.x)??1;this.totalChangeAlongDirection+=this.controllerMovementSinceLastFrame();let t=1;this.controller.type===0&&(t=Math.max(0,1+this.totalChangeAlongDirection*2/e),t=t*t*t),this.grabDistance/e<.8&&(t=1),this.targetDir||(this.targetDir=new k),this.targetDir.set(0,0,-this.grabDistance*t);const g=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),I=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=I.clone()),this.quaternionLerp.slerp(I,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),fI(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(g),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(ye(this.selected)),g.sub(this.localPositionOffsetToGrab_worldSpace)),hi(this.selected,g)}if(this.rigidbodies!=null)for(const e of this.rigidbodies)e.wakeUp();dI.markDirty(this.selected,!0)}}};let uo=xg;r(uo,"Events",{}),r(uo,"Current",[]);var zeA=Object.defineProperty,ZeA=Object.getOwnPropertyDescriptor,sR=(i,A,e,t)=>{for(var g=t>1?void 0:t?ZeA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&zeA(A,e,g),g};class tB extends MA{constructor(){super(...arguments);r(this,"objectBounds",!1);r(this,"color");r(this,"isGizmo",!0);r(this,"_gizmoObject",null);r(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!Pl||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new $f(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=sT(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),OI.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){var e;for(;this._boxHelper;)(e=this._boxHelper)==null||e.update(),yield}}sR([w()],tB.prototype,"objectBounds",2);sR([w(yA)],tB.prototype,"color",2);sR([w()],tB.prototype,"isGizmo",2);const XeA=rA("debugrig");class xw extends MA{awake(){if(XeA){const A=new UA;A.position.y+=.5,this.gameObject.add(A);const e=A.addNewComponent(tB);e&&(e.isGizmo=!1)}}}class mQ{constructor(){r(this,"bb",null);r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}w(){return this.bb.readFloat32(this.bb_pos+12)}static sizeOf(){return 16}static createVec4(A,e,t,g,I){return A.prep(4,16),A.writeFloat32(I),A.writeFloat32(g),A.writeFloat32(t),A.writeFloat32(e),A.offset()}}class kg{constructor(){r(this,"bb",null);r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}static getRootAsVrUserStateBuffer(A,e){return(e||new kg).__init(A.readInt32(A.position())+A.position(),A)}static getSizePrefixedRootAsVrUserStateBuffer(A,e){return A.setPosition(A.position()+nw),(e||new kg).__init(A.readInt32(A.position())+A.position(),A)}guid(A){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,A):null}time(){const A=this.bb.__offset(this.bb_pos,6);return A?this.bb.readInt64(this.bb_pos+A):this.bb.createLong(0,0)}avatarId(A){const e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,A):null}position(A){const e=this.bb.__offset(this.bb_pos,10);return e?(A||new TI).__init(this.bb_pos+e,this.bb):null}rotation(A){const e=this.bb.__offset(this.bb_pos,12);return e?(A||new mQ).__init(this.bb_pos+e,this.bb):null}scale(){const A=this.bb.__offset(this.bb_pos,14);return A?this.bb.readFloat32(this.bb_pos+A):0}posLeftHand(A){const e=this.bb.__offset(this.bb_pos,16);return e?(A||new TI).__init(this.bb_pos+e,this.bb):null}posRightHand(A){const e=this.bb.__offset(this.bb_pos,18);return e?(A||new TI).__init(this.bb_pos+e,this.bb):null}rotLeftHand(A){const e=this.bb.__offset(this.bb_pos,20);return e?(A||new mQ).__init(this.bb_pos+e,this.bb):null}rotRightHand(A){const e=this.bb.__offset(this.bb_pos,22);return e?(A||new mQ).__init(this.bb_pos+e,this.bb):null}static startVrUserStateBuffer(A){A.startObject(10)}static addGuid(A,e){A.addFieldOffset(0,e,0)}static addTime(A,e){A.addFieldInt64(1,e,A.createLong(0,0))}static addAvatarId(A,e){A.addFieldOffset(2,e,0)}static addPosition(A,e){A.addFieldStruct(3,e,0)}static addRotation(A,e){A.addFieldStruct(4,e,0)}static addScale(A,e){A.addFieldFloat32(5,e,0)}static addPosLeftHand(A,e){A.addFieldStruct(6,e,0)}static addPosRightHand(A,e){A.addFieldStruct(7,e,0)}static addRotLeftHand(A,e){A.addFieldStruct(8,e,0)}static addRotRightHand(A,e){A.addFieldStruct(9,e,0)}static endVrUserStateBuffer(A){return A.endObject()}static finishVrUserStateBufferBuffer(A,e){A.finish(e)}static finishSizePrefixedVrUserStateBufferBuffer(A,e){A.finish(e,void 0,!0)}}const wJ=rA("debugxr"),Mc=rA("debugavatar"),nR="VRUS";vM(nR,kg.getRootAsVrUserStateBuffer);function yG(){return new Date().getTime()}function $eA(i){let A=i&4294967295,e=i/Math.pow(2,32)&1048575;return LC.create(A,e)}const mh=class{constructor(A){r(this,"guid");r(this,"time");r(this,"avatarId");r(this,"position",new k);r(this,"rotation",new Ce);r(this,"scale",1);r(this,"posLeftHand",new k);r(this,"posRightHand",new k);r(this,"rotLeftHand",new kA);r(this,"rotRightHand",new kA);this.guid=A}update(A,e,t,g,I){var a,B,Q,E,c,h;this.time=yG(),this.avatarId=I,this.position.set(e.x,e.y,e.z),A&&this.position.applyMatrix4(A.matrixWorld);let o=mh.quat0;const C=mh.quat1;o.set(t.x,t.y,t.z,t.w),o=o.multiplyQuaternions(o,mh.invertRotation),A&&(A.getWorldQuaternion(C),o.multiplyQuaternions(C,o)),this.rotation.set(o.x,o.y,o.z,o.w),this.scale=A.scale.x;const s=(a=g.LeftController)==null?void 0:a.controllerGrip;s&&(s.getWorldPosition(this.posLeftHand),s.getWorldQuaternion(this.rotLeftHand));const n=(B=g.RightController)==null?void 0:B.controllerGrip;if(n&&(n.getWorldPosition(this.posRightHand),n.getWorldQuaternion(this.rotRightHand)),(E=(Q=g.LeftController)==null?void 0:Q.hand)!=null&&E.visible){const l=g.LeftController.wrist;l&&(l.getWorldPosition(this.posLeftHand),l.getWorldQuaternion(this.rotLeftHand))}if((h=(c=g.RightController)==null?void 0:c.hand)!=null&&h.visible){const l=g.RightController.wrist;l&&(l.getWorldPosition(this.posRightHand),l.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(A,e){A.clear();const t=A.createString(this.guid),g=A.createString(this.avatarId);kg.startVrUserStateBuffer(A),kg.addGuid(A,t),kg.addTime(A,$eA(this.time)),kg.addAvatarId(A,g),kg.addPosition(A,TI.createVec3(A,this.position.x,this.position.y,this.position.z)),kg.addRotation(A,mQ.createVec4(A,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),kg.addScale(A,this.scale),kg.addPosLeftHand(A,TI.createVec3(A,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),kg.addPosRightHand(A,TI.createVec3(A,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),kg.addRotLeftHand(A,mQ.createVec4(A,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),kg.addRotRightHand(A,mQ.createVec4(A,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));const I=kg.endVrUserStateBuffer(A);A.finish(I,nR);const o=A.asUint8Array();e.sendBinary(o)}setFromBuffer(A,e){if(!A)return;this.guid=A,this.time=e.time().toFloat64();const t=e.avatarId();t&&(this.avatarId=t);const g=e.position();g&&this.position.set(g.x(),g.y(),g.z());const I=e.rotation();I&&this.rotation.set(I.x(),I.y(),I.z(),I.w());const o=e.posLeftHand();o&&this.posLeftHand.set(o.x(),o.y(),o.z());const C=e.posRightHand();C&&this.posRightHand.set(C.x(),C.y(),C.z());const s=e.rotLeftHand();s&&this.rotLeftHand.set(s.x(),s.y(),s.z(),s.w());const n=e.rotRightHand();n&&this.rotRightHand.set(n.x(),n.y(),n.z(),n.w()),this.scale=e.scale()}};let jo=mh;r(jo,"invertRotation",new kA().setFromAxisAngle(new k(0,1,0),Math.PI)),r(jo,"quat0",new kA),r(jo,"quat1",new kA);class al extends MA{constructor(){super(...arguments);r(this,"webXR",null);r(this,"debugAvatarUser",null);r(this,"voip",null);r(this,"tempState",new jo(""));r(this,"_removeAvatarsList",[]);r(this,"eventSub_ConnectionEvent",null);r(this,"eventSub_WebXRStartEvent",null);r(this,"eventSub_WebXREndEvent",null);r(this,"eventSub_WebXRUpdateEvent",null);r(this,"avatars",{});r(this,"localAvatar",null);r(this,"k_LocalAvatarNoNetworkingGuid","local");r(this,"ownership",null);r(this,"xrState",null);r(this,"builder",new EE(1024))}async awake(){if(this.webXR||(this.webXR=eA.getComponent(this.gameObject,Se)),this.webXR||(this.webXR=eA.findObjectOfType(Se,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=eA.findObjectOfType(Se,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=eA.findObjectOfType(nn,this.context)),Mc){const e="debug-avatar-"+Mc,t=new JC(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof Mc=="string"&&Mc.length>0)if(await t.setAvatarOverride(Mc)){const g=new jo(e);g.position.y+=1;const I=.5;g.posLeftHand.y+=I,g.posLeftHand.x+=I,g.posRightHand.y+=I,g.posRightHand.x-=I,t.tryUpdate(g,0)}else t.destroy()}}onEnable(){if(!this.webXR&&(this.webXR=eA.getComponent(this.gameObject,Se),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),Se.addEventListener(Ft.XRStarted,this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),Se.addEventListener(Ft.XRUpdate,this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),Se.addEventListener(Ft.XRStopped,this.eventSub_WebXREndEvent),this.eventSub_ConnectionEvent=this.onConnected.bind(this),this.context.connection.beginListen(gi.JoinedRoom,this.eventSub_ConnectionEvent),this.context.connection.beginListen("webxr-user-joined",e=>{console.log("webxr user joined evt")}),this.context.connection.beginListen("webxr-user-left",e=>{const t=e.id!==null&&e.id!==void 0;if(t&&(console.log("webxr user left evt"),t)){const g=this.avatars[e.id];g==null||g.destroy(),this.avatars[e.id]=void 0}}),this.context.connection.beginListenBinary(nR,e=>{const t=e.guid();if(!t)return;const g=e.time().toFloat64(),I=this.tempState;I.setFromBuffer(t,e);const o=this.onTryGetAvatar(t,g);o==null||o.tryUpdate(I,g)}),this.context.connection.beginListen("vr-session-update",e=>{const t=e.guid,g=e.time,I=this.onTryGetAvatar(t,g);I==null||I.tryUpdate(e,g)})}onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;const g=new Date().getTime()-t;if(g>5e3)return wJ&&console.log("old data",g,e),null;let I=this.avatars[e];if(I===void 0)try{console.log("create new avatar");const o=new JC(this.context,e,this.webXR);I=o,this.avatars[e]=o}catch(o){this.avatars[e]=null,console.error(o)}return I}onDisable(){this.eventSub_ConnectionEvent&&this.context.connection.stopListen(gi.JoinedRoom,this.eventSub_ConnectionEvent),Se.removeEventListener(Ft.XRStarted,this.eventSub_WebXRStartEvent),Se.removeEventListener(Ft.XRUpdate,this.eventSub_WebXRUpdateEvent),Se.removeEventListener(Ft.XRStopped,this.eventSub_WebXREndEvent)}update(){const e=yG();this.debugAvatarUser&&(this.debugAvatarUser.lastUpdate=e),this.detectPotentiallyDisconnectedAvatarsAndRemove();for(const t in this.avatars){const g=this.avatars[t];g&&g.update()}}detectPotentiallyDisconnectedAvatarsAndRemove(){const e=yG();for(const t in this.avatars){const g=this.avatars[t];if(!g){this._removeAvatarsList.push(t);continue}e-g.lastUpdate>1e4&&(console.log("avatar timed out (didnt receive any updates in a while) - destroying it now"),g.destroy(),this.avatars[t]=void 0)}for(const t of this._removeAvatarsList)delete this.avatars[t];this._removeAvatarsList.length=0}buildLocalAvatar(){var t;if(this.localAvatar)return;const e=((t=this.context.connection)==null?void 0:t.connectionId)??this.k_LocalAvatarNoNetworkingGuid;this.localAvatar=new JC(this.context,e,this.webXR),this.localAvatar.isLocalAvatar=!0,this.localAvatar.setAvatarOverride(this.getAvatarId()),this.avatars[this.localAvatar.guid]=this.localAvatar}onConnected(){var e,t,g;wJ&&console.log("Hey you are connected as "+this.context.connection.connectionId),((e=this.localAvatar)==null?void 0:e.guid)===this.k_LocalAvatarNoNetworkingGuid&&(this.localAvatar&&((t=this.localAvatar)==null||t.destroy(),this.avatars[this.localAvatar.guid]=void 0),this.localAvatar=null,this.xrState=null,(g=this.ownership)==null||g.freeOwnership(),this.ownership=null)}onXRSessionStart(e){var t,g,I;if(console.log("XR session started"),this.context.connection.send("webxr-user-joined",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&((t=this.localAvatar)==null||t.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null),this.xrState=null,(g=this.ownership)==null||g.freeOwnership(),this.ownership=null,this.avatars)for(const o in this.avatars)(I=this.avatars[o])==null||I.updateFlags()}onXRSessionEnded(e){var t;console.log("XR session ended"),this.context.connection.send("webxr-user-left",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&((t=this.localAvatar)==null||t.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null)}onXRSessionUpdate(e){this.xrState??(this.xrState=new jo(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid)),this.ownership??(this.ownership=new rw(this.context.connection,this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid)),this.ownership.guid=this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid,this.buildLocalAvatar();const{frame:t,xr:g,rig:I}=e,o=t.getViewerPose(g.getReferenceSpace());if(!o)return;const C=o==null?void 0:o.transform,s=C.position,n=C.orientation;this.xrState.update(I,s,n,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 rA("avatar")??null}}var AtA=Object.defineProperty,etA=Object.getOwnPropertyDescriptor,qE=(i,A,e,t)=>{for(var g=t>1?void 0:t?etA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&AtA(A,e,g),g};async function jH(){return YG()?!0:"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function zH(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}let zD=!1,ZD=!1;jH().then(i=>zD=i);zH().then(i=>ZD=i);var Ft=(i=>(i.XRStarted="xrStarted",i.XRStopped="xrStopped",i.XRUpdate="xrUpdate",i.RequestVRSession="requestVRSession",i.ModifyAROptions="modify-ar-options",i))(Ft||{}),zB;const Li=(zB=class extends MA{constructor(){super(...arguments);r(this,"enableVR",!0);r(this,"enableAR",!0);r(this,"defaultAvatar");r(this,"handModelPath","");r(this,"createVRButton",!0);r(this,"createARButton",!0);r(this,"controllers",[]);r(this,"rig");r(this,"isInit",!1);r(this,"_requestedAR",!1);r(this,"_requestedVR",!1);r(this,"_isInAR",!1);r(this,"_isInVR",!1);r(this,"_arButton");r(this,"_vrButton");r(this,"webAR",null);r(this,"_transformOrientation",new kA);r(this,"_currentHeadPose",null);r(this,"_originalCameraParent",null);r(this,"_originalCameraPosition",new k);r(this,"_originalCameraRotation",new kA);r(this,"_originalXRRigParent",null);r(this,"_originalXRRigPosition",new k);r(this,"_originalXRRigRotation",new kA);r(this,"xrMirrorWindow",null)}static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(zD||ZD)}static get IsARSupported(){return zD}static get IsVRSupported(){return ZD}static get OptionalFeatures_VR(){return this._optionalFeatures_VR}static get OptionalFeatures_AR(){return this._optionalFeatures_AR}static addEventListener(A,e){return this.events.addEventListener(A,e),e}static removeEventListener(A,e){return this.events.removeEventListener(A,e),e}static dispatchEvent(A,e){this.events.dispatchEvent({type:A,detail:e})}static createVRButton(A,e){Li.XRSupported?A.__internalAwake():console.warn("WebXR is not supported on this device");const t={optionalFeatures:Li.OptionalFeatures_VR},g=hh.createButton(A.context.renderer,t);return g.classList.add("webxr-ar-button"),g.classList.add("webxr-button"),this.resetButtonStyles(g),((e==null?void 0:e.registerClick)??!0)&&g.addEventListener("click",A.onClickedVRButton.bind(A)),g}static createARButton(A,e){var o;A.__internalAwake();const t=(o=A.webAR)==null?void 0:o.getAROverlayContainer(),g={optionalFeatures:[...this.OptionalFeatures_AR]};t?(g.domOverlay={root:t},g.optionalFeatures.push("dom-overlay"),g.optionalFeatures.push("hit-test")):console.warn("No dom overlay root found, HTML overlays on top of screen-based AR will not work.");const I=r6.createButton(A.context.renderer,g,this.onModifyAROptions.bind(this));return I.classList.add("webxr-ar-button"),I.classList.add("webxr-button"),Li.resetButtonStyles(I),((e==null?void 0:e.registerClick)??!0)&&I.addEventListener("click",A.onClickedARButton.bind(A)),I}static onModifyAROptions(A){Li.dispatchEvent("modify-ar-options",A)}static resetButtonStyles(A){A&&(A.style.position="",A.style.bottom="",A.style.left="")}endSession(){const A=this.context.renderer.xr.getSession();A&&A.end()}get Rig(){return this.rig||this.ensureRig(),this.rig}get Controllers(){return this.controllers}get LeftController(){var A,e;return this.controllers.length>0&&((A=this.controllers[0].input)==null?void 0:A.handedness)==="left"?this.controllers[0]:this.controllers.length>1&&((e=this.controllers[1].input)==null?void 0:e.handedness)==="left"?this.controllers[1]:null}get RightController(){var A,e;return this.controllers.length>0&&((A=this.controllers[0].input)==null?void 0:A.handedness)==="right"?this.controllers[0]:this.controllers.length>1&&((e=this.controllers[1].input)==null?void 0:e.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=gg.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!eA.findObjectOfType(al,this.context)){const A=eA.addNewComponent(this.gameObject,al,!1);A.webXR=this}this.webAR=new Rr(this)}start(){location.protocol=="http:"&&location.host.indexOf("localhost")<0&&(oC("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,Li.XRSupported;let A,e;const t=document.createElement("div");t.classList.add("webxr-buttons"),this.context.domElement.append(t),this.enableAR&&this.createARButton&&zD&&(A=Li.createARButton(this),this._arButton=A,t.appendChild(A)),this.createVRButton&&this.enableVR&&ZD&&(e=Li.createVRButton(this),this._vrButton=e,t.appendChild(e)),setTimeout(()=>{Li.resetButtonStyles(e),Li.resetButtonStyles(A)},1e3)}get TransformOrientation(){return this._transformOrientation}get HeadPose(){return this._currentHeadPose}onBeforeRender(A){var t;if(!A)return;const e=this.context.renderer.xr.getSession();if(e){const g=A.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(!g)return;this._currentHeadPose=g;const I=g==null?void 0:g.transform;I&&this._transformOrientation.set(I.orientation.x,I.orientation.y,I.orientation.z,I.orientation.w),Li._isInXr===!1&&e&&this.onEnterXR(e,A);for(const o of this.controllers)o.onUpdate(e);this._isInAR&&((t=this.webAR)==null||t.onUpdate(e,A))}Li.events.dispatchEvent({type:"xrUpdate",frame:A,xr:this.context.renderer.xr,rig:this.rig})}onClickedARButton(){this._isInAR||(this._requestedAR=!0,this._requestedVR=!1,this.captureStateBeforeXR())}onClickedVRButton(){if(!this._isInVR){if(this._requestedVR){this.onExitXR(null);return}this._requestedAR=!1,this._requestedVR=!0,this.captureStateBeforeXR(),this.ensureRig();for(let A=0;A<2;A++)ti.Create(this,A,this.gameObject,MQ.PhysicalDevice);Li.events.dispatchEvent({type:"requestVRSession"})}}captureStateBeforeXR(){this.context.mainCamera&&(this._originalCameraPosition.copy(ye(this.context.mainCamera)),this._originalCameraRotation.copy(Hi(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent),this.Rig&&(this._originalXRRigParent=this.Rig.parent,this._originalXRRigPosition.copy(this.Rig.position),this._originalXRRigRotation.copy(this.Rig.quaternion))}ensureRig(){if(!this.rig){const A=eA.findObjectOfType(xw,this.context);A?this.rig=A.gameObject:(this.rig=new co,this.rig.rotateY(Math.PI),this.rig.name="XRRig",this.context.scene.add(this.rig))}}onEnterXR(A,e){var o,C;console.log("[XR] session begin",A),Li._isInXr=!0,this.ensureRig();const t=this.context.renderer.xr.getReferenceSpace();if(t&&this.rig){const s=e.getViewerPose(t),n=s==null?void 0:s.transform.orientation;if(n){const a=new kA(n.x,n.y,n.z,n.w),B=new Ui().setFromQuaternion(a);this.rig.rotateY(B.y)}}const g=this.context.renderer.xr;if(this.context.mainCamera){const s=g.getCamera(this.context.mainCamera),n=(o=this.context.mainCameraComponent)==null?void 0:o.cullingMask;if(n!==void 0){for(const a of s.cameras)a.layers.mask=n;s.layers.mask=n}else{for(const a of s.cameras)a.layers.enableAll();s.layers.enableAll()}this.rig.add(this.context.mainCamera),this._requestedAR&&this.context.scene.add(this.rig)}const I=this._requestedAR?Mi.AR:Mi.VR;switch(lo.Global.Set(I),I){case Mi.AR:this.context.xrSessionMode=jh.ImmersiveAR,this._isInAR=!0,(C=this.webAR)==null||C.onBegin(A);break;case Mi.VR:this.context.xrSessionMode=jh.ImmersiveVR,this._isInVR=!0,this.onEnterVR(A);break}A.addEventListener("end",()=>{console.log("[XR] session end"),Li._isInXr=!1,this.onExitXR(A)}),this.onEnterXR_HandleMirrorWindow(A),Li.events.dispatchEvent({type:"xrStarted",session:A})}onExitXR(A){var t,g,I;const e=this._isInAR;this._isInAR&&A&&((t=this.webAR)==null||t.onEnd(A)),this._isInAR=!1,this._isInVR=!1,this._requestedAR=!1,this._requestedVR=!1,this.context.xrSessionMode=void 0,this.xrMirrorWindow&&(this.xrMirrorWindow.close(),this.xrMirrorWindow=null),this.destroyControllers(),this.context.mainCamera&&((g=this._originalCameraParent)==null||g.add(this.context.mainCamera),hi(this.context.mainCamera,this._originalCameraPosition),fI(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),e&&((I=this._originalXRRigParent)==null||I.add(this.rig),this.rig.position.copy(this._originalXRRigPosition),this.rig.quaternion.copy(this._originalXRRigRotation)),lo.Global.Set(Mi.Browser|Mi.ThirdPerson),Li.events.dispatchEvent({type:"xrStopped",session:A})}onEnterVR(A){}destroyControllers(){var A;for(let e=this.controllers.length-1;e>=0;e-=1)(A=this.controllers[e])==null||A.destroy();this.controllers.length=0}onEnterXR_HandleMirrorWindow(A){rA("mirror")&&setTimeout(()=>{if(!Li.IsInWebXR)return;const e=new URL(window.location.href);Fh(e.searchParams,Wp,1),Fh(e.searchParams,"isMirror",1);const t=e.toString();this.xrMirrorWindow=window.open(t,"webxr sync","popup=yes"),this.xrMirrorWindow&&(this.xrMirrorWindow.onload=()=>{this.xrMirrorWindow&&(this.xrMirrorWindow.onbeforeunload=()=>{Li.IsInWebXR&&A.end()})})},1e3)}},r(zB,"_isInXr",!1),r(zB,"events",new Pi),r(zB,"_optionalFeatures_VR",["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]),r(zB,"_optionalFeatures_AR",["anchors","local-floor","hand-tracking","layers"]),zB);let Se=Li;qE([w()],Se.prototype,"enableVR",2);qE([w()],Se.prototype,"enableAR",2);qE([w(gg)],Se.prototype,"defaultAvatar",2);qE([w()],Se.prototype,"handModelPath",2);qE([w()],Se.prototype,"createVRButton",2);qE([w()],Se.prototype,"createARButton",2);const DQ=class{constructor(A){r(this,"_webxr");r(this,"reticle",null);r(this,"reticleParent",null);r(this,"hitTestSource",null);r(this,"reticleActive",!0);r(this,"previousBackground",null);r(this,"previousEnvironment",null);r(this,"sessionRoot",null);r(this,"_previousParent",null);r(this,"arDomOverlay",null);r(this,"arOverlayElement",null);r(this,"noHitTestAvailable",!1);r(this,"didPlaceARSessionRoot",!1);this._webxr=A}get webxr(){return this._webxr}get context(){return this.webxr.context}getAROverlayContainer(){this.arDomOverlay=this.webxr.context.domElement;const A=this.arDomOverlay;return A.getAROverlayContainer?this.arOverlayElement=A.getAROverlayContainer():this.arOverlayElement=this.arDomOverlay,this.arOverlayElement}setReticleActive(A){this.reticleActive=A}async onBegin(A){var o,C,s,n;const e=this.webxr.context;this.reticleActive=!0,this.didPlaceARSessionRoot=!1,this.getAROverlayContainer();const t=(o=navigator.userAgent)!=null&&o.includes("OculusBrowser")?MQ.PhysicalDevice:MQ.Touch,g=t===MQ.Touch?4:2;for(let a=0;a<g;a++)ti.Create(this.webxr,a,this.webxr.gameObject,t);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=eA.findObjectOfType(Na,e)),this.previousBackground=e.scene.background,this.previousEnvironment=e.scene.environment,e.scene.background=null,A.requestReferenceSpace("viewer").then(a=>{var B,Q;(Q=(B=A.requestHitTestSource)==null?void 0:B.call(A,{space:a}))==null||Q.then(E=>{this.hitTestSource=E}).catch(E=>{this.noHitTestAvailable=!0,console.warn("WebXR: Hit test not supported",E)})}),!this.reticle&&this.sessionRoot&&(this.reticle=new fA(new aE(.07,.09,32).rotateX(-Math.PI/2),new wt),this.reticle.name="AR Placement reticle",this.reticle.matrixAutoUpdate=!1,this.reticle.visible=!1,this.reticleParent=new UA,this.reticleParent.name="AR Reticle Parent",this.reticleParent.matrixAutoUpdate=!1,this.reticleParent.add(this.reticle),this.webxr.scene?(this.context.scene.add(this.reticleParent),this.context.scene.visible=!0):console.warn("Could not found WebXR Rig")),this._previousParent=this.webxr.gameObject,DQ.tempWebXRObject||(DQ.tempWebXRObject=new UA),this.context.scene.add(DQ.tempWebXRObject),eA.addComponent(DQ.tempWebXRObject,this.webxr),this.sessionRoot?(this.sessionRoot.webAR=this,(C=this.sessionRoot)==null||C.onBegin(A)):console.warn("No WebARSessionRoot found in scene");const I=this.context.domElement;(s=I==null?void 0:I.onEnterAR)==null||s.call(I,A,this.arOverlayElement),(n=this.context.mainCameraComponent)==null||n.applyClearFlagsIfIsActiveCamera()}onEnd(A){var g,I;this._previousParent&&(eA.addComponent(this._previousParent,this.webxr),this._previousParent=null),this.hitTestSource=null;const e=this.webxr.context;e.scene.background=this.previousBackground,e.scene.environment=this.previousEnvironment,this.sessionRoot&&this.sessionRoot.onEnd(this.webxr.Rig,A);const t=this.context.domElement;(g=t.onExitAR)==null||g.call(t,A),(I=this.context.mainCameraComponent)==null||I.applyClearFlagsIfIsActiveCamera()}onUpdate(A,e){var g,I;if(this.noHitTestAvailable===!0){if(this.reticle&&(this.reticle.visible=!1),!this.didPlaceARSessionRoot){this.didPlaceARSessionRoot=!0;const o=this.webxr.Rig,C=ttA.clone();(g=this.sessionRoot)==null||g.placeAt(o,C)}return}if(!this.hitTestSource)return;const t=e.getHitTestResults(this.hitTestSource);if(t.length){const o=t[0],C=this.webxr.context.renderer.xr.getReferenceSpace();if(C){const s=o.getPose(C);if(this.sessionRoot){const n=this.sessionRoot.onUpdate(this.webxr.Rig,A,s);this.didPlaceARSessionRoot=n}if(this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&s)){const n=s.transform.matrix;this.reticle.matrix.fromArray(n),this.webxr.Rig&&this.reticle.matrix.premultiply(this.webxr.Rig.matrix)}}}else(I=this.sessionRoot)==null||I.onUpdate(this.webxr.Rig,A,null),this.reticle&&(this.reticle.visible=!1)}};let Rr=DQ;r(Rr,"tempWebXRObject");const ttA=new OA().identity().makeTranslation(0,0,0);class Sr{constructor(A,e){r(this,"used",!1);r(this,"inputSource");r(this,"object");r(this,"pointerId");r(this,"isDown");r(this,"isUp");r(this,"isPressed");r(this,"isClicked");r(this,"input");r(this,"event");this.event=e,this.input=A}use(){this.used=!0,this.pointerId!==void 0&&this.input.setPointerUsed(this.pointerId)}stopPropagation(){var A;(A=this.event)==null||A.stopImmediatePropagation()}Use(){this.use()}StopPropagation(){var A;(A=this.event)==null||A.stopImmediatePropagation()}}class bE extends MA{awake(){lI.createIfNoneExists(this.context)}onEnable(){var A;(A=lI.get(this.context))==null||A.register(this)}onDisable(){var A;(A=lI.get(this.context))==null||A.unregister(this)}performRaycast(A=null){return null}}class Hr extends bE{constructor(){super(...arguments);r(this,"targets",null);r(this,"raycastHits",[])}start(){this.targets=[this.gameObject]}performRaycast(e=null){return this.targets?(e??(e=new CC),e.targets=this.targets,e.results=this.raycastHits,this.context.physics.raycast(e)):null}}class aR extends Hr{}const Pc=rA("debugeventsystem");var SG=(i=>(i.BeforeHandleInput="BeforeHandleInput",i.AfterHandleInput="AfterHandleInput",i))(SG||{});const wC=class extends MA{constructor(){super();r(this,"raycaster",[]);r(this,"_selectStartFn");r(this,"_selectEndFn");r(this,"_selectUpdateFn");r(this,"_handleEventFn");r(this,"lastPointerEvent",null);r(this,"objectsHoveredThisFrame",[]);r(this,"objectsHoveredLastFrame",[]);r(this,"raisedPointerDownEvents",[]);r(this,"raisedPointerDownObjects",[]);r(this,"_didMove",!1);r(this,"_tempComponentsArray",[]);r(this,"_sortedHits",[]);r(this,"_sortingBuffer",[]);r(this,"_noDepthTestingResults",[]);r(this,"handleEventsArray",[]);r(this,"out",{});r(this,"currentActiveMeshUIComponents",[]);wC.systems.push(this)}static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,wC.systems.length<=0&&wC.systems.push(...eA.findObjectsOfType(wC,e)));for(const g of wC.systems)if(g.context===e)return;const t=new UA;eA.addNewComponent(t,wC),e.scene.add(t)}static get systems(){const e=pe.Current;return this._eventSystemMap.has(e)||this._eventSystemMap.set(e,[]),this._eventSystemMap.get(e)}static get(e){const t=this._eventSystemMap.get(e);return t&&t.length>0?t[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(e,t){ks.update(e,t)}static markUIDirty(e){ks.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.objectsHoveredThisFrame.length>0}onDestroy(){wC.systems.splice(wC.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!eA.findObjectOfType(bE,this.context)){const t=eA.addNewComponent(this.context.scene,Hr);this.raycaster.push(t),Xg()&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found",this)}}register(e){var t;e&&this.raycaster&&!this.raycaster.includes(e)&&((t=this.raycaster)==null||t.push(e))}unregister(e){var g,I;const t=(g=this.raycaster)==null?void 0:g.indexOf(e);t!==void 0&&t!==-1&&((I=this.raycaster)==null||I.splice(t,1))}onEnable(){const e=new Map;this._selectStartFn??(this._selectStartFn=(g,I)=>{if(!I.grab)return;ks.resetLastSelected();const o=new Sr(this.context.input);o.inputSource=g,o.isDown=g.selectionDown,o.isUp=g.selectionUp,o.isPressed=g.selectionPressed,o.isClicked=!1,e.set(g,I.grab),I.grab&&!this.handleEvents(I.grab,o)&&(I.grab=null)}),this._selectEndFn??(this._selectEndFn=(g,I)=>{var s;if(!I.grab)return;const o=new Sr(this.context.input);o.inputSource=g,o.isDown=g.selectionDown,o.isUp=g.selectionUp,o.isPressed=g.selectionPressed,o.isClicked=g.selectionClick,this.handleEvents(I.grab,o);const C=e.get(g);if(e.set(g,null),C)for(let n=0;n<this.raisedPointerDownEvents.length;n++){const a=this.raisedPointerDownEvents[n];this.raisedPointerDownObjects[n]===C&&a&&((s=a.onPointerUp)==null||s.call(a,o),this.raisedPointerDownEvents.splice(n,1),this.raisedPointerDownObjects.splice(n,1),n--)}});const t=new CC;this._selectUpdateFn??(this._selectUpdateFn=g=>{t.ray=g.getRay();const I=this.performRaycast(t);if(!I)return;const o=new Sr(this.context.input);o.inputSource=g,this.handleIntersections(I,o)}),ti.addEventListener(Ss.SelectStart,this._selectStartFn),ti.addEventListener(Ss.SelectEnd,this._selectEndFn),ti.addEventListener(Ss.Update,this._selectUpdateFn),this._handleEventFn??(this._handleEventFn=this.onHandleEvents.bind(this)),this.context.pre_update_callbacks.push(this._handleEventFn)}onDisable(){ti.removeEventListener(Ss.SelectStart,this._selectStartFn),ti.removeEventListener(Ss.SelectEnd,this._selectEndFn),ti.removeEventListener(Ss.Update,this._selectUpdateFn),this.context.pre_update_callbacks.splice(this.context.pre_update_callbacks.indexOf(this._handleEventFn),1)}onHandleEvents(){if(this.objectsHoveredThisFrame.length=0,this.resetMeshUIStates(),Se.IsInWebXR||this.context.input.isKeyPressed("AltLeft")||this.context.input.isKeyPressed("AltRight"))return;if(!this._didMove){const C=this.context.input.getPointerPositionRC(0);if(C&&C.x===0&&C.y===0)return;this._didMove=!0}let e=0;for(const C of this.context.input.foreachPointerId()){const s=this.context.input.getPointerDown(C),n=this.context.input.getPointerUp(C);if(s||n){e=C;break}}const t=this.context.input.getPointerEvent(e),g=new Sr(this.context.input,t);g.inputSource=this.context.input,g.pointerId=e,g.isClicked=this.context.input.getPointerClicked(e),g.isDown=this.context.input.getPointerDown(e),g.isUp=this.context.input.getPointerUp(e),g.isPressed=this.context.input.getPointerPressed(e),Pc&&g.isClicked&&console.log("CLICK",e);const I=this.performRaycast(null);if(!I)return;this.lastPointerEvent=g;const o={sender:this,args:g,hasActiveUI:this.currentActiveMeshUIComponents.length>0};Pc&&g.isClicked&&eg("EventSystem: "+g.pointerId+" - "+this.context.time.frame+" - Up:"+g.isUp+", Down:"+g.isDown),this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:o})),this.handleIntersections(I,g),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:o}))}onBeforeRender(){if(this.lastPointerEvent)this.lastPointerEvent.used=!1;else return;if(this.lastPointerEvent.isUp){for(const t of this.raisedPointerDownEvents)t.onPointerUp&&t.onPointerUp(this.lastPointerEvent);this.raisedPointerDownEvents.length=0,this.raisedPointerDownObjects.length=0}for(const t of this.objectsHoveredLastFrame)if(this.objectsHoveredThisFrame.indexOf(t)<0){this._tempComponentsArray.length=0;const g=eA.getComponentsInParent(t,MA,this._tempComponentsArray);this.lastPointerEvent.object=t;for(let I=0;I<g.length;I++){const o=g[I];if(!o.gameObject||o.destroyed)continue;const C=o;C.onPointerExit&&C.onPointerExit(this.lastPointerEvent)}}const e=this.objectsHoveredLastFrame;this.objectsHoveredLastFrame=this.objectsHoveredThisFrame,this.objectsHoveredThisFrame=e}performRaycast(e){if(!this.raycaster)return null;this._sortedHits.length=0;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;const g=t.performRaycast(e);g&&g.length>0&&this._sortedHits.push(...g)}return this._sortedHits.sort((t,g)=>t.distance-g.distance),this._sortedHits}handleIntersections(e,t){if(!e||e.length<=0)return!1;e=this.sortCandidates(e);for(const g of e){const{object:I}=g;if(this.handleEvents(I,t))return!0}return!1}sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const g=e[t],I=g.object;if(I.material&&I.material.depthTest===!1){this._noDepthTestingResults.push(g);continue}this._sortingBuffer.push(g)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEvents(e,t){if(!this.testIsVisible(e))return t.isClicked&&Pc&&console.log("not allowed",e),!1;const g=e;t.object=e,this.lastPointerEvent=t;const I=e.parent;let o=!1;const C=t.isClicked??!1;let s=null;if(I&&I.isUI){const n=(t.isPressed||t.isClicked)??!1;if(I[Ns]){const a=I[Ns].gameObject;if(a){if(!zQ.isInteractable(a,this.out))return!1;s=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,n),e=a,o=!0}}if(!o&&this.handleMeshUiObjectWithoutShadowDom(I,n))return!0}if(C&&Pc&&console.log(this.context.time.frame,e),this.objectsHoveredThisFrame.push(e),s===null||s.interactable){const n=this.objectsHoveredLastFrame.indexOf(e)>=0;this.handleEventsArray.length=0;const a=eA.getComponentsInParent(e,MA,this.handleEventsArray);for(let B=0;B<a.length;B++){if(t.used)return!0;if(a[B].destroyed)continue;const Q=a[B];if(Q.interactable!==!1){if(Q.onPointerEnter&&(n||Q.onPointerEnter(t)),Q.onPointerMove&&Q.onPointerMove(t),t.isDown&&Q.onPointerDown&&!this.raisedPointerDownEvents.includes(Q)&&(Q.onPointerDown(t),this.raisedPointerDownEvents.push(Q),this.raisedPointerDownObjects.push(g)),t.isUp&&Q.onPointerUp){const E=this.raisedPointerDownEvents.indexOf(Q);E!==-1&&this.raisedPointerDownEvents.splice(E,1),Q.onPointerUp(t)}t.isClicked&&Q.onPointerClick&&Q.onPointerClick(t)}}}return!0}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}handleMeshUIIntersection(e,t){const g=ks.updateState(e,t);return g&&this.currentActiveMeshUIComponents.push(g),g!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&ks.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];ks.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?eA.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}};let lI=wC;r(lI,"_eventSystemMap",new Map),r(lI,"didSearchEventSystem",!1);class ks{static markDirty(){this.needsUpdate=!0}static update(A,e){const t=e.time.frameCount;for(const g of this.lastUpdateFrame)if(g.context===e){if(t===g.frame)return;g.frame=t;let I=this.needsUpdate||t<1;g.nextUpdate===e.time.frameCount&&(I=!0),I&&(Pc&&console.log("Update threemeshui"),this.needsUpdate=!1,A.update());return}this.lastUpdateFrame=[{context:e,frame:t,nextUpdate:t}],A.update()}static updateState(A,e){let t=null;if(A&&(t=this.findBlockInParent(A),t&&t!==this.lastSelected)){if(t.interactable===!1)return null;this.needsUpdate=!0}return t}static resetLastSelected(){const A=this.lastSelected;A&&(this.lastSelected=null,this.resetState(A))}static resetState(A){A&&(this.needsUpdate=!0)}static findBlockInParent(A){return A?A.isBlock?A:this.findBlockInParent(A.parent):null}}r(ks,"lastSelected",null),r(ks,"lastUpdateFrame",[]),r(ks,"needsUpdate",!1);const XD=Symbol("cameraController");function itA(i){return i[XD]}function yJ(i,A,e){e?i[XD]=A:i[XD]===A&&(i[XD]=null)}var gtA=Object.defineProperty,ItA=Object.getOwnPropertyDescriptor,otA=(i,A,e,t)=>{for(var g=t>1?void 0:t?ItA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&gtA(A,e,g),g};const AD=rA("freecam"),SJ=rA("debugcamerafit"),CtA={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let c0;class Bn extends MA{constructor(){super(...arguments);r(this,"autoRotate",!1);r(this,"autoRotateSpeed",1);r(this,"enableKeys",!0);r(this,"enableDamping",!0);r(this,"dampingFactor",.1);r(this,"enableZoom",!0);r(this,"minZoom",0);r(this,"maxZoom",1/0);r(this,"enablePan",!0);r(this,"lookAtConstraint",null);r(this,"lookAtConstraint01",1);r(this,"middleClickToFocus",!0);r(this,"doubleClickToFocus",!0);r(this,"useSlerp",!0);r(this,"debugLog",!1);r(this,"targetLerpSpeed",5);r(this,"_lookTargetPosition");r(this,"_controls",null);r(this,"_cameraObject",null);r(this,"_lerpToTargetPosition",!1);r(this,"_lerpCameraToTarget",!1);r(this,"_cameraTargetPosition",null);r(this,"_inputs",0);r(this,"_enableTime",0);r(this,"_startedListeningToKeyEvents",!1);r(this,"_eventSystem");r(this,"_afterHandleInputFn");r(this,"_camera",null);r(this,"_syncedTransform");r(this,"targetElement",null);r(this,"_shouldDisable",!1);r(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){var t;(t=this.controls)==null||t.addEventListener("start",e)}awake(){this._lookTargetPosition=new k,this._startedListeningToKeyEvents=!1}start(){if(this._controls){const e=eA.getComponent(this.gameObject,Yt);if(e&&!this.setFromTargetPosition()){this.debugLog&&console.log("NO TARGET");const g=ye(e.cam).length(),I=new k(0,0,-g).applyMatrix4(e.cam.matrixWorld);this.setTarget(I,!0)}}this.startCoroutine(this.startRaycastDelayed()),this._eventSystem=lI.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(SG.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var e,t;(e=this._controls)==null||e.dispose(),(t=this._eventSystem)==null||t.removeEventListener(SG.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._enableTime=this.context.time.time;const e=eA.getComponent(this.gameObject,Yt);this._camera=e;const t=e==null?void 0:e.cam;if(t&&yJ(t,this,!0),!this._controls){console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t);const g=this.targetElement??this.context.domElement;this._controls=new a6(t,g),c0===void 0&&(c0={...this._controls.keys})}this._controls&&(AD&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,Wr()&&(this.doubleClickToFocus=!0)),this._controls.enableDamping=this.enableDamping,this._controls.keys=this.enableKeys?c0:CtA,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.addEventListener("start",this.onControlsChangeStarted.bind(this)),(t==null?void 0:t.type)==="PerspectiveCamera"?AD||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):AD||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body))),this._syncedTransform=eA.getComponent(this.gameObject,da)??void 0}onDisable(){var e;(e=this._camera)!=null&&e.cam&&yJ(this._camera.cam,this,!1),this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1)}onControlsChangeStarted(){this._syncedTransform&&this._syncedTransform.requestOwnership()}afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}*startRaycastDelayed(){if(yield,!this.setFromTargetPosition()){const e=new CC;e.screenPoint=new j(0,0),e.lineThreshold=.1;const t=this.context.physics.raycast(e);t.length>0&&this.setTarget(t[0].point,!0)}}onBeforeRender(){var t,g,I;if(!this._controls||this._cameraObject!==this.context.mainCamera)return;(this.context.input.getPointerDown(0)||this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2))&&(this._inputs+=1),this._inputs>0&&(this.autoRotate=!1,this._controls.autoRotate=!1,this._lerpCameraToTarget=!1,this._lerpToTargetPosition=!1),this._inputs=0;let e=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(e||(e=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3),e?this.setTargetFromRaycast():(this.context.input.getPointerDown(0)||this.context.input.mouseWheelChanged)&&(this._lerpToTargetPosition=!1,this._lerpCameraToTarget=!1),this._lerpToTargetPosition||this._lerpCameraToTarget){const o=this.context.time.deltaTime*this.targetLerpSpeed;if(this._lerpCameraToTarget&&this._cameraTargetPosition&&this._cameraObject){if(this.useSlerp){const C=(t=this._cameraObject)==null?void 0:t.position;YL(C,this._cameraTargetPosition,o)}else(g=this._cameraObject)==null||g.position.lerp(this._cameraTargetPosition,o);this._cameraObject.position.distanceTo(this._cameraTargetPosition)<1e-4&&(this._lerpCameraToTarget=!1)}this._lerpToTargetPosition&&(this.lerpTarget(this._lookTargetPosition,o),this._lookTargetPosition.distanceTo(this._controls.target)<1e-5&&(this._lerpToTargetPosition=!1))}!AD&&((I=this.lookAtConstraint)!=null&&I.locked)&&this.setFromTargetPosition(0,this.lookAtConstraint01),this._controls&&!this.context.isInXR&&(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent,this._controls.update())}setCameraTarget(e,t=!1){var g;e?(this._lerpCameraToTarget=!0,this._cameraTargetPosition=e.clone(),t&&this._cameraTargetPosition&&((g=this.controllerObject)==null||g.position.copy(this._cameraTargetPosition))):this._lerpCameraToTarget=!1}setFromTargetPosition(e=0,t=1){var I;if(!this._controls)return!1;const g=(I=this.lookAtConstraint)==null?void 0:I.sources;if(g&&g.length>0){const o=g[e];if(o)return o.getWorldPosition(this._lookTargetPosition),this.lerpTarget(this._lookTargetPosition,t),!0}return!1}setTarget(e=null,t=!1){this._controls&&(e!==null&&this._lookTargetPosition.copy(e),t?this._controls.target.copy(this._lookTargetPosition):this._lerpToTargetPosition=!0)}lerpTarget(e,t){this._controls&&this._controls.target.lerp(e,t)}distanceToTarget(e){return this._controls?this._controls.target.distanceTo(e):-1}setTargetFromRaycast(){var t,g;if(!this.controls)return;const e=this.context.physics.raycast();for(const I of e)if(I.distance>0&&eA.isActiveInHierarchy(I.object)){if(this._lookTargetPosition.copy(I.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;const o=ye(this.context.mainCamera);this._cameraTargetPosition=o.clone().sub(this.controls.target).add(this._lookTargetPosition),(g=(t=this._cameraObject)==null?void 0:t.parent)==null||g.worldToLocal(this._cameraTargetPosition)}break}}fitCamera(e,t=1.1){const g=this._cameraObject,I=this._controls;if(e!=null&&e.length||(e=this.context.scene.children),!g||!I)return;const o=new k,C=new k,s=new mg;s.makeEmpty();for(const l of e)l instanceof Uk||s.expandByObject(l,!0);g.updateMatrixWorld(),g.updateProjectionMatrix(),s.getCenter(C),s.applyMatrix4(g.matrixWorldInverse),s.getSize(o),s.setFromCenterAndSize(C,o);const n=g.fov,a=2*Math.atan(Math.tan(n*Math.PI/360/2)*g.aspect)/Math.PI*360,B=o.y/(2*Math.atan(Math.PI*n/360)),Q=o.x/(2*Math.atan(Math.PI*a/360)),E=t*Math.max(B,Q)+o.z/2;SJ&&console.log("Fit camera to objects",B,Q,"distance",E);const c=ye(g),h=I.target.clone().sub(c).normalize().multiplyScalar(E);if(I.maxDistance=E*10,I.minDistance=E*.01,I.target.copy(C),g.near=E/100,g.far=E*100,g.updateMatrixWorld(),g.updateProjectionMatrix(),hi(g,I.target.clone().sub(h)),SJ){const l=new Uk(s);this.context.scene.add(l),OL(l,Aw(g)),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",d=>{d.code==="KeyF"&&this.fitCamera(e)}))}I.update()}}otA([w(sd)],Bn.prototype,"lookAtConstraint",2);var stA=Object.defineProperty,ntA=Object.getOwnPropertyDescriptor,mo=(i,A,e,t)=>{for(var g=t>1?void 0:t?ntA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&stA(A,e,g),g},ZH=(i=>(i[i.Skybox=1]="Skybox",i[i.SolidColor=2]="SolidColor",i[i.Uninitialized=4]="Uninitialized",i))(ZH||{});const Wc=rA("debugcam"),kJ=rA("debugscreenpointtoray");var uD;const Vc=(uD=class extends MA{constructor(){super(...arguments);r(this,"_nearClipPlane",.1);r(this,"_farClipPlane",1e3);r(this,"orthographic",!1);r(this,"orthographicSize",5);r(this,"ARBackgroundAlpha",0);r(this,"_cullingMask",4294967295);r(this,"_backgroundBlurriness");r(this,"_backgroundIntensity");r(this,"_targetTexture",null);r(this,"_backgroundColor");r(this,"_fov");r(this,"_cam",null);r(this,"_clearFlags",2);r(this,"_skybox")}get isCamera(){return!0}get aspect(){return this._cam instanceof it?this._cam.aspect:this.context.domWidth/this.context.domHeight}get fieldOfView(){return this._cam instanceof it?this._cam.fov:this._fov}set fieldOfView(A){const e=this._fov!=A;if(this._fov=A,e&&this._cam&&this._cam instanceof it){if(this._fov===void 0){console.error("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(A){const e=this._nearClipPlane!=A;this._nearClipPlane=A,this._cam&&e&&(this._cam.near=A,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(A){const e=this._farClipPlane!=A;this._farClipPlane=A,this._cam&&e&&(this._cam.far=A,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(A){A!==this._clearFlags&&(this._clearFlags=A,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(A){this._cullingMask=A,this._cam&&(this._cam.layers.mask=A)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set backgroundBlurriness(A){A!==this._backgroundBlurriness&&(A===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(A,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(A){A!==this._backgroundIntensity&&(A===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(A,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(A){if(A){if(this._backgroundColor)this._backgroundColor.copy(A);else{if(!A.clone)return;this._backgroundColor=A.clone()}A.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(A){this._targetTexture=A}get targetTexture(){return this._targetTexture}get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(A,e,t){let g=this.cam;const I=Vc._origin;I.set(A,e,-1),this.context.input.convertScreenspaceToRaycastSpace(I),kJ&&console.log("screenPointToRay",A.toFixed(2),e.toFixed(2),"now:",I.x.toFixed(2),I.y.toFixed(2),"isInXR:"+this.context.isInXR),I.z=-1,I.unproject(g);const o=Vc._direction.set(I.x,I.y,I.z),C=ye(g);return o.sub(C),o.normalize(),t?(t.set(C,o),t):new on(C.clone(),o.clone())}awake(){this.sourceId||console.warn("Camera has no source - the camera should be exported inside a gltf",this.name),kJ&&window.addEventListener("pointerdown",A=>{const e=A.clientX,t=A.clientY;console.log("touch",e.toFixed(2),t.toFixed(2));const g=this.screenPointToRay(e,t),I="#"+Math.floor(Math.random()*16777215).toString(16);KC.DrawRay(g.origin,g.direction,I,10)})}onEnable(){Wc&&console.log(this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),rtA(this)),this.applyClearFlagsIfIsActiveCamera()}onDisable(){this.context.removeCamera(this)}onBeforeRender(){if(this._cam&&this._targetTexture){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const A=this.context.renderer;A&&this._targetTexture.render(this.context.scene,this._cam,A)}}buildCamera(){if(this._cam)return;const A=this.gameObject.isCamera;let e=null;if(A?(e=this.gameObject,e==null||e.layers.enableAll(),e instanceof it&&(this._fov=e.fov)):e=this.gameObject.children[0],e&&e.isCamera)e.type==="PerspectiveCamera"&&(this._fov&&(e.fov=this._fov),e.near=this._nearClipPlane,e.far=this._farClipPlane,e.updateProjectionMatrix());else if(!this.orthographic)e=new it(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(e.fov=this.fieldOfView),this.gameObject.add(e);else{const t=this.orthographicSize*100;e=new iE(window.innerWidth/-t,window.innerWidth/t,window.innerHeight/t,window.innerHeight/-t,this._nearClipPlane,this._farClipPlane),this.gameObject.add(e)}this._cam=e,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){this.context.mainCameraComponent===this&&this.applyClearFlags()}applyClearFlags(){if(!this._cam){Wc&&console.log("Camera does not exist (apply clear flags)");return}switch(Wc&&eg("apply Camera clear flags: "+this._clearFlags),this._clearFlags){case 1:if(Vc.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}this.enableSkybox(),this._backgroundBlurriness!==void 0&&(this.context.scene.backgroundBlurriness=this._backgroundBlurriness),this._backgroundIntensity!==void 0&&(this.context.scene.backgroundIntensity=this._backgroundIntensity);break;case 2:if(this._backgroundColor){let A=this._backgroundColor.alpha;Vc.backgroundShouldBeTransparent(this.context)&&(A=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,A)}break;case 4:this.context.scene.background=null,this.context.renderer.setClearColor(0,0);break}}enableSkybox(){this._skybox||(this._skybox=new atA(this)),this._skybox.enable()}static backgroundShouldBeTransparent(A){var I,o,C,s;const e=(I=A.renderer.xr)==null?void 0:I.getSession();if(!e)return!1;const t=e.environmentBlendMode;Wc&&eg("Environment blend mode: "+t+" on "+navigator.userAgent);const g=t==="additive"||t==="alpha-blend";if(A.xrSessionMode===jh.ImmersiveAR&&t==="opaque"){if((o=navigator.userAgent)!=null&&o.includes("OculusBrowser"))return!0;if((C=navigator.userAgent)!=null&&C.includes("Mozilla")&&((s=navigator.userAgent)!=null&&s.includes("Mobile WebXRViewer/v2")))return!0}return g}},r(uD,"_origin",new k),r(uD,"_direction",new k),uD);let Yt=Vc;mo([w()],Yt.prototype,"fieldOfView",1);mo([w()],Yt.prototype,"nearClipPlane",1);mo([w()],Yt.prototype,"farClipPlane",1);mo([w()],Yt.prototype,"clearFlags",1);mo([w()],Yt.prototype,"orthographic",2);mo([w()],Yt.prototype,"orthographicSize",2);mo([w()],Yt.prototype,"ARBackgroundAlpha",2);mo([w()],Yt.prototype,"cullingMask",1);mo([w()],Yt.prototype,"backgroundBlurriness",1);mo([w()],Yt.prototype,"backgroundIntensity",1);mo([w(Gt)],Yt.prototype,"backgroundColor",1);mo([w(ra)],Yt.prototype,"targetTexture",1);class atA{constructor(A){r(this,"_camera");r(this,"_skybox");this._camera=A}get context(){var A;return(A=this._camera)==null?void 0:A.context}enable(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?this.context.scene.background!==this._skybox&&(Wc&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=De,this._skybox.mapping=Do,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this._camera.sourceId,this.context.lightmaps)}}function rtA(i){rA("freecam")&&i.context.mainCameraComponent===i&&eA.getOrAddComponent(i.gameObject,Bn)}class ZQ extends MA{constructor(){super(...arguments);r(this,"_listener",null)}get listener(){return this._listener==null&&(this._listener=new FM),this._listener}awake(){Fi.registerWaitForAllowAudio(()=>{if(this.destroyed)return;const e=this.listener;if(e==null||e.parent)return;const t=eA.getComponentInParent(this.gameObject,Yt);t?t.cam.add(e):this.gameObject.add(e)})}}var BtA=Object.defineProperty,QtA=Object.getOwnPropertyDescriptor,Yw=(i,A,e,t)=>{for(var g=t>1?void 0:t?QtA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&BtA(A,e,g),g};class cd{constructor(){r(this,"guid")}}Yw([w()],cd.prototype,"guid",2);class LE{constructor(){r(this,"signal");r(this,"reaction")}}Yw([w(cd)],LE.prototype,"signal",2);Yw([w(DI)],LE.prototype,"reaction",2);var _0;const Ds=(_0=class extends MA{constructor(){super(...arguments);r(this,"events")}static invoke(A){if(Ds.receivers[A]){const e=Ds.receivers[A];if(!e)return;for(const t of e)t.invoke(A)}}onEnable(){if(this.events)for(const A of this.events)Ds.receivers[A.signal.guid]||(Ds.receivers[A.signal.guid]=[]),Ds.receivers[A.signal.guid].push(this)}onDisable(){if(this.events){for(const A of this.events)if(Ds.receivers[A.signal.guid]){const e=Ds.receivers[A.signal.guid].indexOf(this);e>=0&&Ds.receivers[A.signal.guid].splice(e,1)}}}invoke(A){if(!this.events||!Array.isArray(this.events))return;let e=typeof A=="object"?A.guid:A;for(const t of this.events)if(t.signal.guid===e)try{if(t.reaction){if(!t.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",t,this);continue}}else{console.warn("Missing reaction for signal",t,this);continue}t.reaction.invoke()}catch(g){console.error(g)}}},r(_0,"receivers",{}),_0);let vE=Ds;Yw([w(LE)],vE.prototype,"events",2);var RI=(i=>(i.Activation="ActivationTrack",i.Animation="AnimationTrack",i.Audio="AudioTrack",i.Control="ControlTrack",i.Marker="MarkerTrack",i.Signal="SignalTrack",i))(RI||{}),On=(i=>(i[i.None=0]="None",i[i.Hold=1]="Hold",i[i.Loop=2]="Loop",i[i.PingPong=3]="PingPong",i[i.Continue=4]="Continue",i))(On||{}),rR=(i=>(i.Signal="SignalEmitter",i))(rR||{});const mc=rA("debugtimeline"),wf=class extends MA{constructor(){super(...arguments);r(this,"playableAsset");r(this,"playOnAwake");r(this,"extrapolationMode",1);r(this,"waitForAudio",!0);r(this,"_visibilityChangeEvt");r(this,"_clonedPlayableAsset",!1);r(this,"_speed",1);r(this,"_guidsMap");r(this,"_isPlaying",!1);r(this,"_internalUpdateRoutine");r(this,"_isPaused",!1);r(this,"_time",0);r(this,"_duration",0);r(this,"_weight",1);r(this,"_animationTracks",[]);r(this,"_audioTracks",[]);r(this,"_signalTracks",[]);r(this,"_controlTracks",[]);r(this,"_customTracks",[]);r(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks])}static registerCreateTrack(e,t){this.createTrackFunctions[e]=t}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(e){typeof e=="number"&&!Number.isNaN(e)?this._time=e:(mc||zg())&&console.error("INVALID TIMELINE.TIME VALUE",e,this.name)}get duration(){return this._duration}set duration(e){this._duration=e}get weight(){return this._weight}set weight(e){this._weight=e}get speed(){return this._speed}set speed(e){this._speed=e}awake(){var e,t,g;mc&&console.log(this,(e=this.playableAsset)==null?void 0:e.tracks),this.rebuildGraph(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,(t=this.playableAsset)==null?void 0:t.tracks,Array.isArray((g=this.playableAsset)==null?void 0:g.tracks),this)}onEnable(){var e,t;for(const g of this._audioTracks)(e=g.onEnable)==null||e.call(g);for(const g of this._customTracks)(t=g.onEnable)==null||t.call(g);this.playOnAwake&&this.play(),this._visibilityChangeEvt||(this._visibilityChangeEvt=()=>{switch(document.visibilityState){case"hidden":this.setAudioTracksAllowPlaying(!1);break;case"visible":this.setAudioTracksAllowPlaying(!0);break}}),window.addEventListener("visibilitychange",this._visibilityChangeEvt)}onDisable(){var e,t;this.stop();for(const g of this._audioTracks)(e=g.onDisable)==null||e.call(g);for(const g of this._customTracks)(t=g.onDisable)==null||t.call(g);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var e;for(const t of this._allTracks)for(const g of t)(e=g.onDestroy)==null||e.call(g)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const e=this._isPaused==!0;if(this._isPaused=!1,e&&this.invokePauseChangedMethodsOnTracks(),!this._isPlaying){if(this._isPlaying=!0,this.waitForAudio){const t=[];for(const g of this._audioTracks){const I=g.loadAudio(this._time,1,0);I&&t.push(I)}if(t.length>0&&(await Promise.all(t),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!Fi.userInteractionRegistered&&this.waitForAudio;)await Gl(200)}this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate())}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.evaluate(),this.invokePauseChangedMethodsOnTracks()))}stop(){for(const g of this._audioTracks)g.stop();const e=this._isPaused==!0,t=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.evaluate(),e&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,e&&!t&&this.invokePauseChangedMethodsOnTracks(),this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null}evaluate(){if(!this.isValid())return;let e=this._time;switch(this.extrapolationMode){case 0:this._speed>0?e=Math.min(e,this._duration):this._speed<0&&(e=Math.max(e,0)),this._time=e;break;case 1:e%=this._duration,this._time=e;break;case 2:if(e>this._duration){this.stop();return}break}this.internalEvaluate(e)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(const e of this._allTracks)for(const t of e)yield t}get audioTracks(){return this._audioTracks}resolveGuids(e){this._guidsMap=e}invokePauseChangedMethodsOnTracks(){var e;for(const t of this.forEachTrack())(e=t.onPauseChanged)==null||e.call(t)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.evaluate()),yield}internalEvaluate(e){for(const t of this.playableAsset.tracks)if(!t.muted)switch(t.type){case RI.Activation:for(let g=0;g<t.outputs.length;g++){const I=t.outputs[g];if(typeof I=="object"){let o=!1;for(const s of t.clips)s.start<=e&&e<=s.end&&(o=!0);const C=I;C.visible!==void 0&&(C.visible=o)}}break}for(const t of this._animationTracks)t.evaluate(e);for(const t of this._audioTracks)t.evaluate(e);for(const t of this._signalTracks)t.evaluate(e);for(const t of this._controlTracks)t.evaluate(e);for(const t of this._customTracks)t.evaluate(e)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Sf(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const e=this.findRoot(this.gameObject);for(const t of this.playableAsset.tracks){for(let g=t.outputs.length-1;g>=0;g--){let I=t.outputs[g];if(typeof I=="string"){this._guidsMap&&this._guidsMap[I]&&(I=this._guidsMap[I]);const o=eA.findByGuid(I,e);o===null||typeof o!="object"?(t.outputs.splice(g,1),console.warn("Failed to resolve binding",I,t.name,t.type)):(mc&&console.log("Resolved binding",I,"to",o),t.outputs[g]=o)}else if(I===null){if(t.outputs.splice(g,1),wf.createTrackFunctions[t.type])continue;t.type!==RI.Audio&&t.type!==RI.Control&&t.type!==RI.Marker&&t.type!==RI.Signal&&console.warn("Missing binding",I,t.name,t.type,this.name,this.playableAsset.name)}}if(t.type===RI.Control)for(let g=0;g<t.clips.length;g++){const I=t.clips[g];let o=I.asset.sourceObject;if(typeof o=="string"){this._guidsMap&&this._guidsMap[o]&&(o=this._guidsMap[o]);const C=eA.findByGuid(o,e);C===null||typeof C!="object"?console.warn("Failed to resolve sourceObject binding",o,t.name,I):(mc&&console.log("Resolved binding",o,"to",C),I.asset.sourceObject=C)}}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const e of this.playableAsset.tracks)if(e.muted!==!0){for(const t of e.clips)t.end>this._duration&&(this._duration=t.end);for(const t of e.markers)t.time>this._duration&&(this._duration=t.time+.001)}}}setupAndCreateTrackHandlers(){var t,g;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;const e=eA.findObjectOfType(ZQ,this.context);for(const I of this.playableAsset.tracks){const o=I.type,C=wf.createTrackFunctions[o];if(C!=null){const s=C(this,I);if(typeof s.evaluate=="function"){s.director=this,s.track=I,this._customTracks.push(s);continue}}if(I.type===RI.Animation){if(I.clips.length<=0){mc&&console.warn("Animation track has no clips",I);continue}for(let s=I.outputs.length-1;s>=0;s--){let n=I.outputs[s];if(n instanceof UA){const B=eA.getOrAddComponent(n,wI);B&&(n=B)}const a=(t=n==null?void 0:n.gameObject)==null?void 0:t.animations;if(a){const B=new Tw;B.trackOffset=I.trackOffset,B.director=this,B.track=I;for(let Q=0;Q<I.clips.length;Q++){const E=I.clips[Q],c=E.asset;if(!c){console.error("MISSING anim model?","clip#"+Q,E,I,this.playableAsset,this.name);continue}const h=c.clip;let l=h;if((typeof l=="string"||typeof l=="number")&&(l=a.find(p=>p.name===h)),!l){console.warn("Could not find animationClip for model",E,I.name,this.name,(g=this.playableAsset)==null?void 0:g.name);continue}B.mixer||(B.mixer=new Xf(n.gameObject)),B.clips.push(l),B.mixer.uncacheAction(l),B.createHooks(E.asset,l);const d=B.mixer.clipAction(l);B.actions.push(d),B.models.push(E)}this._animationTracks.push(B)}}}else if(I.type===RI.Audio){if(I.clips.length<=0)continue;const s=new Nr;if(s.director=this,s.track=I,this._audioTracks.push(s),!e)continue;s.listener=e.listener;for(let n=0;n<I.clips.length;n++){const a=I.clips[n];s.addModel(a)}}else if(I.type===RI.Marker){const s=new rl;s.director=this,s.track=I;for(const n of I.markers)switch(n.type){case rR.Signal:s.models.push(n),s.didTrigger.push(!1);break}if(s!==null&&s.models.length>0){const n=eA.getComponent(this.gameObject,vE);n&&(s.receivers.push(n),this._signalTracks.push(s))}}else if(I.type===RI.Signal){const s=new rl;s.director=this,s.track=I;for(const n of I.markers)s.models.push(n),s.didTrigger.push(!1);for(const n of I.outputs)s.receivers.push(n);this._signalTracks.push(s)}else if(I.type===RI.Control){const s=new Hw;s.director=this,s.track=I;for(const n of I.clips)s.models.push(n);s.resolveSourceObjects(this.context),this._controlTracks.push(s)}}}setAudioTracksAllowPlaying(e){for(const t of this._audioTracks)t.onAllowAudioChanged(e)}};let Ur=wf;r(Ur,"createTrackFunctions",{});const Fr=rA("debugtimeline");class hd{constructor(){r(this,"director");r(this,"track")}get muted(){return this.track.muted}set muted(A){var e;A!==this.track.muted&&(this.track.muted=A,(e=this.onMuteChanged)==null||e.call(this))}*forEachClip(A=!1){var e;if((e=this.track)!=null&&e.clips)if(A)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(const t of this.track.clips)yield t}getClipTime(A,e){return e.clipIn+(A-e.start)*e.timeScale}getClipTimeNormalized(A,e){return(A-e.start)/e.duration}evaluateWeight(A,e,t,g=!0){if(e<0||e>=t.length)return 0;const I=t[e];if(g||A>=I.start&&A<=I.end){let o=1,C=!1;if(I.easeInDuration>0){const s=Math.min((A-I.start)/I.easeInDuration,1);o*=s}if(I.easeOutDuration>0&&!C){const s=Math.min((I.end-A)/I.easeOutDuration,1);o*=s}return o}return 0}}class EtA{constructor(A){r(this,"clip");r(this,"rootPositionOffset");r(this,"rootQuaternionOffset");r(this,"rootStartPosition");r(this,"rootEndPosition");r(this,"rootStartQuaternion");r(this,"rootEndQuaternion");const e=A.getClip();this.clip=e;const t=A.getRoot(),g=t.name+".position",I=t.name+".quaternion";Fr&&console.log(e.name,e.tracks,g);for(const o of e.tracks)if(!(o.times.length<=0)){if(o.name.endsWith(g))this.rootStartPosition=new k().fromArray(o.values,0),this.rootEndPosition=new k().fromArray(o.values,o.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),Fr&&console.log(this.rootPositionOffset);else if(o.name.endsWith(I)&&(this.rootStartQuaternion=new kA().fromArray(o.values,0),this.rootEndQuaternion=new kA().fromArray(o.values,o.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),Fr)){const C=new Ui().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",C)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class Tw extends hd{constructor(){super(...arguments);r(this,"models",[]);r(this,"trackOffset");r(this,"target");r(this,"mixer");r(this,"clips",[]);r(this,"actions",[]);r(this,"_actionOffsets",[]);r(this,"_didBind",!1);r(this,"_animator",null);r(this,"_animatorWasEnabled",!1);r(this,"_useclipOffsets",!0);r(this,"_totalOffsetPosition",new k);r(this,"_totalOffsetRotation",new kA);r(this,"_totalOffsetPosition2",new k);r(this,"_totalOffsetRotation2",new kA);r(this,"_summedPos",new k);r(this,"_tempPos",new k);r(this,"_summedRot",new kA);r(this,"_tempRot",new kA);r(this,"_clipRotQuat",new kA)}onPauseChanged(){this._animator&&this._animatorWasEnabled!==void 0&&(this._animator.enabled=this.director.isPlaying===!1?this._animatorWasEnabled:!1)}createHooks(e,t){var a,B;if(((a=t.tracks)==null?void 0:a.length)<=0){console.warn("No tracks in AnimationClip",t);return}const g=t.tracks[0].name.split("."),I=g[g.length-2],o=I+".position",C=I+".quaternion";let s=!1,n=!1;for(const Q of t.tracks)Q.name.endsWith(o)?(s=!0,this.createPositionInterpolant(t,e,Q)):Q.name.endsWith(C)&&(n=!0,this.createRotationInterpolant(t,e,Q));if(!s||!n){const Q=(B=this.mixer)==null?void 0:B.getRoot(),E=t.tracks[0],c=E.name.lastIndexOf("."),h=E.name.substring(0,c),l=h.substring(h.lastIndexOf(".")+1),d=Q.getObjectByName(l);if(d)if(s){if(!n){const p=t.tracks[0].name.substring(0,c)+".quaternion";Fr&&console.warn("Create quaternion track",l,d);const u=d.quaternion,D=new jC(p,[0,t.duration],[u.x,u.y,u.z,u.w,u.x,u.y,u.z,u.w]);t.tracks.push(D),this.createRotationInterpolant(t,e,D)}}else{const p=h+".position";Fr&&console.warn("Create position track",l,d);const u=d.position,D=new la(p,[0,t.duration],[u.x,u.y,u.z,u.x,u.y,u.z]);t.tracks.push(D),this.createPositionInterpolant(t,e,D)}}}bind(){if(!this._didBind){this._didBind=!0,Fr&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const e of this.actions){const t=new EtA(e);this._actionOffsets.push(t)}this.target&&(this._animator=eA.getComponent(this.target,wI)??null,this._animator?(this._animatorWasEnabled=this._animator.enabled,this._animator.enabled=!1):this._animatorWasEnabled=!1);for(const e of this.models){const t=e.asset,g=t.position,I=t.rotation;g&&g.x!==void 0&&(g.isVector3||(t.position=new k(g.x,g.y,g.z)),I.isQuaternion||(t.rotation=new kA(I.x,I.y,I.z,I.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new k(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new kA(t.x,t.y,t.z,t.w)))}}evaluate(e){if(this.track.muted||!this.mixer)return;this.bind(),this._animator&&this.director.isPlaying&&this.director.weight>0&&(this._animator.enabled=!1),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let t=0,g=0,I=!1,o=!1;for(let C=0;C<this.clips.length;C++){const s=this.models[C],n=this.actions[C],a=s.asset;n.weight=0;const B=e>=s.start&&e<=s.end,Q=s.preExtrapolationMode,E=s.postExtrapolationMode,c=C<this.clips.length-1?this.models[C+1]:null;let h=B,l=!1;if(!h&&!I&&s.end<e&&E!==On.None?(!c||c.start>e)&&(h=!0,I=!0):C==0&&!h&&!o&&s.start>e&&Q!==On.None&&(!c||c.start<e)&&(h=!0,l=!0,o=!0),h){let d=1;d*=this.evaluateWeight(e,C,this.models,h),d*=this.director.weight;let p=B;l&&Q!==On.Hold&&(e+=s.start,p=!0);let u=this.getClipTime(e,s),D=0;const y=a.duration;if(l&&Q===On.Hold&&(u=0),p){if(a.loop)for(D+=Math.floor(u/(y+1e-6));u>y;)u-=y}else if(!B)switch(E){case On.Loop:u%=y;break;case On.PingPong:const f=Math.floor(u/y)%2!==0;u%=y,f&&(u=y-u);break}s.reversed===!0?n.time=n.getClip().duration-u:n.time=u,n.timeScale=0;const S=d;if(n.weight=S,n.clampWhenFinished=!0,n.isRunning()||n.play(),this._useclipOffsets){const R=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,f=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(g=1-d),t+=1;const M=this._summedPos.set(0,0,0),U=this._tempPos.set(0,0,0),J=this._summedRot.identity(),T=this._tempRot.identity(),Y=a.rotation;Y&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(Y,d));const b=this._actionOffsets[C];if(b.hasOffsets)for(let _=0;_<D;_++)b.rootPositionOffset?U.copy(b.rootPositionOffset):U.set(0,0,0),U.applyQuaternion(J),this._clipRotQuat&&U.applyQuaternion(this._clipRotQuat),b.rootQuaternionOffset&&(T.copy(b.rootQuaternionOffset),J.multiply(T)),M.add(U);this._clipRotQuat&&f.multiply(this._clipRotQuat),f.multiply(J),a.position&&M.add(a.position),R.add(M)}}}this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,g),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,g)),this.mixer.update(e)}createRotationInterpolant(e,t,g){var s;const I=g.createInterpolant.bind(g),o=new kA;this.ensureTrackOffsets();const C=(s=this.trackOffset)==null?void 0:s.rotation;g.createInterpolant=()=>{const n=I(),a=n.evaluate.bind(n);return n.evaluate=B=>{const Q=a(B);return o.set(Q[0],Q[1],Q[2],Q[3]),o.premultiply(this._totalOffsetRotation),C&&o.premultiply(C),Q[0]=o.x,Q[1]=o.y,Q[2]=o.z,Q[3]=o.w,Q},n}}createPositionInterpolant(e,t,g){var a,B;const I=g.createInterpolant.bind(g),o=new k;this.ensureTrackOffsets();const C=(a=this.trackOffset)==null?void 0:a.rotation,s=(B=this.trackOffset)==null?void 0:B.position;let n;g.createInterpolant=()=>{const Q=I(),E=Q.evaluate.bind(Q);return Q.evaluate=c=>{var l,d;const h=E(c);return o.set(h[0],h[1],h[2]),t.removeStartOffset&&(n===void 0?(n=null,n=(d=(l=this._actionOffsets.find(p=>p.clip===e))==null?void 0:l.rootStartPosition)==null?void 0:d.clone()):n!=null&&n.isVector3&&o.sub(n)),o.applyQuaternion(this._totalOffsetRotation),o.add(this._totalOffsetPosition),C&&o.applyQuaternion(C),s&&(o.x-=s.x,o.y+=s.y,o.z+=s.z),h[0]=o.x,h[1]=o.y,h[2]=o.z,h},Q}}}const ctA=rA("mutetimeline"),pQ=class extends hd{constructor(){super(...arguments);r(this,"models",[]);r(this,"listener");r(this,"audio",[]);r(this,"audioContextTimeOffset",[]);r(this,"lastTime",0);r(this,"_audioLoader",null)}getAudioFilePath(e){const t=this.director.sourceId;return wa(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){const g=this.models[t];this.audio[t].setVolume(e?g.asset.volume:0)}}addModel(e){const t=new Zf(this.listener);this.audio.push(t),this.models.push(e)}onDisable(){for(const e of this.audio)e.isPlaying&&e.stop()}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}}stop(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}}evaluate(e){if(ctA||this.track.muted||this.director.speed<0)return;const t=this.director.context.application.muted,g=t?.1:0;for(let I=0;I<this.models.length;I++){const o=this.models[I],C=this.audio[I];if((!C||!C.buffer)&&this.isInTimeRange(o,e-1,e+1)&&this.handleAudioLoading(o,C),Fi.userInteractionRegistered!==!1&&!(C===null||!C.buffer))if(C.playbackRate=this.director.context.time.timeScale,C.loop=o.asset.loop,e>=o.start&&e<=o.end&&e<this.director.duration){if(this.director.isPlaying==!1){if(C.isPlaying&&C.stop(),this.lastTime===e)continue}else if(!C.isPlaying)C.offset=o.clipIn+(e-o.start)*o.timeScale,C.play(g);else{const n=o.clipIn+(e-o.start)*o.timeScale,a=C.context.currentTime-C._startedAt+C.offset;Math.abs(n-a)>.3&&(C.offset=n,C.stop(),C.play(g))}let s=o.asset.volume;if(t&&(s=0),o.easeInDuration>0){const n=Math.min((e-o.start)/o.easeInDuration,1);s*=n}if(o.easeOutDuration>0){const n=Math.min((o.end-e)/o.easeOutDuration,1);s*=n}C.setVolume(s*this.director.weight)}else C.isPlaying&&C.stop()}this.lastTime=e}loadAudio(e,t=0,g=0){let I=null;const o=e-g,C=e+t;for(const s of this.models)if(this.isInTimeRange(s,o,C)){const n=this.audio[this.models.indexOf(s)],a=this.handleAudioLoading(s,n);a!==null&&(I===null&&(I=[]),I.push(a))}return I!==null?Promise.all(I):null}isInTimeRange(e,t,g){return t<=e.start&&g>=e.end||t>=e.start&&t<=e.end||g>=e.start&&g<=e.end}static dispose(){pQ._currentlyLoading.clear()}handleAudioLoading(e,t){this._audioLoader||(this._audioLoader=new Sp);const g=this.getAudioFilePath(e.asset.clip);if(pQ._currentlyLoading.get(g)){const o=pQ._currentlyLoading.get(g);return o.then(C=>{C&&t.setBuffer(C)}),o}Fr&&console.warn("LOAD audio track",g,this.director.sourceId);const I=new Promise((o,C)=>{this._audioLoader.load(g,s=>{t.setBuffer(s),o(s)},void 0,s=>{console.error("Error loading audio",s),o(null)})});return pQ._currentlyLoading.set(g,I),I}};let Nr=pQ;r(Nr,"_currentlyLoading",new Map);class rl extends hd{constructor(){super(...arguments);r(this,"models",[]);r(this,"didTrigger",[]);r(this,"receivers",[])}evaluate(e){var t;if(!this.track.muted)for(let g=0;g<this.models.length;g++){const I=this.models[g],o=this.didTrigger[g],C=I.time-e;let s=!1;if(I.retroActive)s=C<=1e-6;else{const n=Math.abs(C);n>=1e-5&&n<.1&&(s=!0)}if(s){if(!o)if(this.didTrigger[g]=!0,((t=this.receivers)==null?void 0:t.length)<=0)vE.invoke(I.asset);else for(const n of this.receivers)n&&n.invoke(I.asset)}else I.emitOnce||(this.didTrigger[g]=!1)}}}class Hw extends hd{constructor(){super(...arguments);r(this,"models",[]);r(this,"timelines",[]);r(this,"_previousActiveModel",null)}resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const I=this.models[t].asset;if(!I.sourceObject||typeof I.sourceObject!="object"){console.log("no source object, removing model",t,I),this.models.splice(t,1);continue}else{const o=eA.getComponent(I.sourceObject,Ur);this.timelines.push(o),o&&I.updateDirector&&(o.playOnAwake=!1)}}}evaluate(e){var t;this._previousActiveModel=null;for(let g=0;g<this.models.length;g++){const I=this.models[g],o=I.asset;if(e>=I.start&&e<=I.end){this._previousActiveModel=I;const C=this.getClipTime(e,I);if(o.controlActivation){const s=o.sourceObject;s.visible=!0}if(o.updateDirector){const s=this.timelines[g];s&&(s.isPlaying&&s.pause(),s.time=C,s.evaluate())}}else{const C=(t=this._previousActiveModel)==null?void 0:t.asset;if(o.controlActivation){const s=o.sourceObject;(C==null?void 0:C.sourceObject)!==s&&(s.visible=!1)}}}}}var htA=Object.defineProperty,ltA=Object.getOwnPropertyDescriptor,XH=(i,A,e,t)=>{for(var g=t>1?void 0:t?ltA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&htA(A,e,g),g};class ve{constructor(A){r(this,"_active",!0);r(this,"_value");r(this,"_valueRaw");r(this,"_defaultValue");r(this,"valueProcessor");r(this,"onValueChanged");this._value=A,this._defaultValue=A}get overrideState(){return this._active}set overrideState(A){if(this._active===A)return;this._active=A;const e=A?this._valueRaw:this._defaultValue;this.processValue(e,!0)}get value(){return this._valueRaw}set value(A){this.processValue(A,!1)}set defaultValue(A){this._defaultValue=A}__init(){this.processValue(this._valueRaw,!0)}processValue(A,e){if(A==null||!e&&this.testIfValueChanged(A)===!1)return;const t=this._value;!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,A=this._defaultValue,this._valueRaw=A):(this._valueRaw=A,this._active&&this.valueProcessor&&(A=this.valueProcessor(A)),this._value=A),this.onValueChanged&&this.onValueChanged(A,t,this)}testIfValueChanged(A){return this._valueRaw!==A}}XH([w()],ve.prototype,"overrideState",1);XH([w()],ve.prototype,"value",1);var dtA=Object.defineProperty,utA=Object.getOwnPropertyDescriptor,DtA=(i,A,e,t)=>{for(var g=t>1?void 0:t?utA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&dtA(A,e,g),g};const ptA=rA("debugpost");class eI extends Ma{constructor(){super(...arguments);r(this,"active",!0);r(this,"_result")}onEnable(){this.__internalDidAwakeAndStart&&(this.active=!0)}onDisable(){this.active=!1}init(){}apply(){var e;return this._result||(this._result=(e=this.onCreateEffect)==null?void 0:e.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){ptA&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(e=>e.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const e=Object.keys(this);for(const t of e){const g=this[t];g instanceof ve&&g.__init()}}onAfterDeserialize(e,t){if(typeof e=="object"){const g=this.$serializedTypes;if(g){for(const I of Object.keys(g))if(g[I]===ve){const C=e[I];if(C!==void 0){const s=this[I];s.value=C}}}}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof ve){const g=e.value;return this[t].value=g,!0}}}DtA([w()],eI.prototype,"active",2);var ftA=Object.defineProperty,wtA=Object.getOwnPropertyDescriptor,ytA=(i,A,e,t)=>{for(var g=t>1?void 0:t?wtA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&ftA(A,e,g),g};const StA=rA("debugpost"),kG={};function $C(i,A){kG[i]=A}function ktA(i){return i.__type in kG?kG[i.__type]:(StA&&i.__type&&console.warn("Unknown postprocessing type",i.__type,i),eI)}class ld{constructor(){r(this,"components")}init(){var A;(A=this.components)==null||A.forEach(e=>e.init())}}ytA([DE([i=>ktA(i),eI])],ld.prototype,"components",2);var GtA=Object.defineProperty,MtA=Object.getOwnPropertyDescriptor,mtA=(i,A,e,t)=>{for(var g=t>1?void 0:t?MtA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&GtA(A,e,g),g};class dd extends eI{constructor(){super(...arguments);r(this,"preset")}get typeName(){return"Antialiasing"}onCreateEffect(){const e=new zZ({preset:ZB.HIGH,edgeDetectionMode:ZM.DEPTH});return this.preset.onValueChanged=t=>{e.applyPreset(t)},e}}mtA([w(ve)],dd.prototype,"preset",2);$C("Antialiasing",dd);class _w{constructor(){r(this,"files",[])}get extensionName(){return"Audio"}onExportObject(A,e,t){const g=eA.getComponents(A,Fi);if(g.length)for(const I of g){if(!I.playOnAwake)continue;const o=I.clip.split("/").pop();this.files.includes(I.clip)||this.files.push(I.clip),e.addEventListener("serialize",(C,s)=>{C.appendLine(),C.beginBlock(`def SpatialAudio "${e.name}"`),C.appendLine(`uniform asset filePath = @audio/${o}@`),C.appendLine(`uniform token auralMode = "${I.spatialBlend>0?"spatial":"nonSpatial"}"`),C.appendLine(`uniform token playbackMode = "${I.loop?"loopFromStage":"onceFromStart"}"`),C.appendLine(`uniform float gain = ${I.volume}`),C.closeBlock()})}}async onAfterSerialize(A){console.warn("onAfterSerialize",this);for(const e of this.files){const t=e.split("/").pop(),o=await(await(await fetch(e)).blob()).arrayBuffer(),C=new Uint8Array(o);A.files["audio/"+t]=C}}}var RtA=Object.defineProperty,UtA=Object.getOwnPropertyDescriptor,$H=(i,A,e,t)=>{for(var g=t>1?void 0:t?UtA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&RtA(A,e,g),g};const FtA=rA("debugmouth");class ud extends MA{constructor(){super(...arguments);r(this,"idle",[]);r(this,"talking",[]);r(this,"marker",null);r(this,"voip",null);r(this,"lastMouthChangeTime",0);r(this,"mouthChangeLength",0)}awake(){setTimeout(()=>{this.voip=eA.findObjectOfType(nn,this.context),this.marker||(this.marker=eA.getComponentInParent(this.gameObject,tg))},3e3)}update(){var g;if(!this.voip||this.context.time.frameCount%10!==0)return;let e=((g=this.marker)==null?void 0:g.connectionId)??null;if(!e){FtA&&(e=null);return}const t=this.voip.getFrequency(e)??0;this.updateLips(t)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,t)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,t)}}}setMouthShapeActive(e,t){if(e){e!=this.idle?this.idle.map(g=>g.visible=!1):this.talking.map(g=>g.visible=!1);for(let g=0;g<e.length;g++){const I=e[g];I&&(I.visible=g===t)}}}}$H([w(UA)],ud.prototype,"idle",2);$H([w(UA)],ud.prototype,"talking",2);class BR extends MA{constructor(){super(...arguments);r(this,"voip",null);r(this,"marker",null);r(this,"_startPosition",null)}awake(){this.voip=eA.findObjectOfType(nn,this.context),this.marker=eA.getComponentInParent(this.gameObject,tg)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());let g=t/100;this.gameObject.position.y=this._startPosition.y+g*.07}}var NtA=Object.defineProperty,KtA=Object.getOwnPropertyDescriptor,Ow=(i,A,e,t)=>{for(var g=t>1?void 0:t?KtA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&NtA(A,e,g),g};class iB extends MA{constructor(){super(...arguments);r(this,"eyes",[]);r(this,"lastBlinkTime",0);r(this,"blinkLength",0);r(this,"eyesOpen",!0);r(this,"state",null)}awake(){this.state=eA.getComponentInParent(this.gameObject,Eg)}update(){if(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)return;if(this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(const t of this.eyes)t&&(t.visible=this.eyesOpen)}}}Ow([w(UA)],iB.prototype,"eyes",2);Ow([w()],iB.prototype,"lastBlinkTime",2);Ow([w()],iB.prototype,"blinkLength",2);Ow([w()],iB.prototype,"eyesOpen",2);var JtA=Object.defineProperty,qtA=Object.getOwnPropertyDescriptor,QR=(i,A,e,t)=>{for(var g=t>1?void 0:t?qtA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&JtA(A,e,g),g},O0;const A_=(O0=class extends MA{constructor(){super(...arguments);r(this,"head",null);r(this,"eyes",null);r(this,"target",null);r(this,"brain",null);r(this,"vec",new k);r(this,"currentTargetPoint",new k)}awake(){this.brain||(this.brain=eA.getComponentInParent(this.gameObject,el)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=eA.addNewComponent(this.gameObject,el)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}update(){const A=this.target;if(A&&this.head){const e=this.eyes;if(e){const t=ye(A);this.currentTargetPoint.lerp(t,this.context.time.deltaTime/.1);const g=ye(this.head),I=this.vec.copy(this.currentTargetPoint).sub(g).normalize();if(I.length()<.1)return;const o=A_.forward;if(o.set(0,0,1),o.applyQuaternion(Hi(this.head)),o.dot(I)>.45)for(let s=0;s<e.length;s++)e[s].lookAt(this.currentTargetPoint)}}}},r(O0,"forward",new k(0,0,1)),O0);let xE=A_;QR([w(UA)],xE.prototype,"head",2);QR([w(UA)],xE.prototype,"eyes",2);QR([w(UA)],xE.prototype,"target",2);var btA=Object.defineProperty,LtA=Object.getOwnPropertyDescriptor,ER=(i,A,e,t)=>{for(var g=t>1?void 0:t?LtA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&btA(A,e,g),g};class YE extends MA{constructor(){super(...arguments);r(this,"length",1);r(this,"depthTest",!0);r(this,"isGizmo",!0);r(this,"_axes",null)}onEnable(){if(this.isGizmo&&!Pl)return;this._axes||(this._axes=new QE(this.length)),this.gameObject.add(this._axes);const e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}ER([w()],YE.prototype,"length",2);ER([w()],YE.prototype,"depthTest",2);ER([w()],YE.prototype,"isGizmo",2);class cR extends MA{constructor(){super(...arguments);r(this,"from");r(this,"to");r(this,"hint");r(this,"desiredDistance",1)}onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=ye(this.to).clone(),t=ye(this.from).clone(),g=e.distanceTo(t),I=e.clone();I.sub(t);let o=t.clone();o.add(e),o.multiplyScalar(.5);let C=ye(this.hint).clone();C.sub(o);let s=new k;s.crossVectors(C,I),s.crossVectors(I,s),s.normalize();let n=g*.5,a=Math.max(this.desiredDistance,n),B=Math.sqrt(a*a-n*n),Q=s.clone();Q.multiplyScalar(B),Q.add(o),hi(this.gameObject,Q);let E=o.clone();E.sub(s),this.gameObject.lookAt(E)}}class Pw{constructor(){r(this,"behaviours",[]);r(this,"behaviourComponents",[]);r(this,"behaviourComponentsCopy",[])}get extensionName(){return"Behaviour"}addBehavior(A){this.behaviours.push(A)}onBeforeBuildDocument(A){A.root.traverse(e=>{eA.foreachComponent(e,t=>{var I;const g=t;(typeof g.createBehaviours=="function"||typeof g.beforeCreateDocument=="function"||typeof g.afterCreateDocument=="function")&&(this.behaviourComponents.push(g),(I=g.beforeCreateDocument)==null||I.call(g,this,A))},!1)})}onExportObject(A,e,t){var g;for(const I of this.behaviourComponents)(g=I.createBehaviours)==null||g.call(I,this,e,t)}onAfterBuildDocument(A){for(const e of this.behaviourComponents)typeof e.afterCreateDocument=="function"&&e.afterCreateDocument(this,A);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0}onAfterHierarchy(A,e){var t;if((t=this.behaviours)!=null&&t.length){e.beginBlock('def Scope "Behaviors"');for(const g of this.behaviours)g.writeTo(this,A.document,e);e.closeBlock()}}async onAfterSerialize(A){console.log("onAfterSerialize",this.behaviourComponentsCopy);for(const e of this.behaviourComponentsCopy)console.log("behaviour",e),typeof e.afterSerialize=="function"&&(console.log("beh has afterSerialize",e),e.afterSerialize.constructor.name==="AsyncFunction"?await e.afterSerialize(this,A):e.afterSerialize(this,A))}}var vtA=Object.defineProperty,xtA=Object.getOwnPropertyDescriptor,hR=(i,A,e,t)=>{for(var g=t>1?void 0:t?xtA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&vtA(A,e,g),g};class gB extends eI{constructor(){super(...arguments);r(this,"threshold");r(this,"intensity");r(this,"scatter");r(this,"selectiveBloom",!0)}get typeName(){return"Bloom"}init(){this.threshold.defaultValue=1,this.intensity.defaultValue=0,this.scatter.defaultValue=.2,this.selectiveBloom?(this.threshold.valueProcessor=e=>e,this.intensity.valueProcessor=e=>e,this.scatter.valueProcessor=e=>1*Math.PI*(1-e)):(this.threshold.valueProcessor=e=>e,this.intensity.valueProcessor=e=>e,this.scatter.valueProcessor=e=>100*(1-e))}onCreateEffect(){let e;if(this.selectiveBloom){const t=e=new bx(this.context.scene,this.context.mainCamera,{blendFunction:Le.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,intensity:this.intensity.value});t.inverted=!0}else e=new em;return this.intensity.onValueChanged=t=>{e.intensity=t},this.threshold.onValueChanged=t=>{e.luminanceMaterial.threshold=t},this.scatter.onValueChanged=t=>{e.luminancePass.enabled=!0,e.luminanceMaterial.smoothing=t},e}}hR([w(ve)],gB.prototype,"threshold",2);hR([w(ve)],gB.prototype,"intensity",2);hR([w(ve)],gB.prototype,"scatter",2);$C("Bloom",gB);var YtA=Object.defineProperty,TtA=Object.getOwnPropertyDescriptor,aC=(i,A,e,t)=>{for(var g=t>1?void 0:t?TtA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&YtA(A,e,g),g};class As extends MA{constructor(){super(...arguments);r(this,"attachedRigidbody",null);r(this,"isTrigger",!1);r(this,"sharedMaterial")}get isCollider(){return!0}awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(jt))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(jt))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(jt))}onDisable(){var e;(e=this.context.physics.engine)==null||e.removeBody(this)}}aC([w(jt)],As.prototype,"attachedRigidbody",2);aC([w()],As.prototype,"isTrigger",2);aC([w()],As.prototype,"sharedMaterial",2);class Dd extends As{constructor(){super(...arguments);r(this,"radius",.5);r(this,"center",new k(0,0,0))}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addSphereCollider(this,this.center,this.radius)}}aC([w()],Dd.prototype,"radius",2);aC([w(k)],Dd.prototype,"center",2);class pd extends As{constructor(){super(...arguments);r(this,"size",new k(1,1,1));r(this,"center",new k(0,0,0))}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addBoxCollider(this,this.center,this.size)}}aC([w(k)],pd.prototype,"size",2);aC([w(k)],pd.prototype,"center",2);class fd extends As{constructor(){super(...arguments);r(this,"sharedMesh");r(this,"convex",!1)}onEnable(){var e,t,g,I,o;if(super.onEnable(),(e=this.sharedMesh)!=null&&e.isMesh||this.gameObject instanceof fA&&(this.sharedMesh=this.gameObject),(t=this.sharedMesh)!=null&&t.isMesh)(g=this.context.physics.engine)==null||g.addMeshCollider(this,this.sharedMesh,this.convex,Qg(this.gameObject));else{const C=this.sharedMesh;if(C!=null&&C.isGroup){console.warn(`MeshCollider mesh is a group "${(I=this.sharedMesh)==null?void 0:I.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);for(const s in C.children){const n=C.children[s];n.isMesh&&((o=this.context.physics.engine)==null||o.addMeshCollider(this,n,this.convex,Qg(this.gameObject)))}}}}}aC([w()],fd.prototype,"convex",2);class Da extends As{constructor(){super(...arguments);r(this,"center",new k(0,0,0));r(this,"radius",.5);r(this,"height",2)}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addCapsuleCollider(this,this.center,this.height,this.radius)}}aC([w(k)],Da.prototype,"center",2);aC([w()],Da.prototype,"radius",2);aC([w()],Da.prototype,"height",2);function lR(i){const A=i[Ns];return A||(i.parent?lR(i.parent):null)}function tf(i,A){if(!i)return;const e=i.material;if((e==null?void 0:e.isMaterial)===!0){const t=i.parent;t&&t.isText,e.side=A.doubleSided??!0?Nt:Zg,e.shadowSide=A.doubleSided?Nt:Zg,i.castShadow=A.castShadows?A.castShadows:!1,i.receiveShadow=A.receiveShadows?A.receiveShadows:!1}for(const t of i.children)tf(t,A)}function tQ(i,A,e){i[A]===void 0&&console.warn("Field",A,"is undefined on",i);const t=Proxy.revocable(i[A],{set(o,C,s,n){const a=o[C],B=Reflect.set(o,C,s,n);return e(s,a),B}}),g=t.revoke,I=i[A];return t.revoke=()=>{i[A]=I,g()},i[A]=t.proxy,t}const GJ=Symbol("Scheduled action");function HtA(i,A,e=OI.OnBeforeRender){let t=i[GJ];t||(t=i[GJ]={});const g=A.name;t[e]||(t[e]={});const I=t[e];if(I[g])return;function*C(){A==null||A.call(i),I[g]=null}const s=i.startCoroutine(C(),e);I[g]=s}var _tA=Object.defineProperty,OtA=Object.getOwnPropertyDescriptor,IB=(i,A,e,t)=>{for(var g=t>1?void 0:t?OtA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&_tA(A,e,g),g};const h0=rA("debugui"),l0=rA("debuguilayout");class dR{constructor(){r(this,"width");r(this,"height")}}class uR{constructor(){r(this,"x");r(this,"y");r(this,"width");r(this,"height")}}const cC=new k,Rc=new OA,eD=new kA,e_=class extends tC{constructor(){super(...arguments);r(this,"offset",.01);r(this,"_anchoredPosition");r(this,"sizeDelta",new j(100,100));r(this,"pivot",new j(.5,.5));r(this,"anchorMin",new j(0,0));r(this,"anchorMax",new j(1,1));r(this,"offsetMin",new j(0,0));r(this,"offsetMax",new j(0,0));r(this,"lastMatrix");r(this,"rectBlock");r(this,"_transformNeedsUpdate",!1);r(this,"_initialPosition");r(this,"_parentRectTransform");r(this,"_lastUpdateFrame",-1);r(this,"_lastAnchoring");r(this,"_createdBlocks",[]);r(this,"_createdTextBlocks",[])}get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new j),this._anchoredPosition}set anchoredPosition(A){this._anchoredPosition=A}get width(){if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const A=this._parentRectTransform.width,e=this.anchorMax.x-this.anchorMin.x;let t=A*e;return t+=this.sizeDelta.x,t}return this.sizeDelta.x}get height(){if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const A=this._parentRectTransform.height,e=this.anchorMax.y-this.anchorMin.y;let t=A*e;return t+=this.sizeDelta.y,t}return this.sizeDelta.y}awake(){super.awake(),this._anchoredPosition||(this._anchoredPosition=new j),this.lastMatrix=new OA,this.rectBlock=new UA,this.rectBlock.position.z=.1,this.rectBlock.name=this.name,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this.onApplyTransform("RectTransform awake"),tQ(this,"_anchoredPosition",()=>{this.markDirty()}),tQ(this,"sizeDelta",()=>{this.markDirty()}),tQ(this,"pivot",()=>{this.markDirty()}),tQ(this,"anchorMin",()=>{this.markDirty()}),tQ(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var A;super.onEnable(),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(A=this.Canvas)==null||A.registerTransform(this)}onDisable(){var A;super.onDisable(),this.removeShadowComponent(),(A=this.Canvas)==null||A.unregisterTransform(this)}onParentRectTransformChanged(A){this._transformNeedsUpdate||this.onApplyTransform(l0?`${A.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(l0&&console.warn("RectTransform markDirty()",this.name),this._transformNeedsUpdate=!0,this._lastUpdateFrame=-1)}updateTransform(){(this._transformNeedsUpdate||!this.lastMatrix.equals(this.gameObject.matrix))&&this.canUpdate()&&this.onApplyTransform(this._transformNeedsUpdate?"Marked dirty":"Matrix changed")}canUpdate(){return this._transformNeedsUpdate&&this.activeAndEnabled&&this._lastUpdateFrame!==this.context.time.frame}onApplyTransform(A){if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const e=this.shadowComponent;if(!e)return;this.gameObject.parent?this._parentRectTransform=eA.getComponentInParent(this.gameObject.parent,e_):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,l0&&console.warn("RectTransform → ApplyTransform",this.name+" because "+A),this.isRoot()?this.Root.screenspace||(e.rotation.y=Math.PI):(e.matrix.identity(),e.matrixAutoUpdate=!1,cC.set(0,0,0),this.applyPivot(cC),e.matrix.setPosition(cC.x,cC.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(eD.copy(this.gameObject.quaternion),eD.x*=-1,eD.z*=-1,Rc.makeRotationFromQuaternion(eD),e.matrix.premultiply(Rc)),cC.set(0,0,0),this.applyAnchoring(cC),cC.z+=this.offset,Rc.identity(),Rc.setPosition(cC.x,cC.y,cC.z),e.matrix.premultiply(Rc),e.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const t=!0;for(const g of jM(this.gameObject,tC,t,1)){if(g===this||!g.activeAndEnabled)continue;const I=g;I.onParentRectTransformChanged&&I.onParentRectTransformChanged(this)}}applyAnchoring(A){this._lastAnchoring||(this._lastAnchoring=new j);const e=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=e.x,this.gameObject.position.y+=e.y,this._lastAnchoring.copy(this._anchoredPosition),A.x+=this._initialPosition.x-this.gameObject.position.x,A.y+=this._initialPosition.y-this.gameObject.position.y,A.z+=this._initialPosition.z-this.gameObject.position.z;const t=this._parentRectTransform;if(t){let g=0;const I=1-this.anchorMax.y-this.anchorMin.y;g-=t.height*.5*I,A.y+=g;let o=0;const C=1-this.anchorMax.x-this.anchorMin.x;o-=t.width*.5*C,A.x+=o}}applyPivot(A){if(this.pivot&&!this.isRoot()){const e=this.pivot.x-.5;A.x-=e*this.sizeDelta.x*this.gameObject.scale.x;const t=this.pivot.y-.5;A.y-=t*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const A={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:this.offset,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(A),A}ensureValidSize(A,e=1e-4){return A.width<=0&&(A.width=e),A.height<=0&&(A.height=1e-4),A}createNewBlock(A){A={...this.getBasicOptions(),...A},h0&&console.log(this.name,A);const e=new CR(A);return this._createdBlocks.push(e),e}createNewText(A){h0&&console.log(A),A={...this.getBasicOptions(),...A},h0&&console.log(this.name,A);const e=new WH(A);return this._createdTextBlocks.push(e),e}};let Ug=e_;IB([w(j)],Ug.prototype,"anchoredPosition",1);IB([w(j)],Ug.prototype,"sizeDelta",2);IB([w(j)],Ug.prototype,"pivot",2);IB([w(j)],Ug.prototype,"anchorMin",2);IB([w(j)],Ug.prototype,"anchorMax",2);IB([w(j)],Ug.prototype,"offsetMin",2);IB([w(j)],Ug.prototype,"offsetMax",2);class PtA extends PH{constructor(A,e={}){super(A),A._simpleState__activeStates=[],A._simpleState__normalStyles={},A._simpleState__states=e,A._simpleState__statesProperties={};for(const t in e)for(const g in e[t])A._simpleState__statesProperties[g]||(A._simpleState__statesProperties[g]=[]),A._simpleState__statesProperties[g].push(t);for(const t of A._components)A._simpleState__statesProperties[t.id]&&(A._simpleState__normalStyles[t.id]=t.inline?t.inline:t._value);A.__overridedSet=A.set,A.set=this.storeSet.bind(A),A.renderStates=this.renderStates.bind(A),A.setupState=this.setupState.bind(A),A.setState=this.setState.bind(A),A.activatePseudoState=this.activatePseudoState.bind(A),A.deactivatePseudoState=this.deactivatePseudoState.bind(A),A.togglePseudoState=this.togglePseudoState.bind(A)}act(){}attach(){}detach(){}setupState(A,e){this._simpleState__states[A]=e;const t=[];for(const g in e)this._simpleState__statesProperties[g]||(this._simpleState__statesProperties[g]=[],t.push(g)),this._simpleState__statesProperties[g].push(A);for(const g of this._components)t.indexOf(g.id)>-1&&(this._simpleState__normalStyles[g.id]=g.inline?g.inline:g._value)}renderStates(){let A={...this._simpleState__normalStyles};for(const e in this._simpleState__states)this._simpleState__activeStates.indexOf(e)>-1&&(A={...A,...this._simpleState__states[e]});this.set(A,!1)}storeSet(A,e=!0){if(e)for(const t in A)this._simpleState__statesProperties[t]&&(this._simpleState__normalStyles[t]=A[t]);this.__overridedSet(A)}activatePseudoState(A){this._simpleState__activeStates.indexOf(A)===-1&&(this._simpleState__activeStates.push(A),this.renderStates())}deactivatePseudoState(A){const e=this._simpleState__activeStates.indexOf(A);e>-1&&(this._simpleState__activeStates.splice(e,1),this.renderStates())}togglePseudoState(A){const e=this._simpleState__activeStates.indexOf(A);e>-1?this._simpleState__activeStates.splice(e,1):this._simpleState__activeStates.push(A),this.renderStates()}setState(A){Array.isArray(A)?this._simpleState__activeStates=A:this._simpleState__activeStates=[A],this.renderStates()}}var WtA=Object.defineProperty,VtA=Object.getOwnPropertyDescriptor,t_=(i,A,e,t)=>{for(var g=t>1?void 0:t?VtA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&WtA(A,e,g),g};class TE extends MA{constructor(){super(...arguments);r(this,"effectColor");r(this,"effectDistance")}}t_([w(Gt)],TE.prototype,"effectColor",2);t_([w(j)],TE.prototype,"effectDistance",2);var jtA=Object.defineProperty,ztA=Object.getOwnPropertyDescriptor,i_=(i,A,e,t)=>{for(var g=t>1?void 0:t?ztA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&jtA(A,e,g),g};const tD={backgroundColor:new yA(1,1,1),backgroundOpacity:1,borderColor:new yA(1,1,1),borderOpacity:1};var P0;const $D=(P0=class extends tC{constructor(){super(...arguments);r(this,"_alphaFactor",1);r(this,"raycastTarget",!0);r(this,"uiObject",null);r(this,"_color",null);r(this,"_rect",null);r(this,"_stateManager",null);r(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new Gt(1,1,1,1)),this._color}set color(A){(!this._color||this._color.r!==A.r||this._color.g!==A.g||this._color.b!==A.b||this._color.alpha!==A.alpha)&&(this._color||(this._color=new Gt(1,1,1,1)),this._color.copy(A))}setAlphaFactor(A){this._alphaFactor=A,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(tD.backgroundColor=this._color,tD.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(tD,this._alphaFactor),this.uiObject.set(tD),this.markDirty())}get m_Color(){return this._color}get rectTransform(){return this._rect||(this._rect=eA.getComponent(this.gameObject,Ug)),this._rect}onParentRectTransformChanged(){var A;(A=this.uiObject)==null||A.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(){super.__internalNewInstanceCreated(),this._rect=null,this.uiObject=null,this._color&&(this._color=this._color.clone())}setState(A){this.makePanel(),this.uiObject&&(this.uiObject.setState(A),this==null||this.markDirty())}setupState(A){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new PtA(this.uiObject)),this.uiObject.setupState(A.state,A.attributes))}setOptions(A){this.makePanel(),this.uiObject&&this.uiObject.set(A)}awake(){super.awake(),this.makePanel(),tQ(this,"_color",()=>HtA(this,this.onColorChanged))}onEnable(){var A;super.onEnable(),this.uiObject&&((A=this.rectTransform.shadowComponent)==null||A.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const A={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:1};this.onBeforeCreate(A),this.applyEffects(A),this.onCreate(A),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated()}onBeforeCreate(A){}onCreate(A){this.uiObject=this.rectTransform.createNewBlock(A),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(A,e=1){var g;const t=(g=this.gameObject)==null?void 0:g.getComponent(TE);t&&(t.effectDistance&&(A.borderWidth=Math.max(Math.abs(t.effectDistance.x),Math.abs(t.effectDistance.y))),t.effectColor&&(A.borderColor=t.effectColor,A.borderOpacity=t.effectColor.alpha*e))}async setTexture(A){if(this.setOptions({backgroundOpacity:0}),A){if(A.encoding===De)if($D.textureCache.has(A))A=$D.textureCache.get(A);else{const e=A.clone();e.encoding=li,$D.textureCache.set(A,e),A=e}this.setOptions({backgroundImage:A,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"})}else this.setOptions({backgroundImage:null,borderRadius:0,backgroundOpacity:this.color.alpha})}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}},r(P0,"textureCache",new Map),P0);let oB=$D;i_([w(Gt)],oB.prototype,"color",1);i_([w()],oB.prototype,"raycastTarget",2);class wd extends oB{constructor(){super(...arguments);r(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var ZtA=Object.defineProperty,XtA=Object.getOwnPropertyDescriptor,Ww=(i,A,e,t)=>{for(var g=t>1?void 0:t?XtA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&ZtA(A,e,g),g};let DR=class{constructor(){r(this,"texture",null);r(this,"rect")}};Ww([w(He)],DR.prototype,"texture",2);let HE=class extends wd{constructor(){super(...arguments);r(this,"_sprite");r(this,"pixelsPerUnitMultiplier",1)}set image(e){this.sprite?this.sprite.texture=e:(this.sprite=new DR,this.sprite.texture=e),this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(e){this._sprite!==e&&(this._sprite=e,this.onAfterCreated())}isBuiltinSprite(){var e,t,g,I,o,C,s,n;switch((t=(e=this.sprite)==null?void 0:e.texture)==null?void 0:t.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return((o=(I=(g=this.sprite)==null?void 0:g.texture)==null?void 0:I.image)==null?void 0:o.width)===32&&((n=(s=(C=this.sprite)==null?void 0:C.texture)==null?void 0:s.image)==null?void 0:n.height)===32}onBeforeCreate(e){var t,g;super.onBeforeCreate(e),this.isBuiltinSprite()&&(e.borderRadius=5/this.pixelsPerUnitMultiplier,((g=(t=this.sprite)==null?void 0:t.texture)==null?void 0:g.name)==="Knob"&&(e.borderRadius=999))}onAfterCreated(){var e;this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture((e=this.sprite)==null?void 0:e.texture))}};Ww([w(DR)],HE.prototype,"sprite",1);Ww([w()],HE.prototype,"pixelsPerUnitMultiplier",2);class Vw extends wd{constructor(){super(...arguments);r(this,"_mainTexture")}get mainTexture(){return this._mainTexture}set mainTexture(e){this._mainTexture!==e&&(this._mainTexture=e,this.onAfterCreated())}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}Ww([w(He)],Vw.prototype,"mainTexture",1);var $tA=Object.defineProperty,AiA=Object.getOwnPropertyDescriptor,WI=(i,A,e,t)=>{for(var g=t>1?void 0:t?AiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&$tA(A,e,g),g};const OB=rA("debugbutton");class CB{constructor(){r(this,"colorMultiplier");r(this,"disabledColor");r(this,"fadeDuration");r(this,"highlightedColor");r(this,"normalColor");r(this,"pressedColor");r(this,"selectedColor")}}WI([w()],CB.prototype,"colorMultiplier",2);WI([w(Gt)],CB.prototype,"disabledColor",2);WI([w()],CB.prototype,"fadeDuration",2);WI([w(Gt)],CB.prototype,"highlightedColor",2);WI([w(Gt)],CB.prototype,"normalColor",2);WI([w(Gt)],CB.prototype,"pressedColor",2);WI([w(Gt)],CB.prototype,"selectedColor",2);class Qn extends MA{constructor(){super(...arguments);r(this,"onClick");r(this,"_isHovered",!1);r(this,"colors");r(this,"transition");r(this,"animationTriggers");r(this,"animator");r(this,"_interactable",!0);r(this,"_requestedAnimatorTrigger");r(this,"_isInit",!1);r(this,"_image")}onPointerEnter(e){var t,g;OB&&console.log("Button Enter",(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator),this._isHovered=!0,this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&((g=this._image)==null||g.setState("hovered")),this.context.input.setCursorPointer())}onPointerExit(){var e,t;OB&&console.log("Button Exit",(e=this.animationTriggers)==null?void 0:e.highlightedTrigger,this.animator),this._isHovered=!1,this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((t=this._image)==null||t.setState("normal")),this.context.input.setCursorNormal())}onPointerDown(e){var t,g;OB&&console.log("Button Down",(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&((g=this._image)==null||g.setState("pressed")))}onPointerUp(e){var t,g;OB&&console.warn("Button Up",(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator,this._isHovered),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((g=this._image)==null||g.setState(this._isHovered?"hovered":"normal")))}onPointerClick(e){var t;this.interactable&&(OB&&(console.warn("Button Click",this.onClick),eg("CLICKED button "+this.name+" at "+this.context.time.frameCount)),(t=this.onClick)==null||t.invoke())}set interactable(e){this._interactable=e,this._image&&(this._image.setInteractable(e),e?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}set_interactable(e){this.interactable=e}awake(){super.awake(),OB&&console.log(this),this._isInit=!1,this.init()}start(){var e;(e=this._image)==null||e.setInteractable(this.interactable)}onEnable(){super.onEnable()}*setAnimatorTriggerAtEndOfFrame(e){var t;this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&((t=this.animator)==null||t.SetTrigger(e))}init(){this._isInit||(this._isInit=!0,this._image=eA.getComponent(this.gameObject,HE),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){var E,c,h,l,d;e.setInteractable(this.interactable);const t=this.getFinalColor(e.color,(E=this.colors)==null?void 0:E.normalColor),g={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(g);const I=this.getFinalColor(e.color,(c=this.colors)==null?void 0:c.highlightedColor),o={state:"hovered",attributes:{backgroundColor:I,backgroundOpacity:I.alpha}};e.setupState(o);const C=this.getFinalColor(e.color,(h=this.colors)==null?void 0:h.pressedColor),s={state:"pressed",attributes:{backgroundColor:C,backgroundOpacity:C.alpha}};e.setupState(s);const n=this.getFinalColor(e.color,(l=this.colors)==null?void 0:l.selectedColor),a={state:"selected",attributes:{backgroundColor:n,backgroundOpacity:n.alpha}};e.setupState(a);const B=this.getFinalColor(e.color,(d=this.colors)==null?void 0:d.disabledColor),Q={state:"disabled",attributes:{backgroundColor:B,backgroundOpacity:B.alpha}};e.setupState(Q)}getFinalColor(e,t){return t?e.clone().multiply(t):e.clone()}}WI([w(DI)],Qn.prototype,"onClick",2);WI([w()],Qn.prototype,"colors",2);WI([w()],Qn.prototype,"transition",2);WI([w()],Qn.prototype,"animationTriggers",2);WI([w(wI)],Qn.prototype,"animator",2);WI([w()],Qn.prototype,"interactable",1);var eiA=Object.defineProperty,tiA=Object.getOwnPropertyDescriptor,Ki=(i,A,e,t)=>{for(var g=t>1?void 0:t?tiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&eiA(A,e,g),g};const MJ=rA("debuguilayout");class Ja{constructor(){r(this,"left",0);r(this,"right",0);r(this,"top",0);r(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}Ki([w()],Ja.prototype,"left",2);Ki([w()],Ja.prototype,"right",2);Ki([w()],Ja.prototype,"top",2);Ki([w()],Ja.prototype,"bottom",2);class VI extends MA{constructor(){super(...arguments);r(this,"_rectTransform",null);r(this,"_needsUpdate",!1);r(this,"childAlignment",0);r(this,"reverseArrangement",!1);r(this,"spacing",0);r(this,"padding");r(this,"minWidth",0);r(this,"minHeight",0);r(this,"flexibleHeight",0);r(this,"flexibleWidth",0);r(this,"preferredHeight",0);r(this,"preferredWidth",0)}get rectTransform(){return this._rectTransform}onParentRectTransformChanged(e){this._needsUpdate=!0}get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(MJ&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){MJ&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Ug);const e=this.gameObject.getComponentInParent(Fg);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(Fg);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}Ki([w()],VI.prototype,"childAlignment",2);Ki([w()],VI.prototype,"reverseArrangement",2);Ki([w()],VI.prototype,"spacing",2);Ki([w(Ja)],VI.prototype,"padding",2);Ki([w()],VI.prototype,"minWidth",2);Ki([w()],VI.prototype,"minHeight",2);Ki([w()],VI.prototype,"flexibleHeight",2);Ki([w()],VI.prototype,"flexibleWidth",2);Ki([w()],VI.prototype,"preferredHeight",2);Ki([w()],VI.prototype,"preferredWidth",2);class qa extends VI{constructor(){super(...arguments);r(this,"childControlHeight",!0);r(this,"childControlWidth",!0);r(this,"childForceExpandHeight",!1);r(this,"childForceExpandWidth",!1);r(this,"childScaleHeight",!1);r(this,"childScaleWidth",!1)}onCalculateLayout(e){var f;const t=this.primaryAxis,g=e.width;let I=g;const o=e.height;let C=o;I-=this.padding.horizontal,C-=this.padding.vertical,t==="x"?this.padding.horizontal:this.padding.vertical;const s=t==="x",n=s?"y":"x",a=s?this.childControlWidth:this.childControlHeight,B=s?this.childControlHeight:this.childControlWidth,Q=s?this.childForceExpandWidth:this.childForceExpandHeight,E=s?this.childForceExpandHeight:this.childForceExpandWidth,c=s?C:I,h=s?g:o,l=.5*(s?this.childAlignment%3:Math.floor(this.childAlignment/3));let d=0;s?d+=this.padding.left:d+=this.padding.top;let p=0,u=0;for(let M=0;M<this.gameObject.children.length;M++){const U=this.gameObject.children[M],J=eA.getComponent(U,Ug);J!=null&&J.activeAndEnabled&&(u+=1,s?p+=J.width:p+=J.height)}let D=0;const y=this.spacing*(u-1);if(Q||a){let M=0;s?M=I-=y:M=C-=y,u>0&&(D=M/u)}let S=0;S+=this.padding.left,S-=this.padding.right,l!==0&&(d=h-p,d*=l,d-=y*l,s?(d-=this.padding.right*l,d+=this.padding.left*(1-l),d<this.padding.left&&(d=this.padding.left)):(d-=this.padding.bottom*l,d+=this.padding.top*(1-l),d<this.padding.top&&(d=this.padding.top)));let R=1;for(let M=0;M<this.gameObject.children.length;M++){const U=this.gameObject.children[M],J=eA.getComponent(U,Ug);if(J!=null&&J.activeAndEnabled){(f=J.pivot)==null||f.set(.5,.5),J.anchorMin.set(0,1),J.anchorMax.set(0,1);const T=g*.5+S*.5;J.anchoredPosition.x!==T&&(J.anchoredPosition.x=T);const Y=o*-.5;J.anchoredPosition.y!==Y&&(J.anchoredPosition.y=Y),E&&B&&J.sizeDelta[n]!==c&&(J.sizeDelta[n]=c),Q&&a&&J.sizeDelta[t]!==D&&(J.sizeDelta[t]=D);const b=s?J.width:J.height;let _=b*.5;if(d+=_,Q){let $=D*R-D*.5;$>d&&(d=$-D*.5+b+this.padding.left,d-=_)}let AA=d;t==="y"&&(AA=-AA),J.anchoredPosition[t]!==AA&&(J.anchoredPosition[t]=AA),d+=_,d+=this.spacing,R+=1}}}}Ki([w()],qa.prototype,"childControlHeight",2);Ki([w()],qa.prototype,"childControlWidth",2);Ki([w()],qa.prototype,"childForceExpandHeight",2);Ki([w()],qa.prototype,"childForceExpandWidth",2);Ki([w()],qa.prototype,"childScaleHeight",2);Ki([w()],qa.prototype,"childScaleWidth",2);class pR extends qa{get primaryAxis(){return"y"}}class fR extends qa{get primaryAxis(){return"x"}}class wR extends VI{onCalculateLayout(){}}var iiA=Object.defineProperty,giA=Object.getOwnPropertyDescriptor,es=(i,A,e,t)=>{for(var g=t>1?void 0:t?giA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&iiA(A,e,g),g};const d0=rA("debuguilayout"),g_=class extends Ed{constructor(){super(...arguments);r(this,"_renderOnTop");r(this,"_depthWrite",!1);r(this,"_doubleSided",!0);r(this,"_castShadows",!1);r(this,"_receiveShadows",!1);r(this,"_renderMode",-1);r(this,"_rootCanvas");r(this,"_scaleFactor",1);r(this,"worldCamera");r(this,"planeDistance",-1);r(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this));r(this,"previousParent",null);r(this,"_lastMatrixWorld",null);r(this,"_rectTransforms",[]);r(this,"_layoutGroups",new Map);r(this,"onBeforeRenderRoutine",()=>{var A,e;this.previousParent=this.gameObject.parent,this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(A=this.shadowComponent)==null||A.updateMatrixWorld(!0),(e=this.shadowComponent)==null||e.updateWorldMatrix(!0,!0),lI.ensureUpdateMeshUI(fJ,this.context))});r(this,"onAfterRenderRoutine",()=>{var A,e;if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const t=this.context.mainCamera;t==null||t.add(this.gameObject)}else this.previousParent.add(this.gameObject);this.context.renderer.autoClear=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(A=this.shadowComponent)==null||A.updateMatrixWorld(!0),lI.ensureUpdateMeshUI(fJ,this.context),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=!0,this.previousParent.add(this.gameObject)}(e=this._lastMatrixWorld)==null||e.copy(this.gameObject.matrixWorld)});r(this,"_updateRenderSettingsRoutine");r(this,"_activeRenderMode",-1);r(this,"_lastWidth",-1);r(this,"_lastHeight",-1)}get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(A){A!==this._renderOnTop&&(this._renderOnTop=A,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(A){this._depthWrite!==A&&(this._depthWrite=A,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(A){this._doubleSided!==A&&(this._doubleSided=A,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(A){this._castShadows!==A&&(this._castShadows=A,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(A){this._receiveShadows!==A&&(this._receiveShadows=A,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(A){this._renderMode!==A&&(this._renderMode=A,this.onRenderSettingsChanged())}set rootCanvas(A){this._rootCanvas instanceof g_||(this._rootCanvas=A)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(A){this._scaleFactor=A}awake(){var A;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,d0&&console.log("Canvas.Awake()",((A=this.previousParent)==null?void 0:A.name)+"/"+this.gameObject.name),super.awake()}start(){this.onUpdateRenderMode()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new OA,this.onUpdateRenderMode(),document.addEventListener("resize",this._boundRenderSettingsChanged),this.context.pre_render_callbacks.push(this.onBeforeRenderRoutine),this.context.post_render_callbacks.push(this.onAfterRenderRoutine)}onDisable(){super.onDisable(),document.removeEventListener("resize",this._boundRenderSettingsChanged);const A=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);A!==-1&&this.context.pre_render_callbacks.splice(A,1);const e=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);e!==-1&&this.context.post_render_callbacks.splice(e,1)}registerTransform(A){this._rectTransforms.push(A)}unregisterTransform(A){const e=this._rectTransforms.indexOf(A);e!==-1&&this._rectTransforms.splice(e,1)}registerLayoutGroup(A){const e=A.gameObject;this._layoutGroups.set(e,A)}unregisterLayoutGroup(A){const e=A.gameObject;this._layoutGroups.delete(e)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new OA);const A=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);d0&&A&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);let e=!1;for(const t of this._rectTransforms){A&&t.markDirty();let g=this._layoutGroups.get(t.gameObject);t.isDirty&&!g&&(g=t.gameObject.getComponentInParent(VI)),(t.isDirty||g!=null&&g.isDirty)&&(d0&&!e&&console.log("CANVAS UPDATE ### "+t.name+" ##################################### "+this.context.time.frame),g==null||g.updateLayout(),t.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),OI.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),tf(this.shadowComponent,this);for(const A of eA.getComponentsInChildren(this.gameObject,tC))tf(A.shadowComponent,this)}}onUpdateRenderMode(A=!1){if(!A&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let e=this.context.mainCameraComponent,t=10;switch(e&&e.nearClipPlane>0&&e.farClipPlane>0&&(t=Ae.lerp(e.nearClipPlane,e.farClipPlane,.15)),this._renderMode===1&&(this.worldCamera&&(e=this.worldCamera),this.planeDistance>0&&(t=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!e)return;const g=t+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-g,this.gameObject.quaternion.identity();const I=this.gameObject.getComponent(Ug);let o=!1;I.sizeDelta.x!==this.context.domWidth&&(o=!0),I.sizeDelta.y!==this.context.domHeight&&(o=!0);const C=e.fieldOfView*Math.PI/180,s=2*Math.tan(C/2)*Math.abs(g);this.gameObject.scale.x=s/this.context.domHeight,this.gameObject.scale.y=s/this.context.domHeight,this.gameObject.scale.z=.01,o&&(I.sizeDelta.x=this.context.domWidth,I.sizeDelta.y=this.context.domHeight,I==null||I.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};let Fg=g_;es([w()],Fg.prototype,"renderOnTop",1);es([w()],Fg.prototype,"depthWrite",1);es([w()],Fg.prototype,"doubleSided",1);es([w()],Fg.prototype,"castShadows",1);es([w()],Fg.prototype,"receiveShadows",1);es([w()],Fg.prototype,"renderMode",1);es([w(Fg)],Fg.prototype,"rootCanvas",1);es([w()],Fg.prototype,"scaleFactor",1);es([w(Yt)],Fg.prototype,"worldCamera",2);es([w()],Fg.prototype,"planeDistance",2);var IiA=Object.defineProperty,oiA=Object.getOwnPropertyDescriptor,yR=(i,A,e,t)=>{for(var g=t>1?void 0:t?oiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&IiA(A,e,g),g};class _E extends MA{constructor(){super(...arguments);r(this,"_alpha",1);r(this,"interactable",!0);r(this,"blocksRaycasts",!0);r(this,"_isDirty",!1);r(this,"_buffer",[])}get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),OI.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){for(const e of eA.getComponentsInChildren(this.gameObject,tC,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}yR([w()],_E.prototype,"alpha",1);yR([w()],_E.prototype,"interactable",2);yR([w()],_E.prototype,"blocksRaycasts",2);var CiA=Object.defineProperty,siA=Object.getOwnPropertyDescriptor,Ht=(i,A,e,t)=>{for(var g=t>1?void 0:t?siA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&CiA(A,e,g),g};class sB extends MA{constructor(){super(...arguments);r(this,"object");r(this,"target");r(this,"duration",1);r(this,"relativeMotion",!1);r(this,"coroutine",null);r(this,"targetPos",new k);r(this,"targetRot",new kA);r(this,"targetScale",new k)}*moveToTarget(){if(!this.target||!this.object)return;const e=ye(this.object).clone(),t=ye(this.target).clone(),g=Hi(this.object).clone(),I=Hi(this.target).clone(),o=Qg(this.object).clone(),C=Qg(this.target).clone(),s=e.distanceTo(t),n=g.angleTo(I),a=o.distanceTo(C);if(s<.01&&n<.01&&a<.01){hi(this.object,t),fI(this.object,I),Lk(this.object,C),this.coroutine=null;return}let B=0,Q=0;for(;B<1;)B+=this.context.time.deltaTime/this.duration,B>1&&(B=1),Q=B<.5?4*B*B*B:1-Math.pow(-2*B+2,3)/2,this.targetPos.lerpVectors(e,t,Q),this.targetRot.slerpQuaternions(g,I,Q),this.targetScale.lerpVectors(o,C,Q),hi(this.object,this.targetPos),fI(this.object,this.targetRot),Lk(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const e=this.object.position.clone(),t=this.object.quaternion.clone(),g=this.object.scale.clone(),I=this.target.position.clone(),o=this.target.quaternion.clone(),C=this.target.scale.clone();I.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(I),this.targetRot.copy(this.object.quaternion).multiply(o),this.targetScale.copy(this.object.scale).multiply(C);let s=0,n=0;for(;s<1;)s+=this.context.time.deltaTime/this.duration,s>1&&(s=1),n=s<.5?4*s*s*s:1-Math.pow(-2*s+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,n),this.object.quaternion.slerpQuaternions(t,this.targetRot,n),this.object.scale.lerpVectors(g,this.targetScale,n),yield;this.coroutine=null}onPointerClick(){this.coroutine&&this.stopCoroutine(this.coroutine),this.relativeMotion?this.coroutine=this.startCoroutine(this.moveRelative()):this.coroutine=this.startCoroutine(this.moveToTarget())}beforeCreateDocument(e){var t;if(this.target&&this.object&&this.gameObject){const g=new cg("Move to "+((t=this.target)==null?void 0:t.name),pI.tapTrigger(this.gameObject),at.transformAction(this.object,this.target,this.duration,this.relativeMotion?cG.Relative:cG.Absolute));e.addBehavior(g)}}}Ht([w(UA)],sB.prototype,"object",2);Ht([w(UA)],sB.prototype,"target",2);Ht([w()],sB.prototype,"duration",2);Ht([w()],sB.prototype,"relativeMotion",2);var W0;const iQ=(W0=class extends MA{constructor(){super(...arguments);r(this,"materialToSwitch");r(this,"variantMaterial");r(this,"_objectsWithThisMaterial",[]);r(this,"selfModel");r(this,"targetModels",[])}awake(){if(this.variantMaterial&&this.materialToSwitch){const A=eA.findObjectsOfType(Ii);for(const e of A)e.sharedMaterial===this.materialToSwitch&&this._objectsWithThisMaterial.push(e)}}onPointerClick(){if(this.variantMaterial)for(const A of this._objectsWithThisMaterial)A.sharedMaterial=this.variantMaterial}createBehaviours(A,e,t){this._objectsWithThisMaterial.find(I=>I.gameObject.uuid===e.uuid)&&this.targetModels.push(e),this.gameObject.uuid===e.uuid&&(this.selfModel=e,this.materialToSwitch&&(iQ._materialTriggersPerId[this.materialToSwitch.uuid]||(iQ._materialTriggersPerId[this.materialToSwitch.uuid]=[]),iQ._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(A,e){if(!this.materialToSwitch)return;const t=iQ._materialTriggersPerId[this.materialToSwitch.uuid];if(t){const g={};for(const o of t){const C=o.createVariants();C&&C.length>0&&(g[o.selfModel.uuid]=C)}const I=[];for(const o of t){for(const C in g)C!==o.selfModel.uuid&&I.push(g[C]);o.createAndAttachBehaviors(A,g[o.selfModel.uuid],I)}}delete iQ._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(A,e,t){const g=[],I=[];for(const o of this.targetModels){const C=at.fadeAction(o,0,!1);I.push(C)}for(const o of t)I.push(at.fadeAction(o,0,!1));for(const o of e)g.push(at.fadeAction(o,0,!1)),I.push(at.fadeAction(o,0,!0));A.addBehavior(new cg("Select "+this.selfModel.name,pI.tapTrigger(this.selfModel),at.parallel(...I))),A.addBehavior(new cg("Start hidden "+this.selfModel.name,pI.sceneStartTrigger(),at.parallel(...g)))}createVariants(){if(!this.variantMaterial)return null;const A=[];for(const e of this.targetModels){const t=e.clone();t.name+=" variant_"+this.variantMaterial.name,t.name=t.name.replace(/\s/g,"_"),t.material=this.variantMaterial,t.geometry=e.geometry,t.matrix=e.matrix,(!e.parent||!e.parent.isEmpty())&&ho.createEmptyParent(e),e.parent&&e.parent.add(t),A.push(t)}return A}},r(W0,"_materialTriggersPerId",{}),W0);let yd=iQ;Ht([w(Ke)],yd.prototype,"materialToSwitch",2);Ht([w(Ke)],yd.prototype,"variantMaterial",2);class OE extends MA{constructor(){super(...arguments);r(this,"target");r(this,"toggleOnClick",!1);r(this,"targetState",!0);r(this,"hideSelf",!0);r(this,"selfModel");r(this,"otherModel");r(this,"toggleModel");r(this,"stateBeforeCreatingDocument",!1)}onPointerClick(){!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}createBehaviours(e,t,g){t.uuid===this.gameObject.uuid&&(this.selfModel=t)}beforeCreateDocument(){this.stateBeforeCreatingDocument=this.gameObject.visible,this.gameObject.visible=!0}afterCreateDocument(e,t){if(this.target){if(this.otherModel=t.document.findById(this.target.uuid),this.selfModel&&this.otherModel){let g=this.hideSelf;this.targetState,this.toggleOnClick&&(g=!0,this.target.visible,(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&ET.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.clone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel));const I=[];if(g&&I.push(at.fadeAction(this.selfModel,0,!1)),this.toggleModel&&I.push(at.fadeAction(this.toggleModel,0,!0)),I.push(at.fadeAction(this.otherModel,0,this.targetState)),e.addBehavior(new cg("Toggle_"+this.selfModel.name+"_hideSelf",pI.tapTrigger(this.selfModel),at.sequence(...I))),this.toggleOnClick&&this.toggleModel){const o=[];o.push(at.fadeAction(this.toggleModel,0,!1)),o.push(at.fadeAction(this.selfModel,0,!0)),o.push(at.fadeAction(this.otherModel,0,!this.targetState)),e.addBehavior(new cg("Toggle_"+this.selfModel.name+"_toggleSelf",pI.tapTrigger(this.toggleModel),at.sequence(...o))),e.addBehavior(new cg("HideOnStart_"+this.gameObject.name,pI.sceneStartTrigger(),at.fadeAction(this.toggleModel,0,!1)))}}this.gameObject.visible=this.stateBeforeCreatingDocument}}}Ht([w(UA)],OE.prototype,"target",2);Ht([w()],OE.prototype,"targetState",2);Ht([w()],OE.prototype,"hideSelf",2);class SR extends MA{start(){this.gameObject.visible=!1}createBehaviours(A,e,t){e.uuid===this.gameObject.uuid&&A.addBehavior(new cg("HideOnStart_"+this.gameObject.name,pI.sceneStartTrigger(),at.fadeAction(e,0,!1)))}beforeCreateDocument(){this.gameObject.visible=!0}afterCreateDocument(){this.gameObject.visible=!1}}class PE extends MA{constructor(){super(...arguments);r(this,"target");r(this,"duration",.5);r(this,"motionType",mm.bounce)}beforeCreateDocument(){}createBehaviours(e,t,g){if(this.target&&t.uuid===this.gameObject.uuid){const I=new cg("emphasize "+this.name,pI.tapTrigger(this.gameObject),at.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(I)}}afterCreateDocument(e,t){}}Ht([w()],PE.prototype,"target",2);Ht([w()],PE.prototype,"duration",2);Ht([w()],PE.prototype,"motionType",2);class WE extends MA{constructor(){super(...arguments);r(this,"target");r(this,"clip","");r(this,"toggleOnClick",!1)}onPointerClick(){if(!(!this.target&&!this.clip)){if(!this.target){const e=this.gameObject.addNewComponent(Fi);e&&(e.spatialBlend=1,e.volume=1,e.loop=!1,this.target=e)}this.target&&(this.target.isPlaying&&this.toggleOnClick?this.target.stop():(!this.toggleOnClick&&this.target.isPlaying&&this.target.stop(),this.clip?this.target.play(this.clip):this.target.play()))}}createBehaviours(e,t,g){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const I=this.clip?this.clip:this.target?this.target.clip:void 0;if(!I)return;const o=this.target?this.target.gameObject:this.gameObject,C=I.split("/").pop(),s=this.target?this.target.volume:1,n=this.target&&this.target.spatialBlend==0?hG.NonSpatial:hG.Spatial,a=new cg("playAudio "+this.name,pI.tapTrigger(this.gameObject),at.playAudioAction(o,"audio/"+C,DT.Play,s,n));e.addBehavior(a)}}async afterSerialize(e,t){if(!this.target&&!this.clip)return;const g=this.clip?this.clip:this.target?this.target.clip:void 0;if(!g)return;const I=g.split("/").pop(),s=await(await(await fetch(this.clip)).blob()).arrayBuffer(),n=new Uint8Array(s);t.files["audio/"+I]=n}}Ht([w(Fi)],WE.prototype,"target",2);Ht([w(URL)],WE.prototype,"clip",2);Ht([w()],WE.prototype,"toggleOnClick",2);var V0;const gQ=(V0=class extends MA{constructor(){super(...arguments);r(this,"target");r(this,"animator");r(this,"stateName");r(this,"stateNameAfterPlaying");r(this,"loopAfterPlaying",!1);r(this,"selfModel");r(this,"stateAnimationModel");r(this,"stateAnimation");r(this,"stateAfterPlayingAnimationModel");r(this,"stateAfterPlayingAnimation")}onPointerClick(){var A;this.target&&this.stateName&&((A=this.animator)==null||A.play(this.stateName,0,0,.1))}createBehaviours(A,e,t){e.uuid===this.gameObject.uuid&&(this.selfModel=e)}onAfterHierarchy(){gQ.animationActions=[]}afterCreateDocument(A,e){if(!this.stateAnimation||!this.stateAnimationModel)return;e.document.traverse(g=>{var I,o;if(g.uuid===((I=this.target)==null?void 0:I.uuid)&&this.stateAnimation){const C=[];let s=gQ.animationActions.find(a=>a.affectedObjects==g&&a.start==this.stateAnimation.start&&a.duration==this.stateAnimation.duration);if(s||(s=at.startAnimationAction(g,this.stateAnimation.start,this.stateAnimation.duration),gQ.animationActions.push(s)),C.push(s),this.stateAfterPlayingAnimation&&this.stateAfterPlayingAnimationModel){let a=gQ.animationActions.find(Q=>Q.affectedObjects==g&&Q.start==this.stateAfterPlayingAnimation.start&&Q.duration==this.stateAfterPlayingAnimation.duration);a||(a=at.startAnimationAction(g,this.stateAfterPlayingAnimation.start,this.stateAfterPlayingAnimation.duration),gQ.animationActions.push(a));const B=at.sequence(a);this.loopAfterPlaying&&B.makeLooping(),C.push(B)}const n=new cg("tap "+this.name+" for "+this.stateName+" on "+((o=this.target)==null?void 0:o.name),pI.tapTrigger(this.selfModel),at.sequence(...C));A.addBehavior(n)}})}createAnimation(A,e,t){var g,I,o,C;if(this.target&&this.animator){const s=(I=(g=this.animator)==null?void 0:g.runtimeAnimatorController)==null?void 0:I.findState(this.stateName);this.stateAnimationModel=e,this.stateAnimation=A.registerAnimation(this.target,s==null?void 0:s.motion.clip);const n=(C=(o=this.animator)==null?void 0:o.runtimeAnimatorController)==null?void 0:C.findState(this.stateNameAfterPlaying);this.stateAfterPlayingAnimationModel=e,this.stateAfterPlayingAnimation=A.registerAnimation(this.target,n==null?void 0:n.motion.clip)}}},r(V0,"animationActions",[]),V0);let ba=gQ;Ht([w(UA)],ba.prototype,"target",2);Ht([w(wI)],ba.prototype,"animator",2);Ht([w()],ba.prototype,"stateName",2);Ht([w()],ba.prototype,"stateNameAfterPlaying",2);Ht([w()],ba.prototype,"loopAfterPlaying",2);class VE extends MA{constructor(){super(...arguments);r(this,"target")}getType(){}getDuration(){}}Ht([w(UA)],VE.prototype,"target",2);class Sd extends MA{constructor(){super(...arguments);r(this,"target")}}Ht([w(VE)],Sd.prototype,"target",2);class kd extends VE{constructor(){super(...arguments);r(this,"type",1);r(this,"duration",1)}getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Ht([w()],kd.prototype,"type",2);Ht([w()],kd.prototype,"duration",2);class kR extends Sd{}var niA=Object.defineProperty,aiA=Object.getOwnPropertyDescriptor,En=(i,A,e,t)=>{for(var g=t>1?void 0:t?aiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&niA(A,e,g),g};class nB extends MA{constructor(){super(...arguments);r(this,"center",new k(0,0,0));r(this,"radius",.5);r(this,"height",2);r(this,"_rigidbody",null);r(this,"_activeGroundCollisions",new Set)}get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(jt),this._rigidbody||(this._rigidbody=this.gameObject.addNewComponent(jt)),this.rigidbody)}onEnable(){let e=this.rigidbody,t=this.gameObject.getComponent(Da);t||(t=this.gameObject.addNewComponent(Da)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height,this.gameObject.rotation.x=0,this.gameObject.rotation.z=0,e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}onCollisionEnter(e){for(const t of e.contacts)if(t.normal.y>.1){this._activeGroundCollisions.add(e);break}}onCollisionExit(e){this._activeGroundCollisions.delete(e)}get isGrounded(){return this._activeGroundCollisions.size>0}}En([w(k)],nB.prototype,"center",2);En([w()],nB.prototype,"radius",2);En([w()],nB.prototype,"height",2);class cn extends MA{constructor(){super(...arguments);r(this,"controller");r(this,"movementSpeed",2);r(this,"rotationSpeed",2);r(this,"jumpForce",1);r(this,"doubleJumpForce",2);r(this,"animator");r(this,"lookForward",!0);r(this,"_currentSpeed",new k(0,0,0));r(this,"_currentAngularSpeed",new k(0,0,0));r(this,"_temp",new k(0,0,0));r(this,"_jumpCount",0);r(this,"_currentRotation");r(this,"_raycastOptions",new CC)}awake(){this._currentRotation=new kA}update(){var n,a,B,Q,E,c,h,l,d,p,u;(n=this.controller)!=null&&n.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&((a=this.animator)==null||a.setBool("doubleJump",!1)));const e=this.context.input.isKeyPressed("w"),t=this.context.input.isKeyPressed("s"),g=this.context.input.isKeyPressed("a"),I=this.context.input.isKeyPressed("d"),o=this.context.input.isKeyDown(" "),C=(e?1:0)+(t?-1:0);this._currentSpeed.z+=C*this.movementSpeed*this.context.time.deltaTime,(B=this.animator)==null||B.setBool("running",C!=0),(E=this.animator)==null||E.setBool("jumping",((Q=this.controller)==null?void 0:Q.isGrounded)===!0&&o),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp);const s=(g?1:0)+(I?-1:0);if(this._currentAngularSpeed.y+=Ae.toRadians(s*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const D=this.context.mainCameraComponent.forward;D.y=0,D.normalize(),this._currentRotation.setFromUnitVectors(new k(0,0,1),D),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&o&&this.jumpForce>0){let D=(c=this.controller)==null?void 0:c.isGrounded;if(this.doubleJumpForce>0&&!((h=this.controller)!=null&&h.isGrounded)&&this._jumpCount===1&&(D=!0,(l=this.animator)==null||l.setBool("doubleJump",!0)),D){this._jumpCount+=1;const y=this.controller.rigidbody,S=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;y.applyImpulse(new k(0,1,0).multiplyScalar(S))}}if(this.controller){const D=(d=this.controller)==null?void 0:d.rigidbody.getVelocity().y;if(D<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new on),this._raycastOptions.ray.origin.copy(ye(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const y=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const S=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(y),(S.length&&S[0].distance>2||D<-10)&&((p=this.animator)==null||p.setBool("falling",!0))}else(u=this.animator)==null||u.setBool("falling",!1)}}}En([w(nB)],cn.prototype,"controller",2);En([w()],cn.prototype,"movementSpeed",2);En([w()],cn.prototype,"rotationSpeed",2);En([w()],cn.prototype,"jumpForce",2);En([w()],cn.prototype,"doubleJumpForce",2);En([w(wI)],cn.prototype,"animator",2);var riA=Object.defineProperty,BiA=Object.getOwnPropertyDescriptor,QiA=(i,A,e,t)=>{for(var g=t>1?void 0:t?BiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&riA(A,e,g),g};class Gd extends eI{constructor(){super(...arguments);r(this,"intensity")}get typeName(){return"ChromaticAberration"}init(){this.intensity.defaultValue=0}onCreateEffect(){const e=new Nx;return e.offset=new j(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=t=>t*.02,this.intensity.onValueChanged=t=>{e.offset.x=-t,e.offset.y=t},e}}QiA([w(ve)],Gd.prototype,"intensity",2);$C("ChromaticAberration",Gd);var EiA=Object.defineProperty,ciA=Object.getOwnPropertyDescriptor,jw=(i,A,e,t)=>{for(var g=t>1?void 0:t?ciA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&EiA(A,e,g),g};class La extends eI{constructor(){super(...arguments);r(this,"postExposure");r(this,"contrast");r(this,"hueShift");r(this,"saturation")}get typeName(){return"ColorAdjustments"}init(){this.postExposure.valueProcessor=e=>(e=Math.pow(2,e),e),this.postExposure.defaultValue=0,this.contrast.valueProcessor=e=>{let t=1;return e>0?t=200:e<0&&(t=100),e/t},this.contrast.defaultValue=0,this.hueShift.valueProcessor=e=>Math.PI*e/180,this.hueShift.defaultValue=0,this.saturation.valueProcessor=e=>e<0?e/100:e/(100*Math.PI),this.saturation.defaultValue=0}unapply(){this.context.renderer.toneMappingExposure=1}onCreateEffect(){this.context.renderer.toneMapping===Pg&&this.postExposure.overrideState&&(this.context.renderer.toneMapping=Jh);const e=new Fx;this.postExposure.onValueChanged=g=>{this.context.renderer.toneMapping===Pg&&(this.context.renderer.toneMapping=Jh),this.context.renderer.toneMappingExposure=g},this.contrast.onValueChanged=g=>{e.contrast=g};const t=new Jx;return this.hueShift.onValueChanged=g=>t.hue=g,this.saturation.onValueChanged=g=>t.saturation=g,[t,e]}}jw([w(ve)],La.prototype,"postExposure",2);jw([w(ve)],La.prototype,"contrast",2);jw([w(ve)],La.prototype,"hueShift",2);jw([w(ve)],La.prototype,"saturation",2);$C("ColorAdjustments",La);const hiA=(Math.sqrt(5)-1)/4,Cg=(5-Math.sqrt(5))/20,iD=i=>Math.floor(i)|0,gD=new Float64Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]);function liA(i=Math.random){const A=diA(i),e=new Float64Array(A).map(o=>gD[o%32*4]),t=new Float64Array(A).map(o=>gD[o%32*4+1]),g=new Float64Array(A).map(o=>gD[o%32*4+2]),I=new Float64Array(A).map(o=>gD[o%32*4+3]);return function(C,s,n,a){let B,Q,E,c,h;const l=(C+s+n+a)*hiA,d=iD(C+l),p=iD(s+l),u=iD(n+l),D=iD(a+l),y=(d+p+u+D)*Cg,S=d-y,R=p-y,f=u-y,M=D-y,U=C-S,J=s-R,T=n-f,Y=a-M;let b=0,_=0,AA=0,$=0;U>J?b++:_++,U>T?b++:AA++,U>Y?b++:$++,J>T?_++:AA++,J>Y?_++:$++,T>Y?AA++:$++;const X=b>=3?1:0,cA=_>=3?1:0,EA=AA>=3?1:0,NA=$>=3?1:0,uA=b>=2?1:0,gA=_>=2?1:0,aA=AA>=2?1:0,GA=$>=2?1:0,P=b>=1?1:0,vA=_>=1?1:0,KA=AA>=1?1:0,jA=$>=1?1:0,wA=U-X+Cg,ne=J-cA+Cg,dA=T-EA+Cg,lA=Y-NA+Cg,qA=U-uA+2*Cg,ee=J-gA+2*Cg,VA=T-aA+2*Cg,Ee=Y-GA+2*Cg,re=U-P+3*Cg,oe=J-vA+3*Cg,Oe=T-KA+3*Cg,qe=Y-jA+3*Cg,v=U-1+4*Cg,K=J-1+4*Cg,BA=T-1+4*Cg,RA=Y-1+4*Cg,JA=d&255,PA=p&255,ae=u&255,_A=D&255;let q=.6-U*U-J*J-T*T-Y*Y;if(q<0)B=0;else{const xA=JA+A[PA+A[ae+A[_A]]];q*=q,B=q*q*(e[xA]*U+t[xA]*J+g[xA]*T+I[xA]*Y)}let pA=.6-wA*wA-ne*ne-dA*dA-lA*lA;if(pA<0)Q=0;else{const xA=JA+X+A[PA+cA+A[ae+EA+A[_A+NA]]];pA*=pA,Q=pA*pA*(e[xA]*wA+t[xA]*ne+g[xA]*dA+I[xA]*lA)}let XA=.6-qA*qA-ee*ee-VA*VA-Ee*Ee;if(XA<0)E=0;else{const xA=JA+uA+A[PA+gA+A[ae+aA+A[_A+GA]]];XA*=XA,E=XA*XA*(e[xA]*qA+t[xA]*ee+g[xA]*VA+I[xA]*Ee)}let TA=.6-re*re-oe*oe-Oe*Oe-qe*qe;if(TA<0)c=0;else{const xA=JA+P+A[PA+vA+A[ae+KA+A[_A+jA]]];TA*=TA,c=TA*TA*(e[xA]*re+t[xA]*oe+g[xA]*Oe+I[xA]*qe)}let WA=.6-v*v-K*K-BA*BA-RA*RA;if(WA<0)h=0;else{const xA=JA+1+A[PA+1+A[ae+1+A[_A+1]]];WA*=WA,h=WA*WA*(e[xA]*v+t[xA]*K+g[xA]*BA+I[xA]*RA)}return 27*(B+Q+E+c+h)}}function diA(i){const e=new Uint8Array(512);for(let t=0;t<512/2;t++)e[t]=t;for(let t=0;t<512/2-1;t++){const g=t+~~(i()*(256-t)),I=e[t];e[t]=e[g],e[g]=I}for(let t=256;t<512;t++)e[t]=e[t-256];return e}var uiA=Object.defineProperty,DiA=Object.getOwnPropertyDescriptor,Z=(i,A,e,t)=>{for(var g=t>1?void 0:t?DiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&uiA(A,e,g),g};const ID=rA("debugparticles");var RC=(i=>(i[i.Billboard=0]="Billboard",i[i.Stretch=1]="Stretch",i[i.HorizontalBillboard=2]="HorizontalBillboard",i[i.VerticalBillboard=3]="VerticalBillboard",i[i.Mesh=4]="Mesh",i))(RC||{});class va{constructor(){r(this,"alphaKeys");r(this,"colorKeys")}get duration(){return 1}evaluate(A,e){let t,g=0,I=null,o=0;for(let C=0;C<this.alphaKeys.length;C++){const s=this.alphaKeys[C];(s.time<A||!t)&&(t=s,g=C)}for(let C=0;C<this.colorKeys.length;C++){const s=this.colorKeys[C];(s.time<A||!I)&&(I=s,o=C)}if(I)if(o+1<this.colorKeys.length){const s=this.colorKeys[o+1],n=Ae.remap(A,I.time,s.time,0,1);e.r=Ae.lerp(I.color.r,s.color.r,n),e.g=Ae.lerp(I.color.g,s.color.g,n),e.b=Ae.lerp(I.color.b,s.color.b,n)}else e.r=I.color.r,e.g=I.color.g,e.b=I.color.b;if(t)if(g+1<this.alphaKeys.length){const s=this.alphaKeys[g+1],n=Ae.remap(A,t.time,s.time,0,1);e.alpha=Ae.lerp(t.alpha,s.alpha,n)}else e.alpha=t.alpha;return e}}Z([w()],va.prototype,"alphaKeys",2);Z([w()],va.prototype,"colorKeys",2);var zw=(i=>(i[i.Local=0]="Local",i[i.World=1]="World",i[i.Custom=2]="Custom",i))(zw||{}),I_=(i=>(i[i.Sphere=0]="Sphere",i[i.SphereShell=1]="SphereShell",i[i.Hemisphere=2]="Hemisphere",i[i.HemisphereShell=3]="HemisphereShell",i[i.Cone=4]="Cone",i[i.Box=5]="Box",i[i.Mesh=6]="Mesh",i[i.ConeShell=7]="ConeShell",i[i.ConeVolume=8]="ConeVolume",i[i.ConeVolumeShell=9]="ConeVolumeShell",i[i.Circle=10]="Circle",i[i.CircleEdge=11]="CircleEdge",i[i.SingleSidedEdge=12]="SingleSidedEdge",i[i.MeshRenderer=13]="MeshRenderer",i[i.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",i[i.BoxShell=15]="BoxShell",i[i.BoxEdge=16]="BoxEdge",i[i.Donut=17]="Donut",i[i.Rectangle=18]="Rectangle",i[i.Sprite=19]="Sprite",i[i.SpriteRenderer=20]="SpriteRenderer",i))(I_||{});class se{constructor(){r(this,"mode");r(this,"constant");r(this,"constantMin");r(this,"constantMax");r(this,"curve");r(this,"curveMin");r(this,"curveMax");r(this,"curveMultiplier")}evaluate(A,e){const t=e===void 0?Math.random():e;switch(this.mode){case 0:return this.constant;case 1:return A=Ae.clamp01(A),this.curve.evaluate(A)*this.curveMultiplier;case 2:const g=A*this.curveMin.duration,I=A*this.curveMax.duration;return Ae.lerp(this.curveMin.evaluate(g),this.curveMax.evaluate(I),t%1)*this.curveMultiplier;case 3:return Ae.lerp(this.constantMin,this.constantMax,t%1);default:this.curveMax.evaluate(A)*this.curveMultiplier;break}return 0}getMax(){switch(this.mode){case 0:return this.constant;case 1:return this.getMaxFromCurve(this.curve)*this.curveMultiplier;case 2:return Math.max(this.getMaxFromCurve(this.curveMin),this.getMaxFromCurve(this.curveMax))*this.curveMultiplier;case 3:return Math.max(this.constantMin,this.constantMax);default:return 0}}getMaxFromCurve(A){if(!A)return 0;let e=Number.MIN_VALUE;for(let t=0;t<A.keys.length;t++){const g=A.keys[t];g.value>e&&(e=g.value)}return e}}Z([w()],se.prototype,"mode",2);Z([w()],se.prototype,"constant",2);Z([w()],se.prototype,"constantMin",2);Z([w()],se.prototype,"constantMax",2);Z([w(AB)],se.prototype,"curve",2);Z([w(AB)],se.prototype,"curveMin",2);Z([w(AB)],se.prototype,"curveMax",2);Z([w()],se.prototype,"curveMultiplier",2);var DD;const xo=(DD=class{constructor(){r(this,"mode");r(this,"color");r(this,"colorMin");r(this,"colorMax");r(this,"gradient");r(this,"gradientMin");r(this,"gradientMax")}evaluate(i,A){const e=A===void 0?Math.random():A;switch(this.mode){case 0:return this.color;case 1:return this.gradient.evaluate(i,xo._temp),xo._temp;case 2:return xo._temp.lerpColors(this.colorMin,this.colorMax,e);case 3:return this.gradientMin.evaluate(i,xo._temp),this.gradientMax.evaluate(i,xo._temp2),xo._temp.lerp(xo._temp2,e)}return xo._temp.set(16711935),xo._temp.alpha=1,xo._temp}},r(DD,"_temp",new Gt(0,0,0,1)),r(DD,"_temp2",new Gt(0,0,0,1)),DD);let yI=xo;Z([w(Gt)],yI.prototype,"color",2);Z([w(Gt)],yI.prototype,"colorMin",2);Z([w(Gt)],yI.prototype,"colorMax",2);Z([w(va)],yI.prototype,"gradient",2);Z([w(va)],yI.prototype,"gradientMin",2);Z([w(va)],yI.prototype,"gradientMax",2);class ug{constructor(){r(this,"cullingMode");r(this,"duration");r(this,"emitterVelocityMode");r(this,"flipRotation");r(this,"gravityModifier");r(this,"gravityModifierMultiplier");r(this,"loop");r(this,"maxParticles");r(this,"playOnAwake");r(this,"prewarm");r(this,"ringBufferLoopRange");r(this,"ringBufferMode");r(this,"scalingMode");r(this,"simulationSpace");r(this,"simulationSpeed");r(this,"startColor");r(this,"startDelay");r(this,"startDelayMultiplier");r(this,"startLifetime");r(this,"startLifetimeMultiplier");r(this,"startRotation");r(this,"startRotationMultiplier");r(this,"startRotation3D");r(this,"startRotationX");r(this,"startRotationXMultiplier");r(this,"startRotationY");r(this,"startRotationYMultiplier");r(this,"startRotationZ");r(this,"startRotationZMultiplier");r(this,"startSize");r(this,"startSize3D");r(this,"startSizeMultiplier");r(this,"startSizeX");r(this,"startSizeXMultiplier");r(this,"startSizeY");r(this,"startSizeYMultiplier");r(this,"startSizeZ");r(this,"startSizeZMultiplier");r(this,"startSpeed");r(this,"startSpeedMultiplier");r(this,"stopAction");r(this,"useUnscaledTime")}}Z([w(se)],ug.prototype,"gravityModifier",2);Z([w(yI)],ug.prototype,"startColor",2);Z([w(se)],ug.prototype,"startDelay",2);Z([w(se)],ug.prototype,"startLifetime",2);Z([w(se)],ug.prototype,"startRotation",2);Z([w(se)],ug.prototype,"startRotationX",2);Z([w(se)],ug.prototype,"startRotationY",2);Z([w(se)],ug.prototype,"startRotationZ",2);Z([w(se)],ug.prototype,"startSize",2);Z([w(se)],ug.prototype,"startSizeX",2);Z([w(se)],ug.prototype,"startSizeY",2);Z([w(se)],ug.prototype,"startSizeZ",2);Z([w(se)],ug.prototype,"startSpeed",2);class Bl{constructor(){r(this,"cycleCount");r(this,"maxCount");r(this,"minCount");r(this,"probability");r(this,"repeatInterval");r(this,"time");r(this,"count");r(this,"_performed",0)}reset(){this._performed=0}run(A){if(A<=this.time)return this.reset(),0;let e=0;if(this.cycleCount===0||this._performed<this.cycleCount){const t=this.time+this.repeatInterval*this._performed;if(A>=t&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:e=this.count.constant;break;case 3:e=Ae.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:e=this.count.curve.evaluate(Math.random());break;case 2:const g=Math.random();e=Ae.lerp(this.count.curveMin.evaluate(g),this.count.curveMax.evaluate(g),Math.random());break}}return e}}class ts{constructor(){r(this,"enabled");r(this,"bursts");r(this,"rateOverTime");r(this,"rateOverTimeMultiplier");r(this,"rateOverDistance");r(this,"rateOverDistanceMultiplier");r(this,"system")}get burstCount(){var A;return((A=this.bursts)==null?void 0:A.length)??0}reset(){var A;(A=this.bursts)==null||A.forEach(e=>e.reset())}getBurst(){let A=0;if(this.burstCount>0)for(let e=0;e<this.burstCount;e++){const t=this.bursts[e];t.time>=this.system.time&&t.reset(),A+=Math.round(t.run(this.system.time))}return A}}Z([w()],ts.prototype,"enabled",2);Z([w()],ts.prototype,"bursts",2);Z([w(se)],ts.prototype,"rateOverTime",2);Z([w()],ts.prototype,"rateOverTimeMultiplier",2);Z([w(se)],ts.prototype,"rateOverDistance",2);Z([w()],ts.prototype,"rateOverDistanceMultiplier",2);class Md{constructor(){r(this,"enabled");r(this,"color")}}Z([w(yI)],Md.prototype,"color",2);class xa{constructor(){r(this,"enabled");r(this,"separateAxes");r(this,"size");r(this,"sizeMultiplier");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier");r(this,"_time",0);r(this,"_temp",new k)}evaluate(A,e,t){if(e||(e=this._temp),!this.enabled)return e.x=e.y=e.z=1,e;if(this.separateAxes)e.x=this.x.evaluate(A,t)*this.xMultiplier,e.y=this.y.evaluate(A,t)*this.yMultiplier,e.z=this.z.evaluate(A,t)*this.zMultiplier;else{const g=this.size.evaluate(A,t)*this.sizeMultiplier;e.x=g}return e}}Z([w(se)],xa.prototype,"size",2);Z([w(se)],xa.prototype,"x",2);Z([w(se)],xa.prototype,"y",2);Z([w(se)],xa.prototype,"z",2);var pD;const jc=(pD=class{constructor(){r(this,"shapeType",5);r(this,"enabled",!0);r(this,"alignToDirection",!1);r(this,"angle",0);r(this,"arc",360);r(this,"arcSpread");r(this,"arcSpeedMultiplier");r(this,"arcMode");r(this,"boxThickness");r(this,"position");r(this,"rotation");r(this,"_rotation",new Ui);r(this,"scale");r(this,"radius");r(this,"radiusThickness");r(this,"sphericalDirectionAmount");r(this,"randomDirectionAmount");r(this,"randomPositionAmount");r(this,"system");r(this,"_space");r(this,"_worldSpaceMatrix",new OA);r(this,"_worldSpaceMatrixInverse",new OA);r(this,"_vector",new k(0,0,0));r(this,"_temp",new k(0,0,0));r(this,"_dir",new k);r(this,"_loopTime",0);r(this,"_loopDirection",1);ID&&console.log(this)}get type(){return I_[this.shapeType]}initialize(i){this.getPosition(),i.position.copy(this._vector)}toJSON(){return this}clone(){return new jc}update(i,A,e,t){this.system=i,this._space=e,e===1&&(this._worldSpaceMatrix.copy(t.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(i){const A=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return A&&(this._rotation.x=Ae.toRadians(this.rotation.x),this._rotation.y=Ae.toRadians(this.rotation.y),this._rotation.z=Ae.toRadians(this.rotation.z),this._rotation.order="ZYX",i.applyEuler(this._rotation)),A}get vector(){return this._vector}getPosition(){this._vector.set(0,0,0);const i=this._temp.copy(this.position),A=this._space===1;A&&i.applyQuaternion(this.system.worldQuaternion);let e=this.radius;if(A&&(e*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:ID&&KC.DrawBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(i);break;case 4:this.randomConePoint(this.position,this.angle,e,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,e,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,e,this.radiusThickness,this.arc,this._vector);break;default:this._vector.set(0,0,0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),A&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),ID&&KC.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(i){var A;if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const e=i.x,t=i.y,g=i.z;this._dir.set(e,t,g),(A=this.system)!=null&&A.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),ID&&(KC.DrawSphere(i,.01,8925952,.5,!0),KC.DrawDirection(i,this._dir,8925952,.5,!0)),this._dir}randomizePosition(i,A){if(A<=0)return;const e=jc._tempVec;e.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),e.x*=A*this.scale.x,e.y*=A*this.scale.y,e.z*=A*this.scale.z,i.add(e)}randomizeDirection(i,A){if(A===0)return;const e=jc._randomQuat,t=jc._tempVec;t.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),e.setFromAxisAngle(t,A*Math.random()*Math.PI),i.applyQuaternion(e)}spherizeDirection(i,A){if(A===0)return;const e=Math.random()*Math.PI*2,t=Math.acos(1-Math.random()*2),g=Math.sin(t)*Math.cos(e),I=Math.sin(t)*Math.sin(e),o=Math.cos(t),C=new k(g,I,o);i.lerp(C,A)}randomSpherePoint(i,A,e,t,g){const I=Math.random(),o=Math.random(),C=2*Math.PI*I*(t/360),s=Math.acos(2*o-1),n=Ae.lerp(1,1-Math.pow(1-Math.random(),Math.PI),e)*A,a=i.x+this.scale.x*(-n*Math.sin(s)*Math.cos(C)),B=i.y+this.scale.y*(n*Math.sin(s)*Math.sin(C)),Q=i.z+this.scale.z*(n*Math.cos(s));g.x=a,g.y=B,g.z=Q}randomCirclePoint(i,A,e,t,g){const I=Math.random(),o=2*Math.PI*I*(t/360),C=Ae.lerp(1,1-Math.pow(1-Math.random(),Math.PI),e)*A,s=i.x+this.scale.x*C*Math.cos(o),n=i.y+this.scale.y*C*Math.sin(o),a=i.z;g.x=s,g.y=n,g.z=a}randomConePoint(i,A,e,t,g,I,o){let C=0,s=0;switch(I){case 0:C=Math.random(),s=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:C=.5,s=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let n=2*Math.PI*C*(g/360);switch(I){case 2:case 1:n+=Math.PI+.5,n+=this._loopTime*Math.PI*2,n%=Ae.toRadians(g);break}const a=Math.acos(2*s-1),B=Ae.lerp(1,1-Math.pow(1-Math.random(),Math.PI),t)*e,Q=i.x+-B*Math.sin(a)*Math.cos(n),E=i.y+B*Math.sin(a)*Math.sin(n),c=i.z;o.x=Q*this.scale.x,o.y=E*this.scale.y,o.z=c*this.scale.z}},r(pD,"_randomQuat",new kA),r(pD,"_tempVec",new k),pD);let Di=jc;Z([w()],Di.prototype,"shapeType",2);Z([w()],Di.prototype,"enabled",2);Z([w()],Di.prototype,"alignToDirection",2);Z([w()],Di.prototype,"angle",2);Z([w()],Di.prototype,"arc",2);Z([w()],Di.prototype,"arcSpread",2);Z([w()],Di.prototype,"arcSpeedMultiplier",2);Z([w()],Di.prototype,"arcMode",2);Z([w(k)],Di.prototype,"boxThickness",2);Z([w(k)],Di.prototype,"position",2);Z([w(k)],Di.prototype,"rotation",2);Z([w(k)],Di.prototype,"scale",2);Z([w()],Di.prototype,"radius",2);Z([w()],Di.prototype,"radiusThickness",2);Z([w()],Di.prototype,"sphericalDirectionAmount",2);Z([w()],Di.prototype,"randomDirectionAmount",2);Z([w()],Di.prototype,"randomPositionAmount",2);class lt{constructor(){r(this,"damping");r(this,"enabled");r(this,"frequency");r(this,"octaveCount");r(this,"octaveMultiplier");r(this,"octaveScale");r(this,"positionAmount");r(this,"quality");r(this,"remap");r(this,"remapEnabled");r(this,"remapMultiplier");r(this,"remapX");r(this,"remapXMultiplier");r(this,"remapY");r(this,"remapYMultiplier");r(this,"remapZ");r(this,"remapZMultiplier");r(this,"scrollSpeedMultiplier");r(this,"separateAxes");r(this,"strengthMultiplier");r(this,"strengthX");r(this,"strengthXMultiplier");r(this,"strengthY");r(this,"strengthYMultiplier");r(this,"strengthZ");r(this,"strengthZMultiplier");r(this,"_noise");r(this,"_time",0);r(this,"_temp",new k)}update(A){this._time+=A.time.deltaTime*this.scrollSpeedMultiplier}apply(A,e,t,g,I,o){if(!this.enabled)return;this._noise||(this._noise=liA(()=>0));const C=this._temp.set(e.x,e.y,e.z).multiplyScalar(this.frequency),s=this._noise(C.x,C.y,C.z,this._time),n=this._noise(C.x,C.y,C.z,this._time+1e3*this.frequency),a=this._noise(C.x,C.y,C.z,this._time+2e3*this.frequency);this._temp.set(s,n,a).normalize();const B=I/o;let Q=this.positionAmount.evaluate(B);this.separateAxes?(this._temp.x*=Q*this.strengthXMultiplier,this._temp.y*=Q*this.strengthYMultiplier,this._temp.z*=Q*this.strengthZMultiplier):(this.strengthX&&(Q*=this.strengthX.evaluate(B)*1.5),this._temp.multiplyScalar(Q)),t.x+=this._temp.x,t.y+=this._temp.y,t.z+=this._temp.z}}Z([w()],lt.prototype,"damping",2);Z([w()],lt.prototype,"enabled",2);Z([w()],lt.prototype,"frequency",2);Z([w()],lt.prototype,"octaveCount",2);Z([w()],lt.prototype,"octaveMultiplier",2);Z([w()],lt.prototype,"octaveScale",2);Z([w(se)],lt.prototype,"positionAmount",2);Z([w()],lt.prototype,"quality",2);Z([w(se)],lt.prototype,"remap",2);Z([w()],lt.prototype,"remapEnabled",2);Z([w()],lt.prototype,"remapMultiplier",2);Z([w(se)],lt.prototype,"remapX",2);Z([w()],lt.prototype,"remapXMultiplier",2);Z([w(se)],lt.prototype,"remapY",2);Z([w()],lt.prototype,"remapYMultiplier",2);Z([w(se)],lt.prototype,"remapZ",2);Z([w()],lt.prototype,"remapZMultiplier",2);Z([w()],lt.prototype,"scrollSpeedMultiplier",2);Z([w()],lt.prototype,"separateAxes",2);Z([w()],lt.prototype,"strengthMultiplier",2);Z([w(se)],lt.prototype,"strengthX",2);Z([w()],lt.prototype,"strengthXMultiplier",2);Z([w(se)],lt.prototype,"strengthY",2);Z([w()],lt.prototype,"strengthYMultiplier",2);Z([w(se)],lt.prototype,"strengthZ",2);Z([w()],lt.prototype,"strengthZMultiplier",2);class _t{constructor(){r(this,"enabled");r(this,"attachRibbonToTransform",!1);r(this,"colorOverLifetime");r(this,"colorOverTrail");r(this,"dieWithParticles",!0);r(this,"inheritParticleColor",!0);r(this,"lifetime");r(this,"lifetimeMultiplier");r(this,"minVertexDistance",.2);r(this,"mode",0);r(this,"ratio",1);r(this,"ribbonCount",1);r(this,"shadowBias",0);r(this,"sizeAffectsLifetime",!1);r(this,"sizeAffectsWidth",!1);r(this,"splitSubEmitterRibbons",!1);r(this,"textureMode",0);r(this,"widthOverTrail");r(this,"widthOverTrailMultiplier");r(this,"worldSpace",!1)}getWidth(A,e,t){let g=this.widthOverTrail.evaluate(t);return t===0&&(g=A),A*=g,A}getColor(A,e,t){const g=this.colorOverTrail.evaluate(t),I=this.colorOverLifetime.evaluate(e);A.x*=g.r*I.r,A.y*=g.g*I.g,A.z*=g.b*I.b,A.w*=g.alpha*I.alpha}}Z([w()],_t.prototype,"enabled",2);Z([w()],_t.prototype,"attachRibbonToTransform",2);Z([w(yI)],_t.prototype,"colorOverLifetime",2);Z([w(yI)],_t.prototype,"colorOverTrail",2);Z([w()],_t.prototype,"dieWithParticles",2);Z([w()],_t.prototype,"inheritParticleColor",2);Z([w(se)],_t.prototype,"lifetime",2);Z([w()],_t.prototype,"lifetimeMultiplier",2);Z([w()],_t.prototype,"minVertexDistance",2);Z([w()],_t.prototype,"mode",2);Z([w()],_t.prototype,"ratio",2);Z([w()],_t.prototype,"ribbonCount",2);Z([w()],_t.prototype,"shadowBias",2);Z([w()],_t.prototype,"sizeAffectsLifetime",2);Z([w()],_t.prototype,"sizeAffectsWidth",2);Z([w()],_t.prototype,"splitSubEmitterRibbons",2);Z([w()],_t.prototype,"textureMode",2);Z([w(se)],_t.prototype,"widthOverTrail",2);Z([w()],_t.prototype,"widthOverTrailMultiplier",2);Z([w()],_t.prototype,"worldSpace",2);class zt{constructor(){r(this,"enabled");r(this,"space",0);r(this,"orbitalX");r(this,"orbitalY");r(this,"orbitalZ");r(this,"orbitalXMultiplier");r(this,"orbitalYMultiplier");r(this,"orbitalZMultiplier");r(this,"orbitalOffsetX");r(this,"orbitalOffsetY");r(this,"orbitalOffsetZ");r(this,"speedModifier");r(this,"speedModifierMultiplier");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier");r(this,"_system");r(this,"_temp",new k);r(this,"_temp2",new k);r(this,"_temp3",new k);r(this,"_hasOrbital",!1);r(this,"_index",0);r(this,"_orbitalMatrix",new OA)}update(A){this._system=A}init(A){this._index==0&&(A.debug=!0),this._index+=1,A.orbitx=this.orbitalX.evaluate(Math.random()),A.orbity=this.orbitalY.evaluate(Math.random()),A.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=A.orbitx!=0||A.orbity!=0||A.orbitz!=0}apply(A,e,t,g,I,o,C){var E;if(!this.enabled)return;const s=o/C,n=this.speedModifier.evaluate(s)*this.speedModifierMultiplier,a=this.x.evaluate(s),B=this.y.evaluate(s),Q=this.z.evaluate(s);if(this._temp.set(-a,B,Q),this._system,this._hasOrbital&&((E=this._system)==null?void 0:E.worldPos)){const h=this._temp2.set(t.x,t.y,t.z),l=this.orbitalXMultiplier,d=this.orbitalYMultiplier,p=this.orbitalZMultiplier,u=n*Math.PI*2*10,D=Math.cos(u*l),y=Math.sin(u*l),S=Math.cos(u*d),R=Math.sin(u*d),f=Math.cos(u*p),M=Math.sin(u*p),U=h.x*(S*f)+h.y*(S*M)+h.z*-R,J=h.x*(y*R*f-D*M)+h.y*(y*R*M+D*f)+h.z*(y*S),T=h.x*(D*R*f+y*M)+h.y*(D*R*M-y*f)+h.z*(D*S),Y=this._temp3.set(h.x-U,h.y-J,h.z-T);Y.normalize(),Y.multiplyScalar(.2/I*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),g.x+=Y.x,g.y+=Y.y,g.z+=Y.z}g.x+=this._temp.x,g.y+=this._temp.y,g.z+=this._temp.z,g.x*=n,g.y*=n,g.z*=n}}Z([w()],zt.prototype,"enabled",2);Z([w()],zt.prototype,"space",2);Z([w(se)],zt.prototype,"orbitalX",2);Z([w(se)],zt.prototype,"orbitalY",2);Z([w(se)],zt.prototype,"orbitalZ",2);Z([w()],zt.prototype,"orbitalXMultiplier",2);Z([w()],zt.prototype,"orbitalYMultiplier",2);Z([w()],zt.prototype,"orbitalZMultiplier",2);Z([w()],zt.prototype,"orbitalOffsetX",2);Z([w()],zt.prototype,"orbitalOffsetY",2);Z([w()],zt.prototype,"orbitalOffsetZ",2);Z([w(se)],zt.prototype,"speedModifier",2);Z([w()],zt.prototype,"speedModifierMultiplier",2);Z([w(se)],zt.prototype,"x",2);Z([w()],zt.prototype,"xMultiplier",2);Z([w(se)],zt.prototype,"y",2);Z([w()],zt.prototype,"yMultiplier",2);Z([w(se)],zt.prototype,"z",2);Z([w()],zt.prototype,"zMultiplier",2);class Dg{constructor(){r(this,"animation");r(this,"enabled");r(this,"cycleCount");r(this,"frameOverTime");r(this,"frameOverTimeMultiplier");r(this,"numTilesX");r(this,"numTilesY");r(this,"startFrame");r(this,"startFrameMultiplier");r(this,"rowMode");r(this,"rowIndex");r(this,"spriteCount");r(this,"timeMode")}sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:case 2:case 1:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?Math.random()*(this.numTilesX*this.numTilesY):0}evaluate(A){if(!this.sampleOnceAtStart())return this.getIndex(A)}getIndex(A){const e=this.numTilesX*this.numTilesY;A=A*this.cycleCount;let t=this.frameOverTime.evaluate(A%1);return t*=this.frameOverTimeMultiplier,t*=e,t=t%e,t=Math.floor(t),t}}Z([w()],Dg.prototype,"animation",2);Z([w()],Dg.prototype,"enabled",2);Z([w()],Dg.prototype,"cycleCount",2);Z([w(se)],Dg.prototype,"frameOverTime",2);Z([w()],Dg.prototype,"frameOverTimeMultiplier",2);Z([w()],Dg.prototype,"numTilesX",2);Z([w()],Dg.prototype,"numTilesY",2);Z([w(se)],Dg.prototype,"startFrame",2);Z([w()],Dg.prototype,"startFrameMultiplier",2);Z([w()],Dg.prototype,"rowMode",2);Z([w()],Dg.prototype,"rowIndex",2);Z([w()],Dg.prototype,"spriteCount",2);Z([w()],Dg.prototype,"timeMode",2);class Ro{constructor(){r(this,"enabled");r(this,"separateAxes");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier")}evaluate(A,e){return this.enabled?this.separateAxes?0:this.z.evaluate(A,e)*-1:0}}Z([w()],Ro.prototype,"enabled",2);Z([w()],Ro.prototype,"separateAxes",2);Z([w(se)],Ro.prototype,"x",2);Z([w()],Ro.prototype,"xMultiplier",2);Z([w(se)],Ro.prototype,"y",2);Z([w()],Ro.prototype,"yMultiplier",2);Z([w(se)],Ro.prototype,"z",2);Z([w()],Ro.prototype,"zMultiplier",2);class jI{constructor(){r(this,"enabled");r(this,"range");r(this,"separateAxes");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier")}evaluate(A,e){if(!this.enabled)return 0;if(!this.separateAxes){const t=Ae.lerp(this.range.x,this.range.y,e);return this.z.evaluate(t)*-1}return 0}}Z([w()],jI.prototype,"enabled",2);Z([w()],jI.prototype,"range",2);Z([w()],jI.prototype,"separateAxes",2);Z([w(se)],jI.prototype,"x",2);Z([w()],jI.prototype,"xMultiplier",2);Z([w(se)],jI.prototype,"y",2);Z([w()],jI.prototype,"yMultiplier",2);Z([w(se)],jI.prototype,"z",2);Z([w()],jI.prototype,"zMultiplier",2);class Ji{constructor(){r(this,"enabled");r(this,"dampen");r(this,"drag");r(this,"dragMultiplier");r(this,"limit");r(this,"limitMultiplier");r(this,"separateAxes");r(this,"limitX");r(this,"limitXMultiplier");r(this,"limitY");r(this,"limitYMultiplier");r(this,"limitZ");r(this,"limitZMultiplier");r(this,"multiplyDragByParticleSize",!1);r(this,"multiplyDragByParticleVelocity",!1);r(this,"space");r(this,"_temp",new k);r(this,"_temp2",new k)}apply(A,e,t,g,I,o,C){if(this.enabled){const s=this.limit.evaluate(I)*this.limitMultiplier;if(e.length()>s){this._temp.copy(e).normalize().multiplyScalar(s);let a=this.dampen*.5;e.x=Ae.lerp(e.x,this._temp.x,a),e.y=Ae.lerp(e.y,this._temp.y,a),e.z=Ae.lerp(e.z,this._temp.z,a),t.x=Ae.lerp(t.x,this._temp.x,a),t.y=Ae.lerp(t.y,this._temp.y,a),t.z=Ae.lerp(t.z,this._temp.z,a)}}}}Z([w()],Ji.prototype,"enabled",2);Z([w()],Ji.prototype,"dampen",2);Z([w(se)],Ji.prototype,"drag",2);Z([w()],Ji.prototype,"dragMultiplier",2);Z([w(se)],Ji.prototype,"limit",2);Z([w()],Ji.prototype,"limitMultiplier",2);Z([w()],Ji.prototype,"separateAxes",2);Z([w(se)],Ji.prototype,"limitX",2);Z([w()],Ji.prototype,"limitXMultiplier",2);Z([w(se)],Ji.prototype,"limitY",2);Z([w()],Ji.prototype,"limitYMultiplier",2);Z([w(se)],Ji.prototype,"limitZ",2);Z([w()],Ji.prototype,"limitZMultiplier",2);Z([w()],Ji.prototype,"multiplyDragByParticleSize",2);Z([w()],Ji.prototype,"multiplyDragByParticleVelocity",2);Z([w()],Ji.prototype,"space",2);class Ya{constructor(){r(this,"enabled");r(this,"curve");r(this,"curveMultiplier");r(this,"mode");r(this,"system");r(this,"_lastWorldPosition");r(this,"_velocity",new k);r(this,"_temp",new k)}update(A){this.enabled&&this.system.worldspace!==!1&&(this._lastWorldPosition?(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)):(this._velocity.set(0,0,0),this._lastWorldPosition=this.system.worldPos.clone()))}applyInitial(A){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const e=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(e),A.add(this._temp)}}applyCurrent(A,e,t){if(this.enabled&&this.system.worldspace!==!1&&this.mode===1){const g=this.curve.evaluate(e,t);this._temp.copy(this._velocity).multiplyScalar(g),A.add(this._temp)}}}Z([w()],Ya.prototype,"enabled",2);Z([w(se)],Ya.prototype,"curve",2);Z([w()],Ya.prototype,"curveMultiplier",2);Z([w()],Ya.prototype,"mode",2);class tI{constructor(){r(this,"enabled");r(this,"range");r(this,"separateAxes");r(this,"size");r(this,"sizeMultiplier");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier")}evaluate(A,e,t,g){const I=A.length(),o=Ae.remap(I,this.range.x,this.range.y,0,1),C=this.size.evaluate(o,t);return g*C}}Z([w()],tI.prototype,"enabled",2);Z([w(j)],tI.prototype,"range",2);Z([w()],tI.prototype,"separateAxes",2);Z([w(se)],tI.prototype,"size",2);Z([w()],tI.prototype,"sizeMultiplier",2);Z([w(se)],tI.prototype,"x",2);Z([w()],tI.prototype,"xMultiplier",2);Z([w(se)],tI.prototype,"y",2);Z([w()],tI.prototype,"yMultiplier",2);Z([w(se)],tI.prototype,"z",2);Z([w()],tI.prototype,"zMultiplier",2);class aB{constructor(){r(this,"enabled");r(this,"range");r(this,"color")}evaluate(A,e,t){const g=A.length(),I=Ae.remap(g,this.range.x,this.range.y,0,1),o=this.color.evaluate(I,e);t.x*=o.r,t.y*=o.g,t.z*=o.b,t.w*=o.alpha}}Z([w()],aB.prototype,"enabled",2);Z([w(j)],aB.prototype,"range",2);Z([w(yI)],aB.prototype,"color",2);function piA(i){const A=i.domElement.querySelector("link[rel='ar']");if(A)return A;const e=document.createElement("div");e.classList.add("menu"),e.classList.add("quicklook-menu"),e.style.display="none",e.style.visibility="hidden";const t=document.createElement("button");t.id="open-in-ar",t.innerText="Open in QuickLook",e.appendChild(t);const g=document.createElement("a");g.id="needle-usdz-link",g.style.display="none",g.rel="ar",g.href="",e.appendChild(g);const I=document.createElement("img");return I.id="button",g.appendChild(I),i.domElement.appendChild(e),g}function fiA(){var i=new Date;const A=i.getMonth()+1,e=i.getDate(),t=i.getHours(),g=i.getMinutes(),I=i.getSeconds(),o=(A<10?"0":"")+A,C=(e<10?"0":"")+e,s=(t<10?"0":"")+t,n=(g<10?"0":"")+g,a=(I<10?"0":"")+I;return i.getFullYear()+o+C+"-"+s+n+a}const oD=rA("debugusdz");function wiA(i,A){const e=[],t=eA.getComponentsInChildren(i,wI);let g=!1;oD&&console.log(t);for(const I of t){if(!I||!I.runtimeAnimatorController)continue;oD&&console.log(I);const o=[];for(const C of I.runtimeAnimatorController.enumerateActions()){oD&&console.log(C);const s=C.getClip();if(!g&&s.tracks.length>0){g=!0;const n=s.tracks[0],a=n.name.substring(0,n.name.lastIndexOf(".")),B=new _I(a+".position",[0,.01],[0,0,0,0,0,0]),Q=new _I(a+".quaternion",[0,.01],[0,0,0,1,0,0,0,1]);o.push(new So("rest",.01,[B,Q]))}o.includes(s)||o.push(s)}e.push({root:I.gameObject,clips:o})}oD&&console.log(e);for(const I of e)for(const o of I.clips)A.registerAnimation(I.root,o)}var yiA=Object.defineProperty,SiA=Object.getOwnPropertyDescriptor,hn=(i,A,e,t)=>{for(var g=t>1?void 0:t?SiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&yiA(A,e,g),g};const u0=rA("debugtext");var vi=(i=>(i[i.UpperLeft=0]="UpperLeft",i[i.UpperCenter=1]="UpperCenter",i[i.UpperRight=2]="UpperRight",i[i.MiddleLeft=3]="MiddleLeft",i[i.MiddleCenter=4]="MiddleCenter",i[i.MiddleRight=5]="MiddleRight",i[i.LowerLeft=6]="LowerLeft",i[i.LowerCenter=7]="LowerCenter",i[i.LowerRight=8]="LowerRight",i))(vi||{});class iI extends oB{constructor(){super(...arguments);r(this,"alignment",0);r(this,"verticalOverflow",0);r(this,"horizontalOverflow",0);r(this,"lineSpacing",1);r(this,"supportRichText",!1);r(this,"font");r(this,"fontStyle",0);r(this,"_text","");r(this,"_fontSize",12);r(this,"_textMeshUi",null);r(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(e){var t;super.setAlphaFactor(e),(t=this.uiObject)==null||t.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){var t;this._fontSize=e,(t=this.uiObject)==null||t.set({fontSize:e})}onColorChanged(){var e;(e=this.uiObject)==null||e.set({color:this.color,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeRender(){this.uiObject&&this.Root.screenspace&&this.updateOverflow()}updateOverflow(){var t;const e=(t=this.uiObject)==null?void 0:t._overflow;e&&(e._needsUpdate=!0,this.markDirty())}onCreate(e){u0&&console.log(this),this.horizontalOverflow==1&&(e.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,e.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,e.lineHeight=this.lineSpacing,delete e.backgroundOpacity,delete e.backgroundColor,u0&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),u0&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=t.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}getTextOpts(){let e=this.fontSize;const t={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.setFont(t,this.fontStyle),t}onEnable(){super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 0:case 3:case 6:e.textAlign="left";break;case 1:case 4:case 7:e.textAlign="center";break;case 2:case 5:case 8:e.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:e.alignItems="start";break;case 3:case 4:case 5:e.alignItems="center";break;case 6:case 7:case 8:e.alignItems="end";break}return e}feedText(e,t){var g,I,o;if(!this.uiObject)return null;if(this._textMeshUi||(this._textMeshUi=[]),!t||e.length===0)this.uiObject.textContent=e;else{let C=this.getNextTag(e);if(C)C.startIndex>0&&this.uiObject.add(new jD({textContent:e.substring(0,C.startIndex),color:"inherit"}));else return this.uiObject.textContent=e;const s=[];for(;C;){const n=this.getNextTag(e,C.endIndex),a={fontFamily:(g=this.uiObject)==null?void 0:g.get("fontFamily"),color:"inherit",textContent:""};n?(a.textContent=this.getText(e,C,n),this.handleTag(C,a,s),(I=this.uiObject)==null||I.add(new jD(a))):(a.textContent=e.substring(C.endIndex),this.handleTag(C,a,s),(o=this.uiObject)==null||o.add(new jD(a))),C=n}}return null}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,g={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let I=!1;if(this._textMeshUi)for(let o=0;o<this._textMeshUi.length;o++){if(e[o]===!0)continue;I=!0;const C=this._textMeshUi[o];C.textContent&&(tf(C,g),e[o]=!0)}if(!I)break;yield}}handleTag(e,t,g){if(e.isEndTag){if(g.length>0){const I=g.pop();if(I)for(const o in I.previousValues){const C=I.previousValues[o];t[o]=C}}}else if(e.type.includes("color")){const I=new D0(e,{color:t.color});if(g.push(I),e.type.length>6){const o=parseInt("0x"+e.type.substring(7));t.color=o}else t.color=new yA(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const I=new D0(e,{fontWeight:700});g.push(I)}else if(e.type=="i"){this.setFont(t,2);const I=new D0(e,{fontStyle:"italic"});g.push(I)}}getText(e,t,g){return e.substring(t.endIndex,g.startIndex)}getNextTag(e,t=0){const g=e.indexOf("<",t),I=e.indexOf(">",g);if(g>=0&&I>=0){const o=e.substring(g+1,I);return{type:o,startIndex:g,endIndex:I+1,isEndTag:o.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;let g=this.font,I=wG.getFontFamily(g);I||(I=wG.addFontFamily(g)),e.fontFamily=I;const o=g.toLowerCase();switch(t){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal",o.includes("-bold")||(g+="-bold");break;case 2:e.fontWeight=400,e.fontStyle="italic",o.includes("-italic")||(g+="-italic");break;case 3:e.fontStyle="italic",e.fontWeight=400,o.includes("-bold")||(g+="-bold"),o.includes("-italic")||(g+="-italic")}let C=I.getVariant(e.fontWeight,e.fontStyle);if(!C){let s=g;s!=null&&s.endsWith("-msdf.json")||(s+="-msdf.json");let n=g;n!=null&&n.endsWith(".png")||(n+=".png"),C=I.addVariant(e.fontWeight,e.fontStyle,s,n),C==null||C.addEventListener("ready",()=>{this.markDirty()})}}}hn([w()],iI.prototype,"alignment",2);hn([w()],iI.prototype,"verticalOverflow",2);hn([w()],iI.prototype,"horizontalOverflow",2);hn([w()],iI.prototype,"lineSpacing",2);hn([w()],iI.prototype,"supportRichText",2);hn([w(URL)],iI.prototype,"font",2);hn([w()],iI.prototype,"fontStyle",2);hn([w()],iI.prototype,"text",1);hn([w()],iI.prototype,"fontSize",1);class D0{constructor(A,e){r(this,"tag");r(this,"previousValues");this.tag=A,this.previousValues=e}}class ea{constructor(A){r(this,"id");r(this,"content","");r(this,"font",[]);r(this,"pointSize",144);r(this,"width");r(this,"height");r(this,"depth");r(this,"wrapMode");r(this,"horizontalAlignment");r(this,"verticalAlignment");r(this,"material");this.id=A}static getId(){return this.global_id++}setDepth(A){return this.depth=A,this}setPointSize(A){return this.pointSize=A,this}setHorizontalAlignment(A){return this.horizontalAlignment=A,this}setVerticalAlignment(A){return this.verticalAlignment=A,this}writeTo(A,e){var g;e.beginBlock(`def Preliminary_Text "${this.id}"`),this.content&&e.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(g=this.font)==null||g.push("sans-serif"));const t=this.font.map(I=>`"${I}"`).join(", ");e.appendLine(`string[] font = [ ${t} ]`),e.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&e.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&e.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&e.appendLine(`double depth = ${this.depth}`),this.wrapMode&&e.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&e.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&e.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&e.appendLine(`rel material:binding = </Materials/Material_${this.material.id}>`),e.closeBlock()}}r(ea,"global_id",0);class Zw{static singleLine(A,e,t){const g=new ea("text_"+ea.getId());return g.content=A,e&&(g.pointSize=e),t&&(g.depth=t),g}static multiLine(A,e,t,g,I,o){const C=new ea("text_"+ea.getId());return C.content=A,C.width=e,C.height=t,C.horizontalAlignment=g,C.verticalAlignment=I,o!==void 0&&(C.wrapMode=o),C}}const kiA=new OA().makeRotationY(Math.PI);class Xw{get extensionName(){return"text"}onExportObject(A,e,t){const g=eA.getComponent(A,iI);if(g){const I=eA.getComponent(A,Ug);let o=100,C=100;I&&(o=I.width,C=I.height);const s=e.clone();s.matrix=kiA.clone();const n=new yA().copySRGBToLinear(g.color);s.material=new jr({color:n,emissive:n}),e.add(s),s.addEventListener("serialize",(a,B)=>{const Q=Zw.multiLine(g.text,o,C,"center","bottom","flowing");this.setTextAlignment(Q,g.alignment),this.setOverflow(Q,g),s.material&&(Q.material=s.material),Q.pointSize=this.convertToTextSize(g.fontSize),Q.depth=.001,Q.writeTo(void 0,a)})}}convertToTextSize(A){return 1/.0502*144*A}setOverflow(A,e){e.horizontalOverflow?A.wrapMode="singleLine":A.wrapMode="flowing"}setTextAlignment(A,e){switch(e){case vi.LowerLeft:case vi.MiddleLeft:case vi.UpperLeft:A.horizontalAlignment="left";break;case vi.LowerCenter:case vi.MiddleCenter:case vi.UpperCenter:A.horizontalAlignment="center";break;case vi.LowerRight:case vi.MiddleRight:case vi.UpperRight:A.horizontalAlignment="right";break}switch(e){case vi.LowerLeft:case vi.LowerCenter:case vi.LowerRight:A.verticalAlignment="bottom";break;case vi.MiddleLeft:case vi.MiddleCenter:case vi.MiddleRight:A.verticalAlignment="middle";break;case vi.UpperLeft:case vi.UpperCenter:case vi.UpperRight:A.verticalAlignment="top";break}}}var GiA=Object.defineProperty,MiA=Object.getOwnPropertyDescriptor,Uo=(i,A,e,t)=>{for(var g=t>1?void 0:t?MiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&GiA(A,e,g),g};const hC=rA("debugusdz");class Ta{constructor(){r(this,"callToAction");r(this,"checkoutTitle");r(this,"checkoutSubtitle");r(this,"callToActionURL")}}Uo([w()],Ta.prototype,"callToAction",2);Uo([w()],Ta.prototype,"checkoutTitle",2);Uo([w()],Ta.prototype,"checkoutSubtitle",2);Uo([w()],Ta.prototype,"callToActionURL",2);class Fo extends MA{constructor(){super(...arguments);r(this,"objectToExport");r(this,"autoExportAnimations",!1);r(this,"exportFileName");r(this,"customUsdzFile");r(this,"customBranding");r(this,"anchoringType","plane");r(this,"planeAnchoringAlignment","horizontal");r(this,"interactive",!0);r(this,"extensions",[]);r(this,"link");r(this,"webxr");r(this,"webARSessionRoot");r(this,"lastCallback");r(this,"_quicklookButton");r(this,"_quicklookButtonContainer",null)}start(){var e,t,g,I;hC&&(console.log(this),console.log("Debug USDZ, press 't' to export"),window.addEventListener("keydown",o=>{switch(o.key){case"t":this.exportAsync();break}}),Wr()&&setTimeout(()=>{this.exportAsync()},2e3)),(e=document.getElementById("open-in-ar"))==null||e.addEventListener("click",o=>{o.preventDefault(),this.exportAsync()}),this.objectToExport||(this.objectToExport=this.gameObject),!((g=(t=this.objectToExport)==null?void 0:t.children)!=null&&g.length)&&!((I=this.objectToExport)!=null&&I.isMesh)&&(this.objectToExport=this.context.scene),this.interactive&&(this.extensions.push(new Pw),this.extensions.push(new _w),this.extensions.push(new Xw))}onEnable(){const e=Nh(),t=Gs();(hC||e&&t)&&(this.addQuicklookButton(),this.webARSessionRoot=eA.findObjectOfType(Na)??void 0,this.lastCallback=this.quicklookCallback.bind(this),this.link=piA(this.context),this.link.addEventListener("message",this.lastCallback)),hC&&eg("USDZ Exporter enabled: "+this.name)}onDisable(){var g;(g=this.link)==null||g.removeEventListener("message",this.lastCallback);const e=Nh(),t=Gs();(hC||e&&t)&&this.removeQuicklookButton(),hC&&eg("USDZ Exporter disabled: "+this.name)}async exportAsync(){var E;let e=this.exportFileName??((E=this.objectToExport)==null?void 0:E.name)??this.name;if(na()||(e+="-MadeWithNeedle"),e+="-"+fiA(),this.customUsdzFile){const c=this.buildQuicklookOverlay();hC&&console.log(c);const h=c.callToAction?encodeURIComponent(c.callToAction):"",l=c.checkoutTitle?encodeURIComponent(c.checkoutTitle):"",d=c.checkoutSubtitle?encodeURIComponent(c.checkoutSubtitle):"";this.link.href=this.customUsdzFile+`#callToAction=${h}&checkoutTitle=${l}&checkoutSubtitle=${d}&callToActionURL=${c.callToActionURL}`,console.log(this.link.href),this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=e+".usdz",this.link.click();return}if(!this.objectToExport)return;if(this.webARSessionRoot){const c=this.webARSessionRoot.gameObject,h=1/this.webARSessionRoot.arScale;c.matrix.makeScale(h,h,h),this.webARSessionRoot.invertForward&&c.matrix.multiply(new OA().makeRotationY(Math.PI))}const t=new xX,g=[...this.extensions],I=new Gw;g.push(I),this.autoExportAnimations&&wiA(this.objectToExport,I);const o={self:this,exporter:t,extensions:g,object:this.objectToExport};this.dispatchEvent(new CustomEvent("before-export",{detail:o})),t.debug=hC,this.anchoringType!=="plane"&&this.anchoringType!=="none"&&this.anchoringType!=="image"&&this.anchoringType!=="face"&&(this.anchoringType="plane"),this.planeAnchoringAlignment!=="horizontal"&&this.planeAnchoringAlignment!=="vertical"&&this.planeAnchoringAlignment!=="any"&&(this.planeAnchoringAlignment="horizontal");const C=await t.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:g,quickLookCompatible:!0}),s=new Blob([C],{type:"application/octet-stream"});this.dispatchEvent(new CustomEvent("after-export",{detail:o}));const n=this.buildQuicklookOverlay();hC&&console.log(n);const a=n.callToAction?encodeURIComponent(n.callToAction):"",B=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",Q=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=URL.createObjectURL(s)+`#callToAction=${a}&checkoutTitle=${B}&checkoutSubtitle=${Q}&callToActionURL=${n.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=e+".usdz",this.link.click()}quicklookCallback(e){if((e==null?void 0:e.data)=="_apple_ar_quicklook_button_tapped"){hC&&oC("Quicklook closed via call to action button");var t=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(t),!t.defaultPrevented){const g=new URLSearchParams(this.link.href);if(g){const I=g.get("callToActionURL");hC&&eg("Quicklook url: "+I),I&&(na()?globalThis.open(I,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",I))}}}}buildQuicklookOverlay(){var t,g,I;const e={};return this.customBranding&&Object.assign(e,this.customBranding),na()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),e.callToAction="Close",e.checkoutTitle="🌵 Made with Needle",e.checkoutSubtitle="_"),(t=e.callToAction)!=null&&t.length||(e.callToAction="Close"),(g=e.checkoutTitle)!=null&&g.length||(e.checkoutTitle="🌵 Made with Needle"),(I=e.checkoutSubtitle)!=null&&I.length||(e.checkoutSubtitle="_"),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:e})),e}async createQuicklookButton(){var e,t;if(!this.webxr)if(await Gl(1),this.webxr=eA.findObjectOfType(Se)??void 0,this.webxr)if(this.webxr.VRButton&&((e=this.webxr.VRButton.parentElement)==null||e.removeChild(this.webxr.VRButton)),this.webxr.ARButton&&this._quicklookButton!==this.webxr.ARButton){this._quicklookButton=this.webxr.ARButton;const g=(t=this.webxr.ARButton.parentElement)==null?void 0:t.querySelector("a");g&&(g.href=""),this.webxr.ARButton.innerText="Open in Quicklook",this.webxr.ARButton.disabled=!1,this.webxr.ARButton.addEventListener("click",I=>{I.preventDefault(),this.exportAsync()}),this.webxr.ARButton.classList.add("quicklook-ar-button"),this._quicklookButtonContainer=this.webxr.ARButton.parentElement,this.dispatchEvent(new CustomEvent("created-button",{detail:this.webxr.ARButton}))}else{this.webxr.createARButton=!1,this.webxr.createVRButton=!1;let g=window.document.querySelector(".webxr-buttons");g||(g=document.createElement("div"),g.classList.add("webxr-buttons"));const I=document.createElement("button");I.innerText="Open in Quicklook",I.addEventListener("click",()=>{this.exportAsync()}),I.classList.add("webxr-ar-button"),I.classList.add("webxr-button"),I.classList.add("quicklook-ar-button"),g.appendChild(I),this._quicklookButtonContainer=g,this.dispatchEvent(new CustomEvent("created-button",{detail:I}))}else console.warn("Could not find WebXR component: will not create Quicklook button",pe.Current)}async addQuicklookButton(){await this.createQuicklookButton(),this._quicklookButton&&this._quicklookButtonContainer&&this._quicklookButtonContainer.appendChild(this._quicklookButton)}removeQuicklookButton(){var e;(e=this._quicklookButton)==null||e.remove()}}Uo([w(UA)],Fo.prototype,"objectToExport",2);Uo([w()],Fo.prototype,"autoExportAnimations",2);Uo([w()],Fo.prototype,"exportFileName",2);Uo([w(URL)],Fo.prototype,"customUsdzFile",2);Uo([w(Ta)],Fo.prototype,"customBranding",2);Uo([w()],Fo.prototype,"anchoringType",2);Uo([w()],Fo.prototype,"planeAnchoringAlignment",2);Uo([w()],Fo.prototype,"interactive",2);const mJ=rA("debugdeletable");class $w extends Qo{}class GR extends MA{constructor(){super(...arguments);r(this,"deleteBoxes",[])}awake(){this.deleteBoxes=eA.findObjectsOfType($w,this.context)}update(){for(const e of this.deleteBoxes){const t=this.gameObject;if(e.isInBox(t)===!0){const I=eA.getComponentInParent(this.gameObject,FE);I?mJ&&console.warn("Can not delete object with usage marker",this.guid,I):(mJ&&console.log("DESTROY",this.gameObject),Bw(this.gameObject,this.context.connection))}}}}var miA=Object.defineProperty,RiA=Object.getOwnPropertyDescriptor,rB=(i,A,e,t)=>{for(var g=t>1?void 0:t?RiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&miA(A,e,g),g};class rC extends eI{constructor(){super(...arguments);r(this,"mode");r(this,"focusDistance");r(this,"focalLength");r(this,"aperture");r(this,"gaussianMaxRadius");r(this,"resolutionScale");r(this,"bokehScale")}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=t=>{const g=t/300,I=2;return Ae.lerp(I,.01,g)};const e=20;this.aperture.valueProcessor=t=>{const g=1-t/32;return Ae.lerp(1,e,g)}}onCreateEffect(){if(this.mode===0)return;const e=1/window.devicePixelRatio;if(this.resolutionScale===void 0){let g=1;Wr()&&(g=.6),this.resolutionScale=new ve(g*e)}const t=new Kx(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=g=>{t.circleOfConfusionMaterial.worldFocusDistance=g},this.focalLength.onValueChanged=g=>t.circleOfConfusionMaterial.worldFocusRange=g,this.aperture.onValueChanged=g=>t.bokehScale=g,this.resolutionScale&&(this.resolutionScale.onValueChanged=g=>t.resolution.scale=g),[t]}unapply(){}}rB([w()],rC.prototype,"mode",2);rB([w(ve)],rC.prototype,"focusDistance",2);rB([w(ve)],rC.prototype,"focalLength",2);rB([w(ve)],rC.prototype,"aperture",2);rB([w(ve)],rC.prototype,"gaussianMaxRadius",2);rB([w(ve)],rC.prototype,"resolutionScale",2);rB([w(ve)],rC.prototype,"bokehScale",2);$C("DepthOfField",rC);var UiA=Object.defineProperty,FiA=Object.getOwnPropertyDescriptor,NiA=(i,A,e,t)=>{for(var g=t>1?void 0:t?FiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&UiA(A,e,g),g};class Ay extends MA{constructor(){super(...arguments);r(this,"visibleOn")}onEnable(){this.apply()}apply(){this.test()||eA.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:KiA()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}NiA([w()],Ay.prototype,"visibleOn",2);let CD;function KiA(){if(CD===!0||CD===!1)return CD;let i=!1;return function(A){(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(A)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(A.substr(0,4)))&&(i=!0)}(navigator.userAgent||navigator.vendor||window.opera),CD=i,i}class MR{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(A){}}var o_=(i=>(i.SelectStart="selectstart",i.SelectEnd="selectend",i))(o_||{});const fs=class extends UE{constructor(){super();r(this,"transformSelf",!0);r(this,"orbit",null);r(this,"selectStartEventListener",[]);r(this,"selectEndEventListener",[]);r(this,"_dragHelper",null);r(this,"_draggingRigidbodies",[]);r(this,"_waitingForDragStart",null);r(this,"_isDragging",!1);r(this,"_marker",null);r(this,"_dragDelta");r(this,"_didDrag",!1);r(this,"_activePointerId");this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new j}static get HasAnySelected(){return this._active>0}addDragEventListener(e,t){switch(e){case"selectstart":this.selectStartEventListener.push(t);break;case"selectend":this.selectEndEventListener.push(t);break}}start(){this.orbit=eA.findObjectOfType(Bn,this.context)}allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||Se.IsInWebXR)return;const t=eA.getComponentInParent(e.object,fs);!t||t!==this||(fs.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){this.allowEdit(this.gameObject)&&(Se.IsInWebXR||fs.lastHovered===e.object&&(this.context.domElement.style.cursor="auto"))}onPointerDown(e){this.allowEdit(this.gameObject)&&(Se.IsInWebXR||(fs._active+=1,this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation(),this.orbit&&(this.orbit.enabled=!1)))}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&(fs._active>0&&(fs._active-=1),!Se.IsInWebXR&&(this.onDragEnd(e),e.StopPropagation(),this.orbit&&(this.orbit.enabled=!0)))}update(){var e;if(!Se.IsInWebXR){if(this._waitingForDragStart){if(!this._didDrag){const g=this.context.input.getPointerPositionDelta(0);if(g&&this._dragDelta.add(g),this._dragDelta.length()>2)this._didDrag=!0;else return}const t=this._waitingForDragStart;this._waitingForDragStart=null,this.onDragStart(t)}this._dragHelper&&this._dragHelper.hasSelected&&this.onUpdateDrag(),(((e=this._dragHelper)==null?void 0:e.hasSelected)===!1||this._activePointerId!==void 0&&this.context.input.getPointerPressed(this._activePointerId)===!1)&&this.onDragEnd(null)}}onDragStart(e){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new Ap(this.context.mainCamera);else return;if(!e||!e.object)return;const t=eA.getComponentInParent(e.object,fs);if(!t||t!==this)return;let g=e.object;this.transformSelf&&(g=this.gameObject);const I={selected:g,attached:g};for(const n of this.selectStartEventListener)n(this,I);if(this._activePointerId=e.pointerId,!I.attached)return;I.attached,g=I.attached,this._isDragging=!0,this._dragHelper.setSelected(g,this.context),this.orbit&&(this.orbit.enabled=!1);const o=eA.getComponentInChildren(g,da);o&&(o.fastMode=!0,o==null||o.requestOwnership()),this._marker=eA.addNewComponent(g,FE),this._draggingRigidbodies.length=0;const C=eA.getComponentsInChildren(g,jt);C&&this._draggingRigidbodies.push(...C);const s=cp();eA.invokeOnChildren(this._dragHelper.selected,s("onDragStart"))}onUpdateDrag(){if(this._dragHelper){this._dragHelper.onUpdate(this.context);for(const e of this._draggingRigidbodies)e.wakeUp(),e.resetVelocities()}}onDragEnd(e){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;for(const I of this._draggingRigidbodies)I.setVelocity(I.smoothedVelocity);this._draggingRigidbodies.length=0;const t=this._dragHelper.selected;if(this._dragHelper.setSelected(null,this.context),this.orbit&&(this.orbit.enabled=!0),e!=null&&e.object){const I=eA.getComponentInChildren(e.object,da);I&&(I.fastMode=!1)}this._marker&&this._marker.destroy();for(const I of this.selectEndEventListener)I(this);const g=cp();eA.invokeOnChildren(t,g("onDragEnd"))}};let ta=fs;r(ta,"_active",0),r(ta,"lastHovered");const vU=class{constructor(A){r(this,"_selected",null);r(this,"_context",null);r(this,"_camera");r(this,"_cameraPlane",new ro);r(this,"_hasGroundPlane",!1);r(this,"_groundPlane",new ro);r(this,"_groundOffset",new k);r(this,"_groundOffsetFactor",0);r(this,"_groundDistance",0);r(this,"_groundPlanePoint",new k);r(this,"_raycaster",new BE);r(this,"_cameraPlaneOffset",new k);r(this,"_intersection",new k);r(this,"_worldPosition",new k);r(this,"_inverseMatrix",new OA);r(this,"_rbs",[]);r(this,"_groundLine");r(this,"_groundMarker");r(this,"_groundOffsetVector",new k(0,1,0));r(this,"_requireUpdateGroundPlane",!0);r(this,"_didDragOnGroundPlaneLastFrame",!1);this._camera=A;const e=new Qi(vU.geometry),t=e.material;t.color=new yA(.4,.4,.4),e.layers.set(2),e.name="line",e.scale.y=1,this._groundLine=e;const g=new Go(.5,22,22),I=new wt({color:t.color}),o=new fA(g,I);o.visible=!1,o.layers.set(2),this._groundMarker=o}get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}setSelected(A,e){if(this._selected&&e)for(const t of this._rbs)t.wakeUp(),t.setVelocity(0,0,0);if(this._selected&&jg.Remove(e,this._selected),this._selected=A,this._context=e,this._rbs.length=0,A?(e.scene.add(this._groundLine),e.scene.add(this._groundMarker)):(this._groundLine.removeFromParent(),this._groundMarker.removeFromParent()),this._selected){if(!e){console.error("DragHelper: no context");return}jg.Add(e,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this.onUpdateScreenSpacePlane()}}onUpdate(A){var C,s,n,a,B;if(!this._context)return;const e="Space",t="KeyD",g=((C=this._context)==null?void 0:C.input.isKeyPressed(e))||((s=this._context)==null?void 0:s.input.isKeyPressed(t)),I=this._context.input.getTouchesPressedCount()>=2||g;if(I){const Q=this._context.input.getPointerPositionDelta(0);Q&&(this._groundOffsetVector.set(0,1,0),(n=this._selected)==null||n.rotateOnWorldAxis(this._groundOffsetVector,Q.x*this._context.time.deltaTime))}const o=this._context.input.getPointerPositionRC(0);if(o&&(this._raycaster.setFromCamera(o,this._camera),this._selected)){this._groundOffsetVector.set(0,1,0);const Q=ye(this._camera).clone().sub(ye(this._selected)).normalize(),E=Math.abs(Q.dot(this._groundOffsetVector)),c=((a=this._context)==null?void 0:a.input.isKeyPressed(e))||((B=this._context)==null?void 0:B.input.isKeyPressed(t)),h=!I&&E>.2&&!c&&this._context.input.getPointerPressedCount()<=1,l=this._didDragOnGroundPlaneLastFrame!==h;if(this._didDragOnGroundPlaneLastFrame=h,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!h||l)&&this.onUpdateGroundPlane(),this._requireUpdateGroundPlane=!1,this._hasGroundPlane)if(this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection)){const d=this._intersection.y;if(this._groundPlanePoint.copy(this._intersection).sub(this._groundOffset),this._groundPlanePoint.y=d,h){this._groundOffsetVector.set(0,1,0);const p=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(p,this._groundPlanePoint,!1),this.onDidUpdate();return}}else this._groundPlanePoint.set(0,99999,0);l&&this.onUpdateScreenSpacePlane(),this._requireUpdateGroundPlane=!0,this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&(this.onUpdateWorldPosition(this._intersection.sub(this._cameraPlaneOffset),this._groundPlanePoint,!0),this.onDidUpdate())}}onUpdateWorldPosition(A,e,t){if(this._selected){if(t){const g=ye(this._selected);g.y=A.y,A=g}if(hi(this._selected,A),hi(this._groundLine,A),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=e!==null,e){const g=ye(this._camera).distanceTo(e)*.01;this._groundMarker.scale.set(g,g,g),hi(this._groundMarker,e)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;const A=this._context.input.getPointerPositionRC(0);A&&(this._raycaster.setFromCamera(A,this._camera),this._cameraPlane.setFromNormalAndCoplanarPoint(this._camera.getWorldDirection(this._cameraPlane.normal),this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld)),this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&this._selected.parent&&(this._inverseMatrix.copy(this._selected.parent.matrixWorld).invert(),this._cameraPlaneOffset.copy(this._intersection).sub(this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld))))}onUpdateGroundPlane(){if(!this._selected||!this._context)return;const A=ye(this._selected),e=new on(new k(0,.1,0).add(A),new k(0,-1,0)),t=new CC;t.ignore=[this._selected];const g=this._context.physics.raycastFromRay(e,t);for(let I=0;I<g.length;I++){const o=g[I];if(!o.face||this.contains(this._selected,o.object))continue;const C=new k(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(C,o.point);break}this._hasGroundPlane=!0,this._groundPlane.setFromNormalAndCoplanarPoint(e.direction.multiplyScalar(-1),e.origin),this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection),this._groundDistance=this._intersection.distanceTo(A),this._groundOffset.copy(this._intersection).sub(A)}onDidUpdate(){dI.markDirty(this._selected);for(const A of this._rbs)A.wakeUp(),A.resetForcesAndTorques(),A.setAngularVelocity(0,0,0)}contains(A,e){if(A===e)return!0;if(A.children){for(const t of A.children)if(this.contains(t,e))return!0}return!1}};let Ap=vU;r(Ap,"geometry",new ue().setFromPoints([new k(0,0,0),new k(0,-1,0)]));function mR(i,A,e){console.warn("Adding components on object has been temporarily disabled")}var C_=(i=>(i.File_Spawned="file-spawned",i))(C_||{});class s_{constructor(A,e,t,g,I,o,C,s){r(this,"guid");r(this,"file_name");r(this,"file_hash");r(this,"file_size");r(this,"position");r(this,"seed");r(this,"sender");r(this,"serverUrl");r(this,"parentGuid");r(this,"boundsSize");this.seed=e,this.guid=t,this.file_name=g,this.file_hash=I,this.file_size=o,this.position=C,this.sender=A,this.serverUrl=s}}async function GG(i,A,e){const t=i.name;return t.endsWith(".gltf")||t.endsWith(".glb")?new Promise((g,I)=>{const o=new FileReader;o.readAsArrayBuffer(i),o.onloadend=async C=>{const s=o.result,n=Qw(),a=new Vg(n),B=await eC().parseSync(A,s,i.name,a);if(B&&B.scene){const Q=B.scene;if(!Q.guid){const E=new Vg(n);Q.guid=E.generateUUID()}e&&JiA(A.connection,i,n,Q,e),mR(),g(B)}}}):(console.warn("Unsupported file type: "+t),console.log(i),null)}async function n_(i,A){return new Promise(async(e,t)=>{const g=Qw(),I=new Vg(g),o=i.toString(),C=await eC().loadSync(A,o,o,I);C&&C.scene?(C.scene,mR(),e(C)):console.warn("Unsupported file type: "+i.toString())})}ii.registerCallback(LI.ContextCreated,i=>{a_(i.context)});function a_(i){i.connection.beginListen("file-spawned",async A=>{if(A.sender!==i.connection.connectionId){console.log("received file event",A),qiA(A,i);let e=null;try{e=await im(A.file_name,A.file_hash,A.file_size,A.serverUrl)}finally{biA(A)}if(e){const t=new Vg(A.seed),g=await eC().parseSync(i,e,null,t);if(g&&g.scene){const I=g.scene;if(mR(),A.parentGuid){const o=Xl(A.parentGuid,i.scene);"add"in o&&o.add(I)}I.parent||i.scene.add(I),A.position!==null&&I.position.copy(A.position)}}else console.error("download didnt return file")}})}async function JiA(i,A,e,t,g){if(!i.connectionId){console.error("Can not upload file - no connection id");return}if(!t.guid){console.error("Can not upload file - no guid",t,t.guid);return}const I=await Ox(A,g);if(!I)return;if(!I.filename){console.error("Can not send upload event - no filename",A.name);return}if(!I.hash){console.error("Can not send upload event - no hash",A.name);return}const o=new s_(i.connectionId,e,t.guid,I.filename,I.hash,A.size,t.position,I.url??g);t.parent&&(o.parentGuid=t.parent.guid),i.send("file-spawned",o)}const MG={};function qiA(i,A){const e=new Dt,t=new fA(e,new wt({color:65280})),g=new $f(t,5592405);if(MG[i.guid]=g,A.scene.add(g),i.parentGuid){const I=Xl(i.parentGuid,A.scene);I&&I.add(g)}i.position&&g.position.copy(i.position)}function biA(i,A){const e=i.guid,t=MG[e];t&&(delete MG[e],t.removeFromParent())}var LiA=Object.defineProperty,viA=Object.getOwnPropertyDescriptor,RR=(i,A,e,t)=>{for(var g=t>1?void 0:t?viA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&LiA(A,e,g),g};const xiA=rA("debugnet"),mG=class extends MA{constructor(){super(...arguments);r(this,"url",null);r(this,"urlParameterName",null);r(this,"localhost",null)}awake(){xiA&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let A=this.url?mG.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const I=rA(this.urlParameterName);I&&typeof I=="string"&&(A=I)}if(!A)return null;const t=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(A);return t!=null&&t.groups?(t==null?void 0:t.groups.socket_prefix)?A:"wss://"+(t==null?void 0:t.groups.url):null}static GetUrl(A,e){let t=A;const g=mG.IsLocalNetwork()&&e;return g&&(t=e),A!=null&&A.startsWith("/")&&(t=(g?t:window.location.origin)+A),t}static IsLocalNetwork(A=window.location.hostname){return zg(A)}};let BB=mG;RR([w()],BB.prototype,"url",2);RR([w()],BB.prototype,"urlParameterName",2);RR([w()],BB.prototype,"localhost",2);var YiA=Object.defineProperty,TiA=Object.getOwnPropertyDescriptor,r_=(i,A,e,t)=>{for(var g=t>1?void 0:t?TiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&YiA(A,e,g),g};class md extends MA{constructor(){super(...arguments);r(this,"filesBackendUrl");r(this,"localhost");r(this,"_dragOver");r(this,"_drop")}onEnable(){this.filesBackendUrl=this.filesBackendUrl?BB.GetUrl(this.filesBackendUrl,this.localhost):void 0,this._dragOver=this.onDrag.bind(this),this._drop=this.onDrop.bind(this),this.context.domElement.addEventListener("dragover",this._dragOver),this.context.domElement.addEventListener("drop",this._drop)}onDisable(){this.context.domElement.removeEventListener("dragover",this._dragOver),this.context.domElement.removeEventListener("drop",this._drop)}onDrag(e){e.preventDefault()}async addFiles(e){for(const t of e){if(!t)continue;console.log("Register file "+t.name+" to",this.filesBackendUrl,t);const g=await GG(t,this.context,this.filesBackendUrl);this.dispatchEvent(new CustomEvent("file-dropped",{detail:t})),g&&this.addObject(void 0,g)}}async onDrop(e){if(console.log(e),!e.dataTransfer)return;e.preventDefault();const t=e.dataTransfer.items;if(t)for(const g in t){const I=t[g];if(I.kind==="file"){const o=I.getAsFile();if(!o)continue;console.log("Register file "+o.name+" to",this.filesBackendUrl,o);const C=await GG(o,this.context,this.filesBackendUrl);this.dispatchEvent(new CustomEvent("file-dropped",{detail:o})),C&&this.addObject(e,C)}else I.kind==="string"&&I.type=="text/plain"&&I.getAsString(async o=>{console.log("dropped url",o);try{const C=new URL(o);if(!C)return;const s=await n_(C,this.context);s&&this.addObject(e,s)}catch{console.log("dropped string is not a valid URL!",o)}})}}async addObject(e,t){console.log("Dropped",t);const g=t.scene;if(e!==void 0){const I=new CC;I.setMask(16777215),I.screenPointFromOffset(e.offsetX,e.offsetY);const o=this.context.physics.raycast(I);if(o&&o.length>0)for(const C of o){g.position.copy(C.point);break}}this.gameObject.add(g),this.dispatchEvent(new CustomEvent("object-added",{detail:t}))}}r_([w()],md.prototype,"filesBackendUrl",2);r_([w()],md.prototype,"localhost",2);var HiA=Object.defineProperty,_iA=Object.getOwnPropertyDescriptor,ey=(i,A,e,t)=>{for(var g=t>1?void 0:t?_iA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&HiA(A,e,g),g};class QB extends UE{constructor(){super(...arguments);r(this,"parent",null);r(this,"object",null);r(this,"limitCount",10);r(this,"limitInterval",60);r(this,"_currentCount",0);r(this,"_startPosition",null);r(this,"_startQuaternion",null)}awake(){var t,g;if(this.object){if(this.object===this.gameObject){console.error("Can not duplicate self");return}this.object.visible=!1,this._startPosition=((t=this.object.position)==null?void 0:t.clone())??new k(0,0,0),this._startQuaternion=((g=this.object.quaternion)==null?void 0:g.clone())??new kA(0,0,0,1)}const e=eA.getComponentInParent(this.gameObject,ta);e?e.addDragEventListener(o_.SelectStart,(I,o)=>{if(this._currentCount>=this.limitCount){o.attached=null;return}const C=this.handleDuplication(o.selected);C&&(console.assert(C!==o.selected,"Duplicated object is original"),o.attached=C)}):console.warn("Could no find drag controls in parent",this.name),ti.addEventListener(Ss.SelectStart,(I,o)=>{if(this._currentCount>=this.limitCount){o.grab=null;return}const C=this.handleDuplication(o.selected);C&&(o.grab=C)}),this.cloneLimitIntervalFn()}cloneLimitIntervalFn(){this.destroyed||(this._currentCount>0&&(this._currentCount-=1),setTimeout(()=>{this.cloneLimitIntervalFn()},this.limitInterval/this.limitCount*1e3))}handleDuplication(e){var t;if(this._currentCount>=this.limitCount||!this.object)return null;if(e===this.gameObject||this.handleMultiObject(e)){if(this.object===this.gameObject)return null;this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);const g=new TC;this.parent||(this.parent=this.gameObject.parent),this.parent&&(g.parent=this.parent.guid??((t=this.parent.userData)==null?void 0:t.guid),g.keepWorldPosition=!0),g.position=this.worldPosition,g.rotation=this.worldQuaternion,g.context=this.context,this._currentCount+=1;const I=eA.instantiateSynced(this.object,g);return console.assert(I!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),I}return null}handleMultiObject(e){return this.gameObject.type==="Group"||this.gameObject.type==="Object3D"?this.isInChildren(this.gameObject,e):!1}isInChildren(e,t){if(!e)return!1;if(e===t)return!0;if(e.children){for(let g of e.children)if(this.isInChildren(g,t))return!0}return!1}}ey([w(UA)],QB.prototype,"parent",2);ey([w(UA)],QB.prototype,"object",2);ey([w()],QB.prototype,"limitCount",2);ey([w()],QB.prototype,"limitInterval",2);var IQ=(i=>(i[i.PointerEnter=0]="PointerEnter",i[i.PointerExit=1]="PointerExit",i[i.PointerDown=2]="PointerDown",i[i.PointerUp=3]="PointerUp",i[i.PointerClick=4]="PointerClick",i[i.Drag=5]="Drag",i[i.Drop=6]="Drop",i[i.Scroll=7]="Scroll",i[i.UpdateSelected=8]="UpdateSelected",i[i.Select=9]="Select",i[i.Deselect=10]="Deselect",i[i.Move=11]="Move",i[i.InitializePotentialDrag=12]="InitializePotentialDrag",i[i.BeginDrag=13]="BeginDrag",i[i.EndDrag=14]="EndDrag",i[i.Submit=15]="Submit",i[i.Cancel=16]="Cancel",i))(IQ||{}),OiA=Object.defineProperty,PiA=Object.getOwnPropertyDescriptor,UR=(i,A,e,t)=>{for(var g=t>1?void 0:t?PiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&OiA(A,e,g),g};class FR{constructor(){r(this,"eventID");r(this,"callback")}}UR([w()],FR.prototype,"eventID",2);UR([w(DI)],FR.prototype,"callback",2);class ty extends MA{constructor(){super(...arguments);r(this,"triggers")}invoke(e){if(this.triggers)for(const t of this.triggers)t.eventID===e&&t.callback.invoke()}onPointerClick(e){this.invoke(IQ.PointerClick)}onPointerEnter(e){this.invoke(IQ.PointerEnter)}onPointerExit(e){this.invoke(IQ.PointerExit)}onPointerDown(e){this.invoke(IQ.PointerDown)}onPointerUp(e){this.invoke(IQ.PointerUp)}}UR([w(FR)],ty.prototype,"triggers",2);var WiA=Object.defineProperty,ViA=Object.getOwnPropertyDescriptor,NR=(i,A,e,t)=>{for(var g=t>1?void 0:t?ViA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&WiA(A,e,g),g};class KR extends MA{constructor(){super(...arguments);r(this,"connectedBody");r(this,"_rigidBody",null)}get rigidBody(){return this._rigidBody}onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(jt)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.createJoint(this.rigidBody,this.connectedBody)}}NR([w(jt)],KR.prototype,"connectedBody",2);class JR extends KR{createJoint(A,e){var t;(t=this.context.physics.engine)==null||t.addFixedJoint(A,e)}}class Rd extends KR{constructor(){super(...arguments);r(this,"anchor");r(this,"axis")}createJoint(e,t){var g;this.axis&&this.anchor&&((g=this.context.physics.engine)==null||g.addHingeJoint(e,t,this.anchor,this.axis))}}NR([w(k)],Rd.prototype,"anchor",2);NR([w(k)],Rd.prototype,"axis",2);const jiA={type:"change"};let ziA=class extends Pi{constructor(A,e){super(),this.object=A,this.domElement=e,this.movementSpeed=1,this.rollSpeed=.005,this.dragToLook=!1,this.autoForward=!1;const t=this,g=1e-6,I=new kA,o=new k;this.tmpQuaternion=new kA,this.status=0,this.moveState={up:0,down:0,left:0,right:0,forward:0,back:0,pitchUp:0,pitchDown:0,yawLeft:0,yawRight:0,rollLeft:0,rollRight:0},this.moveVector=new k(0,0,0),this.rotationVector=new k(0,0,0),this.keydown=function(Q){if(!Q.altKey){switch(Q.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=.1;break;case"KeyW":this.moveState.forward=1;break;case"KeyS":this.moveState.back=1;break;case"KeyA":this.moveState.left=1;break;case"KeyD":this.moveState.right=1;break;case"KeyR":this.moveState.up=1;break;case"KeyF":this.moveState.down=1;break;case"ArrowUp":this.moveState.pitchUp=1;break;case"ArrowDown":this.moveState.pitchDown=1;break;case"ArrowLeft":this.moveState.yawLeft=1;break;case"ArrowRight":this.moveState.yawRight=1;break;case"KeyQ":this.moveState.rollLeft=1;break;case"KeyE":this.moveState.rollRight=1;break}this.updateMovementVector(),this.updateRotationVector()}},this.keyup=function(Q){switch(Q.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=1;break;case"KeyW":this.moveState.forward=0;break;case"KeyS":this.moveState.back=0;break;case"KeyA":this.moveState.left=0;break;case"KeyD":this.moveState.right=0;break;case"KeyR":this.moveState.up=0;break;case"KeyF":this.moveState.down=0;break;case"ArrowUp":this.moveState.pitchUp=0;break;case"ArrowDown":this.moveState.pitchDown=0;break;case"ArrowLeft":this.moveState.yawLeft=0;break;case"ArrowRight":this.moveState.yawRight=0;break;case"KeyQ":this.moveState.rollLeft=0;break;case"KeyE":this.moveState.rollRight=0;break}this.updateMovementVector(),this.updateRotationVector()},this.pointerdown=function(Q){if(this.dragToLook)this.status++;else{switch(Q.button){case 0:this.moveState.forward=1;break;case 2:this.moveState.back=1;break}this.updateMovementVector()}},this.pointermove=function(Q){if(!this.dragToLook||this.status>0){const E=this.getContainerDimensions(),c=E.size[0]/2,h=E.size[1]/2;this.moveState.yawLeft=-(Q.pageX-E.offset[0]-c)/c,this.moveState.pitchDown=(Q.pageY-E.offset[1]-h)/h,this.updateRotationVector()}},this.pointerup=function(Q){if(this.dragToLook)this.status--,this.moveState.yawLeft=this.moveState.pitchDown=0;else{switch(Q.button){case 0:this.moveState.forward=0;break;case 2:this.moveState.back=0;break}this.updateMovementVector()}this.updateRotationVector()},this.update=function(Q){const E=Q*t.movementSpeed,c=Q*t.rollSpeed;t.object.translateX(t.moveVector.x*E),t.object.translateY(t.moveVector.y*E),t.object.translateZ(t.moveVector.z*E),t.tmpQuaternion.set(t.rotationVector.x*c,t.rotationVector.y*c,t.rotationVector.z*c,1).normalize(),t.object.quaternion.multiply(t.tmpQuaternion),(o.distanceToSquared(t.object.position)>g||8*(1-I.dot(t.object.quaternion))>g)&&(t.dispatchEvent(jiA),I.copy(t.object.quaternion),o.copy(t.object.position))},this.updateMovementVector=function(){const Q=this.moveState.forward||this.autoForward&&!this.moveState.back?1:0;this.moveVector.x=-this.moveState.left+this.moveState.right,this.moveVector.y=-this.moveState.down+this.moveState.up,this.moveVector.z=-Q+this.moveState.back},this.updateRotationVector=function(){this.rotationVector.x=-this.moveState.pitchDown+this.moveState.pitchUp,this.rotationVector.y=-this.moveState.yawRight+this.moveState.yawLeft,this.rotationVector.z=-this.moveState.rollRight+this.moveState.rollLeft},this.getContainerDimensions=function(){return this.domElement!=document?{size:[this.domElement.offsetWidth,this.domElement.offsetHeight],offset:[this.domElement.offsetLeft,this.domElement.offsetTop]}:{size:[window.innerWidth,window.innerHeight],offset:[0,0]}},this.dispose=function(){this.domElement.removeEventListener("contextmenu",RJ),this.domElement.removeEventListener("pointerdown",s),this.domElement.removeEventListener("pointermove",C),this.domElement.removeEventListener("pointerup",n),window.removeEventListener("keydown",a),window.removeEventListener("keyup",B)};const C=this.pointermove.bind(this),s=this.pointerdown.bind(this),n=this.pointerup.bind(this),a=this.keydown.bind(this),B=this.keyup.bind(this);this.domElement.addEventListener("contextmenu",RJ),this.domElement.addEventListener("pointerdown",s),this.domElement.addEventListener("pointermove",C),this.domElement.addEventListener("pointerup",n),window.addEventListener("keydown",a),window.addEventListener("keyup",B),this.updateMovementVector(),this.updateRotationVector()}};function RJ(i){i.preventDefault()}class qR extends MA{constructor(){super(...arguments);r(this,"_controls",null)}onEnable(){var t;const e=(t=eA.getComponent(this.gameObject,Yt))==null?void 0:t.cam;this._controls=new ziA(e,this.context.renderer.domElement),this._controls.rollSpeed=.5,this._controls.movementSpeed=3,this._controls.dragToLook=!0}onDisable(){var e;(e=this._controls)==null||e.dispose(),this._controls=null}update(){this._controls&&this._controls.update(this.context.time.deltaTime)}}var ZiA=Object.defineProperty,XiA=Object.getOwnPropertyDescriptor,bR=(i,A,e,t)=>{for(var g=t>1?void 0:t?XiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&ZiA(A,e,g),g};class jE extends MA{constructor(){super(...arguments);r(this,"_fog")}get fog(){return this._fog||(this._fog=new nM(0,0,50)),this._fog}get mode(){return 1}set near(e){this.fog.near=e}get near(){return this.fog.near}set far(e){this.fog.far=e}get far(){return this.fog.far}set color(e){this.fog.color.copy(e)}get color(){return this.fog.color}onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}bR([w()],jE.prototype,"near",1);bR([w()],jE.prototype,"far",1);bR([w(yA)],jE.prototype,"color",1);let p0,f0,PB,sD;function w0(i,A,e){f0||(f0=new og(2,2,1,1)),PB||(PB=new Ze({uniforms:{blitTexture:new SA(i)},vertexShader:`
4561
+ `&&i.length>1&&qH([e],i[i.length-2]),A.offsetX}function reA(i){if(!i[0])return 0;let A=[],e;for(let t=0;t<i.length;t++){const g=i[t];if(g.char&&DJ[g.char]&&i.length>t){A.push(g),e=i[t+1];continue}break}bH(A,e),A=[],e=null;for(let t=i.length-1;t>0;t--){const g=i[t];if(g.char&&DJ[g.char]&&t>0){A.push(g),e=i[t-1];continue}break}return qH(A,e),i[0].offsetX}function BeA(i){return i[0]?i[0].offsetX:0}function qH(i,A){if(A)for(let e=0;e<i.length;e++){const t=i[e];t.fontFactor=0,t.offsetX=A.offsetX+A.cumulativeWidth,t.cumulativeWidth=0}}function bH(i,A){if(A)for(let e=0;e<i.length;e++){const t=i[e];t.fontFactor=0,t.offsetX=A.offsetX,t.cumulativeWidth=0}}function LH(i,A,e,t){if(t=t||0,!i[A])return t;const g=i[A];return g.lineBreak?t+g.xadvance:LH(i,A+1,e,t+g.xadvance+g.xoffset+g.kerning+e.LETTERSPACING)}function QeA(i,A,e,t){return!i||!i.char||A+e<t.INNER_WIDTH?!1:t.BREAKON.indexOf(i.char)>-1}class vH extends _T{constructor(){super(),this._input="inherit",this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}_computeFromInherited(A){super._computeFromInherited(A),A._fontSize._needsProcess=!0,A._layouter._needsProcess=!0}}class xH extends Tt{constructor(){super("fontSize","inherit",!0),this._allowsInherit=!1}computeOutputValue(A){this._value=this._inheritedInput,A._font._fontVariant&&(A._bounds._needsProcess=!0,A._layouter._needsProcess=!0)}process(A){if(!A._font._fontVariant||!A._font._fontVariant.isReady)return;const e=this._value/A._font._fontVariant.typographic.size,t=A._inlines._value;for(let g=0;g<t.length;g++){const I=t[g];I.resetOffsets(),I.fontSize=this._value,I.fontFactor=e}}get value(){return this._value}}class YH extends OT{constructor(){super("segments",1,!1),this._notInheritedValue=void 0}update(A,e){this._notInheritedValue=this._value,this._notInheritedValue==="inherit"&&(this._notInheritedValue=this.getInheritedInput(A)),A._layouter._needsUpdate=!0}set value(A){this._value!==A&&(this._value=A,this._needsUpdate=!0)}get value(){return this._value==="inherit"?this._notInheritedValue:this._value}}class EeA extends YH{constructor(){super(),this._value="inherit"}}class ceA extends Kw{constructor(){super(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}_computeFromInherited(A){super._computeFromInherited(A),A._parent._value._layouter._needsProcess=!1}process(A){if(this._value!=="none"){const e=A._whiteSpace._whiteSpacedContent,t=A._inlines._value;for(let g=1;g<t.length;g++){const I=e[g-1]+e[g];t[g].kerning=A._font._fontVariant.getKerningAmount(I)}}}}class TH extends ht{constructor(){super("children",null,!1),this._uis=[]}update(A,e){}process(A){}_compute(A){}dispose(){}}function heA(i,A=!1){const e=i[0].index!==null,t=new Set(Object.keys(i[0].attributes)),g=new Set(Object.keys(i[0].morphAttributes)),I={},o={},C=i[0].morphTargetsRelative,s=new $A.BufferGeometry;let n=0;for(let a=0;a<i.length;++a){const B=i[a];let Q=0;if(e!==(B.index!==null))return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+a+". All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them."),null;for(const E in B.attributes){if(!t.has(E))return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+a+'. All geometries must have compatible attributes; make sure "'+E+'" attribute exists among all geometries, or in none of them.'),null;I[E]===void 0&&(I[E]=[]),I[E].push(B.attributes[E]),Q++}if(Q!==t.size)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+a+". Make sure all geometries have the same number of attributes."),null;if(C!==B.morphTargetsRelative)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+a+". .morphTargetsRelative must be consistent throughout all geometries."),null;for(const E in B.morphAttributes){if(!g.has(E))return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+a+". .morphAttributes must be consistent throughout all geometries."),null;o[E]===void 0&&(o[E]=[]),o[E].push(B.morphAttributes[E])}if(s.userData.mergedUserData=s.userData.mergedUserData||[],s.userData.mergedUserData.push(B.userData),A){let E;if(e)E=B.index.count;else if(B.attributes.position!==void 0)E=B.attributes.position.count;else return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+a+". The geometry must have either an index or a position attribute"),null;s.addGroup(n,E,a),n+=E}}if(e){let a=0;const B=[];for(let Q=0;Q<i.length;++Q){const E=i[Q].index;for(let c=0;c<E.count;++c)B.push(E.getX(c)+a);a+=i[Q].attributes.position.count}s.setIndex(B)}for(const a in I){const B=pJ(I[a]);if(!B)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the "+a+" attribute."),null;s.setAttribute(a,B)}for(const a in o){const B=o[a][0].length;if(B===0)break;s.morphAttributes=s.morphAttributes||{},s.morphAttributes[a]=[];for(let Q=0;Q<B;++Q){const E=[];for(let h=0;h<o[a].length;++h)E.push(o[a][h][Q]);const c=pJ(E);if(!c)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the "+a+" morphAttribute."),null;s.morphAttributes[a].push(c)}}return s}function pJ(i){let A,e,t,g=0;for(let C=0;C<i.length;++C){const s=i[C];if(s.isInterleavedBufferAttribute)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. InterleavedBufferAttributes are not supported."),null;if(A===void 0&&(A=s.array.constructor),A!==s.array.constructor)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes."),null;if(e===void 0&&(e=s.itemSize),e!==s.itemSize)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes."),null;if(t===void 0&&(t=s.normalized),t!==s.normalized)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes."),null;g+=s.array.length}const I=new A(g);let o=0;for(let C=0;C<i.length;++C)I.set(i[C].array,o),o+=i[C].array.length;return new $A.BufferAttribute(I,e,t)}class leA extends ht{constructor(){super("renderer")}render(A){if(!A._inlines._value||!A._inlines._value.length)return;const e=A._inlines._value.map(g=>A._font._fontVariant.getGeometricGlyph(g,A).translate(g.offsetX,g.offsetY,0)),t=heA(e);A.setFontMesh(new $A.Mesh(t,A.fontMaterial)),A._fontMesh.renderOrder=1/0}}class deA extends Jm{constructor(){super(),this._allowsInherit=!1,this._needsUpdate=!1}computeOutputValue(A){this._value=this._inheritedInput,A._layouter._needsProcess=!0}}class jQ extends Qd{constructor(e={}){const t={};jQ.definePropertiesValues(t,e);super(t,e);r(this,"_rebuildParentUI",()=>{super._rebuildParentUI(),this._layouter._needsUpdate=!0});jQ.init(this)}add(e){const t=[];for(let g=0;g<arguments.length;g++){const I=arguments[g];!I.isUI||I.isInline?(t.push(I),I.position.z=.005):console.warn("Block element can only contain Box elements.",I)}return super.add(...t)}set textContent(e){this._textContent.value=e}get textContent(){return this._textContent._value}set invertAlpha(e){this._invertAlpha.value=e}get invertAlpha(){return this._invertAlpha._value}static definePropertiesValues(e,t){e.children||(e.children=TH),e.textContent||(e.textContent=XAA),e.glyphs||(e.glyphs=AeA),e.inlines||(e.inlines=$AA),e.layouter||(e.layouter=UH),e.renderer||(e.renderer=leA),e.fontFamily||(e.fontFamily=KH),e.fontWeight||(e.fontWeight=NH),e.fontStyle||(e.fontStyle=FH),e.fontSize||(e.fontSize=xH),e.color||(e.color=eeA),e.backgroundColor||(e.backgroundColor=teA),e.lineBreak||(e.lineBreak=RH),e.letterSpacing||(e.letterSpacing=vH),e.whiteSpace||(e.whiteSpace=oR),e.segments||(e.segments=EeA),e.textAlign||(e.textAlign=deA),e.fontKerning||(e.fontKerning=ceA)}static init(e){Object.defineProperties(e,{isInline:{configurable:!1,enumerable:!0,value:!0}})}}class ueA extends FT{constructor(){super("textContent",null,!1),this._needsUpdate=!1}set value(A){this._value!==A&&(this._value=A,this._needsUpdate=!0)}update(A,e){this._needsUpdate=!1;for(let t=A.children.length-1;t>=0;t--){const g=A.children[t];g.isUI&&(A.remove(g),g.clear())}A._children._uis=[],this._value&&A.add(new jQ({name:"anonymousInline",textContent:this._value}))}}class DeA extends Array{constructor(...A){super(...A),this.width=0,this.height=0}}class peA extends ht{constructor(){super("layouter",null,!1),this._value=null}update(A,e){}process(A){let e=A._width._value;A._width._auto?e=1/0:e=A._bounds._innerWidth;const t=A._lineHeight._value,g=new DeA(new uJ);let I=0;A._children._inlines.forEach(B=>{if(!B._inlines.value)return;this._resetInlines(B);const Q=B._fontSize._value,E=B._letterSpacing._value*Q,c=B._whiteSpace._value,h=B._lineBreak._value,l={WHITESPACE:c,LETTERSPACING:E,BREAKON:h,INNER_WIDTH:e},d=B._whiteSpace._inlineWrapper;I+=B._margin._value.w+B._padding._value.w,B._inlines.value.forEach((p,u,D)=>{const y=g[g.length-1];if(d(D,u,I,l)){if(g.push(new uJ(p)),p.offsetX=p.xoffset,p.width===0){I=0;return}p.cumulativeWidth=p.xadvance+E,I=p.cumulativeWidth;return}g[g.length-1].push(p),p.offsetX=I+p.xoffset+p.kerning,p.cumulativeWidth=p.xadvance+p.kerning+E,I+=p.cumulativeWidth,y.length-1===1&&y[y.length-2].width===0&&(p.offsetX-=p.xoffset,I-=p.xoffset)}),I+=B._margin._value.y+B._padding._value.y});const o=A._whiteSpace._inlineCollapser;let C=0,s=0,n=0;g.forEach((B,Q)=>{const E=o(B);let c=0,h=0;if(B.forEach(l=>{c=Math.max(c,l.lineHeight),h=Math.max(h,l.lineBase),l.offsetX-=E}),B.lineHeight=c,B.lineBase=h,Q===0?n=-(c*t-c)*.5:n-=g[Q-1].lineHeight*t,B.y=n,B.x=0,B.forEach(l=>{l.offsetY=n-l.anchor,l.lineHeight<B.lineHeight&&(l.offsetY-=B.lineBase-l.lineBase)}),s+=B.lineHeight*t,B.width=0,B[0]){const l=B[B.length-1];B.width=l.offsetX+l.cumulativeWidth+l.paddingRight+l.marginRight+B[0].offsetX,C=Math.max(C,B.width)}}),g.height=s,g.width=C,this._value=g,e===1/0&&A._bounds.setChildrenWidth(A,g.width),A._height._auto&&A._bounds.setChildrenHeight(A,g.height);const a=A._parent._value;a&&(a._autoSize._needsProcess=!0,a._flexDirection._needsProcess=!0),A._inlineJustificator._needsProcess=!0,A._textAlign._needsProcess=!0,A._overflow._needsUpdate=!0}_resetInlines(A){A._fontSize.process(A)}}class feA extends Jm{constructor(){super(),this._allowsInherit=!1,this._needsUpdate=!0}computeOutputValue(A){this._value=this._inheritedInput,this._needsProcess=!0}process(A){weA(A),A._renderer._needsRender=!0}}function weA(i){const A=i._layouter._value,e=i._textAlign._value,t=i._bounds._innerWidth;for(let g=0;g<A.length;g++){const I=A[g],o=yeA(i,I,g===A.length-1),C=i._padding._value,s=i._borderWidth._value,n=(-C.w+C.y)/2+(-s.w+s.y)/2;I.x+=o;for(let a=0;a<I.length;a++)I[a].offsetX+=o-n}if(e.indexOf("justify")===0)for(let g=0;g<A.length;g++){const I=A[g];if(e.indexOf("-")!==-1&&g===A.length-1)return;const o=t-I.width;if(o<=0)return;let C=0;for(let B=1;B<I.length-1;B++)C+=I[B].char===" "?1:0;const s=o/C;let n=1;e==="justify-right"&&(I.reverse(),n=-1);let a=0;for(let B=1;B<=I.length-1;B++){const Q=I[B];Q.offsetX+=a*n,a+=Q.char===" "?s:0}e==="justify-right"&&I.reverse()}}function yeA(i,A,e){switch(i._textAlign._value){case"justify-left":case"justify":case"left":return-i._bounds._innerWidth/2;case"justify-right":case"right":return-A.width+i._bounds._innerWidth/2;case"center":return-A.width/2;case"justify-center":return e?-A.width/2:-i._bounds._innerWidth/2;default:console.warn(`textAlign: '${i._textAlign._value}' is not valid`)}}class SeA extends qm{constructor(){super(),this._value=this._input="column",this._allowsInherit=!1,this._needsUpdate=!0}computeOutputValue(A){this._value=this._inheritedInput}}class keA extends TT{constructor(){super(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}}class GeA extends Kw{constructor(){super(),this._value=this._input=this.getDefaultValue(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}_computeFromInherited(A){super._computeFromInherited(A)}}class MeA extends GH{constructor(){super(),this._innerWidth=1/0,this._innerHeight=0}}class meA extends ht{constructor(){super("children",null,!1);r(this,"_sortOrder",(e,t)=>e._order._value<t._order._value?-1:e._order._value>t._order._value?1:this._uis.indexOf(e)<this._uis.indexOf(t)?-1:1);this._uis=[],this._inlines=[],this._boxes=[]}update(e,t){this._compute(e),this._needsProcess=!0}process(e){this._compute(e),e._overflow._needsRender=!0}_compute(e){this._uis=e.children.filter(t=>t.visible&&t.isUI),this._inlines=this._uis.filter(t=>t.isInline).sort(this._sortOrder)}dispose(){this._inlines=null}}class ReA extends ht{constructor(){super("autosize")}process(A){if(A._layouter._value&&A._layouter._value.length){const e=A._layouter._value,t=A._padding._value,g=A._borderWidth._value;A._width._auto&&A._bounds.setOffsetWidth(A,e.width+t.w+t.y+g.w+g.y),A._height._auto&&A._bounds.setOffsetHeight(A,e.height+t.x+t.z+g.x+g.z)}}}class UeA extends mH{constructor(){super("renderer"),this._needsUpdate=!1}render(A){super.render(A);for(const e of A._children._inlines)e._renderer.render(e);A.performAfterUpdate()}}class sl extends ol{constructor(A={},e={}){sl.definePropertiesValues(e,A),super(e,A),sl.init(this)}add(A){const e=[];let t=!1;for(let g=0;g<arguments.length;g++){const I=arguments[g];!I.isUI||I.isInline?(I.isInline&&(t=!0),e.push(I)):console.warn("Block element can only contain Box elements.",I)}return e.length>0&&super.add(...e),t&&(this._children._needsUpdate=!0,this._layouter._needsProcess=!0),this}set textContent(A){this._textContent.value=A}get textContent(){return super.textContent}set invertAlpha(A){this._invertAlpha.value=A}get invertAlpha(){return this._invertAlpha._value}get lines(){return this._layouter._value}static definePropertiesValues(A,e){A.flexDirection=SeA,A.justifyContent=bm,A.alignItems=Km,A.bounds=MeA,A.autoSize=ReA,A.renderer=UeA,A.children||(A.children=meA),A.textContent||(A.textContent=ueA),A.layouter||(A.layouter=peA),A.lineHeight||(A.lineHeight=keA),A.textAlign||(A.textAlign=feA),A.whiteSpace||(A.whiteSpace=oR),A.fontKerning||(A.fontKerning=GeA),A.segments||(A.segments=YH),e.width||(e.width="100%"),e.fontSide||(e.fontSide=0)}static init(A){Object.defineProperties(A,{isText:{configurable:!1,enumerable:!0,value:!0}})}}class FeA extends ht{constructor(){super("inlines",null,!1),this._value=[]}process(A){this._value[0].paddingLeft=A._padding._value.w,this._value[0].marginLeft=A._margin._value.w;const e=this._value.length-1;this._value[e].paddingRight=A._padding._value.y,this._value[e].marginRight=A._margin._value.y}}class NeA extends ht{constructor(){super("renderer")}render(A){A._backgroundMesh||A.setBackgroundMesh(new MH(A)),A._backgroundMesh.position.x=A._inlines._value[0].offsetX+A._inlines._value[0].width/2,A._backgroundMesh.position.y=A._inlines._value[0].offsetY+A._inlines._value[0].lineBase/2,A._bounds.render(A)}}class KeA extends ht{constructor(){super("bounds",null,!1),this._size=new $A.Vector3(1,1,1),this._offsetWidth=0,this._offsetHeight=0,this._innerWidth=0,this._innerHeight=0}update(A,e){this.output(e),this._needsProcess=!0}process(A){this._offsetWidth=this._innerWidth=A._inlines._value[0].width,this._offsetHeight=this._innerHeight=A._inlines._value[0].height,this._needsRender=!0,A._borderWidth._needsRender=!0,A._borderRadius._needsRender=!0}render(A){this._size.x=this._offsetWidth,this._size.y=this._offsetHeight}output(A){A.size=this._size}}class nl extends Qd{constructor(A={}){const e={};nl.definePropertiesValues(e,A),super(e,A),nl.init(this)}clear(){for(const A of this._inlines._value)A.clear();return super.clear()}bindBackgroundMeshProperties(){this._backgroundMesh.raycast=()=>{},this._bounds._size=this._backgroundMesh.scale,this._bounds._needsUpdate=!0}unbindBackgroundMeshProperties(){this._bounds._size=new $A.Vector3(1,1,1),this._bounds._needsUpdate=!0}add(A){const e=[];for(let t=0;t<arguments.length;t++){const g=arguments[t];g.isUI?console.warn("ThreeMeshUI::InlineBlockElement cannot contains UI Elements.",g):(e.push(g),g.position.z=.005)}return super.add(...e)}static definePropertiesValues(A,e){A.children||(A.children=TH),A.bounds||(A.bounds=KeA),A.inlines||(A.inlines=FeA),A.layouter||(A.layouter=UH),A.renderer||(A.renderer=NeA),A.fontFamily||(A.fontFamily=KH),A.fontWeight||(A.fontWeight=NH),A.fontStyle||(A.fontStyle=FH),A.fontSize||(A.fontSize=xH),A.backgroundColor||(A.backgroundColor=mT),A.lineBreak||(A.lineBreak=RH),A.letterSpacing||(A.letterSpacing=vH),A.whiteSpace||(A.whiteSpace=oR),A.fontKerning||(A.fontKerning=Kw),e.backgroundSize||(e.backgroundSize="cover"),e.width||(e.width="100%"),e.height||(e.height="100%"),e.boxSizing||(e.boxSizing="border-box")}static init(A){Object.defineProperties(A,{isInline:{configurable:!1,enumerable:!0,value:!0},isInlineBlock:{configurable:!1,enumerable:!0,value:!0}}),A._inlines._value=[new JeA(A)],A.backgroundMaterial=new kH,A._renderer.render(A)}}class JeA extends bT{constructor(A){super(),this._uiElement=A}get xadvance(){const A=this._uiElement._padding._value,e=this._uiElement._width;return e._relative?e._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):A.w+A.y+e.value}get width(){const A=this._uiElement._width;return A._relative?A._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):A.value}get height(){const A=this._uiElement._height;return A._relative?A._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):A.value}get anchor(){return this.height}get lineHeight(){const A=this._uiElement._height;return A._relative?A._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):A.value}get lineBase(){const A=this._uiElement._height;return A._relative?A._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):A.value}clear(){this._uiElement=null}}class HH{constructor(A){this._subject=A}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 _H=()=>$p.update(),OH={BaseProperty:ht,Block:Cl,Text:sl,Inline:jQ,InlineBlock:nl,MeshUIBaseElement:Qd,FontLibrary:Tr,update:_H,MSDFFontMaterialUtils:ao,ShaderChunkUI:SH,Behavior:HH,FontVariant:nd};typeof global<"u"&&(global.ThreeMeshUI=OH);const qeA=OH;var beA=Ni.w8,PH=Ni.cg,CR=Ni.gO,LeA=Ni.wb,wG=Ni.zV,veA=Ni.HS,xeA=Ni.Ec,jD=Ni.gF,YeA=Ni.ol,TeA=Ni.pz,HeA=Ni.tx,_eA=Ni.hj,OeA=Ni.FV,PeA=Ni.sV,WH=Ni.xv,WeA=Ni.mx,VeA=Ni.gE,jeA=Ni.ZP,VH=Ni.Vx;const fJ=Object.freeze(Object.defineProperty({__proto__:null,BaseProperty:beA,Behavior:PH,Block:CR,DefaultValues:LeA,FontLibrary:wG,FontVariant:veA,InheritableProperty:xeA,Inline:jD,InlineBlock:YeA,InlineGlyph:TeA,MSDFFontMaterialUtils:HeA,MaterialTransformers:_eA,MeshUIBaseElement:OeA,ShaderChunkUI:PeA,Text:WH,TypographicFont:WeA,TypographicGlyph:VeA,default:jeA,update:VH},Symbol.toStringTag,{value:"Module"}));CR.prototype.interactable={get(){return this.interactive},set(i){this.interactable=i}};const Ns=Symbol("shadowDomOwner");class tC extends MA{constructor(){super(...arguments);r(this,"shadowComponent",null);r(this,"_controlsChildLayout",!0);r(this,"_root");r(this,"_parentComponent")}isRoot(){var e;return((e=this.Root)==null?void 0:e.gameObject)===this.gameObject}get canvas(){const e=this.Root;return e!=null&&e.isCanvas?e:null}markDirty(){lI.markUIDirty(this.context)}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}get Root(){return this._root===void 0&&(this._root=eA.getComponentInParent(this.gameObject,Ed)),this._root}get Canvas(){return this.canvas}__internalNewInstanceCreated(){super.__internalNewInstanceCreated(),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0}onEnable(){super.onEnable()}addShadowComponent(e,t){var o;this.removeShadowComponent();const g=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=eA.getComponentInParent(g,tC),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[Ns]=this,this.setShadowComponentOwner(e);let I=!1;if(((o=this.Root)==null?void 0:o.gameObject)===this.gameObject)this.gameObject.add(e);else{let C=this._parentComponent.shadowComponent;C&&(C==null||C.add(e),I=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),Pl&&e.add(new QE(.5)),this.onAfterAddedToScene(),I&&VH()}set(e){}setShadowComponentOwner(e){if(e&&(e[Ns]===void 0||e[Ns]===this)&&(e[Ns]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,g){if(e&&e[Ns]===t){g(e);for(const I of e.children)this.traverseOwnedShadowComponents(I,t,g)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class Ed extends tC{awake(){super.awake()}}class zQ{static getObject(A){const e=A[Ns];return e&&(e.isComponent===!0?A=e.gameObject:A=e),A}static isInteractable(A,e){if(e&&(e.canvasGroup=void 0,e.graphic=void 0),A==null||!A.visible||(A=this.getObject(A),!A.visible))return!1;const t=this.tryFindCanvasGroup(A);if((t==null?void 0:t.isCanvasGroup)===!0&&(e&&(e.canvasGroup=t),t.blocksRaycasts===!1||t.interactable===!1))return!1;const g=xr(A,I=>{if(I.isGraphic===!0)return I},!1);return e&&(g==null?void 0:g.isGraphic)===!0&&(e.graphic=g),!((g==null?void 0:g.raycastTarget)===!1||(g==null?void 0:g.layer)===2)}static tryFindCanvasGroup(A){if(!A)return null;const e=xr(A,t=>{const g=t;if(g.blocksRaycasts!==void 0&&g.interactable!==void 0)return g},!1);return e!==void 0?e:this.tryFindCanvasGroup(A.parent)}}const Oc=rA("debugwebxrcontroller");var MQ=(i=>(i[i.PhysicalDevice=0]="PhysicalDevice",i[i.Touch=1]="Touch",i))(MQ||{}),Ss=(i=>(i.SelectStart="select-start",i.SelectEnd="select-end",i.Update="update",i))(Ss||{});class vw extends MA{}const Xi=class extends MA{constructor(){super(...arguments);r(this,"webXR");r(this,"index",-1);r(this,"controllerModel");r(this,"controller");r(this,"controllerGrip");r(this,"hand");r(this,"handPointerModel");r(this,"grabbed",null);r(this,"input",null);r(this,"type",0);r(this,"showRaycastLine",!0);r(this,"_wristQuaternion",null);r(this,"movementVector",new k);r(this,"worldRot",new kA);r(this,"joystick",new j);r(this,"didRotate",!1);r(this,"didTeleport",!1);r(this,"didChangeScale",!1);r(this,"lastHit",null);r(this,"raycastLine",null);r(this,"_raycastHitPoint",null);r(this,"_connnectedCallback",null);r(this,"_disconnectedCallback",null);r(this,"_selectStartEvt",null);r(this,"_selectEndEvt",null);r(this,"_selectionPressed",!1);r(this,"_selectionPressedLastFrame",!1);r(this,"_selectionStartTime",0);r(this,"_selectionEndTime",0);r(this,"_useSmoothing",!0);r(this,"_isConnected",!1);r(this,"rayRotation",new kA);r(this,"_pinchStartTime");r(this,"selectStartCallback",null);r(this,"lastSelectStartObject",null);r(this,"_didNotEndSelection",!1);r(this,"closeGrabBoundingBoxHelper")}static CreateRaycastLine(){const e=new Qi(this.geometry),t=e.material;return t.color=this.raycastColor,e.layers.set(2),e.name="line",e.scale.z=1,e}static CreateRaycastHitPoint(){const e=new Go(.5,22,22),t=new wt({color:this.raycastColor}),g=new fA(e,t);return g.visible=!1,g.layers.set(2),g}static Create(e,t,g,I){const o=g?eA.addNewComponent(g,Xi,!1):new Xi;o.webXR=e,o.index=t,o.type=I;const C=e.context;o.controller=C.renderer.xr.getController(t),o.controllerGrip=C.renderer.xr.getControllerGrip(t),o.controllerModel=this.Factory.createControllerModel(o.controller),o.controllerGrip.add(o.controllerModel),o.hand=C.renderer.xr.getHand(t);const s=new pE;ed(s,C),o.webXR.handModelPath&&o.webXR.handModelPath!==""?s.setPath(wa(e.sourceId,o.webXR.handModelPath)):s.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/");const n=new f6(o.hand,s);return o.hand.add(n),o.hand.traverse(a=>a.layers.set(2)),o.handPointerModel=new m6(o.hand,o.controller),o.controller.addEventListener("connected",a=>{o.setControllerLayers(o.controllerModel,2),o.setControllerLayers(o.controllerGrip,2),o.setControllerLayers(o.hand,2),setTimeout(()=>{o.setControllerLayers(o.controllerModel,2),o.setControllerLayers(o.controllerGrip,2),o.setControllerLayers(o.hand,2)},1e3)}),o.hand.addEventListener("connected",a=>{var Q;if(a.data.hand){e.Rig&&e.Rig.add(o.hand),o.type=0,o.handPointerModel.traverse(c=>c.layers.set(2)),(Q=o.handPointerModel.pointerObject)==null||Q.traverse(c=>c.layers.set(2));const E=o.hand.joints;if(E)for(const c of Object.keys(E)){const h=E[c];h.parent||o.hand.add(h)}}}),o}static addEventListener(e,t){const g=this.eventSubs[e]??[];g.push(t),this.eventSubs[e]=g}static removeEventListener(e,t){if(!t)return;const g=this.eventSubs[e]??[],I=g.indexOf(t);I>=0&&g.splice(I,1),this.eventSubs[e]=g}get isUsingHands(){var t;const e=(t=this.input)==null?void 0:t.hand;return e!=null}get wrist(){if(!this.hand)return null;const e=this.hand.joints;return e?e.wrist:null}getWristQuaternion(){const e=this.wrist;return e?(this._wristQuaternion||(this._wristQuaternion=new kA),Hi(e).multiply(this._wristQuaternion.setFromEuler(new Ui(-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 e,t,g;this.type===1&&(this.controllerGrip.removeEventListener("connected",this._connnectedCallback),this.controllerGrip.removeEventListener("disconnected",this._disconnectedCallback),this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),(e=this.hand)==null||e.clear(),(t=this.controllerGrip)==null||t.clear(),(g=this.controller)==null||g.clear()}onEnable(){var e,t,g,I,o;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=Xi.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=Xi.CreateRaycastHitPoint()),(e=this.webXR.Rig)==null||e.add(this.hand),(t=this.webXR.Rig)==null||t.add(this.controllerGrip),(g=this.webXR.Rig)==null||g.add(this.controller),(I=this.webXR.Rig)==null||I.add(this.raycastLine),(o=this.raycastLine)==null||o.add(this._raycastHitPoint),this._raycastHitPoint.visible=!1,this.hand.add(this.handPointerModel),Oc&&console.log("ADDED TO RIG",this.webXR.Rig)}onDisable(){var t,g,I,o,C;(t=this.hand)==null||t.removeFromParent(),(g=this.controllerGrip)==null||g.removeFromParent(),(I=this.controller)==null||I.removeFromParent(),(o=this.raycastLine)==null||o.removeFromParent(),(C=this._raycastHitPoint)==null||C.removeFromParent();const e=this.webXR.Controllers.indexOf(this);e>=0&&this.webXR.Controllers.splice(e,1)}onSourceConnected(e){if(this._isConnected){console.warn("Received connected event for controller that is already connected",this.index,e);return}this._isConnected=!0,this.input=e.data,this.type===1&&(this.onSelectStart(),this.createPointerEvent("down"))}onSourceDisconnected(e){if(!this._isConnected){console.warn("Received discnnected event for controller that is not connected",e);return}this._isConnected=!1,this.type===1&&(this.onSelectEnd(),this.createPointerEvent("up")),this.input=null}createPointerEvent(e){switch(e){case"down":this.context.input.createPointerDown({clientX:0,clientY:0,button:this.index,pointerType:"touch"});break;case"move":break;case"up":this.context.input.createPointerUp({clientX:0,clientY:0,button:this.index,pointerType:"touch"});break}}update(){this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));const e=Xi.eventSubs.update;if(e&&e.length>0)for(const I of e)I(this);let t=1;this.type===0?t=this.context.time.deltaTime/.1:this.isUsingHands&&this.handPointerModel.pinched&&(t=this.context.time.deltaTime/.3),this.rayRotation.slerp(Hi(this.controller),this.useSmoothing?t:1);const g=ye(this.controller);if(this.isUsingHands&&this.handPointerModel.cursorObject&&(this.handPointerModel.cursorObject.visible=!1),this.raycastLine){const I=this.showRaycastLine&&this.type!==1;if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed&&I,hi(this.raycastLine,g);const o=this.hand.joints;if(o&&o.wrist&&this.grabbed&&this.grabbed.isCloseGrab){const s=this.getWristQuaternion();s&&this.rayRotation.copy(s)}fI(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=I,fI(this.raycastLine,this.rayRotation),hi(this.raycastLine,g)}this.lastHit=this.updateLastHit(),this.grabbed&&this.grabbed.update(),this._selectionPressedLastFrame=this._selectionPressed,this.selectStartCallback&&this.selectStartCallback()}onUpdate(e){var I,o;if(this.lastHit=null,!e||e.inputSources.length<=this.index){this.input=null;return}if(this.type===0&&(this.input=e.inputSources[this.index]),!this.input)return;const t=this.webXR.Rig;if(!t)return;this._didNotEndSelection&&!this.handPointerModel.pinched&&(this._didNotEndSelection=!1,this.onSelectEnd()),this.updateStick(this.input);const g=(o=(I=this.input)==null?void 0:I.gamepad)==null?void 0:o.buttons;switch(this.input.handedness){case"left":const C=3*Xi.MovementSpeedFactor,s=2,n=Ae.clamp01(this.joystick.length()*2),a=this.joystick.x>0?1:-1;let B=Math.pow(this.joystick.x,s);B*=a,B*=n;const Q=this.joystick.y>0?1:-1;let E=Math.pow(this.joystick.y,s);E*=Q,B*=n,t.getWorldQuaternion(this.worldRot),this.movementVector.set(B,0,E),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),this.movementVector.multiplyScalar(C*this.context.time.deltaTime),t.position.add(this.movementVector),this.isUsingHands&&this.runTeleport(t,g);break;case"right":const c=this.joystick.x,h=Math.abs(c);if(h<.4)this.didRotate=!1;else if(h>.5&&!this.didRotate){const l=c>0?-1:1;t.rotateY(Ae.toRadians(30*l)),this.didRotate=!0}this.runTeleport(t,g);break}}runTeleport(e,t){var s,n,a;let g=-this.joystick.y;if((s=this.hand)!=null&&s.visible&&!this.grabbed){const B=this.handPointerModel.isPinched();B&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),B&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(g=this.handPointerModel.isPinched()?1:0),B||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;let I=g>.5&&this.webXR.IsInVR,o=this.webXR.Rig?((a=(n=this.webXR.Rig)==null?void 0:n.scale)==null?void 0:a.x)<.999:!1,C=null;if(t&&this.input&&!this.input.hand)for(let B=0;B<t.length;B++){const Q=t[B];if(B===4)if(Q.pressed&&!this.didChangeScale&&this.webXR.IsInVR){this.didChangeScale=!0;const E=this.webXR.Rig;if(E)if(o){o=!1,E.scale.set(1,1,1),C=1,Xi.MovementSpeedFactor=1;const c=this.context.mainCamera;Xi.PreviousCameraFarDistance&&(c.far=Xi.PreviousCameraFarDistance)}else{o=!0,I=!0,C=.1,Xi.MovementSpeedFactor=C*2;const c=this.context.mainCamera;Xi.PreviousCameraFarDistance=c.far,c.far/=C}}else Q.pressed||(this.didChangeScale=!1)}if(I){if(!this.didTeleport){const B=this.raycast();if(this.didTeleport=!0,B&&B.length>0){const Q=B[0];if(o||this.isValidTeleportTarget(Q.object)){const E=Q.point;hi(e,E)}}}}else g<.1&&(this.didTeleport=!1);C!==null&&(e.scale.set(C,C,C),e.updateMatrixWorld())}isValidTeleportTarget(e){return eA.getComponentInParent(e,vw)!=null}updateStick(e){var t;!e||!e.gamepad||((t=e.gamepad.axes)==null?void 0:t.length)<4||(this.joystick.x=e.gamepad.axes[2],this.joystick.y=e.gamepad.axes[3])}updateLastHit(){var I;const e=this.raycast(),t=e?e[0]:null;this.lastHit=t;let g=1;if(this.webXR.Rig&&(g/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=g*(((I=this.lastHit)==null?void 0:I.distance)??9999);const o=this.raycastLine.material;t!=null?o.color=Xi.raycastColor:o.color=Xi.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;const o=Ae.clamp(this.lastHit.distance*.01*g,.015,.1);this._raycastHitPoint.scale.set(o,o,o)}this._raycastHitPoint.visible=this.lastHit!==null&&this.lastHit!==void 0}return t}onSelectStart(){this.context.connection.allowEditing&&(this.selectStartCallback=()=>this.onHandleSelectStart())}onHandleSelectStart(){this.selectStartCallback=null,this._selectionPressed=!0,this._selectionStartTime=this.context.time.time,this._selectionEndTime=1e3;let e=null,t=!1;if(this.isUsingHands?(e=this.overlap(),e.length<=0?(e=this.raycast(),t=!1):t=!0):e=this.raycast(),Oc&&console.log("onHandleSelectStart","close grab? "+t,"intersections",e),e&&e.length>0)for(const g of e){const I=g.object;this.lastSelectStartObject=I;const o={selected:I,grab:I},C=Xi.eventSubs["select-start"];if(C&&C.length>0)for(const s of C)s(this,o);o.grab!==I&&Oc&&console.log("Grabbed object changed","original",I,"new",o.grab),o.grab&&(this.grabbed=uo.TryTake(this,o.grab,g,t));break}else{const g=Xi.eventSubs["select-start"],I={selected:null,grab:null};if(g&&g.length>0)for(const o of g)o(this,I)}}onSelectEnd(){var g;if(this.isUsingHands&&this.handPointerModel.pinched){this._didNotEndSelection=!0;return}if(!this._selectionPressed)return;this.selectStartCallback=null,this._selectionPressed=!1,this._selectionEndTime=this.context.time.time;const e={grab:((g=this.grabbed)==null?void 0:g.selected)??this.lastSelectStartObject},t=Xi.eventSubs["select-end"];if(t&&t.length>0)for(const I of t)I(this,e);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(e){return!(!e||eA.isActiveInHierarchy(e)===!1||zQ.isInteractable(e)===!1)}setControllerLayers(e,t){var g,I;if(e&&(e.layers.set(t),e.children))for(const o of e.children)((g=this.grabbed)==null?void 0:g.selected)===o||((I=this.grabbed)==null?void 0:I.selectedMesh)===o||this.setControllerLayers(o,t)}getRay(){const e=new on;return e.origin.copy(ye(this.controller)),e.direction.set(0,0,-1).applyQuaternion(this.rayRotation),e}overlap(){const e=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(Oc&&(!this.closeGrabBoundingBoxHelper&&e&&(this.closeGrabBoundingBoxHelper=new $f(e,16776960),this.scene.add(this.closeGrabBoundingBoxHelper)),this.closeGrabBoundingBoxHelper&&e&&this.closeGrabBoundingBoxHelper.setFromObject(e)),!e)return new Array;const t=ye(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){const e=new CC;e.layerMask=new yo,e.layerMask.enableAll(),e.layerMask.disable(2),e.ray=this.getRay();const t=this.context.physics.raycast(e);for(let g=0;g<t.length;g++){const I=t[g],o=I.object;if(!this.testIsVisible(o)){t.splice(g,1),g--;continue}I.object=zQ.getObject(o);break}return t}};let ti=Xi;r(ti,"Factory",new Y6),r(ti,"raycastColor",new yA(.9,.3,.3)),r(ti,"raycastNoHitColor",new yA(.6,.6,.6)),r(ti,"geometry",new ue().setFromPoints([new k(0,0,0),new k(0,0,-1)])),r(ti,"handModels",{}),r(ti,"eventSubs",{}),r(ti,"PreviousCameraFarDistance"),r(ti,"MovementSpeedFactor",1);var ef=(i=>(i.WillTake="WillTake",i.DidTake="DidTake",i.WillFree="WillFree",i.DidFree="DidFree",i))(ef||{});const xg=class{constructor(){r(this,"sync",null);r(this,"selected",null);r(this,"selectedParent",null);r(this,"selectedMesh",null);r(this,"controller",null);r(this,"grabTime",0);r(this,"grabUUID","");r(this,"isCloseGrab",!1);r(this,"originalMaterial",null);r(this,"usageMarker",null);r(this,"rigidbodies",null);r(this,"didReparent",!1);r(this,"grabDistance",0);r(this,"interactable",null);r(this,"positionSource",null);r(this,"grabPoint",new k);r(this,"localPositionOffsetToGrab",null);r(this,"localPositionOffsetToGrab_worldSpace",new k);r(this,"localQuaternionToGrab",new kA(0,0,0,1));r(this,"targetDir",null);r(this,"quaternionLerp",null);r(this,"controllerDir",new k);r(this,"controllerWorldPos",new k);r(this,"lastControllerWorldPos",new k);r(this,"controllerPosDelta",new k);r(this,"totalChangeAlongDirection",0);r(this,"rigPositionLastFrame",new k)}static AddEventListener(A,e){return xg.Events[A]||(xg.Events[A]=[]),xg.Events[A].push(e),e}static RemoveEventListener(A,e){if(!e||!xg.Events[A])return;const t=xg.Events[A].indexOf(e);t>=0&&xg.Events[A].splice(t,1)}static Register(A){this.Current.find(e=>e===A)||this.Current.push(A)}static Remove(A){const e=this.Current.indexOf(A);e>=0&&this.Current.splice(e,1)}static TryTake(A,e,t,g){const I=eA.getComponentInParent(e,UE);if(I)e=I.gameObject;else return Oc&&console.warn("Prevented taking object that is not interactable",e),null;let o=e;const C=eA.getComponentInParent(e,da);C&&(C.requestOwnership(),o=C.gameObject);for(const n of this.Current)if(n.selected===o)return n.controller===A||(n.free(),n.Take(A,o,e,C,I,t,g)),n;const s=new xg;return s.Take(A,o,e,C,I,t,g),s}Take(A,e,t,g,I,o,C){var E,c;if(console.assert(e!==null,"Expected object to be taken but was",e),A.isUsingHands?this.positionSource=C?A.wrist:A.controller:this.positionSource=A.controller,!this.positionSource)return console.warn("No position source"),this;const s={controller:A,take:e,hit:t,sync:g,interactable:I};(E=xg.Events.WillTake)==null||E.forEach(h=>h(this,s));const n=t;n!=null&&n.material&&(this.originalMaterial=n.material,Array.isArray(n.material)||(n.material=n.material.clone(),n.material&&n.material.emissive&&(n.material.emissive.b=.2))),this.selected=e,this.selectedParent||(this.selectedParent=e.parent),this.selectedMesh=n,this.controller=A,this.interactable=I,this.isCloseGrab=C,this.didReparent=!1,this.sync=g,this.grabTime=A.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=eA.addNewComponent(this.selected,FE),this.rigidbodies=eA.getComponentsInChildren(this.selected,jt),ye(this.positionSource,this.lastControllerWorldPos);const a=()=>C?this.lastControllerWorldPos.clone():o.point.clone();this.grabDistance=a().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(a());const B=A.isUsingHands&&C?this.controller.getWristQuaternion().clone():A.rayRotation.clone();Hi(this.selected,this.localQuaternionToGrab).premultiply(B.invert());const Q=this.controller.webXR.Rig;return Q&&this.rigPositionLastFrame.copy(ye(Q)),jg.Add(A.context,this.selected),xg.Register(this),this.sync&&(this.sync.fastMode=!0),(c=xg.Events.DidTake)==null||c.forEach(h=>h(this,s)),this}free(){var g,I,o,C;if(!this.selected)return;const A={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};(g=xg.Events.WillFree)==null||g.forEach(s=>s(this,A)),jg.Remove(this.controller.context,this.selected),xg.Remove(this),this.sync&&(this.sync.fastMode=!1);const e=this.selectedMesh;e&&this.originalMaterial&&e.material&&(e.material=this.originalMaterial);const t=this.selected;if(this.didReparent&&t.parent){const s=this.selectedParent;s?s.attach(t):(I=this.controller)==null||I.context.scene.attach(t)}if((o=this.usageMarker)==null||o.destroy(),this.controller&&(this.controller.grabbed=null),this.selected=null,this.selectedParent=null,this.selectedMesh=null,this.sync=null,this.rigidbodies)for(const s of this.rigidbodies)s.wakeUp(),s.setVelocity(s.smoothedVelocity);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,(C=xg.Events.DidFree)==null||C.forEach(s=>s(this,A))}controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),ye(this.positionSource,this.controllerWorldPos),this.controllerPosDelta.copy(this.controllerWorldPos),this.controllerPosDelta.sub(this.lastControllerWorldPos),this.lastControllerWorldPos.copy(this.controllerWorldPos);const A=this.controller.webXR.Rig;if(A){const t=ye(A),g=this.rigPositionLastFrame.sub(t);this.controllerPosDelta.add(g),this.rigPositionLastFrame.copy(t)}return this.controllerDir.dot(this.controllerPosDelta)}update(){var A;if(this.rigidbodies)for(const e of this.rigidbodies)e.resetVelocities();if(this.sync&&this.controller&&this.controller.context.connection.isInRoom&&this.controller.context.time.time-this.grabTime>3&&this.sync.hasOwnership()===!1&&(console.log("no ownership, will leave",this.sync.guid),this.free()),!(this.interactable&&!this.interactable.canGrab)){if(!this.didReparent&&this.selected&&this.controller){const e=((A=this.controller.webXR.Rig)==null?void 0:A.scale.x)??1;this.totalChangeAlongDirection+=this.controllerMovementSinceLastFrame();let t=1;this.controller.type===0&&(t=Math.max(0,1+this.totalChangeAlongDirection*2/e),t=t*t*t),this.grabDistance/e<.8&&(t=1),this.targetDir||(this.targetDir=new k),this.targetDir.set(0,0,-this.grabDistance*t);const g=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),I=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=I.clone()),this.quaternionLerp.slerp(I,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),fI(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(g),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(ye(this.selected)),g.sub(this.localPositionOffsetToGrab_worldSpace)),hi(this.selected,g)}if(this.rigidbodies!=null)for(const e of this.rigidbodies)e.wakeUp();dI.markDirty(this.selected,!0)}}};let uo=xg;r(uo,"Events",{}),r(uo,"Current",[]);var zeA=Object.defineProperty,ZeA=Object.getOwnPropertyDescriptor,sR=(i,A,e,t)=>{for(var g=t>1?void 0:t?ZeA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&zeA(A,e,g),g};class tB extends MA{constructor(){super(...arguments);r(this,"objectBounds",!1);r(this,"color");r(this,"isGizmo",!0);r(this,"_gizmoObject",null);r(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!Pl||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new $f(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=sT(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),OI.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){var e;for(;this._boxHelper;)(e=this._boxHelper)==null||e.update(),yield}}sR([w()],tB.prototype,"objectBounds",2);sR([w(yA)],tB.prototype,"color",2);sR([w()],tB.prototype,"isGizmo",2);const XeA=rA("debugrig");class xw extends MA{awake(){if(XeA){const A=new UA;A.position.y+=.5,this.gameObject.add(A);const e=A.addNewComponent(tB);e&&(e.isGizmo=!1)}}}class mQ{constructor(){r(this,"bb",null);r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}w(){return this.bb.readFloat32(this.bb_pos+12)}static sizeOf(){return 16}static createVec4(A,e,t,g,I){return A.prep(4,16),A.writeFloat32(I),A.writeFloat32(g),A.writeFloat32(t),A.writeFloat32(e),A.offset()}}class kg{constructor(){r(this,"bb",null);r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}static getRootAsVrUserStateBuffer(A,e){return(e||new kg).__init(A.readInt32(A.position())+A.position(),A)}static getSizePrefixedRootAsVrUserStateBuffer(A,e){return A.setPosition(A.position()+nw),(e||new kg).__init(A.readInt32(A.position())+A.position(),A)}guid(A){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,A):null}time(){const A=this.bb.__offset(this.bb_pos,6);return A?this.bb.readInt64(this.bb_pos+A):this.bb.createLong(0,0)}avatarId(A){const e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,A):null}position(A){const e=this.bb.__offset(this.bb_pos,10);return e?(A||new TI).__init(this.bb_pos+e,this.bb):null}rotation(A){const e=this.bb.__offset(this.bb_pos,12);return e?(A||new mQ).__init(this.bb_pos+e,this.bb):null}scale(){const A=this.bb.__offset(this.bb_pos,14);return A?this.bb.readFloat32(this.bb_pos+A):0}posLeftHand(A){const e=this.bb.__offset(this.bb_pos,16);return e?(A||new TI).__init(this.bb_pos+e,this.bb):null}posRightHand(A){const e=this.bb.__offset(this.bb_pos,18);return e?(A||new TI).__init(this.bb_pos+e,this.bb):null}rotLeftHand(A){const e=this.bb.__offset(this.bb_pos,20);return e?(A||new mQ).__init(this.bb_pos+e,this.bb):null}rotRightHand(A){const e=this.bb.__offset(this.bb_pos,22);return e?(A||new mQ).__init(this.bb_pos+e,this.bb):null}static startVrUserStateBuffer(A){A.startObject(10)}static addGuid(A,e){A.addFieldOffset(0,e,0)}static addTime(A,e){A.addFieldInt64(1,e,A.createLong(0,0))}static addAvatarId(A,e){A.addFieldOffset(2,e,0)}static addPosition(A,e){A.addFieldStruct(3,e,0)}static addRotation(A,e){A.addFieldStruct(4,e,0)}static addScale(A,e){A.addFieldFloat32(5,e,0)}static addPosLeftHand(A,e){A.addFieldStruct(6,e,0)}static addPosRightHand(A,e){A.addFieldStruct(7,e,0)}static addRotLeftHand(A,e){A.addFieldStruct(8,e,0)}static addRotRightHand(A,e){A.addFieldStruct(9,e,0)}static endVrUserStateBuffer(A){return A.endObject()}static finishVrUserStateBufferBuffer(A,e){A.finish(e)}static finishSizePrefixedVrUserStateBufferBuffer(A,e){A.finish(e,void 0,!0)}}const wJ=rA("debugxr"),Mc=rA("debugavatar"),nR="VRUS";vM(nR,kg.getRootAsVrUserStateBuffer);function yG(){return new Date().getTime()}function $eA(i){let A=i&4294967295,e=i/Math.pow(2,32)&1048575;return LC.create(A,e)}const mh=class{constructor(A){r(this,"guid");r(this,"time");r(this,"avatarId");r(this,"position",new k);r(this,"rotation",new Ce);r(this,"scale",1);r(this,"posLeftHand",new k);r(this,"posRightHand",new k);r(this,"rotLeftHand",new kA);r(this,"rotRightHand",new kA);this.guid=A}update(A,e,t,g,I){var a,B,Q,E,c,h;this.time=yG(),this.avatarId=I,this.position.set(e.x,e.y,e.z),A&&this.position.applyMatrix4(A.matrixWorld);let o=mh.quat0;const C=mh.quat1;o.set(t.x,t.y,t.z,t.w),o=o.multiplyQuaternions(o,mh.invertRotation),A&&(A.getWorldQuaternion(C),o.multiplyQuaternions(C,o)),this.rotation.set(o.x,o.y,o.z,o.w),this.scale=A.scale.x;const s=(a=g.LeftController)==null?void 0:a.controllerGrip;s&&(s.getWorldPosition(this.posLeftHand),s.getWorldQuaternion(this.rotLeftHand));const n=(B=g.RightController)==null?void 0:B.controllerGrip;if(n&&(n.getWorldPosition(this.posRightHand),n.getWorldQuaternion(this.rotRightHand)),(E=(Q=g.LeftController)==null?void 0:Q.hand)!=null&&E.visible){const l=g.LeftController.wrist;l&&(l.getWorldPosition(this.posLeftHand),l.getWorldQuaternion(this.rotLeftHand))}if((h=(c=g.RightController)==null?void 0:c.hand)!=null&&h.visible){const l=g.RightController.wrist;l&&(l.getWorldPosition(this.posRightHand),l.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(A,e){A.clear();const t=A.createString(this.guid),g=A.createString(this.avatarId);kg.startVrUserStateBuffer(A),kg.addGuid(A,t),kg.addTime(A,$eA(this.time)),kg.addAvatarId(A,g),kg.addPosition(A,TI.createVec3(A,this.position.x,this.position.y,this.position.z)),kg.addRotation(A,mQ.createVec4(A,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),kg.addScale(A,this.scale),kg.addPosLeftHand(A,TI.createVec3(A,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),kg.addPosRightHand(A,TI.createVec3(A,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),kg.addRotLeftHand(A,mQ.createVec4(A,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),kg.addRotRightHand(A,mQ.createVec4(A,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));const I=kg.endVrUserStateBuffer(A);A.finish(I,nR);const o=A.asUint8Array();e.sendBinary(o)}setFromBuffer(A,e){if(!A)return;this.guid=A,this.time=e.time().toFloat64();const t=e.avatarId();t&&(this.avatarId=t);const g=e.position();g&&this.position.set(g.x(),g.y(),g.z());const I=e.rotation();I&&this.rotation.set(I.x(),I.y(),I.z(),I.w());const o=e.posLeftHand();o&&this.posLeftHand.set(o.x(),o.y(),o.z());const C=e.posRightHand();C&&this.posRightHand.set(C.x(),C.y(),C.z());const s=e.rotLeftHand();s&&this.rotLeftHand.set(s.x(),s.y(),s.z(),s.w());const n=e.rotRightHand();n&&this.rotRightHand.set(n.x(),n.y(),n.z(),n.w()),this.scale=e.scale()}};let jo=mh;r(jo,"invertRotation",new kA().setFromAxisAngle(new k(0,1,0),Math.PI)),r(jo,"quat0",new kA),r(jo,"quat1",new kA);class al extends MA{constructor(){super(...arguments);r(this,"webXR",null);r(this,"debugAvatarUser",null);r(this,"voip",null);r(this,"tempState",new jo(""));r(this,"_removeAvatarsList",[]);r(this,"eventSub_ConnectionEvent",null);r(this,"eventSub_WebXRStartEvent",null);r(this,"eventSub_WebXREndEvent",null);r(this,"eventSub_WebXRUpdateEvent",null);r(this,"avatars",{});r(this,"localAvatar",null);r(this,"k_LocalAvatarNoNetworkingGuid","local");r(this,"ownership",null);r(this,"xrState",null);r(this,"builder",new EE(1024))}async awake(){if(this.webXR||(this.webXR=eA.getComponent(this.gameObject,Se)),this.webXR||(this.webXR=eA.findObjectOfType(Se,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=eA.findObjectOfType(Se,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=eA.findObjectOfType(nn,this.context)),Mc){const e="debug-avatar-"+Mc,t=new JC(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof Mc=="string"&&Mc.length>0)if(await t.setAvatarOverride(Mc)){const g=new jo(e);g.position.y+=1;const I=.5;g.posLeftHand.y+=I,g.posLeftHand.x+=I,g.posRightHand.y+=I,g.posRightHand.x-=I,t.tryUpdate(g,0)}else t.destroy()}}onEnable(){if(!this.webXR&&(this.webXR=eA.getComponent(this.gameObject,Se),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),Se.addEventListener(Ft.XRStarted,this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),Se.addEventListener(Ft.XRUpdate,this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),Se.addEventListener(Ft.XRStopped,this.eventSub_WebXREndEvent),this.eventSub_ConnectionEvent=this.onConnected.bind(this),this.context.connection.beginListen(gi.JoinedRoom,this.eventSub_ConnectionEvent),this.context.connection.beginListen("webxr-user-joined",e=>{console.log("webxr user joined evt")}),this.context.connection.beginListen("webxr-user-left",e=>{const t=e.id!==null&&e.id!==void 0;if(t&&(console.log("webxr user left evt"),t)){const g=this.avatars[e.id];g==null||g.destroy(),this.avatars[e.id]=void 0}}),this.context.connection.beginListenBinary(nR,e=>{const t=e.guid();if(!t)return;const g=e.time().toFloat64(),I=this.tempState;I.setFromBuffer(t,e);const o=this.onTryGetAvatar(t,g);o==null||o.tryUpdate(I,g)}),this.context.connection.beginListen("vr-session-update",e=>{const t=e.guid,g=e.time,I=this.onTryGetAvatar(t,g);I==null||I.tryUpdate(e,g)})}onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;const g=new Date().getTime()-t;if(g>5e3)return wJ&&console.log("old data",g,e),null;let I=this.avatars[e];if(I===void 0)try{console.log("create new avatar");const o=new JC(this.context,e,this.webXR);I=o,this.avatars[e]=o}catch(o){this.avatars[e]=null,console.error(o)}return I}onDisable(){this.eventSub_ConnectionEvent&&this.context.connection.stopListen(gi.JoinedRoom,this.eventSub_ConnectionEvent),Se.removeEventListener(Ft.XRStarted,this.eventSub_WebXRStartEvent),Se.removeEventListener(Ft.XRUpdate,this.eventSub_WebXRUpdateEvent),Se.removeEventListener(Ft.XRStopped,this.eventSub_WebXREndEvent)}update(){const e=yG();this.debugAvatarUser&&(this.debugAvatarUser.lastUpdate=e),this.detectPotentiallyDisconnectedAvatarsAndRemove();for(const t in this.avatars){const g=this.avatars[t];g&&g.update()}}detectPotentiallyDisconnectedAvatarsAndRemove(){const e=yG();for(const t in this.avatars){const g=this.avatars[t];if(!g){this._removeAvatarsList.push(t);continue}e-g.lastUpdate>1e4&&(console.log("avatar timed out (didnt receive any updates in a while) - destroying it now"),g.destroy(),this.avatars[t]=void 0)}for(const t of this._removeAvatarsList)delete this.avatars[t];this._removeAvatarsList.length=0}buildLocalAvatar(){var t;if(this.localAvatar)return;const e=((t=this.context.connection)==null?void 0:t.connectionId)??this.k_LocalAvatarNoNetworkingGuid;this.localAvatar=new JC(this.context,e,this.webXR),this.localAvatar.isLocalAvatar=!0,this.localAvatar.setAvatarOverride(this.getAvatarId()),this.avatars[this.localAvatar.guid]=this.localAvatar}onConnected(){var e,t,g;wJ&&console.log("Hey you are connected as "+this.context.connection.connectionId),((e=this.localAvatar)==null?void 0:e.guid)===this.k_LocalAvatarNoNetworkingGuid&&(this.localAvatar&&((t=this.localAvatar)==null||t.destroy(),this.avatars[this.localAvatar.guid]=void 0),this.localAvatar=null,this.xrState=null,(g=this.ownership)==null||g.freeOwnership(),this.ownership=null)}onXRSessionStart(e){var t,g,I;if(console.log("XR session started"),this.context.connection.send("webxr-user-joined",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&((t=this.localAvatar)==null||t.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null),this.xrState=null,(g=this.ownership)==null||g.freeOwnership(),this.ownership=null,this.avatars)for(const o in this.avatars)(I=this.avatars[o])==null||I.updateFlags()}onXRSessionEnded(e){var t;console.log("XR session ended"),this.context.connection.send("webxr-user-left",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&((t=this.localAvatar)==null||t.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null)}onXRSessionUpdate(e){this.xrState??(this.xrState=new jo(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid)),this.ownership??(this.ownership=new rw(this.context.connection,this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid)),this.ownership.guid=this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid,this.buildLocalAvatar();const{frame:t,xr:g,rig:I}=e,o=t.getViewerPose(g.getReferenceSpace());if(!o)return;const C=o==null?void 0:o.transform,s=C.position,n=C.orientation;this.xrState.update(I,s,n,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 rA("avatar")??null}}var AtA=Object.defineProperty,etA=Object.getOwnPropertyDescriptor,qE=(i,A,e,t)=>{for(var g=t>1?void 0:t?etA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&AtA(A,e,g),g};async function jH(){return YG()?!0:"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function zH(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}let zD=!1,ZD=!1;jH().then(i=>zD=i);zH().then(i=>ZD=i);var Ft=(i=>(i.XRStarted="xrStarted",i.XRStopped="xrStopped",i.XRUpdate="xrUpdate",i.RequestVRSession="requestVRSession",i.ModifyAROptions="modify-ar-options",i))(Ft||{}),zB;const Li=(zB=class extends MA{constructor(){super(...arguments);r(this,"enableVR",!0);r(this,"enableAR",!0);r(this,"defaultAvatar");r(this,"handModelPath","");r(this,"createVRButton",!0);r(this,"createARButton",!0);r(this,"controllers",[]);r(this,"rig");r(this,"isInit",!1);r(this,"_requestedAR",!1);r(this,"_requestedVR",!1);r(this,"_isInAR",!1);r(this,"_isInVR",!1);r(this,"_arButton");r(this,"_vrButton");r(this,"webAR",null);r(this,"_transformOrientation",new kA);r(this,"_currentHeadPose",null);r(this,"_originalCameraParent",null);r(this,"_originalCameraPosition",new k);r(this,"_originalCameraRotation",new kA);r(this,"_originalXRRigParent",null);r(this,"_originalXRRigPosition",new k);r(this,"_originalXRRigRotation",new kA);r(this,"xrMirrorWindow",null)}static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(zD||ZD)}static get IsARSupported(){return zD}static get IsVRSupported(){return ZD}static get OptionalFeatures_VR(){return this._optionalFeatures_VR}static get OptionalFeatures_AR(){return this._optionalFeatures_AR}static addEventListener(A,e){return this.events.addEventListener(A,e),e}static removeEventListener(A,e){return this.events.removeEventListener(A,e),e}static dispatchEvent(A,e){this.events.dispatchEvent({type:A,detail:e})}static createVRButton(A,e){Li.XRSupported?A.__internalAwake():console.warn("WebXR is not supported on this device");const t={optionalFeatures:Li.OptionalFeatures_VR},g=hh.createButton(A.context.renderer,t);return g.classList.add("webxr-ar-button"),g.classList.add("webxr-button"),this.resetButtonStyles(g),((e==null?void 0:e.registerClick)??!0)&&g.addEventListener("click",A.onClickedVRButton.bind(A)),g}static createARButton(A,e){var o;A.__internalAwake();const t=(o=A.webAR)==null?void 0:o.getAROverlayContainer(),g={optionalFeatures:[...this.OptionalFeatures_AR]};t?(g.domOverlay={root:t},g.optionalFeatures.push("dom-overlay"),g.optionalFeatures.push("hit-test")):console.warn("No dom overlay root found, HTML overlays on top of screen-based AR will not work.");const I=r6.createButton(A.context.renderer,g,this.onModifyAROptions.bind(this));return I.classList.add("webxr-ar-button"),I.classList.add("webxr-button"),Li.resetButtonStyles(I),((e==null?void 0:e.registerClick)??!0)&&I.addEventListener("click",A.onClickedARButton.bind(A)),I}static onModifyAROptions(A){Li.dispatchEvent("modify-ar-options",A)}static resetButtonStyles(A){A&&(A.style.position="",A.style.bottom="",A.style.left="")}endSession(){const A=this.context.renderer.xr.getSession();A&&A.end()}get Rig(){return this.rig||this.ensureRig(),this.rig}get Controllers(){return this.controllers}get LeftController(){var A,e;return this.controllers.length>0&&((A=this.controllers[0].input)==null?void 0:A.handedness)==="left"?this.controllers[0]:this.controllers.length>1&&((e=this.controllers[1].input)==null?void 0:e.handedness)==="left"?this.controllers[1]:null}get RightController(){var A,e;return this.controllers.length>0&&((A=this.controllers[0].input)==null?void 0:A.handedness)==="right"?this.controllers[0]:this.controllers.length>1&&((e=this.controllers[1].input)==null?void 0:e.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=gg.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!eA.findObjectOfType(al,this.context)){const A=eA.addNewComponent(this.gameObject,al,!1);A.webXR=this}this.webAR=new Rr(this)}start(){location.protocol=="http:"&&location.host.indexOf("localhost")<0&&(oC("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,Li.XRSupported;let A,e;const t=document.createElement("div");t.classList.add("webxr-buttons"),this.context.domElement.append(t),this.enableAR&&this.createARButton&&zD&&(A=Li.createARButton(this),this._arButton=A,t.appendChild(A)),this.createVRButton&&this.enableVR&&ZD&&(e=Li.createVRButton(this),this._vrButton=e,t.appendChild(e)),setTimeout(()=>{Li.resetButtonStyles(e),Li.resetButtonStyles(A)},1e3)}get TransformOrientation(){return this._transformOrientation}get HeadPose(){return this._currentHeadPose}onBeforeRender(A){var t;if(!A)return;const e=this.context.renderer.xr.getSession();if(e){const g=A.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(!g)return;this._currentHeadPose=g;const I=g==null?void 0:g.transform;I&&this._transformOrientation.set(I.orientation.x,I.orientation.y,I.orientation.z,I.orientation.w),Li._isInXr===!1&&e&&this.onEnterXR(e,A);for(const o of this.controllers)o.onUpdate(e);this._isInAR&&((t=this.webAR)==null||t.onUpdate(e,A))}Li.events.dispatchEvent({type:"xrUpdate",frame:A,xr:this.context.renderer.xr,rig:this.rig})}onClickedARButton(){this._isInAR||(this._requestedAR=!0,this._requestedVR=!1,this.captureStateBeforeXR())}onClickedVRButton(){if(!this._isInVR){if(this._requestedVR){this.onExitXR(null);return}this._requestedAR=!1,this._requestedVR=!0,this.captureStateBeforeXR(),this.ensureRig();for(let A=0;A<2;A++)ti.Create(this,A,this.gameObject,MQ.PhysicalDevice);Li.events.dispatchEvent({type:"requestVRSession"})}}captureStateBeforeXR(){this.context.mainCamera&&(this._originalCameraPosition.copy(ye(this.context.mainCamera)),this._originalCameraRotation.copy(Hi(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent),this.Rig&&(this._originalXRRigParent=this.Rig.parent,this._originalXRRigPosition.copy(this.Rig.position),this._originalXRRigRotation.copy(this.Rig.quaternion))}ensureRig(){if(!this.rig){const A=eA.findObjectOfType(xw,this.context);A?this.rig=A.gameObject:(this.rig=new co,this.rig.rotateY(Math.PI),this.rig.name="XRRig",this.context.scene.add(this.rig))}}onEnterXR(A,e){var o,C;console.log("[XR] session begin",A),Li._isInXr=!0,this.ensureRig();const t=this.context.renderer.xr.getReferenceSpace();if(t&&this.rig){const s=e.getViewerPose(t),n=s==null?void 0:s.transform.orientation;if(n){const a=new kA(n.x,n.y,n.z,n.w),B=new Ui().setFromQuaternion(a);this.rig.rotateY(B.y)}}const g=this.context.renderer.xr;if(this.context.mainCamera){const s=g.getCamera(this.context.mainCamera),n=(o=this.context.mainCameraComponent)==null?void 0:o.cullingMask;if(n!==void 0){for(const a of s.cameras)a.layers.mask=n;s.layers.mask=n}else{for(const a of s.cameras)a.layers.enableAll();s.layers.enableAll()}this.rig.add(this.context.mainCamera),this._requestedAR&&this.context.scene.add(this.rig)}const I=this._requestedAR?Mi.AR:Mi.VR;switch(lo.Global.Set(I),I){case Mi.AR:this.context.xrSessionMode=jh.ImmersiveAR,this._isInAR=!0,(C=this.webAR)==null||C.onBegin(A);break;case Mi.VR:this.context.xrSessionMode=jh.ImmersiveVR,this._isInVR=!0,this.onEnterVR(A);break}A.addEventListener("end",()=>{console.log("[XR] session end"),Li._isInXr=!1,this.onExitXR(A)}),this.onEnterXR_HandleMirrorWindow(A),Li.events.dispatchEvent({type:"xrStarted",session:A})}onExitXR(A){var t,g,I;const e=this._isInAR;this._isInAR&&A&&((t=this.webAR)==null||t.onEnd(A)),this._isInAR=!1,this._isInVR=!1,this._requestedAR=!1,this._requestedVR=!1,this.context.xrSessionMode=void 0,this.xrMirrorWindow&&(this.xrMirrorWindow.close(),this.xrMirrorWindow=null),this.destroyControllers(),this.context.mainCamera&&((g=this._originalCameraParent)==null||g.add(this.context.mainCamera),hi(this.context.mainCamera,this._originalCameraPosition),fI(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),e&&((I=this._originalXRRigParent)==null||I.add(this.rig),this.rig.position.copy(this._originalXRRigPosition),this.rig.quaternion.copy(this._originalXRRigRotation)),lo.Global.Set(Mi.Browser|Mi.ThirdPerson),Li.events.dispatchEvent({type:"xrStopped",session:A})}onEnterVR(A){}destroyControllers(){var A;for(let e=this.controllers.length-1;e>=0;e-=1)(A=this.controllers[e])==null||A.destroy();this.controllers.length=0}onEnterXR_HandleMirrorWindow(A){rA("mirror")&&setTimeout(()=>{if(!Li.IsInWebXR)return;const e=new URL(window.location.href);Fh(e.searchParams,Wp,1),Fh(e.searchParams,"isMirror",1);const t=e.toString();this.xrMirrorWindow=window.open(t,"webxr sync","popup=yes"),this.xrMirrorWindow&&(this.xrMirrorWindow.onload=()=>{this.xrMirrorWindow&&(this.xrMirrorWindow.onbeforeunload=()=>{Li.IsInWebXR&&A.end()})})},1e3)}},r(zB,"_isInXr",!1),r(zB,"events",new Pi),r(zB,"_optionalFeatures_VR",["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]),r(zB,"_optionalFeatures_AR",["anchors","local-floor","hand-tracking","layers"]),zB);let Se=Li;qE([w()],Se.prototype,"enableVR",2);qE([w()],Se.prototype,"enableAR",2);qE([w(gg)],Se.prototype,"defaultAvatar",2);qE([w()],Se.prototype,"handModelPath",2);qE([w()],Se.prototype,"createVRButton",2);qE([w()],Se.prototype,"createARButton",2);const DQ=class{constructor(A){r(this,"_webxr");r(this,"reticle",null);r(this,"reticleParent",null);r(this,"hitTestSource",null);r(this,"reticleActive",!0);r(this,"previousBackground",null);r(this,"previousEnvironment",null);r(this,"sessionRoot",null);r(this,"_previousParent",null);r(this,"arDomOverlay",null);r(this,"arOverlayElement",null);r(this,"noHitTestAvailable",!1);r(this,"didPlaceARSessionRoot",!1);this._webxr=A}get webxr(){return this._webxr}get context(){return this.webxr.context}getAROverlayContainer(){this.arDomOverlay=this.webxr.context.domElement;const A=this.arDomOverlay;return A.getAROverlayContainer?this.arOverlayElement=A.getAROverlayContainer():this.arOverlayElement=this.arDomOverlay,this.arOverlayElement}setReticleActive(A){this.reticleActive=A}async onBegin(A){var o,C,s,n;const e=this.webxr.context;this.reticleActive=!0,this.didPlaceARSessionRoot=!1,this.getAROverlayContainer();const t=(o=navigator.userAgent)!=null&&o.includes("OculusBrowser")?MQ.PhysicalDevice:MQ.Touch,g=t===MQ.Touch?4:2;for(let a=0;a<g;a++)ti.Create(this.webxr,a,this.webxr.gameObject,t);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=eA.findObjectOfType(Na,e)),this.previousBackground=e.scene.background,this.previousEnvironment=e.scene.environment,e.scene.background=null,A.requestReferenceSpace("viewer").then(a=>{var B,Q;(Q=(B=A.requestHitTestSource)==null?void 0:B.call(A,{space:a}))==null||Q.then(E=>{this.hitTestSource=E}).catch(E=>{this.noHitTestAvailable=!0,console.warn("WebXR: Hit test not supported",E)})}),!this.reticle&&this.sessionRoot&&(this.reticle=new fA(new aE(.07,.09,32).rotateX(-Math.PI/2),new wt),this.reticle.name="AR Placement reticle",this.reticle.matrixAutoUpdate=!1,this.reticle.visible=!1,this.reticleParent=new UA,this.reticleParent.name="AR Reticle Parent",this.reticleParent.matrixAutoUpdate=!1,this.reticleParent.add(this.reticle),this.webxr.scene?(this.context.scene.add(this.reticleParent),this.context.scene.visible=!0):console.warn("Could not found WebXR Rig")),this._previousParent=this.webxr.gameObject,DQ.tempWebXRObject||(DQ.tempWebXRObject=new UA),this.context.scene.add(DQ.tempWebXRObject),eA.addComponent(DQ.tempWebXRObject,this.webxr),this.sessionRoot?(this.sessionRoot.webAR=this,(C=this.sessionRoot)==null||C.onBegin(A)):console.warn("No WebARSessionRoot found in scene");const I=this.context.domElement;(s=I==null?void 0:I.onEnterAR)==null||s.call(I,A,this.arOverlayElement),(n=this.context.mainCameraComponent)==null||n.applyClearFlagsIfIsActiveCamera()}onEnd(A){var g,I;this._previousParent&&(eA.addComponent(this._previousParent,this.webxr),this._previousParent=null),this.hitTestSource=null;const e=this.webxr.context;e.scene.background=this.previousBackground,e.scene.environment=this.previousEnvironment,this.sessionRoot&&this.sessionRoot.onEnd(this.webxr.Rig,A);const t=this.context.domElement;(g=t.onExitAR)==null||g.call(t,A),(I=this.context.mainCameraComponent)==null||I.applyClearFlagsIfIsActiveCamera()}onUpdate(A,e){var g,I;if(this.noHitTestAvailable===!0){if(this.reticle&&(this.reticle.visible=!1),!this.didPlaceARSessionRoot){this.didPlaceARSessionRoot=!0;const o=this.webxr.Rig,C=ttA.clone();(g=this.sessionRoot)==null||g.placeAt(o,C)}return}if(!this.hitTestSource)return;const t=e.getHitTestResults(this.hitTestSource);if(t.length){const o=t[0],C=this.webxr.context.renderer.xr.getReferenceSpace();if(C){const s=o.getPose(C);if(this.sessionRoot){const n=this.sessionRoot.onUpdate(this.webxr.Rig,A,s);this.didPlaceARSessionRoot=n}if(this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&s)){const n=s.transform.matrix;this.reticle.matrix.fromArray(n),this.webxr.Rig&&this.reticle.matrix.premultiply(this.webxr.Rig.matrix)}}}else(I=this.sessionRoot)==null||I.onUpdate(this.webxr.Rig,A,null),this.reticle&&(this.reticle.visible=!1)}};let Rr=DQ;r(Rr,"tempWebXRObject");const ttA=new OA().identity().makeTranslation(0,0,0);class Sr{constructor(A,e){r(this,"used",!1);r(this,"inputSource");r(this,"object");r(this,"pointerId");r(this,"isDown");r(this,"isUp");r(this,"isPressed");r(this,"isClicked");r(this,"input");r(this,"event");this.event=e,this.input=A}use(){this.used=!0,this.pointerId!==void 0&&this.input.setPointerUsed(this.pointerId)}stopPropagation(){var A;(A=this.event)==null||A.stopImmediatePropagation()}Use(){this.use()}StopPropagation(){var A;(A=this.event)==null||A.stopImmediatePropagation()}}class bE extends MA{awake(){lI.createIfNoneExists(this.context)}onEnable(){var A;(A=lI.get(this.context))==null||A.register(this)}onDisable(){var A;(A=lI.get(this.context))==null||A.unregister(this)}performRaycast(A=null){return null}}class Hr extends bE{constructor(){super(...arguments);r(this,"targets",null);r(this,"raycastHits",[])}start(){this.targets=[this.gameObject]}performRaycast(e=null){return this.targets?(e??(e=new CC),e.targets=this.targets,e.results=this.raycastHits,this.context.physics.raycast(e)):null}}class aR extends Hr{}const Pc=rA("debugeventsystem");var SG=(i=>(i.BeforeHandleInput="BeforeHandleInput",i.AfterHandleInput="AfterHandleInput",i))(SG||{});const wC=class extends MA{constructor(){super();r(this,"raycaster",[]);r(this,"_selectStartFn");r(this,"_selectEndFn");r(this,"_selectUpdateFn");r(this,"_handleEventFn");r(this,"lastPointerEvent",null);r(this,"objectsHoveredThisFrame",[]);r(this,"objectsHoveredLastFrame",[]);r(this,"raisedPointerDownEvents",[]);r(this,"raisedPointerDownObjects",[]);r(this,"_didMove",!1);r(this,"_tempComponentsArray",[]);r(this,"_sortedHits",[]);r(this,"_sortingBuffer",[]);r(this,"_noDepthTestingResults",[]);r(this,"handleEventsArray",[]);r(this,"out",{});r(this,"currentActiveMeshUIComponents",[]);wC.systems.push(this)}static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,wC.systems.length<=0&&wC.systems.push(...eA.findObjectsOfType(wC,e)));for(const g of wC.systems)if(g.context===e)return;const t=new UA;eA.addNewComponent(t,wC),e.scene.add(t)}static get systems(){const e=pe.Current;return this._eventSystemMap.has(e)||this._eventSystemMap.set(e,[]),this._eventSystemMap.get(e)}static get(e){const t=this._eventSystemMap.get(e);return t&&t.length>0?t[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(e,t){ks.update(e,t)}static markUIDirty(e){ks.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.objectsHoveredThisFrame.length>0}onDestroy(){wC.systems.splice(wC.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!eA.findObjectOfType(bE,this.context)){const t=eA.addNewComponent(this.context.scene,Hr);this.raycaster.push(t),Xg()&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found",this)}}register(e){var t;e&&this.raycaster&&!this.raycaster.includes(e)&&((t=this.raycaster)==null||t.push(e))}unregister(e){var g,I;const t=(g=this.raycaster)==null?void 0:g.indexOf(e);t!==void 0&&t!==-1&&((I=this.raycaster)==null||I.splice(t,1))}onEnable(){const e=new Map;this._selectStartFn??(this._selectStartFn=(g,I)=>{if(!I.grab)return;ks.resetLastSelected();const o=new Sr(this.context.input);o.inputSource=g,o.isDown=g.selectionDown,o.isUp=g.selectionUp,o.isPressed=g.selectionPressed,o.isClicked=!1,e.set(g,I.grab),I.grab&&!this.handleEvents(I.grab,o)&&(I.grab=null)}),this._selectEndFn??(this._selectEndFn=(g,I)=>{var s;if(!I.grab)return;const o=new Sr(this.context.input);o.inputSource=g,o.isDown=g.selectionDown,o.isUp=g.selectionUp,o.isPressed=g.selectionPressed,o.isClicked=g.selectionClick,this.handleEvents(I.grab,o);const C=e.get(g);if(e.set(g,null),C)for(let n=0;n<this.raisedPointerDownEvents.length;n++){const a=this.raisedPointerDownEvents[n];this.raisedPointerDownObjects[n]===C&&a&&((s=a.onPointerUp)==null||s.call(a,o),this.raisedPointerDownEvents.splice(n,1),this.raisedPointerDownObjects.splice(n,1),n--)}});const t=new CC;this._selectUpdateFn??(this._selectUpdateFn=g=>{t.ray=g.getRay();const I=this.performRaycast(t);if(!I)return;const o=new Sr(this.context.input);o.inputSource=g,this.handleIntersections(I,o)}),ti.addEventListener(Ss.SelectStart,this._selectStartFn),ti.addEventListener(Ss.SelectEnd,this._selectEndFn),ti.addEventListener(Ss.Update,this._selectUpdateFn),this._handleEventFn??(this._handleEventFn=this.onHandleEvents.bind(this)),this.context.pre_update_callbacks.push(this._handleEventFn)}onDisable(){ti.removeEventListener(Ss.SelectStart,this._selectStartFn),ti.removeEventListener(Ss.SelectEnd,this._selectEndFn),ti.removeEventListener(Ss.Update,this._selectUpdateFn),this.context.pre_update_callbacks.splice(this.context.pre_update_callbacks.indexOf(this._handleEventFn),1)}onHandleEvents(){if(this.objectsHoveredThisFrame.length=0,this.resetMeshUIStates(),Se.IsInWebXR||this.context.input.isKeyPressed("AltLeft")||this.context.input.isKeyPressed("AltRight"))return;if(!this._didMove){const C=this.context.input.getPointerPositionRC(0);if(C&&C.x===0&&C.y===0)return;this._didMove=!0}let e=0;for(const C of this.context.input.foreachPointerId()){const s=this.context.input.getPointerDown(C),n=this.context.input.getPointerUp(C);if(s||n){e=C;break}}const t=this.context.input.getPointerEvent(e),g=new Sr(this.context.input,t);g.inputSource=this.context.input,g.pointerId=e,g.isClicked=this.context.input.getPointerClicked(e),g.isDown=this.context.input.getPointerDown(e),g.isUp=this.context.input.getPointerUp(e),g.isPressed=this.context.input.getPointerPressed(e),Pc&&g.isClicked&&console.log("CLICK",e);const I=this.performRaycast(null);if(!I)return;this.lastPointerEvent=g;const o={sender:this,args:g,hasActiveUI:this.currentActiveMeshUIComponents.length>0};Pc&&g.isClicked&&eg("EventSystem: "+g.pointerId+" - "+this.context.time.frame+" - Up:"+g.isUp+", Down:"+g.isDown),this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:o})),this.handleIntersections(I,g),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:o}))}onBeforeRender(){if(this.lastPointerEvent)this.lastPointerEvent.used=!1;else return;if(this.lastPointerEvent.isUp){for(const t of this.raisedPointerDownEvents)t.onPointerUp&&t.onPointerUp(this.lastPointerEvent);this.raisedPointerDownEvents.length=0,this.raisedPointerDownObjects.length=0}for(const t of this.objectsHoveredLastFrame)if(this.objectsHoveredThisFrame.indexOf(t)<0){this._tempComponentsArray.length=0;const g=eA.getComponentsInParent(t,MA,this._tempComponentsArray);this.lastPointerEvent.object=t;for(let I=0;I<g.length;I++){const o=g[I];if(!o.gameObject||o.destroyed)continue;const C=o;C.onPointerExit&&C.onPointerExit(this.lastPointerEvent)}}const e=this.objectsHoveredLastFrame;this.objectsHoveredLastFrame=this.objectsHoveredThisFrame,this.objectsHoveredThisFrame=e}performRaycast(e){if(!this.raycaster)return null;this._sortedHits.length=0;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;const g=t.performRaycast(e);g&&g.length>0&&this._sortedHits.push(...g)}return this._sortedHits.sort((t,g)=>t.distance-g.distance),this._sortedHits}handleIntersections(e,t){if(!e||e.length<=0)return!1;e=this.sortCandidates(e);for(const g of e){const{object:I}=g;if(this.handleEvents(I,t))return!0}return!1}sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const g=e[t],I=g.object;if(I.material&&I.material.depthTest===!1){this._noDepthTestingResults.push(g);continue}this._sortingBuffer.push(g)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEvents(e,t){if(!this.testIsVisible(e))return t.isClicked&&Pc&&console.log("not allowed",e),!1;const g=e;t.object=e,this.lastPointerEvent=t;const I=e.parent;let o=!1;const C=t.isClicked??!1;let s=null;if(I&&I.isUI){const n=(t.isPressed||t.isClicked)??!1;if(I[Ns]){const a=I[Ns].gameObject;if(a){if(!zQ.isInteractable(a,this.out))return!1;s=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,n),e=a,o=!0}}if(!o&&this.handleMeshUiObjectWithoutShadowDom(I,n))return!0}if(C&&Pc&&console.log(this.context.time.frame,e),this.objectsHoveredThisFrame.push(e),s===null||s.interactable){const n=this.objectsHoveredLastFrame.indexOf(e)>=0;this.handleEventsArray.length=0;const a=eA.getComponentsInParent(e,MA,this.handleEventsArray);for(let B=0;B<a.length;B++){if(t.used)return!0;if(a[B].destroyed)continue;const Q=a[B];if(Q.interactable!==!1){if(Q.onPointerEnter&&(n||Q.onPointerEnter(t)),Q.onPointerMove&&Q.onPointerMove(t),t.isDown&&Q.onPointerDown&&!this.raisedPointerDownEvents.includes(Q)&&(Q.onPointerDown(t),this.raisedPointerDownEvents.push(Q),this.raisedPointerDownObjects.push(g)),t.isUp&&Q.onPointerUp){const E=this.raisedPointerDownEvents.indexOf(Q);E!==-1&&this.raisedPointerDownEvents.splice(E,1),Q.onPointerUp(t)}t.isClicked&&Q.onPointerClick&&Q.onPointerClick(t)}}}return!0}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}handleMeshUIIntersection(e,t){const g=ks.updateState(e,t);return g&&this.currentActiveMeshUIComponents.push(g),g!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&ks.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];ks.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?eA.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}};let lI=wC;r(lI,"_eventSystemMap",new Map),r(lI,"didSearchEventSystem",!1);class ks{static markDirty(){this.needsUpdate=!0}static update(A,e){const t=e.time.frameCount;for(const g of this.lastUpdateFrame)if(g.context===e){if(t===g.frame)return;g.frame=t;let I=this.needsUpdate||t<1;g.nextUpdate===e.time.frameCount&&(I=!0),I&&(Pc&&console.log("Update threemeshui"),this.needsUpdate=!1,A.update());return}this.lastUpdateFrame=[{context:e,frame:t,nextUpdate:t}],A.update()}static updateState(A,e){let t=null;if(A&&(t=this.findBlockInParent(A),t&&t!==this.lastSelected)){if(t.interactable===!1)return null;this.needsUpdate=!0}return t}static resetLastSelected(){const A=this.lastSelected;A&&(this.lastSelected=null,this.resetState(A))}static resetState(A){A&&(this.needsUpdate=!0)}static findBlockInParent(A){return A?A.isBlock?A:this.findBlockInParent(A.parent):null}}r(ks,"lastSelected",null),r(ks,"lastUpdateFrame",[]),r(ks,"needsUpdate",!1);const XD=Symbol("cameraController");function itA(i){return i[XD]}function yJ(i,A,e){e?i[XD]=A:i[XD]===A&&(i[XD]=null)}var gtA=Object.defineProperty,ItA=Object.getOwnPropertyDescriptor,otA=(i,A,e,t)=>{for(var g=t>1?void 0:t?ItA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&gtA(A,e,g),g};const AD=rA("freecam"),SJ=rA("debugcamerafit"),CtA={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let c0;class Bn extends MA{constructor(){super(...arguments);r(this,"autoRotate",!1);r(this,"autoRotateSpeed",1);r(this,"enableKeys",!0);r(this,"enableDamping",!0);r(this,"dampingFactor",.1);r(this,"enableZoom",!0);r(this,"minZoom",0);r(this,"maxZoom",1/0);r(this,"enablePan",!0);r(this,"lookAtConstraint",null);r(this,"lookAtConstraint01",1);r(this,"middleClickToFocus",!0);r(this,"doubleClickToFocus",!0);r(this,"useSlerp",!0);r(this,"debugLog",!1);r(this,"targetLerpSpeed",5);r(this,"_lookTargetPosition");r(this,"_controls",null);r(this,"_cameraObject",null);r(this,"_lerpToTargetPosition",!1);r(this,"_lerpCameraToTarget",!1);r(this,"_cameraTargetPosition",null);r(this,"_inputs",0);r(this,"_enableTime",0);r(this,"_startedListeningToKeyEvents",!1);r(this,"_eventSystem");r(this,"_afterHandleInputFn");r(this,"_camera",null);r(this,"_syncedTransform");r(this,"targetElement",null);r(this,"onControlsChangeStarted",()=>{this._syncedTransform&&this._syncedTransform.requestOwnership()});r(this,"_shouldDisable",!1);r(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){var t;(t=this.controls)==null||t.addEventListener("start",e)}awake(){this._lookTargetPosition=new k,this._startedListeningToKeyEvents=!1}start(){if(this._controls){const e=eA.getComponent(this.gameObject,Yt);if(e&&!this.setFromTargetPosition()){this.debugLog&&console.log("NO TARGET");const g=ye(e.cam).length(),I=new k(0,0,-g).applyMatrix4(e.cam.matrixWorld);this.setTarget(I,!0)}}this.startCoroutine(this.startRaycastDelayed()),this._eventSystem=lI.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(SG.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var e,t;(e=this._controls)==null||e.dispose(),(t=this._eventSystem)==null||t.removeEventListener(SG.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._enableTime=this.context.time.time;const e=eA.getComponent(this.gameObject,Yt);this._camera=e;const t=e==null?void 0:e.cam;if(t&&yJ(t,this,!0),!this._controls){console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t);const g=this.targetElement??this.context.domElement,I=t==null?void 0:t.quaternion.clone();this._controls=new a6(t,g),t==null||t.quaternion.copy(I),c0===void 0&&(c0={...this._controls.keys})}this._controls&&(AD&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,Wr()&&(this.doubleClickToFocus=!0)),this._controls.enableDamping=this.enableDamping,this._controls.keys=this.enableKeys?c0:CtA,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.addEventListener("start",this.onControlsChangeStarted),(t==null?void 0:t.type)==="PerspectiveCamera"?AD||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):AD||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body))),this._syncedTransform=eA.getComponent(this.gameObject,da)??void 0}onDisable(){var e;(e=this._camera)!=null&&e.cam&&yJ(this._camera.cam,this,!1),this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted))}afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}*startRaycastDelayed(){if(yield,!this.setFromTargetPosition()){const e=new CC;e.screenPoint=new j(0,0),e.lineThreshold=.1;const t=this.context.physics.raycast(e);t.length>0&&this.setTarget(t[0].point,!0)}}onBeforeRender(){var t,g,I;if(!this._controls||this._cameraObject!==this.context.mainCamera)return;(this.context.input.getPointerDown(0)||this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2))&&(this._inputs+=1),this._inputs>0&&(this.autoRotate=!1,this._controls.autoRotate=!1,this._lerpCameraToTarget=!1,this._lerpToTargetPosition=!1),this._inputs=0;let e=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(e||(e=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3),e?this.setTargetFromRaycast():(this.context.input.getPointerDown(0)||this.context.input.mouseWheelChanged)&&(this._lerpToTargetPosition=!1,this._lerpCameraToTarget=!1),this._lerpToTargetPosition||this._lerpCameraToTarget){const o=this.context.time.deltaTime*this.targetLerpSpeed;if(this._lerpCameraToTarget&&this._cameraTargetPosition&&this._cameraObject){if(this.useSlerp){const C=(t=this._cameraObject)==null?void 0:t.position;YL(C,this._cameraTargetPosition,o)}else(g=this._cameraObject)==null||g.position.lerp(this._cameraTargetPosition,o);this._cameraObject.position.distanceTo(this._cameraTargetPosition)<1e-4&&(this._lerpCameraToTarget=!1)}this._lerpToTargetPosition&&(this.lerpTarget(this._lookTargetPosition,o),this._lookTargetPosition.distanceTo(this._controls.target)<1e-5&&(this._lerpToTargetPosition=!1))}!AD&&((I=this.lookAtConstraint)!=null&&I.locked)&&this.setFromTargetPosition(0,this.lookAtConstraint01),this._controls&&!this.context.isInXR&&(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent,this._controls.update())}setCameraTarget(e,t=!1){var g;e?(this._lerpCameraToTarget=!0,this._cameraTargetPosition=e.clone(),t&&this._cameraTargetPosition&&((g=this.controllerObject)==null||g.position.copy(this._cameraTargetPosition))):this._lerpCameraToTarget=!1}setFromTargetPosition(e=0,t=1){var I;if(!this._controls)return!1;const g=(I=this.lookAtConstraint)==null?void 0:I.sources;if(g&&g.length>0){const o=g[e];if(o)return o.getWorldPosition(this._lookTargetPosition),this.lerpTarget(this._lookTargetPosition,t),!0}return!1}setTarget(e=null,t=!1){this._controls&&(e!==null&&this._lookTargetPosition.copy(e),t?this._controls.target.copy(this._lookTargetPosition):this._lerpToTargetPosition=!0)}lerpTarget(e,t){this._controls&&this._controls.target.lerp(e,t)}distanceToTarget(e){return this._controls?this._controls.target.distanceTo(e):-1}setTargetFromRaycast(){var t,g;if(!this.controls)return;const e=this.context.physics.raycast();for(const I of e)if(I.distance>0&&eA.isActiveInHierarchy(I.object)){if(this._lookTargetPosition.copy(I.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;const o=ye(this.context.mainCamera);this._cameraTargetPosition=o.clone().sub(this.controls.target).add(this._lookTargetPosition),(g=(t=this._cameraObject)==null?void 0:t.parent)==null||g.worldToLocal(this._cameraTargetPosition)}break}}fitCamera(e,t=1.1){const g=this._cameraObject,I=this._controls;if(e!=null&&e.length||(e=this.context.scene.children),!g||!I)return;const o=new k,C=new k,s=new mg;s.makeEmpty();for(const l of e)l instanceof Uk||s.expandByObject(l,!0);g.updateMatrixWorld(),g.updateProjectionMatrix(),s.getCenter(C),s.applyMatrix4(g.matrixWorldInverse),s.getSize(o),s.setFromCenterAndSize(C,o);const n=g.fov,a=2*Math.atan(Math.tan(n*Math.PI/360/2)*g.aspect)/Math.PI*360,B=o.y/(2*Math.atan(Math.PI*n/360)),Q=o.x/(2*Math.atan(Math.PI*a/360)),E=t*Math.max(B,Q)+o.z/2;SJ&&console.log("Fit camera to objects",B,Q,"distance",E);const c=ye(g),h=I.target.clone().sub(c).normalize().multiplyScalar(E);if(I.maxDistance=E*10,I.minDistance=E*.01,I.target.copy(C),g.near=E/100,g.far=E*100,g.updateMatrixWorld(),g.updateProjectionMatrix(),hi(g,I.target.clone().sub(h)),SJ){const l=new Uk(s);this.context.scene.add(l),OL(l,Aw(g)),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",d=>{d.code==="KeyF"&&this.fitCamera(e)}))}I.update()}}otA([w(sd)],Bn.prototype,"lookAtConstraint",2);var stA=Object.defineProperty,ntA=Object.getOwnPropertyDescriptor,mo=(i,A,e,t)=>{for(var g=t>1?void 0:t?ntA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&stA(A,e,g),g},ZH=(i=>(i[i.Skybox=1]="Skybox",i[i.SolidColor=2]="SolidColor",i[i.Uninitialized=4]="Uninitialized",i))(ZH||{});const Wc=rA("debugcam"),kJ=rA("debugscreenpointtoray");var uD;const Vc=(uD=class extends MA{constructor(){super(...arguments);r(this,"_nearClipPlane",.1);r(this,"_farClipPlane",1e3);r(this,"orthographic",!1);r(this,"orthographicSize",5);r(this,"ARBackgroundAlpha",0);r(this,"_cullingMask",4294967295);r(this,"_backgroundBlurriness");r(this,"_backgroundIntensity");r(this,"_targetTexture",null);r(this,"_backgroundColor");r(this,"_fov");r(this,"_cam",null);r(this,"_clearFlags",2);r(this,"_skybox")}get isCamera(){return!0}get aspect(){return this._cam instanceof it?this._cam.aspect:this.context.domWidth/this.context.domHeight}get fieldOfView(){return this._cam instanceof it?this._cam.fov:this._fov}set fieldOfView(A){const e=this._fov!=A;if(this._fov=A,e&&this._cam&&this._cam instanceof it){if(this._fov===void 0){console.error("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(A){const e=this._nearClipPlane!=A;this._nearClipPlane=A,this._cam&&e&&(this._cam.near=A,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(A){const e=this._farClipPlane!=A;this._farClipPlane=A,this._cam&&e&&(this._cam.far=A,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(A){A!==this._clearFlags&&(this._clearFlags=A,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(A){this._cullingMask=A,this._cam&&(this._cam.layers.mask=A)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set backgroundBlurriness(A){A!==this._backgroundBlurriness&&(A===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(A,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(A){A!==this._backgroundIntensity&&(A===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(A,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(A){if(A){if(this._backgroundColor)this._backgroundColor.copy(A);else{if(!A.clone)return;this._backgroundColor=A.clone()}A.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(A){this._targetTexture=A}get targetTexture(){return this._targetTexture}get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(A,e,t){let g=this.cam;const I=Vc._origin;I.set(A,e,-1),this.context.input.convertScreenspaceToRaycastSpace(I),kJ&&console.log("screenPointToRay",A.toFixed(2),e.toFixed(2),"now:",I.x.toFixed(2),I.y.toFixed(2),"isInXR:"+this.context.isInXR),I.z=-1,I.unproject(g);const o=Vc._direction.set(I.x,I.y,I.z),C=ye(g);return o.sub(C),o.normalize(),t?(t.set(C,o),t):new on(C.clone(),o.clone())}awake(){kJ&&window.addEventListener("pointerdown",A=>{const e=A.clientX,t=A.clientY;console.log("touch",e.toFixed(2),t.toFixed(2));const g=this.screenPointToRay(e,t),I="#"+Math.floor(Math.random()*16777215).toString(16);KC.DrawRay(g.origin,g.direction,I,10)})}onEnable(){Wc&&console.log(this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),rtA(this)),this.applyClearFlagsIfIsActiveCamera()}onDisable(){this.context.removeCamera(this)}onBeforeRender(){if(this._cam&&this._targetTexture){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const A=this.context.renderer;A&&this._targetTexture.render(this.context.scene,this._cam,A)}}buildCamera(){if(this._cam)return;const A=this.gameObject.isCamera;let e=null;if(A?(e=this.gameObject,e==null||e.layers.enableAll(),e instanceof it&&(this._fov=e.fov)):e=this.gameObject.children[0],e&&e.isCamera)e.type==="PerspectiveCamera"&&(this._fov&&(e.fov=this._fov),e.near=this._nearClipPlane,e.far=this._farClipPlane,e.updateProjectionMatrix());else if(!this.orthographic)e=new it(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(e.fov=this.fieldOfView),this.gameObject.add(e);else{const t=this.orthographicSize*100;e=new iE(window.innerWidth/-t,window.innerWidth/t,window.innerHeight/t,window.innerHeight/-t,this._nearClipPlane,this._farClipPlane),this.gameObject.add(e)}this._cam=e,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){this.context.mainCameraComponent===this&&this.applyClearFlags()}applyClearFlags(){if(!this._cam){Wc&&console.log("Camera does not exist (apply clear flags)");return}switch(Wc&&eg("apply Camera clear flags: "+this._clearFlags),this._clearFlags){case 1:if(Vc.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}this.enableSkybox(),this._backgroundBlurriness!==void 0&&(this.context.scene.backgroundBlurriness=this._backgroundBlurriness),this._backgroundIntensity!==void 0&&(this.context.scene.backgroundIntensity=this._backgroundIntensity);break;case 2:if(this._backgroundColor){let A=this._backgroundColor.alpha;Vc.backgroundShouldBeTransparent(this.context)&&(A=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,A)}break;case 4:this.context.scene.background=null,this.context.renderer.setClearColor(0,0);break}}enableSkybox(){this._skybox||(this._skybox=new atA(this)),this._skybox.enable()}static backgroundShouldBeTransparent(A){var I,o,C,s;const e=(I=A.renderer.xr)==null?void 0:I.getSession();if(!e)return!1;const t=e.environmentBlendMode;Wc&&eg("Environment blend mode: "+t+" on "+navigator.userAgent);const g=t==="additive"||t==="alpha-blend";if(A.xrSessionMode===jh.ImmersiveAR&&t==="opaque"){if((o=navigator.userAgent)!=null&&o.includes("OculusBrowser"))return!0;if((C=navigator.userAgent)!=null&&C.includes("Mozilla")&&((s=navigator.userAgent)!=null&&s.includes("Mobile WebXRViewer/v2")))return!0}return g}},r(uD,"_origin",new k),r(uD,"_direction",new k),uD);let Yt=Vc;mo([w()],Yt.prototype,"fieldOfView",1);mo([w()],Yt.prototype,"nearClipPlane",1);mo([w()],Yt.prototype,"farClipPlane",1);mo([w()],Yt.prototype,"clearFlags",1);mo([w()],Yt.prototype,"orthographic",2);mo([w()],Yt.prototype,"orthographicSize",2);mo([w()],Yt.prototype,"ARBackgroundAlpha",2);mo([w()],Yt.prototype,"cullingMask",1);mo([w()],Yt.prototype,"backgroundBlurriness",1);mo([w()],Yt.prototype,"backgroundIntensity",1);mo([w(Gt)],Yt.prototype,"backgroundColor",1);mo([w(ra)],Yt.prototype,"targetTexture",1);class atA{constructor(A){r(this,"_camera");r(this,"_skybox");this._camera=A}get context(){var A;return(A=this._camera)==null?void 0:A.context}enable(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?this.context.scene.background!==this._skybox&&(Wc&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=De,this._skybox.mapping=Do,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this._camera.sourceId,this.context.lightmaps)}}function rtA(i){rA("freecam")&&i.context.mainCameraComponent===i&&eA.getOrAddComponent(i.gameObject,Bn)}class ZQ extends MA{constructor(){super(...arguments);r(this,"_listener",null)}get listener(){return this._listener==null&&(this._listener=new FM),this._listener}awake(){Fi.registerWaitForAllowAudio(()=>{if(this.destroyed)return;const e=this.listener;if(e==null||e.parent)return;const t=eA.getComponentInParent(this.gameObject,Yt);t?t.cam.add(e):this.gameObject.add(e)})}}var BtA=Object.defineProperty,QtA=Object.getOwnPropertyDescriptor,Yw=(i,A,e,t)=>{for(var g=t>1?void 0:t?QtA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&BtA(A,e,g),g};class cd{constructor(){r(this,"guid")}}Yw([w()],cd.prototype,"guid",2);class LE{constructor(){r(this,"signal");r(this,"reaction")}}Yw([w(cd)],LE.prototype,"signal",2);Yw([w(DI)],LE.prototype,"reaction",2);var _0;const Ds=(_0=class extends MA{constructor(){super(...arguments);r(this,"events")}static invoke(A){if(Ds.receivers[A]){const e=Ds.receivers[A];if(!e)return;for(const t of e)t.invoke(A)}}onEnable(){if(this.events)for(const A of this.events)Ds.receivers[A.signal.guid]||(Ds.receivers[A.signal.guid]=[]),Ds.receivers[A.signal.guid].push(this)}onDisable(){if(this.events){for(const A of this.events)if(Ds.receivers[A.signal.guid]){const e=Ds.receivers[A.signal.guid].indexOf(this);e>=0&&Ds.receivers[A.signal.guid].splice(e,1)}}}invoke(A){if(!this.events||!Array.isArray(this.events))return;let e=typeof A=="object"?A.guid:A;for(const t of this.events)if(t.signal.guid===e)try{if(t.reaction){if(!t.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",t,this);continue}}else{console.warn("Missing reaction for signal",t,this);continue}t.reaction.invoke()}catch(g){console.error(g)}}},r(_0,"receivers",{}),_0);let vE=Ds;Yw([w(LE)],vE.prototype,"events",2);var RI=(i=>(i.Activation="ActivationTrack",i.Animation="AnimationTrack",i.Audio="AudioTrack",i.Control="ControlTrack",i.Marker="MarkerTrack",i.Signal="SignalTrack",i))(RI||{}),On=(i=>(i[i.None=0]="None",i[i.Hold=1]="Hold",i[i.Loop=2]="Loop",i[i.PingPong=3]="PingPong",i[i.Continue=4]="Continue",i))(On||{}),rR=(i=>(i.Signal="SignalEmitter",i))(rR||{});const mc=rA("debugtimeline"),wf=class extends MA{constructor(){super(...arguments);r(this,"playableAsset");r(this,"playOnAwake");r(this,"extrapolationMode",1);r(this,"waitForAudio",!0);r(this,"_visibilityChangeEvt");r(this,"_clonedPlayableAsset",!1);r(this,"_speed",1);r(this,"_guidsMap");r(this,"_isPlaying",!1);r(this,"_internalUpdateRoutine");r(this,"_isPaused",!1);r(this,"_time",0);r(this,"_duration",0);r(this,"_weight",1);r(this,"_animationTracks",[]);r(this,"_audioTracks",[]);r(this,"_signalTracks",[]);r(this,"_controlTracks",[]);r(this,"_customTracks",[]);r(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks])}static registerCreateTrack(e,t){this.createTrackFunctions[e]=t}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(e){typeof e=="number"&&!Number.isNaN(e)?this._time=e:(mc||zg())&&console.error("INVALID TIMELINE.TIME VALUE",e,this.name)}get duration(){return this._duration}set duration(e){this._duration=e}get weight(){return this._weight}set weight(e){this._weight=e}get speed(){return this._speed}set speed(e){this._speed=e}awake(){var e,t,g;mc&&console.log(this,(e=this.playableAsset)==null?void 0:e.tracks),this.rebuildGraph(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,(t=this.playableAsset)==null?void 0:t.tracks,Array.isArray((g=this.playableAsset)==null?void 0:g.tracks),this)}onEnable(){var e,t;for(const g of this._audioTracks)(e=g.onEnable)==null||e.call(g);for(const g of this._customTracks)(t=g.onEnable)==null||t.call(g);this.playOnAwake&&this.play(),this._visibilityChangeEvt||(this._visibilityChangeEvt=()=>{switch(document.visibilityState){case"hidden":this.setAudioTracksAllowPlaying(!1);break;case"visible":this.setAudioTracksAllowPlaying(!0);break}}),window.addEventListener("visibilitychange",this._visibilityChangeEvt)}onDisable(){var e,t;this.stop();for(const g of this._audioTracks)(e=g.onDisable)==null||e.call(g);for(const g of this._customTracks)(t=g.onDisable)==null||t.call(g);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var e;for(const t of this._allTracks)for(const g of t)(e=g.onDestroy)==null||e.call(g)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const e=this._isPaused==!0;if(this._isPaused=!1,e&&this.invokePauseChangedMethodsOnTracks(),!this._isPlaying){if(this._isPlaying=!0,this.waitForAudio){const t=[];for(const g of this._audioTracks){const I=g.loadAudio(this._time,1,0);I&&t.push(I)}if(t.length>0&&(await Promise.all(t),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!Fi.userInteractionRegistered&&this.waitForAudio;)await Gl(200)}this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate())}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.evaluate(),this.invokePauseChangedMethodsOnTracks()))}stop(){for(const g of this._audioTracks)g.stop();const e=this._isPaused==!0,t=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.evaluate(),e&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,e&&!t&&this.invokePauseChangedMethodsOnTracks(),this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null}evaluate(){if(!this.isValid())return;let e=this._time;switch(this.extrapolationMode){case 0:this._speed>0?e=Math.min(e,this._duration):this._speed<0&&(e=Math.max(e,0)),this._time=e;break;case 1:e%=this._duration,this._time=e;break;case 2:if(e>this._duration){this.stop();return}break}this.internalEvaluate(e)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(const e of this._allTracks)for(const t of e)yield t}get audioTracks(){return this._audioTracks}resolveGuids(e){this._guidsMap=e}invokePauseChangedMethodsOnTracks(){var e;for(const t of this.forEachTrack())(e=t.onPauseChanged)==null||e.call(t)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.evaluate()),yield}internalEvaluate(e){for(const t of this.playableAsset.tracks)if(!t.muted)switch(t.type){case RI.Activation:for(let g=0;g<t.outputs.length;g++){const I=t.outputs[g];if(typeof I=="object"){let o=!1;for(const s of t.clips)s.start<=e&&e<=s.end&&(o=!0);const C=I;C.visible!==void 0&&(C.visible=o)}}break}for(const t of this._animationTracks)t.evaluate(e);for(const t of this._audioTracks)t.evaluate(e);for(const t of this._signalTracks)t.evaluate(e);for(const t of this._controlTracks)t.evaluate(e);for(const t of this._customTracks)t.evaluate(e)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Sf(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const e=this.findRoot(this.gameObject);for(const t of this.playableAsset.tracks){for(let g=t.outputs.length-1;g>=0;g--){let I=t.outputs[g];if(typeof I=="string"){this._guidsMap&&this._guidsMap[I]&&(I=this._guidsMap[I]);const o=eA.findByGuid(I,e);o===null||typeof o!="object"?(t.outputs.splice(g,1),console.warn("Failed to resolve binding",I,t.name,t.type)):(mc&&console.log("Resolved binding",I,"to",o),t.outputs[g]=o)}else if(I===null){if(t.outputs.splice(g,1),wf.createTrackFunctions[t.type])continue;t.type!==RI.Audio&&t.type!==RI.Control&&t.type!==RI.Marker&&t.type!==RI.Signal&&console.warn("Missing binding",I,t.name,t.type,this.name,this.playableAsset.name)}}if(t.type===RI.Control)for(let g=0;g<t.clips.length;g++){const I=t.clips[g];let o=I.asset.sourceObject;if(typeof o=="string"){this._guidsMap&&this._guidsMap[o]&&(o=this._guidsMap[o]);const C=eA.findByGuid(o,e);C===null||typeof C!="object"?console.warn("Failed to resolve sourceObject binding",o,t.name,I):(mc&&console.log("Resolved binding",o,"to",C),I.asset.sourceObject=C)}}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const e of this.playableAsset.tracks)if(e.muted!==!0){for(const t of e.clips)t.end>this._duration&&(this._duration=t.end);for(const t of e.markers)t.time>this._duration&&(this._duration=t.time+.001)}}}setupAndCreateTrackHandlers(){var t,g;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;const e=eA.findObjectOfType(ZQ,this.context);for(const I of this.playableAsset.tracks){const o=I.type,C=wf.createTrackFunctions[o];if(C!=null){const s=C(this,I);if(typeof s.evaluate=="function"){s.director=this,s.track=I,this._customTracks.push(s);continue}}if(I.type===RI.Animation){if(I.clips.length<=0){mc&&console.warn("Animation track has no clips",I);continue}for(let s=I.outputs.length-1;s>=0;s--){let n=I.outputs[s];if(n instanceof UA){const B=eA.getOrAddComponent(n,wI);B&&(n=B)}const a=(t=n==null?void 0:n.gameObject)==null?void 0:t.animations;if(a){const B=new Tw;B.trackOffset=I.trackOffset,B.director=this,B.track=I;for(let Q=0;Q<I.clips.length;Q++){const E=I.clips[Q],c=E.asset;if(!c){console.error("MISSING anim model?","clip#"+Q,E,I,this.playableAsset,this.name);continue}const h=c.clip;let l=h;if((typeof l=="string"||typeof l=="number")&&(l=a.find(p=>p.name===h)),!l){console.warn("Could not find animationClip for model",E,I.name,this.name,(g=this.playableAsset)==null?void 0:g.name);continue}B.mixer||(B.mixer=new Xf(n.gameObject)),B.clips.push(l),B.mixer.uncacheAction(l),B.createHooks(E.asset,l);const d=B.mixer.clipAction(l);B.actions.push(d),B.models.push(E)}this._animationTracks.push(B)}}}else if(I.type===RI.Audio){if(I.clips.length<=0)continue;const s=new Nr;if(s.director=this,s.track=I,this._audioTracks.push(s),!e)continue;s.listener=e.listener;for(let n=0;n<I.clips.length;n++){const a=I.clips[n];s.addModel(a)}}else if(I.type===RI.Marker){const s=new rl;s.director=this,s.track=I;for(const n of I.markers)switch(n.type){case rR.Signal:s.models.push(n),s.didTrigger.push(!1);break}if(s!==null&&s.models.length>0){const n=eA.getComponent(this.gameObject,vE);n&&(s.receivers.push(n),this._signalTracks.push(s))}}else if(I.type===RI.Signal){const s=new rl;s.director=this,s.track=I;for(const n of I.markers)s.models.push(n),s.didTrigger.push(!1);for(const n of I.outputs)s.receivers.push(n);this._signalTracks.push(s)}else if(I.type===RI.Control){const s=new Hw;s.director=this,s.track=I;for(const n of I.clips)s.models.push(n);s.resolveSourceObjects(this.context),this._controlTracks.push(s)}}}setAudioTracksAllowPlaying(e){for(const t of this._audioTracks)t.onAllowAudioChanged(e)}};let Ur=wf;r(Ur,"createTrackFunctions",{});const Fr=rA("debugtimeline");class hd{constructor(){r(this,"director");r(this,"track")}get muted(){return this.track.muted}set muted(A){var e;A!==this.track.muted&&(this.track.muted=A,(e=this.onMuteChanged)==null||e.call(this))}*forEachClip(A=!1){var e;if((e=this.track)!=null&&e.clips)if(A)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(const t of this.track.clips)yield t}getClipTime(A,e){return e.clipIn+(A-e.start)*e.timeScale}getClipTimeNormalized(A,e){return(A-e.start)/e.duration}evaluateWeight(A,e,t,g=!0){if(e<0||e>=t.length)return 0;const I=t[e];if(g||A>=I.start&&A<=I.end){let o=1,C=!1;if(I.easeInDuration>0){const s=Math.min((A-I.start)/I.easeInDuration,1);o*=s}if(I.easeOutDuration>0&&!C){const s=Math.min((I.end-A)/I.easeOutDuration,1);o*=s}return o}return 0}}class EtA{constructor(A){r(this,"clip");r(this,"rootPositionOffset");r(this,"rootQuaternionOffset");r(this,"rootStartPosition");r(this,"rootEndPosition");r(this,"rootStartQuaternion");r(this,"rootEndQuaternion");const e=A.getClip();this.clip=e;const t=A.getRoot(),g=t.name+".position",I=t.name+".quaternion";Fr&&console.log(e.name,e.tracks,g);for(const o of e.tracks)if(!(o.times.length<=0)){if(o.name.endsWith(g))this.rootStartPosition=new k().fromArray(o.values,0),this.rootEndPosition=new k().fromArray(o.values,o.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),Fr&&console.log(this.rootPositionOffset);else if(o.name.endsWith(I)&&(this.rootStartQuaternion=new kA().fromArray(o.values,0),this.rootEndQuaternion=new kA().fromArray(o.values,o.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),Fr)){const C=new Ui().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",C)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class Tw extends hd{constructor(){super(...arguments);r(this,"models",[]);r(this,"trackOffset");r(this,"target");r(this,"mixer");r(this,"clips",[]);r(this,"actions",[]);r(this,"_actionOffsets",[]);r(this,"_didBind",!1);r(this,"_animator",null);r(this,"_animatorWasEnabled",!1);r(this,"_useclipOffsets",!0);r(this,"_totalOffsetPosition",new k);r(this,"_totalOffsetRotation",new kA);r(this,"_totalOffsetPosition2",new k);r(this,"_totalOffsetRotation2",new kA);r(this,"_summedPos",new k);r(this,"_tempPos",new k);r(this,"_summedRot",new kA);r(this,"_tempRot",new kA);r(this,"_clipRotQuat",new kA)}onPauseChanged(){this._animator&&this._animatorWasEnabled!==void 0&&(this._animator.enabled=this.director.isPlaying===!1?this._animatorWasEnabled:!1)}createHooks(e,t){var a,B;if(((a=t.tracks)==null?void 0:a.length)<=0){console.warn("No tracks in AnimationClip",t);return}const g=t.tracks[0].name.split("."),I=g[g.length-2],o=I+".position",C=I+".quaternion";let s=!1,n=!1;for(const Q of t.tracks)Q.name.endsWith(o)?(s=!0,this.createPositionInterpolant(t,e,Q)):Q.name.endsWith(C)&&(n=!0,this.createRotationInterpolant(t,e,Q));if(!s||!n){const Q=(B=this.mixer)==null?void 0:B.getRoot(),E=t.tracks[0],c=E.name.lastIndexOf("."),h=E.name.substring(0,c),l=h.substring(h.lastIndexOf(".")+1),d=Q.getObjectByName(l);if(d)if(s){if(!n){const p=t.tracks[0].name.substring(0,c)+".quaternion";Fr&&console.warn("Create quaternion track",l,d);const u=d.quaternion,D=new jC(p,[0,t.duration],[u.x,u.y,u.z,u.w,u.x,u.y,u.z,u.w]);t.tracks.push(D),this.createRotationInterpolant(t,e,D)}}else{const p=h+".position";Fr&&console.warn("Create position track",l,d);const u=d.position,D=new la(p,[0,t.duration],[u.x,u.y,u.z,u.x,u.y,u.z]);t.tracks.push(D),this.createPositionInterpolant(t,e,D)}}}bind(){if(!this._didBind){this._didBind=!0,Fr&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const e of this.actions){const t=new EtA(e);this._actionOffsets.push(t)}this.target&&(this._animator=eA.getComponent(this.target,wI)??null,this._animator?(this._animatorWasEnabled=this._animator.enabled,this._animator.enabled=!1):this._animatorWasEnabled=!1);for(const e of this.models){const t=e.asset,g=t.position,I=t.rotation;g&&g.x!==void 0&&(g.isVector3||(t.position=new k(g.x,g.y,g.z)),I.isQuaternion||(t.rotation=new kA(I.x,I.y,I.z,I.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new k(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new kA(t.x,t.y,t.z,t.w)))}}evaluate(e){if(this.track.muted||!this.mixer)return;this.bind(),this._animator&&this.director.isPlaying&&this.director.weight>0&&(this._animator.enabled=!1),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let t=0,g=0,I=!1,o=!1;for(let C=0;C<this.clips.length;C++){const s=this.models[C],n=this.actions[C],a=s.asset;n.weight=0;const B=e>=s.start&&e<=s.end,Q=s.preExtrapolationMode,E=s.postExtrapolationMode,c=C<this.clips.length-1?this.models[C+1]:null;let h=B,l=!1;if(!h&&!I&&s.end<e&&E!==On.None?(!c||c.start>e)&&(h=!0,I=!0):C==0&&!h&&!o&&s.start>e&&Q!==On.None&&(!c||c.start<e)&&(h=!0,l=!0,o=!0),h){let d=1;d*=this.evaluateWeight(e,C,this.models,h),d*=this.director.weight;let p=B;l&&Q!==On.Hold&&(e+=s.start,p=!0);let u=this.getClipTime(e,s),D=0;const y=a.duration;if(l&&Q===On.Hold&&(u=0),p){if(a.loop)for(D+=Math.floor(u/(y+1e-6));u>y;)u-=y}else if(!B)switch(E){case On.Loop:u%=y;break;case On.PingPong:const f=Math.floor(u/y)%2!==0;u%=y,f&&(u=y-u);break}s.reversed===!0?n.time=n.getClip().duration-u:n.time=u,n.timeScale=0;const S=d;if(n.weight=S,n.clampWhenFinished=!0,n.isRunning()||n.play(),this._useclipOffsets){const R=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,f=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(g=1-d),t+=1;const M=this._summedPos.set(0,0,0),U=this._tempPos.set(0,0,0),J=this._summedRot.identity(),T=this._tempRot.identity(),Y=a.rotation;Y&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(Y,d));const b=this._actionOffsets[C];if(b.hasOffsets)for(let _=0;_<D;_++)b.rootPositionOffset?U.copy(b.rootPositionOffset):U.set(0,0,0),U.applyQuaternion(J),this._clipRotQuat&&U.applyQuaternion(this._clipRotQuat),b.rootQuaternionOffset&&(T.copy(b.rootQuaternionOffset),J.multiply(T)),M.add(U);this._clipRotQuat&&f.multiply(this._clipRotQuat),f.multiply(J),a.position&&M.add(a.position),R.add(M)}}}this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,g),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,g)),this.mixer.update(e)}createRotationInterpolant(e,t,g){var s;const I=g.createInterpolant.bind(g),o=new kA;this.ensureTrackOffsets();const C=(s=this.trackOffset)==null?void 0:s.rotation;g.createInterpolant=()=>{const n=I(),a=n.evaluate.bind(n);return n.evaluate=B=>{const Q=a(B);return o.set(Q[0],Q[1],Q[2],Q[3]),o.premultiply(this._totalOffsetRotation),C&&o.premultiply(C),Q[0]=o.x,Q[1]=o.y,Q[2]=o.z,Q[3]=o.w,Q},n}}createPositionInterpolant(e,t,g){var a,B;const I=g.createInterpolant.bind(g),o=new k;this.ensureTrackOffsets();const C=(a=this.trackOffset)==null?void 0:a.rotation,s=(B=this.trackOffset)==null?void 0:B.position;let n;g.createInterpolant=()=>{const Q=I(),E=Q.evaluate.bind(Q);return Q.evaluate=c=>{var l,d;const h=E(c);return o.set(h[0],h[1],h[2]),t.removeStartOffset&&(n===void 0?(n=null,n=(d=(l=this._actionOffsets.find(p=>p.clip===e))==null?void 0:l.rootStartPosition)==null?void 0:d.clone()):n!=null&&n.isVector3&&o.sub(n)),o.applyQuaternion(this._totalOffsetRotation),o.add(this._totalOffsetPosition),C&&o.applyQuaternion(C),s&&(o.x-=s.x,o.y+=s.y,o.z+=s.z),h[0]=o.x,h[1]=o.y,h[2]=o.z,h},Q}}}const ctA=rA("mutetimeline"),pQ=class extends hd{constructor(){super(...arguments);r(this,"models",[]);r(this,"listener");r(this,"audio",[]);r(this,"audioContextTimeOffset",[]);r(this,"lastTime",0);r(this,"_audioLoader",null)}getAudioFilePath(e){const t=this.director.sourceId;return wa(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){const g=this.models[t];this.audio[t].setVolume(e?g.asset.volume:0)}}addModel(e){const t=new Zf(this.listener);this.audio.push(t),this.models.push(e)}onDisable(){for(const e of this.audio)e.isPlaying&&e.stop()}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}}stop(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}}evaluate(e){if(ctA||this.track.muted||this.director.speed<0)return;const t=this.director.context.application.muted,g=t?.1:0;for(let I=0;I<this.models.length;I++){const o=this.models[I],C=this.audio[I];if((!C||!C.buffer)&&this.isInTimeRange(o,e-1,e+1)&&this.handleAudioLoading(o,C),Fi.userInteractionRegistered!==!1&&!(C===null||!C.buffer))if(C.playbackRate=this.director.context.time.timeScale,C.loop=o.asset.loop,e>=o.start&&e<=o.end&&e<this.director.duration){if(this.director.isPlaying==!1){if(C.isPlaying&&C.stop(),this.lastTime===e)continue}else if(!C.isPlaying)C.offset=o.clipIn+(e-o.start)*o.timeScale,C.play(g);else{const n=o.clipIn+(e-o.start)*o.timeScale,a=C.context.currentTime-C._startedAt+C.offset;Math.abs(n-a)>.3&&(C.offset=n,C.stop(),C.play(g))}let s=o.asset.volume;if(t&&(s=0),o.easeInDuration>0){const n=Math.min((e-o.start)/o.easeInDuration,1);s*=n}if(o.easeOutDuration>0){const n=Math.min((o.end-e)/o.easeOutDuration,1);s*=n}C.setVolume(s*this.director.weight)}else C.isPlaying&&C.stop()}this.lastTime=e}loadAudio(e,t=0,g=0){let I=null;const o=e-g,C=e+t;for(const s of this.models)if(this.isInTimeRange(s,o,C)){const n=this.audio[this.models.indexOf(s)],a=this.handleAudioLoading(s,n);a!==null&&(I===null&&(I=[]),I.push(a))}return I!==null?Promise.all(I):null}isInTimeRange(e,t,g){return t<=e.start&&g>=e.end||t>=e.start&&t<=e.end||g>=e.start&&g<=e.end}static dispose(){pQ._currentlyLoading.clear()}handleAudioLoading(e,t){this._audioLoader||(this._audioLoader=new Sp);const g=this.getAudioFilePath(e.asset.clip);if(pQ._currentlyLoading.get(g)){const o=pQ._currentlyLoading.get(g);return o.then(C=>{C&&t.setBuffer(C)}),o}Fr&&console.warn("LOAD audio track",g,this.director.sourceId);const I=new Promise((o,C)=>{this._audioLoader.load(g,s=>{t.setBuffer(s),o(s)},void 0,s=>{console.error("Error loading audio",s),o(null)})});return pQ._currentlyLoading.set(g,I),I}};let Nr=pQ;r(Nr,"_currentlyLoading",new Map);class rl extends hd{constructor(){super(...arguments);r(this,"models",[]);r(this,"didTrigger",[]);r(this,"receivers",[])}evaluate(e){var t;if(!this.track.muted)for(let g=0;g<this.models.length;g++){const I=this.models[g],o=this.didTrigger[g],C=I.time-e;let s=!1;if(I.retroActive)s=C<=1e-6;else{const n=Math.abs(C);n>=1e-5&&n<.1&&(s=!0)}if(s){if(!o)if(this.didTrigger[g]=!0,((t=this.receivers)==null?void 0:t.length)<=0)vE.invoke(I.asset);else for(const n of this.receivers)n&&n.invoke(I.asset)}else I.emitOnce||(this.didTrigger[g]=!1)}}}class Hw extends hd{constructor(){super(...arguments);r(this,"models",[]);r(this,"timelines",[]);r(this,"_previousActiveModel",null)}resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const I=this.models[t].asset;if(!I.sourceObject||typeof I.sourceObject!="object"){console.log("no source object, removing model",t,I),this.models.splice(t,1);continue}else{const o=eA.getComponent(I.sourceObject,Ur);this.timelines.push(o),o&&I.updateDirector&&(o.playOnAwake=!1)}}}evaluate(e){var t;this._previousActiveModel=null;for(let g=0;g<this.models.length;g++){const I=this.models[g],o=I.asset;if(e>=I.start&&e<=I.end){this._previousActiveModel=I;const C=this.getClipTime(e,I);if(o.controlActivation){const s=o.sourceObject;s.visible=!0}if(o.updateDirector){const s=this.timelines[g];s&&(s.isPlaying&&s.pause(),s.time=C,s.evaluate())}}else{const C=(t=this._previousActiveModel)==null?void 0:t.asset;if(o.controlActivation){const s=o.sourceObject;(C==null?void 0:C.sourceObject)!==s&&(s.visible=!1)}}}}}var htA=Object.defineProperty,ltA=Object.getOwnPropertyDescriptor,XH=(i,A,e,t)=>{for(var g=t>1?void 0:t?ltA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&htA(A,e,g),g};class ve{constructor(A){r(this,"_active",!0);r(this,"_value");r(this,"_valueRaw");r(this,"_defaultValue");r(this,"valueProcessor");r(this,"onValueChanged");this._value=A,this._defaultValue=A}get overrideState(){return this._active}set overrideState(A){if(this._active===A)return;this._active=A;const e=A?this._valueRaw:this._defaultValue;this.processValue(e,!0)}get value(){return this._valueRaw}set value(A){this.processValue(A,!1)}set defaultValue(A){this._defaultValue=A}__init(){this.processValue(this._valueRaw,!0)}processValue(A,e){if(A==null||!e&&this.testIfValueChanged(A)===!1)return;const t=this._value;!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,A=this._defaultValue,this._valueRaw=A):(this._valueRaw=A,this._active&&this.valueProcessor&&(A=this.valueProcessor(A)),this._value=A),this.onValueChanged&&this.onValueChanged(A,t,this)}testIfValueChanged(A){return this._valueRaw!==A}}XH([w()],ve.prototype,"overrideState",1);XH([w()],ve.prototype,"value",1);var dtA=Object.defineProperty,utA=Object.getOwnPropertyDescriptor,DtA=(i,A,e,t)=>{for(var g=t>1?void 0:t?utA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&dtA(A,e,g),g};const ptA=rA("debugpost");class eI extends Ma{constructor(){super(...arguments);r(this,"active",!0);r(this,"_result")}onEnable(){this.__internalDidAwakeAndStart&&(this.active=!0)}onDisable(){this.active=!1}init(){}apply(){var e;return this._result||(this._result=(e=this.onCreateEffect)==null?void 0:e.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){ptA&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(e=>e.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const e=Object.keys(this);for(const t of e){const g=this[t];g instanceof ve&&g.__init()}}onAfterDeserialize(e,t){if(typeof e=="object"){const g=this.$serializedTypes;if(g){for(const I of Object.keys(g))if(g[I]===ve){const C=e[I];if(C!==void 0){const s=this[I];s.value=C}}}}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof ve){const g=e.value;return this[t].value=g,!0}}}DtA([w()],eI.prototype,"active",2);var ftA=Object.defineProperty,wtA=Object.getOwnPropertyDescriptor,ytA=(i,A,e,t)=>{for(var g=t>1?void 0:t?wtA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&ftA(A,e,g),g};const StA=rA("debugpost"),kG={};function $C(i,A){kG[i]=A}function ktA(i){return i.__type in kG?kG[i.__type]:(StA&&i.__type&&console.warn("Unknown postprocessing type",i.__type,i),eI)}class ld{constructor(){r(this,"components")}init(){var A;(A=this.components)==null||A.forEach(e=>e.init())}}ytA([DE([i=>ktA(i),eI])],ld.prototype,"components",2);var GtA=Object.defineProperty,MtA=Object.getOwnPropertyDescriptor,mtA=(i,A,e,t)=>{for(var g=t>1?void 0:t?MtA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&GtA(A,e,g),g};class dd extends eI{constructor(){super(...arguments);r(this,"preset")}get typeName(){return"Antialiasing"}onCreateEffect(){const e=new zZ({preset:ZB.HIGH,edgeDetectionMode:ZM.DEPTH});return this.preset.onValueChanged=t=>{e.applyPreset(t)},e}}mtA([w(ve)],dd.prototype,"preset",2);$C("Antialiasing",dd);class _w{constructor(){r(this,"files",[])}get extensionName(){return"Audio"}onExportObject(A,e,t){const g=eA.getComponents(A,Fi);if(g.length)for(const I of g){if(!I.playOnAwake)continue;const o=I.clip.split("/").pop();this.files.includes(I.clip)||this.files.push(I.clip),e.addEventListener("serialize",(C,s)=>{C.appendLine(),C.beginBlock(`def SpatialAudio "${e.name}"`),C.appendLine(`uniform asset filePath = @audio/${o}@`),C.appendLine(`uniform token auralMode = "${I.spatialBlend>0?"spatial":"nonSpatial"}"`),C.appendLine(`uniform token playbackMode = "${I.loop?"loopFromStage":"onceFromStart"}"`),C.appendLine(`uniform float gain = ${I.volume}`),C.closeBlock()})}}async onAfterSerialize(A){console.warn("onAfterSerialize",this);for(const e of this.files){const t=e.split("/").pop(),o=await(await(await fetch(e)).blob()).arrayBuffer(),C=new Uint8Array(o);A.files["audio/"+t]=C}}}var RtA=Object.defineProperty,UtA=Object.getOwnPropertyDescriptor,$H=(i,A,e,t)=>{for(var g=t>1?void 0:t?UtA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&RtA(A,e,g),g};const FtA=rA("debugmouth");class ud extends MA{constructor(){super(...arguments);r(this,"idle",[]);r(this,"talking",[]);r(this,"marker",null);r(this,"voip",null);r(this,"lastMouthChangeTime",0);r(this,"mouthChangeLength",0)}awake(){setTimeout(()=>{this.voip=eA.findObjectOfType(nn,this.context),this.marker||(this.marker=eA.getComponentInParent(this.gameObject,tg))},3e3)}update(){var g;if(!this.voip||this.context.time.frameCount%10!==0)return;let e=((g=this.marker)==null?void 0:g.connectionId)??null;if(!e){FtA&&(e=null);return}const t=this.voip.getFrequency(e)??0;this.updateLips(t)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,t)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,t)}}}setMouthShapeActive(e,t){if(e){e!=this.idle?this.idle.map(g=>g.visible=!1):this.talking.map(g=>g.visible=!1);for(let g=0;g<e.length;g++){const I=e[g];I&&(I.visible=g===t)}}}}$H([w(UA)],ud.prototype,"idle",2);$H([w(UA)],ud.prototype,"talking",2);class BR extends MA{constructor(){super(...arguments);r(this,"voip",null);r(this,"marker",null);r(this,"_startPosition",null)}awake(){this.voip=eA.findObjectOfType(nn,this.context),this.marker=eA.getComponentInParent(this.gameObject,tg)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());let g=t/100;this.gameObject.position.y=this._startPosition.y+g*.07}}var NtA=Object.defineProperty,KtA=Object.getOwnPropertyDescriptor,Ow=(i,A,e,t)=>{for(var g=t>1?void 0:t?KtA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&NtA(A,e,g),g};class iB extends MA{constructor(){super(...arguments);r(this,"eyes",[]);r(this,"lastBlinkTime",0);r(this,"blinkLength",0);r(this,"eyesOpen",!0);r(this,"state",null)}awake(){this.state=eA.getComponentInParent(this.gameObject,Eg)}update(){if(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)return;if(this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(const t of this.eyes)t&&(t.visible=this.eyesOpen)}}}Ow([w(UA)],iB.prototype,"eyes",2);Ow([w()],iB.prototype,"lastBlinkTime",2);Ow([w()],iB.prototype,"blinkLength",2);Ow([w()],iB.prototype,"eyesOpen",2);var JtA=Object.defineProperty,qtA=Object.getOwnPropertyDescriptor,QR=(i,A,e,t)=>{for(var g=t>1?void 0:t?qtA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&JtA(A,e,g),g},O0;const A_=(O0=class extends MA{constructor(){super(...arguments);r(this,"head",null);r(this,"eyes",null);r(this,"target",null);r(this,"brain",null);r(this,"vec",new k);r(this,"currentTargetPoint",new k)}awake(){this.brain||(this.brain=eA.getComponentInParent(this.gameObject,el)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=eA.addNewComponent(this.gameObject,el)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}update(){const A=this.target;if(A&&this.head){const e=this.eyes;if(e){const t=ye(A);this.currentTargetPoint.lerp(t,this.context.time.deltaTime/.1);const g=ye(this.head),I=this.vec.copy(this.currentTargetPoint).sub(g).normalize();if(I.length()<.1)return;const o=A_.forward;if(o.set(0,0,1),o.applyQuaternion(Hi(this.head)),o.dot(I)>.45)for(let s=0;s<e.length;s++)e[s].lookAt(this.currentTargetPoint)}}}},r(O0,"forward",new k(0,0,1)),O0);let xE=A_;QR([w(UA)],xE.prototype,"head",2);QR([w(UA)],xE.prototype,"eyes",2);QR([w(UA)],xE.prototype,"target",2);var btA=Object.defineProperty,LtA=Object.getOwnPropertyDescriptor,ER=(i,A,e,t)=>{for(var g=t>1?void 0:t?LtA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&btA(A,e,g),g};class YE extends MA{constructor(){super(...arguments);r(this,"length",1);r(this,"depthTest",!0);r(this,"isGizmo",!0);r(this,"_axes",null)}onEnable(){if(this.isGizmo&&!Pl)return;this._axes||(this._axes=new QE(this.length)),this.gameObject.add(this._axes);const e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}ER([w()],YE.prototype,"length",2);ER([w()],YE.prototype,"depthTest",2);ER([w()],YE.prototype,"isGizmo",2);class cR extends MA{constructor(){super(...arguments);r(this,"from");r(this,"to");r(this,"hint");r(this,"desiredDistance",1)}onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=ye(this.to).clone(),t=ye(this.from).clone(),g=e.distanceTo(t),I=e.clone();I.sub(t);let o=t.clone();o.add(e),o.multiplyScalar(.5);let C=ye(this.hint).clone();C.sub(o);let s=new k;s.crossVectors(C,I),s.crossVectors(I,s),s.normalize();let n=g*.5,a=Math.max(this.desiredDistance,n),B=Math.sqrt(a*a-n*n),Q=s.clone();Q.multiplyScalar(B),Q.add(o),hi(this.gameObject,Q);let E=o.clone();E.sub(s),this.gameObject.lookAt(E)}}class Pw{constructor(){r(this,"behaviours",[]);r(this,"behaviourComponents",[]);r(this,"behaviourComponentsCopy",[])}get extensionName(){return"Behaviour"}addBehavior(A){this.behaviours.push(A)}onBeforeBuildDocument(A){A.root.traverse(e=>{eA.foreachComponent(e,t=>{var I;const g=t;(typeof g.createBehaviours=="function"||typeof g.beforeCreateDocument=="function"||typeof g.afterCreateDocument=="function")&&(this.behaviourComponents.push(g),(I=g.beforeCreateDocument)==null||I.call(g,this,A))},!1)})}onExportObject(A,e,t){var g;for(const I of this.behaviourComponents)(g=I.createBehaviours)==null||g.call(I,this,e,t)}onAfterBuildDocument(A){for(const e of this.behaviourComponents)typeof e.afterCreateDocument=="function"&&e.afterCreateDocument(this,A);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0}onAfterHierarchy(A,e){var t;if((t=this.behaviours)!=null&&t.length){e.beginBlock('def Scope "Behaviors"');for(const g of this.behaviours)g.writeTo(this,A.document,e);e.closeBlock()}}async onAfterSerialize(A){console.log("onAfterSerialize",this.behaviourComponentsCopy);for(const e of this.behaviourComponentsCopy)console.log("behaviour",e),typeof e.afterSerialize=="function"&&(console.log("beh has afterSerialize",e),e.afterSerialize.constructor.name==="AsyncFunction"?await e.afterSerialize(this,A):e.afterSerialize(this,A))}}var vtA=Object.defineProperty,xtA=Object.getOwnPropertyDescriptor,hR=(i,A,e,t)=>{for(var g=t>1?void 0:t?xtA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&vtA(A,e,g),g};class gB extends eI{constructor(){super(...arguments);r(this,"threshold");r(this,"intensity");r(this,"scatter");r(this,"selectiveBloom",!0)}get typeName(){return"Bloom"}init(){this.threshold.defaultValue=1,this.intensity.defaultValue=0,this.scatter.defaultValue=.2,this.selectiveBloom?(this.threshold.valueProcessor=e=>e,this.intensity.valueProcessor=e=>e,this.scatter.valueProcessor=e=>1*Math.PI*(1-e)):(this.threshold.valueProcessor=e=>e,this.intensity.valueProcessor=e=>e,this.scatter.valueProcessor=e=>100*(1-e))}onCreateEffect(){let e;if(this.selectiveBloom){const t=e=new bx(this.context.scene,this.context.mainCamera,{blendFunction:Le.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,intensity:this.intensity.value});t.inverted=!0}else e=new em;return this.intensity.onValueChanged=t=>{e.intensity=t},this.threshold.onValueChanged=t=>{e.luminanceMaterial.threshold=t},this.scatter.onValueChanged=t=>{e.luminancePass.enabled=!0,e.luminanceMaterial.smoothing=t},e}}hR([w(ve)],gB.prototype,"threshold",2);hR([w(ve)],gB.prototype,"intensity",2);hR([w(ve)],gB.prototype,"scatter",2);$C("Bloom",gB);var YtA=Object.defineProperty,TtA=Object.getOwnPropertyDescriptor,aC=(i,A,e,t)=>{for(var g=t>1?void 0:t?TtA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&YtA(A,e,g),g};class As extends MA{constructor(){super(...arguments);r(this,"attachedRigidbody",null);r(this,"isTrigger",!1);r(this,"sharedMaterial")}get isCollider(){return!0}awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(jt))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(jt))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(jt))}onDisable(){var e;(e=this.context.physics.engine)==null||e.removeBody(this)}}aC([w(jt)],As.prototype,"attachedRigidbody",2);aC([w()],As.prototype,"isTrigger",2);aC([w()],As.prototype,"sharedMaterial",2);class Dd extends As{constructor(){super(...arguments);r(this,"radius",.5);r(this,"center",new k(0,0,0))}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addSphereCollider(this,this.center,this.radius)}}aC([w()],Dd.prototype,"radius",2);aC([w(k)],Dd.prototype,"center",2);class pd extends As{constructor(){super(...arguments);r(this,"size",new k(1,1,1));r(this,"center",new k(0,0,0))}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addBoxCollider(this,this.center,this.size)}}aC([w(k)],pd.prototype,"size",2);aC([w(k)],pd.prototype,"center",2);class fd extends As{constructor(){super(...arguments);r(this,"sharedMesh");r(this,"convex",!1)}onEnable(){var e,t,g,I,o;if(super.onEnable(),(e=this.sharedMesh)!=null&&e.isMesh||this.gameObject instanceof fA&&(this.sharedMesh=this.gameObject),(t=this.sharedMesh)!=null&&t.isMesh)(g=this.context.physics.engine)==null||g.addMeshCollider(this,this.sharedMesh,this.convex,Qg(this.gameObject));else{const C=this.sharedMesh;if(C!=null&&C.isGroup){console.warn(`MeshCollider mesh is a group "${(I=this.sharedMesh)==null?void 0:I.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);for(const s in C.children){const n=C.children[s];n.isMesh&&((o=this.context.physics.engine)==null||o.addMeshCollider(this,n,this.convex,Qg(this.gameObject)))}}}}}aC([w()],fd.prototype,"convex",2);class Da extends As{constructor(){super(...arguments);r(this,"center",new k(0,0,0));r(this,"radius",.5);r(this,"height",2)}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addCapsuleCollider(this,this.center,this.height,this.radius)}}aC([w(k)],Da.prototype,"center",2);aC([w()],Da.prototype,"radius",2);aC([w()],Da.prototype,"height",2);function lR(i){const A=i[Ns];return A||(i.parent?lR(i.parent):null)}function tf(i,A){if(!i)return;const e=i.material;if((e==null?void 0:e.isMaterial)===!0){const t=i.parent;t&&t.isText,e.side=A.doubleSided??!0?Nt:Zg,e.shadowSide=A.doubleSided?Nt:Zg,i.castShadow=A.castShadows?A.castShadows:!1,i.receiveShadow=A.receiveShadows?A.receiveShadows:!1}for(const t of i.children)tf(t,A)}function tQ(i,A,e){i[A]===void 0&&console.warn("Field",A,"is undefined on",i);const t=Proxy.revocable(i[A],{set(o,C,s,n){const a=o[C],B=Reflect.set(o,C,s,n);return e(s,a),B}}),g=t.revoke,I=i[A];return t.revoke=()=>{i[A]=I,g()},i[A]=t.proxy,t}const GJ=Symbol("Scheduled action");function HtA(i,A,e=OI.OnBeforeRender){let t=i[GJ];t||(t=i[GJ]={});const g=A.name;t[e]||(t[e]={});const I=t[e];if(I[g])return;function*C(){A==null||A.call(i),I[g]=null}const s=i.startCoroutine(C(),e);I[g]=s}var _tA=Object.defineProperty,OtA=Object.getOwnPropertyDescriptor,IB=(i,A,e,t)=>{for(var g=t>1?void 0:t?OtA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&_tA(A,e,g),g};const h0=rA("debugui"),l0=rA("debuguilayout");class dR{constructor(){r(this,"width");r(this,"height")}}class uR{constructor(){r(this,"x");r(this,"y");r(this,"width");r(this,"height")}}const cC=new k,Rc=new OA,eD=new kA,e_=class extends tC{constructor(){super(...arguments);r(this,"offset",.01);r(this,"_anchoredPosition");r(this,"sizeDelta",new j(100,100));r(this,"pivot",new j(.5,.5));r(this,"anchorMin",new j(0,0));r(this,"anchorMax",new j(1,1));r(this,"offsetMin",new j(0,0));r(this,"offsetMax",new j(0,0));r(this,"lastMatrix");r(this,"rectBlock");r(this,"_transformNeedsUpdate",!1);r(this,"_initialPosition");r(this,"_parentRectTransform");r(this,"_lastUpdateFrame",-1);r(this,"_lastAnchoring");r(this,"_createdBlocks",[]);r(this,"_createdTextBlocks",[])}get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new j),this._anchoredPosition}set anchoredPosition(A){this._anchoredPosition=A}get width(){if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const A=this._parentRectTransform.width,e=this.anchorMax.x-this.anchorMin.x;let t=A*e;return t+=this.sizeDelta.x,t}return this.sizeDelta.x}get height(){if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const A=this._parentRectTransform.height,e=this.anchorMax.y-this.anchorMin.y;let t=A*e;return t+=this.sizeDelta.y,t}return this.sizeDelta.y}awake(){super.awake(),this._anchoredPosition||(this._anchoredPosition=new j),this.lastMatrix=new OA,this.rectBlock=new UA,this.rectBlock.position.z=.1,this.rectBlock.name=this.name,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this.onApplyTransform("RectTransform awake"),tQ(this,"_anchoredPosition",()=>{this.markDirty()}),tQ(this,"sizeDelta",()=>{this.markDirty()}),tQ(this,"pivot",()=>{this.markDirty()}),tQ(this,"anchorMin",()=>{this.markDirty()}),tQ(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var A;super.onEnable(),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(A=this.Canvas)==null||A.registerTransform(this)}onDisable(){var A;super.onDisable(),this.removeShadowComponent(),(A=this.Canvas)==null||A.unregisterTransform(this)}onParentRectTransformChanged(A){this._transformNeedsUpdate||this.onApplyTransform(l0?`${A.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(l0&&console.warn("RectTransform markDirty()",this.name),this._transformNeedsUpdate=!0,this._lastUpdateFrame=-1)}updateTransform(){(this._transformNeedsUpdate||!this.lastMatrix.equals(this.gameObject.matrix))&&this.canUpdate()&&this.onApplyTransform(this._transformNeedsUpdate?"Marked dirty":"Matrix changed")}canUpdate(){return this._transformNeedsUpdate&&this.activeAndEnabled&&this._lastUpdateFrame!==this.context.time.frame}onApplyTransform(A){if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const e=this.shadowComponent;if(!e)return;this.gameObject.parent?this._parentRectTransform=eA.getComponentInParent(this.gameObject.parent,e_):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,l0&&console.warn("RectTransform → ApplyTransform",this.name+" because "+A),this.isRoot()?this.Root.screenspace||(e.rotation.y=Math.PI):(e.matrix.identity(),e.matrixAutoUpdate=!1,cC.set(0,0,0),this.applyPivot(cC),e.matrix.setPosition(cC.x,cC.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(eD.copy(this.gameObject.quaternion),eD.x*=-1,eD.z*=-1,Rc.makeRotationFromQuaternion(eD),e.matrix.premultiply(Rc)),cC.set(0,0,0),this.applyAnchoring(cC),cC.z+=this.offset,Rc.identity(),Rc.setPosition(cC.x,cC.y,cC.z),e.matrix.premultiply(Rc),e.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const t=!0;for(const g of jM(this.gameObject,tC,t,1)){if(g===this||!g.activeAndEnabled)continue;const I=g;I.onParentRectTransformChanged&&I.onParentRectTransformChanged(this)}}applyAnchoring(A){this._lastAnchoring||(this._lastAnchoring=new j);const e=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=e.x,this.gameObject.position.y+=e.y,this._lastAnchoring.copy(this._anchoredPosition),A.x+=this._initialPosition.x-this.gameObject.position.x,A.y+=this._initialPosition.y-this.gameObject.position.y,A.z+=this._initialPosition.z-this.gameObject.position.z;const t=this._parentRectTransform;if(t){let g=0;const I=1-this.anchorMax.y-this.anchorMin.y;g-=t.height*.5*I,A.y+=g;let o=0;const C=1-this.anchorMax.x-this.anchorMin.x;o-=t.width*.5*C,A.x+=o}}applyPivot(A){if(this.pivot&&!this.isRoot()){const e=this.pivot.x-.5;A.x-=e*this.sizeDelta.x*this.gameObject.scale.x;const t=this.pivot.y-.5;A.y-=t*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const A={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:this.offset,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(A),A}ensureValidSize(A,e=1e-4){return A.width<=0&&(A.width=e),A.height<=0&&(A.height=1e-4),A}createNewBlock(A){A={...this.getBasicOptions(),...A},h0&&console.log(this.name,A);const e=new CR(A);return this._createdBlocks.push(e),e}createNewText(A){h0&&console.log(A),A={...this.getBasicOptions(),...A},h0&&console.log(this.name,A);const e=new WH(A);return this._createdTextBlocks.push(e),e}};let Ug=e_;IB([w(j)],Ug.prototype,"anchoredPosition",1);IB([w(j)],Ug.prototype,"sizeDelta",2);IB([w(j)],Ug.prototype,"pivot",2);IB([w(j)],Ug.prototype,"anchorMin",2);IB([w(j)],Ug.prototype,"anchorMax",2);IB([w(j)],Ug.prototype,"offsetMin",2);IB([w(j)],Ug.prototype,"offsetMax",2);class PtA extends PH{constructor(A,e={}){super(A),A._simpleState__activeStates=[],A._simpleState__normalStyles={},A._simpleState__states=e,A._simpleState__statesProperties={};for(const t in e)for(const g in e[t])A._simpleState__statesProperties[g]||(A._simpleState__statesProperties[g]=[]),A._simpleState__statesProperties[g].push(t);for(const t of A._components)A._simpleState__statesProperties[t.id]&&(A._simpleState__normalStyles[t.id]=t.inline?t.inline:t._value);A.__overridedSet=A.set,A.set=this.storeSet.bind(A),A.renderStates=this.renderStates.bind(A),A.setupState=this.setupState.bind(A),A.setState=this.setState.bind(A),A.activatePseudoState=this.activatePseudoState.bind(A),A.deactivatePseudoState=this.deactivatePseudoState.bind(A),A.togglePseudoState=this.togglePseudoState.bind(A)}act(){}attach(){}detach(){}setupState(A,e){this._simpleState__states[A]=e;const t=[];for(const g in e)this._simpleState__statesProperties[g]||(this._simpleState__statesProperties[g]=[],t.push(g)),this._simpleState__statesProperties[g].push(A);for(const g of this._components)t.indexOf(g.id)>-1&&(this._simpleState__normalStyles[g.id]=g.inline?g.inline:g._value)}renderStates(){let A={...this._simpleState__normalStyles};for(const e in this._simpleState__states)this._simpleState__activeStates.indexOf(e)>-1&&(A={...A,...this._simpleState__states[e]});this.set(A,!1)}storeSet(A,e=!0){if(e)for(const t in A)this._simpleState__statesProperties[t]&&(this._simpleState__normalStyles[t]=A[t]);this.__overridedSet(A)}activatePseudoState(A){this._simpleState__activeStates.indexOf(A)===-1&&(this._simpleState__activeStates.push(A),this.renderStates())}deactivatePseudoState(A){const e=this._simpleState__activeStates.indexOf(A);e>-1&&(this._simpleState__activeStates.splice(e,1),this.renderStates())}togglePseudoState(A){const e=this._simpleState__activeStates.indexOf(A);e>-1?this._simpleState__activeStates.splice(e,1):this._simpleState__activeStates.push(A),this.renderStates()}setState(A){Array.isArray(A)?this._simpleState__activeStates=A:this._simpleState__activeStates=[A],this.renderStates()}}var WtA=Object.defineProperty,VtA=Object.getOwnPropertyDescriptor,t_=(i,A,e,t)=>{for(var g=t>1?void 0:t?VtA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&WtA(A,e,g),g};class TE extends MA{constructor(){super(...arguments);r(this,"effectColor");r(this,"effectDistance")}}t_([w(Gt)],TE.prototype,"effectColor",2);t_([w(j)],TE.prototype,"effectDistance",2);var jtA=Object.defineProperty,ztA=Object.getOwnPropertyDescriptor,i_=(i,A,e,t)=>{for(var g=t>1?void 0:t?ztA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&jtA(A,e,g),g};const tD={backgroundColor:new yA(1,1,1),backgroundOpacity:1,borderColor:new yA(1,1,1),borderOpacity:1};var P0;const $D=(P0=class extends tC{constructor(){super(...arguments);r(this,"_alphaFactor",1);r(this,"raycastTarget",!0);r(this,"uiObject",null);r(this,"_color",null);r(this,"_rect",null);r(this,"_stateManager",null);r(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new Gt(1,1,1,1)),this._color}set color(A){(!this._color||this._color.r!==A.r||this._color.g!==A.g||this._color.b!==A.b||this._color.alpha!==A.alpha)&&(this._color||(this._color=new Gt(1,1,1,1)),this._color.copy(A))}setAlphaFactor(A){this._alphaFactor=A,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(tD.backgroundColor=this._color,tD.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(tD,this._alphaFactor),this.uiObject.set(tD),this.markDirty())}get m_Color(){return this._color}get rectTransform(){return this._rect||(this._rect=eA.getComponent(this.gameObject,Ug)),this._rect}onParentRectTransformChanged(){var A;(A=this.uiObject)==null||A.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(){super.__internalNewInstanceCreated(),this._rect=null,this.uiObject=null,this._color&&(this._color=this._color.clone())}setState(A){this.makePanel(),this.uiObject&&(this.uiObject.setState(A),this==null||this.markDirty())}setupState(A){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new PtA(this.uiObject)),this.uiObject.setupState(A.state,A.attributes))}setOptions(A){this.makePanel(),this.uiObject&&this.uiObject.set(A)}awake(){super.awake(),this.makePanel(),tQ(this,"_color",()=>HtA(this,this.onColorChanged))}onEnable(){var A;super.onEnable(),this.uiObject&&((A=this.rectTransform.shadowComponent)==null||A.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const A={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:1};this.onBeforeCreate(A),this.applyEffects(A),this.onCreate(A),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated()}onBeforeCreate(A){}onCreate(A){this.uiObject=this.rectTransform.createNewBlock(A),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(A,e=1){var g;const t=(g=this.gameObject)==null?void 0:g.getComponent(TE);t&&(t.effectDistance&&(A.borderWidth=Math.max(Math.abs(t.effectDistance.x),Math.abs(t.effectDistance.y))),t.effectColor&&(A.borderColor=t.effectColor,A.borderOpacity=t.effectColor.alpha*e))}async setTexture(A){if(this.setOptions({backgroundOpacity:0}),A){if(A.encoding===De)if($D.textureCache.has(A))A=$D.textureCache.get(A);else{const e=A.clone();e.encoding=li,$D.textureCache.set(A,e),A=e}this.setOptions({backgroundImage:A,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"})}else this.setOptions({backgroundImage:null,borderRadius:0,backgroundOpacity:this.color.alpha})}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}},r(P0,"textureCache",new Map),P0);let oB=$D;i_([w(Gt)],oB.prototype,"color",1);i_([w()],oB.prototype,"raycastTarget",2);class wd extends oB{constructor(){super(...arguments);r(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var ZtA=Object.defineProperty,XtA=Object.getOwnPropertyDescriptor,Ww=(i,A,e,t)=>{for(var g=t>1?void 0:t?XtA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&ZtA(A,e,g),g};let DR=class{constructor(){r(this,"texture",null);r(this,"rect")}};Ww([w(He)],DR.prototype,"texture",2);let HE=class extends wd{constructor(){super(...arguments);r(this,"_sprite");r(this,"pixelsPerUnitMultiplier",1)}set image(e){this.sprite?this.sprite.texture=e:(this.sprite=new DR,this.sprite.texture=e),this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(e){this._sprite!==e&&(this._sprite=e,this.onAfterCreated())}isBuiltinSprite(){var e,t,g,I,o,C,s,n;switch((t=(e=this.sprite)==null?void 0:e.texture)==null?void 0:t.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return((o=(I=(g=this.sprite)==null?void 0:g.texture)==null?void 0:I.image)==null?void 0:o.width)===32&&((n=(s=(C=this.sprite)==null?void 0:C.texture)==null?void 0:s.image)==null?void 0:n.height)===32}onBeforeCreate(e){var t,g;super.onBeforeCreate(e),this.isBuiltinSprite()&&(e.borderRadius=5/this.pixelsPerUnitMultiplier,((g=(t=this.sprite)==null?void 0:t.texture)==null?void 0:g.name)==="Knob"&&(e.borderRadius=999))}onAfterCreated(){var e;this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture((e=this.sprite)==null?void 0:e.texture))}};Ww([w(DR)],HE.prototype,"sprite",1);Ww([w()],HE.prototype,"pixelsPerUnitMultiplier",2);class Vw extends wd{constructor(){super(...arguments);r(this,"_mainTexture")}get mainTexture(){return this._mainTexture}set mainTexture(e){this._mainTexture!==e&&(this._mainTexture=e,this.onAfterCreated())}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}Ww([w(He)],Vw.prototype,"mainTexture",1);var $tA=Object.defineProperty,AiA=Object.getOwnPropertyDescriptor,WI=(i,A,e,t)=>{for(var g=t>1?void 0:t?AiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&$tA(A,e,g),g};const OB=rA("debugbutton");class CB{constructor(){r(this,"colorMultiplier");r(this,"disabledColor");r(this,"fadeDuration");r(this,"highlightedColor");r(this,"normalColor");r(this,"pressedColor");r(this,"selectedColor")}}WI([w()],CB.prototype,"colorMultiplier",2);WI([w(Gt)],CB.prototype,"disabledColor",2);WI([w()],CB.prototype,"fadeDuration",2);WI([w(Gt)],CB.prototype,"highlightedColor",2);WI([w(Gt)],CB.prototype,"normalColor",2);WI([w(Gt)],CB.prototype,"pressedColor",2);WI([w(Gt)],CB.prototype,"selectedColor",2);class Qn extends MA{constructor(){super(...arguments);r(this,"onClick");r(this,"_isHovered",!1);r(this,"colors");r(this,"transition");r(this,"animationTriggers");r(this,"animator");r(this,"_interactable",!0);r(this,"_requestedAnimatorTrigger");r(this,"_isInit",!1);r(this,"_image")}onPointerEnter(e){var t,g;OB&&console.log("Button Enter",(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator),this._isHovered=!0,this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&((g=this._image)==null||g.setState("hovered")),this.context.input.setCursorPointer())}onPointerExit(){var e,t;OB&&console.log("Button Exit",(e=this.animationTriggers)==null?void 0:e.highlightedTrigger,this.animator),this._isHovered=!1,this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((t=this._image)==null||t.setState("normal")),this.context.input.setCursorNormal())}onPointerDown(e){var t,g;OB&&console.log("Button Down",(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&((g=this._image)==null||g.setState("pressed")))}onPointerUp(e){var t,g;OB&&console.warn("Button Up",(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator,this._isHovered),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((g=this._image)==null||g.setState(this._isHovered?"hovered":"normal")))}onPointerClick(e){var t;this.interactable&&(OB&&(console.warn("Button Click",this.onClick),eg("CLICKED button "+this.name+" at "+this.context.time.frameCount)),(t=this.onClick)==null||t.invoke())}set interactable(e){this._interactable=e,this._image&&(this._image.setInteractable(e),e?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}set_interactable(e){this.interactable=e}awake(){super.awake(),OB&&console.log(this),this._isInit=!1,this.init()}start(){var e;(e=this._image)==null||e.setInteractable(this.interactable)}onEnable(){super.onEnable()}*setAnimatorTriggerAtEndOfFrame(e){var t;this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&((t=this.animator)==null||t.SetTrigger(e))}init(){this._isInit||(this._isInit=!0,this._image=eA.getComponent(this.gameObject,HE),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){var E,c,h,l,d;e.setInteractable(this.interactable);const t=this.getFinalColor(e.color,(E=this.colors)==null?void 0:E.normalColor),g={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(g);const I=this.getFinalColor(e.color,(c=this.colors)==null?void 0:c.highlightedColor),o={state:"hovered",attributes:{backgroundColor:I,backgroundOpacity:I.alpha}};e.setupState(o);const C=this.getFinalColor(e.color,(h=this.colors)==null?void 0:h.pressedColor),s={state:"pressed",attributes:{backgroundColor:C,backgroundOpacity:C.alpha}};e.setupState(s);const n=this.getFinalColor(e.color,(l=this.colors)==null?void 0:l.selectedColor),a={state:"selected",attributes:{backgroundColor:n,backgroundOpacity:n.alpha}};e.setupState(a);const B=this.getFinalColor(e.color,(d=this.colors)==null?void 0:d.disabledColor),Q={state:"disabled",attributes:{backgroundColor:B,backgroundOpacity:B.alpha}};e.setupState(Q)}getFinalColor(e,t){return t?e.clone().multiply(t):e.clone()}}WI([w(DI)],Qn.prototype,"onClick",2);WI([w()],Qn.prototype,"colors",2);WI([w()],Qn.prototype,"transition",2);WI([w()],Qn.prototype,"animationTriggers",2);WI([w(wI)],Qn.prototype,"animator",2);WI([w()],Qn.prototype,"interactable",1);var eiA=Object.defineProperty,tiA=Object.getOwnPropertyDescriptor,Ki=(i,A,e,t)=>{for(var g=t>1?void 0:t?tiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&eiA(A,e,g),g};const MJ=rA("debuguilayout");class Ja{constructor(){r(this,"left",0);r(this,"right",0);r(this,"top",0);r(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}Ki([w()],Ja.prototype,"left",2);Ki([w()],Ja.prototype,"right",2);Ki([w()],Ja.prototype,"top",2);Ki([w()],Ja.prototype,"bottom",2);class VI extends MA{constructor(){super(...arguments);r(this,"_rectTransform",null);r(this,"_needsUpdate",!1);r(this,"childAlignment",0);r(this,"reverseArrangement",!1);r(this,"spacing",0);r(this,"padding");r(this,"minWidth",0);r(this,"minHeight",0);r(this,"flexibleHeight",0);r(this,"flexibleWidth",0);r(this,"preferredHeight",0);r(this,"preferredWidth",0)}get rectTransform(){return this._rectTransform}onParentRectTransformChanged(e){this._needsUpdate=!0}get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(MJ&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){MJ&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Ug);const e=this.gameObject.getComponentInParent(Fg);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(Fg);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}Ki([w()],VI.prototype,"childAlignment",2);Ki([w()],VI.prototype,"reverseArrangement",2);Ki([w()],VI.prototype,"spacing",2);Ki([w(Ja)],VI.prototype,"padding",2);Ki([w()],VI.prototype,"minWidth",2);Ki([w()],VI.prototype,"minHeight",2);Ki([w()],VI.prototype,"flexibleHeight",2);Ki([w()],VI.prototype,"flexibleWidth",2);Ki([w()],VI.prototype,"preferredHeight",2);Ki([w()],VI.prototype,"preferredWidth",2);class qa extends VI{constructor(){super(...arguments);r(this,"childControlHeight",!0);r(this,"childControlWidth",!0);r(this,"childForceExpandHeight",!1);r(this,"childForceExpandWidth",!1);r(this,"childScaleHeight",!1);r(this,"childScaleWidth",!1)}onCalculateLayout(e){var f;const t=this.primaryAxis,g=e.width;let I=g;const o=e.height;let C=o;I-=this.padding.horizontal,C-=this.padding.vertical,t==="x"?this.padding.horizontal:this.padding.vertical;const s=t==="x",n=s?"y":"x",a=s?this.childControlWidth:this.childControlHeight,B=s?this.childControlHeight:this.childControlWidth,Q=s?this.childForceExpandWidth:this.childForceExpandHeight,E=s?this.childForceExpandHeight:this.childForceExpandWidth,c=s?C:I,h=s?g:o,l=.5*(s?this.childAlignment%3:Math.floor(this.childAlignment/3));let d=0;s?d+=this.padding.left:d+=this.padding.top;let p=0,u=0;for(let M=0;M<this.gameObject.children.length;M++){const U=this.gameObject.children[M],J=eA.getComponent(U,Ug);J!=null&&J.activeAndEnabled&&(u+=1,s?p+=J.width:p+=J.height)}let D=0;const y=this.spacing*(u-1);if(Q||a){let M=0;s?M=I-=y:M=C-=y,u>0&&(D=M/u)}let S=0;S+=this.padding.left,S-=this.padding.right,l!==0&&(d=h-p,d*=l,d-=y*l,s?(d-=this.padding.right*l,d+=this.padding.left*(1-l),d<this.padding.left&&(d=this.padding.left)):(d-=this.padding.bottom*l,d+=this.padding.top*(1-l),d<this.padding.top&&(d=this.padding.top)));let R=1;for(let M=0;M<this.gameObject.children.length;M++){const U=this.gameObject.children[M],J=eA.getComponent(U,Ug);if(J!=null&&J.activeAndEnabled){(f=J.pivot)==null||f.set(.5,.5),J.anchorMin.set(0,1),J.anchorMax.set(0,1);const T=g*.5+S*.5;J.anchoredPosition.x!==T&&(J.anchoredPosition.x=T);const Y=o*-.5;J.anchoredPosition.y!==Y&&(J.anchoredPosition.y=Y),E&&B&&J.sizeDelta[n]!==c&&(J.sizeDelta[n]=c),Q&&a&&J.sizeDelta[t]!==D&&(J.sizeDelta[t]=D);const b=s?J.width:J.height;let _=b*.5;if(d+=_,Q){let $=D*R-D*.5;$>d&&(d=$-D*.5+b+this.padding.left,d-=_)}let AA=d;t==="y"&&(AA=-AA),J.anchoredPosition[t]!==AA&&(J.anchoredPosition[t]=AA),d+=_,d+=this.spacing,R+=1}}}}Ki([w()],qa.prototype,"childControlHeight",2);Ki([w()],qa.prototype,"childControlWidth",2);Ki([w()],qa.prototype,"childForceExpandHeight",2);Ki([w()],qa.prototype,"childForceExpandWidth",2);Ki([w()],qa.prototype,"childScaleHeight",2);Ki([w()],qa.prototype,"childScaleWidth",2);class pR extends qa{get primaryAxis(){return"y"}}class fR extends qa{get primaryAxis(){return"x"}}class wR extends VI{onCalculateLayout(){}}var iiA=Object.defineProperty,giA=Object.getOwnPropertyDescriptor,es=(i,A,e,t)=>{for(var g=t>1?void 0:t?giA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&iiA(A,e,g),g};const d0=rA("debuguilayout"),g_=class extends Ed{constructor(){super(...arguments);r(this,"_renderOnTop");r(this,"_depthWrite",!1);r(this,"_doubleSided",!0);r(this,"_castShadows",!1);r(this,"_receiveShadows",!1);r(this,"_renderMode",-1);r(this,"_rootCanvas");r(this,"_scaleFactor",1);r(this,"worldCamera");r(this,"planeDistance",-1);r(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this));r(this,"previousParent",null);r(this,"_lastMatrixWorld",null);r(this,"_rectTransforms",[]);r(this,"_layoutGroups",new Map);r(this,"onBeforeRenderRoutine",()=>{var A,e;this.previousParent=this.gameObject.parent,this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(A=this.shadowComponent)==null||A.updateMatrixWorld(!0),(e=this.shadowComponent)==null||e.updateWorldMatrix(!0,!0),lI.ensureUpdateMeshUI(fJ,this.context))});r(this,"onAfterRenderRoutine",()=>{var A,e;if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const t=this.context.mainCamera;t==null||t.add(this.gameObject)}else this.previousParent.add(this.gameObject);this.context.renderer.autoClear=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(A=this.shadowComponent)==null||A.updateMatrixWorld(!0),lI.ensureUpdateMeshUI(fJ,this.context),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=!0,this.previousParent.add(this.gameObject)}(e=this._lastMatrixWorld)==null||e.copy(this.gameObject.matrixWorld)});r(this,"_updateRenderSettingsRoutine");r(this,"_activeRenderMode",-1);r(this,"_lastWidth",-1);r(this,"_lastHeight",-1)}get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(A){A!==this._renderOnTop&&(this._renderOnTop=A,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(A){this._depthWrite!==A&&(this._depthWrite=A,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(A){this._doubleSided!==A&&(this._doubleSided=A,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(A){this._castShadows!==A&&(this._castShadows=A,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(A){this._receiveShadows!==A&&(this._receiveShadows=A,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(A){this._renderMode!==A&&(this._renderMode=A,this.onRenderSettingsChanged())}set rootCanvas(A){this._rootCanvas instanceof g_||(this._rootCanvas=A)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(A){this._scaleFactor=A}awake(){var A;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,d0&&console.log("Canvas.Awake()",((A=this.previousParent)==null?void 0:A.name)+"/"+this.gameObject.name),super.awake()}start(){this.onUpdateRenderMode()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new OA,this.onUpdateRenderMode(),document.addEventListener("resize",this._boundRenderSettingsChanged),this.context.pre_render_callbacks.push(this.onBeforeRenderRoutine),this.context.post_render_callbacks.push(this.onAfterRenderRoutine)}onDisable(){super.onDisable(),document.removeEventListener("resize",this._boundRenderSettingsChanged);const A=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);A!==-1&&this.context.pre_render_callbacks.splice(A,1);const e=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);e!==-1&&this.context.post_render_callbacks.splice(e,1)}registerTransform(A){this._rectTransforms.push(A)}unregisterTransform(A){const e=this._rectTransforms.indexOf(A);e!==-1&&this._rectTransforms.splice(e,1)}registerLayoutGroup(A){const e=A.gameObject;this._layoutGroups.set(e,A)}unregisterLayoutGroup(A){const e=A.gameObject;this._layoutGroups.delete(e)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new OA);const A=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);d0&&A&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);let e=!1;for(const t of this._rectTransforms){A&&t.markDirty();let g=this._layoutGroups.get(t.gameObject);t.isDirty&&!g&&(g=t.gameObject.getComponentInParent(VI)),(t.isDirty||g!=null&&g.isDirty)&&(d0&&!e&&console.log("CANVAS UPDATE ### "+t.name+" ##################################### "+this.context.time.frame),g==null||g.updateLayout(),t.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),OI.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),tf(this.shadowComponent,this);for(const A of eA.getComponentsInChildren(this.gameObject,tC))tf(A.shadowComponent,this)}}onUpdateRenderMode(A=!1){if(!A&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let e=this.context.mainCameraComponent,t=10;switch(e&&e.nearClipPlane>0&&e.farClipPlane>0&&(t=Ae.lerp(e.nearClipPlane,e.farClipPlane,.15)),this._renderMode===1&&(this.worldCamera&&(e=this.worldCamera),this.planeDistance>0&&(t=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!e)return;const g=t+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-g,this.gameObject.quaternion.identity();const I=this.gameObject.getComponent(Ug);let o=!1;I.sizeDelta.x!==this.context.domWidth&&(o=!0),I.sizeDelta.y!==this.context.domHeight&&(o=!0);const C=e.fieldOfView*Math.PI/180,s=2*Math.tan(C/2)*Math.abs(g);this.gameObject.scale.x=s/this.context.domHeight,this.gameObject.scale.y=s/this.context.domHeight,this.gameObject.scale.z=.01,o&&(I.sizeDelta.x=this.context.domWidth,I.sizeDelta.y=this.context.domHeight,I==null||I.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};let Fg=g_;es([w()],Fg.prototype,"renderOnTop",1);es([w()],Fg.prototype,"depthWrite",1);es([w()],Fg.prototype,"doubleSided",1);es([w()],Fg.prototype,"castShadows",1);es([w()],Fg.prototype,"receiveShadows",1);es([w()],Fg.prototype,"renderMode",1);es([w(Fg)],Fg.prototype,"rootCanvas",1);es([w()],Fg.prototype,"scaleFactor",1);es([w(Yt)],Fg.prototype,"worldCamera",2);es([w()],Fg.prototype,"planeDistance",2);var IiA=Object.defineProperty,oiA=Object.getOwnPropertyDescriptor,yR=(i,A,e,t)=>{for(var g=t>1?void 0:t?oiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&IiA(A,e,g),g};class _E extends MA{constructor(){super(...arguments);r(this,"_alpha",1);r(this,"interactable",!0);r(this,"blocksRaycasts",!0);r(this,"_isDirty",!1);r(this,"_buffer",[])}get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),OI.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){for(const e of eA.getComponentsInChildren(this.gameObject,tC,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}yR([w()],_E.prototype,"alpha",1);yR([w()],_E.prototype,"interactable",2);yR([w()],_E.prototype,"blocksRaycasts",2);var CiA=Object.defineProperty,siA=Object.getOwnPropertyDescriptor,Ht=(i,A,e,t)=>{for(var g=t>1?void 0:t?siA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&CiA(A,e,g),g};class sB extends MA{constructor(){super(...arguments);r(this,"object");r(this,"target");r(this,"duration",1);r(this,"relativeMotion",!1);r(this,"coroutine",null);r(this,"targetPos",new k);r(this,"targetRot",new kA);r(this,"targetScale",new k)}*moveToTarget(){if(!this.target||!this.object)return;const e=ye(this.object).clone(),t=ye(this.target).clone(),g=Hi(this.object).clone(),I=Hi(this.target).clone(),o=Qg(this.object).clone(),C=Qg(this.target).clone(),s=e.distanceTo(t),n=g.angleTo(I),a=o.distanceTo(C);if(s<.01&&n<.01&&a<.01){hi(this.object,t),fI(this.object,I),Lk(this.object,C),this.coroutine=null;return}let B=0,Q=0;for(;B<1;)B+=this.context.time.deltaTime/this.duration,B>1&&(B=1),Q=B<.5?4*B*B*B:1-Math.pow(-2*B+2,3)/2,this.targetPos.lerpVectors(e,t,Q),this.targetRot.slerpQuaternions(g,I,Q),this.targetScale.lerpVectors(o,C,Q),hi(this.object,this.targetPos),fI(this.object,this.targetRot),Lk(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const e=this.object.position.clone(),t=this.object.quaternion.clone(),g=this.object.scale.clone(),I=this.target.position.clone(),o=this.target.quaternion.clone(),C=this.target.scale.clone();I.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(I),this.targetRot.copy(this.object.quaternion).multiply(o),this.targetScale.copy(this.object.scale).multiply(C);let s=0,n=0;for(;s<1;)s+=this.context.time.deltaTime/this.duration,s>1&&(s=1),n=s<.5?4*s*s*s:1-Math.pow(-2*s+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,n),this.object.quaternion.slerpQuaternions(t,this.targetRot,n),this.object.scale.lerpVectors(g,this.targetScale,n),yield;this.coroutine=null}onPointerClick(){this.coroutine&&this.stopCoroutine(this.coroutine),this.relativeMotion?this.coroutine=this.startCoroutine(this.moveRelative()):this.coroutine=this.startCoroutine(this.moveToTarget())}beforeCreateDocument(e){var t;if(this.target&&this.object&&this.gameObject){const g=new cg("Move to "+((t=this.target)==null?void 0:t.name),pI.tapTrigger(this.gameObject),at.transformAction(this.object,this.target,this.duration,this.relativeMotion?cG.Relative:cG.Absolute));e.addBehavior(g)}}}Ht([w(UA)],sB.prototype,"object",2);Ht([w(UA)],sB.prototype,"target",2);Ht([w()],sB.prototype,"duration",2);Ht([w()],sB.prototype,"relativeMotion",2);var W0;const iQ=(W0=class extends MA{constructor(){super(...arguments);r(this,"materialToSwitch");r(this,"variantMaterial");r(this,"_objectsWithThisMaterial",[]);r(this,"selfModel");r(this,"targetModels",[])}awake(){if(this.variantMaterial&&this.materialToSwitch){const A=eA.findObjectsOfType(Ii);for(const e of A)e.sharedMaterial===this.materialToSwitch&&this._objectsWithThisMaterial.push(e)}}onPointerClick(){if(this.variantMaterial)for(const A of this._objectsWithThisMaterial)A.sharedMaterial=this.variantMaterial}createBehaviours(A,e,t){this._objectsWithThisMaterial.find(I=>I.gameObject.uuid===e.uuid)&&this.targetModels.push(e),this.gameObject.uuid===e.uuid&&(this.selfModel=e,this.materialToSwitch&&(iQ._materialTriggersPerId[this.materialToSwitch.uuid]||(iQ._materialTriggersPerId[this.materialToSwitch.uuid]=[]),iQ._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(A,e){if(!this.materialToSwitch)return;const t=iQ._materialTriggersPerId[this.materialToSwitch.uuid];if(t){const g={};for(const o of t){const C=o.createVariants();C&&C.length>0&&(g[o.selfModel.uuid]=C)}const I=[];for(const o of t){for(const C in g)C!==o.selfModel.uuid&&I.push(g[C]);o.createAndAttachBehaviors(A,g[o.selfModel.uuid],I)}}delete iQ._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(A,e,t){const g=[],I=[];for(const o of this.targetModels){const C=at.fadeAction(o,0,!1);I.push(C)}for(const o of t)I.push(at.fadeAction(o,0,!1));for(const o of e)g.push(at.fadeAction(o,0,!1)),I.push(at.fadeAction(o,0,!0));A.addBehavior(new cg("Select "+this.selfModel.name,pI.tapTrigger(this.selfModel),at.parallel(...I))),A.addBehavior(new cg("Start hidden "+this.selfModel.name,pI.sceneStartTrigger(),at.parallel(...g)))}createVariants(){if(!this.variantMaterial)return null;const A=[];for(const e of this.targetModels){const t=e.clone();t.name+=" variant_"+this.variantMaterial.name,t.name=t.name.replace(/\s/g,"_"),t.material=this.variantMaterial,t.geometry=e.geometry,t.matrix=e.matrix,(!e.parent||!e.parent.isEmpty())&&ho.createEmptyParent(e),e.parent&&e.parent.add(t),A.push(t)}return A}},r(W0,"_materialTriggersPerId",{}),W0);let yd=iQ;Ht([w(Ke)],yd.prototype,"materialToSwitch",2);Ht([w(Ke)],yd.prototype,"variantMaterial",2);class OE extends MA{constructor(){super(...arguments);r(this,"target");r(this,"toggleOnClick",!1);r(this,"targetState",!0);r(this,"hideSelf",!0);r(this,"selfModel");r(this,"otherModel");r(this,"toggleModel");r(this,"stateBeforeCreatingDocument",!1)}onPointerClick(){!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}createBehaviours(e,t,g){t.uuid===this.gameObject.uuid&&(this.selfModel=t)}beforeCreateDocument(){this.stateBeforeCreatingDocument=this.gameObject.visible,this.gameObject.visible=!0}afterCreateDocument(e,t){if(this.target){if(this.otherModel=t.document.findById(this.target.uuid),this.selfModel&&this.otherModel){let g=this.hideSelf;this.targetState,this.toggleOnClick&&(g=!0,this.target.visible,(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&ET.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.clone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel));const I=[];if(g&&I.push(at.fadeAction(this.selfModel,0,!1)),this.toggleModel&&I.push(at.fadeAction(this.toggleModel,0,!0)),I.push(at.fadeAction(this.otherModel,0,this.targetState)),e.addBehavior(new cg("Toggle_"+this.selfModel.name+"_hideSelf",pI.tapTrigger(this.selfModel),at.sequence(...I))),this.toggleOnClick&&this.toggleModel){const o=[];o.push(at.fadeAction(this.toggleModel,0,!1)),o.push(at.fadeAction(this.selfModel,0,!0)),o.push(at.fadeAction(this.otherModel,0,!this.targetState)),e.addBehavior(new cg("Toggle_"+this.selfModel.name+"_toggleSelf",pI.tapTrigger(this.toggleModel),at.sequence(...o))),e.addBehavior(new cg("HideOnStart_"+this.gameObject.name,pI.sceneStartTrigger(),at.fadeAction(this.toggleModel,0,!1)))}}this.gameObject.visible=this.stateBeforeCreatingDocument}}}Ht([w(UA)],OE.prototype,"target",2);Ht([w()],OE.prototype,"targetState",2);Ht([w()],OE.prototype,"hideSelf",2);class SR extends MA{start(){this.gameObject.visible=!1}createBehaviours(A,e,t){e.uuid===this.gameObject.uuid&&A.addBehavior(new cg("HideOnStart_"+this.gameObject.name,pI.sceneStartTrigger(),at.fadeAction(e,0,!1)))}beforeCreateDocument(){this.gameObject.visible=!0}afterCreateDocument(){this.gameObject.visible=!1}}class PE extends MA{constructor(){super(...arguments);r(this,"target");r(this,"duration",.5);r(this,"motionType",mm.bounce)}beforeCreateDocument(){}createBehaviours(e,t,g){if(this.target&&t.uuid===this.gameObject.uuid){const I=new cg("emphasize "+this.name,pI.tapTrigger(this.gameObject),at.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(I)}}afterCreateDocument(e,t){}}Ht([w()],PE.prototype,"target",2);Ht([w()],PE.prototype,"duration",2);Ht([w()],PE.prototype,"motionType",2);class WE extends MA{constructor(){super(...arguments);r(this,"target");r(this,"clip","");r(this,"toggleOnClick",!1)}onPointerClick(){if(!(!this.target&&!this.clip)){if(!this.target){const e=this.gameObject.addNewComponent(Fi);e&&(e.spatialBlend=1,e.volume=1,e.loop=!1,this.target=e)}this.target&&(this.target.isPlaying&&this.toggleOnClick?this.target.stop():(!this.toggleOnClick&&this.target.isPlaying&&this.target.stop(),this.clip?this.target.play(this.clip):this.target.play()))}}createBehaviours(e,t,g){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const I=this.clip?this.clip:this.target?this.target.clip:void 0;if(!I)return;const o=this.target?this.target.gameObject:this.gameObject,C=I.split("/").pop(),s=this.target?this.target.volume:1,n=this.target&&this.target.spatialBlend==0?hG.NonSpatial:hG.Spatial,a=new cg("playAudio "+this.name,pI.tapTrigger(this.gameObject),at.playAudioAction(o,"audio/"+C,DT.Play,s,n));e.addBehavior(a)}}async afterSerialize(e,t){if(!this.target&&!this.clip)return;const g=this.clip?this.clip:this.target?this.target.clip:void 0;if(!g)return;const I=g.split("/").pop(),s=await(await(await fetch(this.clip)).blob()).arrayBuffer(),n=new Uint8Array(s);t.files["audio/"+I]=n}}Ht([w(Fi)],WE.prototype,"target",2);Ht([w(URL)],WE.prototype,"clip",2);Ht([w()],WE.prototype,"toggleOnClick",2);var V0;const gQ=(V0=class extends MA{constructor(){super(...arguments);r(this,"target");r(this,"animator");r(this,"stateName");r(this,"stateNameAfterPlaying");r(this,"loopAfterPlaying",!1);r(this,"selfModel");r(this,"stateAnimationModel");r(this,"stateAnimation");r(this,"stateAfterPlayingAnimationModel");r(this,"stateAfterPlayingAnimation")}onPointerClick(){var A;this.target&&this.stateName&&((A=this.animator)==null||A.play(this.stateName,0,0,.1))}createBehaviours(A,e,t){e.uuid===this.gameObject.uuid&&(this.selfModel=e)}onAfterHierarchy(){gQ.animationActions=[]}afterCreateDocument(A,e){if(!this.stateAnimation||!this.stateAnimationModel)return;e.document.traverse(g=>{var I,o;if(g.uuid===((I=this.target)==null?void 0:I.uuid)&&this.stateAnimation){const C=[];let s=gQ.animationActions.find(a=>a.affectedObjects==g&&a.start==this.stateAnimation.start&&a.duration==this.stateAnimation.duration);if(s||(s=at.startAnimationAction(g,this.stateAnimation.start,this.stateAnimation.duration),gQ.animationActions.push(s)),C.push(s),this.stateAfterPlayingAnimation&&this.stateAfterPlayingAnimationModel){let a=gQ.animationActions.find(Q=>Q.affectedObjects==g&&Q.start==this.stateAfterPlayingAnimation.start&&Q.duration==this.stateAfterPlayingAnimation.duration);a||(a=at.startAnimationAction(g,this.stateAfterPlayingAnimation.start,this.stateAfterPlayingAnimation.duration),gQ.animationActions.push(a));const B=at.sequence(a);this.loopAfterPlaying&&B.makeLooping(),C.push(B)}const n=new cg("tap "+this.name+" for "+this.stateName+" on "+((o=this.target)==null?void 0:o.name),pI.tapTrigger(this.selfModel),at.sequence(...C));A.addBehavior(n)}})}createAnimation(A,e,t){var g,I,o,C;if(this.target&&this.animator){const s=(I=(g=this.animator)==null?void 0:g.runtimeAnimatorController)==null?void 0:I.findState(this.stateName);this.stateAnimationModel=e,this.stateAnimation=A.registerAnimation(this.target,s==null?void 0:s.motion.clip);const n=(C=(o=this.animator)==null?void 0:o.runtimeAnimatorController)==null?void 0:C.findState(this.stateNameAfterPlaying);this.stateAfterPlayingAnimationModel=e,this.stateAfterPlayingAnimation=A.registerAnimation(this.target,n==null?void 0:n.motion.clip)}}},r(V0,"animationActions",[]),V0);let ba=gQ;Ht([w(UA)],ba.prototype,"target",2);Ht([w(wI)],ba.prototype,"animator",2);Ht([w()],ba.prototype,"stateName",2);Ht([w()],ba.prototype,"stateNameAfterPlaying",2);Ht([w()],ba.prototype,"loopAfterPlaying",2);class VE extends MA{constructor(){super(...arguments);r(this,"target")}getType(){}getDuration(){}}Ht([w(UA)],VE.prototype,"target",2);class Sd extends MA{constructor(){super(...arguments);r(this,"target")}}Ht([w(VE)],Sd.prototype,"target",2);class kd extends VE{constructor(){super(...arguments);r(this,"type",1);r(this,"duration",1)}getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Ht([w()],kd.prototype,"type",2);Ht([w()],kd.prototype,"duration",2);class kR extends Sd{}var niA=Object.defineProperty,aiA=Object.getOwnPropertyDescriptor,En=(i,A,e,t)=>{for(var g=t>1?void 0:t?aiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&niA(A,e,g),g};class nB extends MA{constructor(){super(...arguments);r(this,"center",new k(0,0,0));r(this,"radius",.5);r(this,"height",2);r(this,"_rigidbody",null);r(this,"_activeGroundCollisions",new Set)}get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(jt),this._rigidbody||(this._rigidbody=this.gameObject.addNewComponent(jt)),this.rigidbody)}onEnable(){let e=this.rigidbody,t=this.gameObject.getComponent(Da);t||(t=this.gameObject.addNewComponent(Da)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height,this.gameObject.rotation.x=0,this.gameObject.rotation.z=0,e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}onCollisionEnter(e){for(const t of e.contacts)if(t.normal.y>.1){this._activeGroundCollisions.add(e);break}}onCollisionExit(e){this._activeGroundCollisions.delete(e)}get isGrounded(){return this._activeGroundCollisions.size>0}}En([w(k)],nB.prototype,"center",2);En([w()],nB.prototype,"radius",2);En([w()],nB.prototype,"height",2);class cn extends MA{constructor(){super(...arguments);r(this,"controller");r(this,"movementSpeed",2);r(this,"rotationSpeed",2);r(this,"jumpForce",1);r(this,"doubleJumpForce",2);r(this,"animator");r(this,"lookForward",!0);r(this,"_currentSpeed",new k(0,0,0));r(this,"_currentAngularSpeed",new k(0,0,0));r(this,"_temp",new k(0,0,0));r(this,"_jumpCount",0);r(this,"_currentRotation");r(this,"_raycastOptions",new CC)}awake(){this._currentRotation=new kA}update(){var n,a,B,Q,E,c,h,l,d,p,u;(n=this.controller)!=null&&n.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&((a=this.animator)==null||a.setBool("doubleJump",!1)));const e=this.context.input.isKeyPressed("w"),t=this.context.input.isKeyPressed("s"),g=this.context.input.isKeyPressed("a"),I=this.context.input.isKeyPressed("d"),o=this.context.input.isKeyDown(" "),C=(e?1:0)+(t?-1:0);this._currentSpeed.z+=C*this.movementSpeed*this.context.time.deltaTime,(B=this.animator)==null||B.setBool("running",C!=0),(E=this.animator)==null||E.setBool("jumping",((Q=this.controller)==null?void 0:Q.isGrounded)===!0&&o),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp);const s=(g?1:0)+(I?-1:0);if(this._currentAngularSpeed.y+=Ae.toRadians(s*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const D=this.context.mainCameraComponent.forward;D.y=0,D.normalize(),this._currentRotation.setFromUnitVectors(new k(0,0,1),D),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&o&&this.jumpForce>0){let D=(c=this.controller)==null?void 0:c.isGrounded;if(this.doubleJumpForce>0&&!((h=this.controller)!=null&&h.isGrounded)&&this._jumpCount===1&&(D=!0,(l=this.animator)==null||l.setBool("doubleJump",!0)),D){this._jumpCount+=1;const y=this.controller.rigidbody,S=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;y.applyImpulse(new k(0,1,0).multiplyScalar(S))}}if(this.controller){const D=(d=this.controller)==null?void 0:d.rigidbody.getVelocity().y;if(D<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new on),this._raycastOptions.ray.origin.copy(ye(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const y=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const S=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(y),(S.length&&S[0].distance>2||D<-10)&&((p=this.animator)==null||p.setBool("falling",!0))}else(u=this.animator)==null||u.setBool("falling",!1)}}}En([w(nB)],cn.prototype,"controller",2);En([w()],cn.prototype,"movementSpeed",2);En([w()],cn.prototype,"rotationSpeed",2);En([w()],cn.prototype,"jumpForce",2);En([w()],cn.prototype,"doubleJumpForce",2);En([w(wI)],cn.prototype,"animator",2);var riA=Object.defineProperty,BiA=Object.getOwnPropertyDescriptor,QiA=(i,A,e,t)=>{for(var g=t>1?void 0:t?BiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&riA(A,e,g),g};class Gd extends eI{constructor(){super(...arguments);r(this,"intensity")}get typeName(){return"ChromaticAberration"}init(){this.intensity.defaultValue=0}onCreateEffect(){const e=new Nx;return e.offset=new j(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=t=>t*.02,this.intensity.onValueChanged=t=>{e.offset.x=-t,e.offset.y=t},e}}QiA([w(ve)],Gd.prototype,"intensity",2);$C("ChromaticAberration",Gd);var EiA=Object.defineProperty,ciA=Object.getOwnPropertyDescriptor,jw=(i,A,e,t)=>{for(var g=t>1?void 0:t?ciA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&EiA(A,e,g),g};class La extends eI{constructor(){super(...arguments);r(this,"postExposure");r(this,"contrast");r(this,"hueShift");r(this,"saturation")}get typeName(){return"ColorAdjustments"}init(){this.postExposure.valueProcessor=e=>(e=Math.pow(2,e),e),this.postExposure.defaultValue=0,this.contrast.valueProcessor=e=>{let t=1;return e>0?t=200:e<0&&(t=100),e/t},this.contrast.defaultValue=0,this.hueShift.valueProcessor=e=>Math.PI*e/180,this.hueShift.defaultValue=0,this.saturation.valueProcessor=e=>e<0?e/100:e/(100*Math.PI),this.saturation.defaultValue=0}unapply(){this.context.renderer.toneMappingExposure=1}onCreateEffect(){this.context.renderer.toneMapping===Pg&&this.postExposure.overrideState&&(this.context.renderer.toneMapping=Jh);const e=new Fx;this.postExposure.onValueChanged=g=>{this.context.renderer.toneMapping===Pg&&(this.context.renderer.toneMapping=Jh),this.context.renderer.toneMappingExposure=g},this.contrast.onValueChanged=g=>{e.contrast=g};const t=new Jx;return this.hueShift.onValueChanged=g=>t.hue=g,this.saturation.onValueChanged=g=>t.saturation=g,[t,e]}}jw([w(ve)],La.prototype,"postExposure",2);jw([w(ve)],La.prototype,"contrast",2);jw([w(ve)],La.prototype,"hueShift",2);jw([w(ve)],La.prototype,"saturation",2);$C("ColorAdjustments",La);const hiA=(Math.sqrt(5)-1)/4,Cg=(5-Math.sqrt(5))/20,iD=i=>Math.floor(i)|0,gD=new Float64Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]);function liA(i=Math.random){const A=diA(i),e=new Float64Array(A).map(o=>gD[o%32*4]),t=new Float64Array(A).map(o=>gD[o%32*4+1]),g=new Float64Array(A).map(o=>gD[o%32*4+2]),I=new Float64Array(A).map(o=>gD[o%32*4+3]);return function(C,s,n,a){let B,Q,E,c,h;const l=(C+s+n+a)*hiA,d=iD(C+l),p=iD(s+l),u=iD(n+l),D=iD(a+l),y=(d+p+u+D)*Cg,S=d-y,R=p-y,f=u-y,M=D-y,U=C-S,J=s-R,T=n-f,Y=a-M;let b=0,_=0,AA=0,$=0;U>J?b++:_++,U>T?b++:AA++,U>Y?b++:$++,J>T?_++:AA++,J>Y?_++:$++,T>Y?AA++:$++;const X=b>=3?1:0,cA=_>=3?1:0,EA=AA>=3?1:0,NA=$>=3?1:0,uA=b>=2?1:0,gA=_>=2?1:0,aA=AA>=2?1:0,GA=$>=2?1:0,P=b>=1?1:0,vA=_>=1?1:0,KA=AA>=1?1:0,jA=$>=1?1:0,wA=U-X+Cg,ne=J-cA+Cg,dA=T-EA+Cg,lA=Y-NA+Cg,qA=U-uA+2*Cg,ee=J-gA+2*Cg,VA=T-aA+2*Cg,Ee=Y-GA+2*Cg,re=U-P+3*Cg,oe=J-vA+3*Cg,Oe=T-KA+3*Cg,qe=Y-jA+3*Cg,v=U-1+4*Cg,K=J-1+4*Cg,BA=T-1+4*Cg,RA=Y-1+4*Cg,JA=d&255,PA=p&255,ae=u&255,_A=D&255;let q=.6-U*U-J*J-T*T-Y*Y;if(q<0)B=0;else{const xA=JA+A[PA+A[ae+A[_A]]];q*=q,B=q*q*(e[xA]*U+t[xA]*J+g[xA]*T+I[xA]*Y)}let pA=.6-wA*wA-ne*ne-dA*dA-lA*lA;if(pA<0)Q=0;else{const xA=JA+X+A[PA+cA+A[ae+EA+A[_A+NA]]];pA*=pA,Q=pA*pA*(e[xA]*wA+t[xA]*ne+g[xA]*dA+I[xA]*lA)}let XA=.6-qA*qA-ee*ee-VA*VA-Ee*Ee;if(XA<0)E=0;else{const xA=JA+uA+A[PA+gA+A[ae+aA+A[_A+GA]]];XA*=XA,E=XA*XA*(e[xA]*qA+t[xA]*ee+g[xA]*VA+I[xA]*Ee)}let TA=.6-re*re-oe*oe-Oe*Oe-qe*qe;if(TA<0)c=0;else{const xA=JA+P+A[PA+vA+A[ae+KA+A[_A+jA]]];TA*=TA,c=TA*TA*(e[xA]*re+t[xA]*oe+g[xA]*Oe+I[xA]*qe)}let WA=.6-v*v-K*K-BA*BA-RA*RA;if(WA<0)h=0;else{const xA=JA+1+A[PA+1+A[ae+1+A[_A+1]]];WA*=WA,h=WA*WA*(e[xA]*v+t[xA]*K+g[xA]*BA+I[xA]*RA)}return 27*(B+Q+E+c+h)}}function diA(i){const e=new Uint8Array(512);for(let t=0;t<512/2;t++)e[t]=t;for(let t=0;t<512/2-1;t++){const g=t+~~(i()*(256-t)),I=e[t];e[t]=e[g],e[g]=I}for(let t=256;t<512;t++)e[t]=e[t-256];return e}var uiA=Object.defineProperty,DiA=Object.getOwnPropertyDescriptor,Z=(i,A,e,t)=>{for(var g=t>1?void 0:t?DiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&uiA(A,e,g),g};const ID=rA("debugparticles");var RC=(i=>(i[i.Billboard=0]="Billboard",i[i.Stretch=1]="Stretch",i[i.HorizontalBillboard=2]="HorizontalBillboard",i[i.VerticalBillboard=3]="VerticalBillboard",i[i.Mesh=4]="Mesh",i))(RC||{});class va{constructor(){r(this,"alphaKeys");r(this,"colorKeys")}get duration(){return 1}evaluate(A,e){let t,g=0,I=null,o=0;for(let C=0;C<this.alphaKeys.length;C++){const s=this.alphaKeys[C];(s.time<A||!t)&&(t=s,g=C)}for(let C=0;C<this.colorKeys.length;C++){const s=this.colorKeys[C];(s.time<A||!I)&&(I=s,o=C)}if(I)if(o+1<this.colorKeys.length){const s=this.colorKeys[o+1],n=Ae.remap(A,I.time,s.time,0,1);e.r=Ae.lerp(I.color.r,s.color.r,n),e.g=Ae.lerp(I.color.g,s.color.g,n),e.b=Ae.lerp(I.color.b,s.color.b,n)}else e.r=I.color.r,e.g=I.color.g,e.b=I.color.b;if(t)if(g+1<this.alphaKeys.length){const s=this.alphaKeys[g+1],n=Ae.remap(A,t.time,s.time,0,1);e.alpha=Ae.lerp(t.alpha,s.alpha,n)}else e.alpha=t.alpha;return e}}Z([w()],va.prototype,"alphaKeys",2);Z([w()],va.prototype,"colorKeys",2);var zw=(i=>(i[i.Local=0]="Local",i[i.World=1]="World",i[i.Custom=2]="Custom",i))(zw||{}),I_=(i=>(i[i.Sphere=0]="Sphere",i[i.SphereShell=1]="SphereShell",i[i.Hemisphere=2]="Hemisphere",i[i.HemisphereShell=3]="HemisphereShell",i[i.Cone=4]="Cone",i[i.Box=5]="Box",i[i.Mesh=6]="Mesh",i[i.ConeShell=7]="ConeShell",i[i.ConeVolume=8]="ConeVolume",i[i.ConeVolumeShell=9]="ConeVolumeShell",i[i.Circle=10]="Circle",i[i.CircleEdge=11]="CircleEdge",i[i.SingleSidedEdge=12]="SingleSidedEdge",i[i.MeshRenderer=13]="MeshRenderer",i[i.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",i[i.BoxShell=15]="BoxShell",i[i.BoxEdge=16]="BoxEdge",i[i.Donut=17]="Donut",i[i.Rectangle=18]="Rectangle",i[i.Sprite=19]="Sprite",i[i.SpriteRenderer=20]="SpriteRenderer",i))(I_||{});class se{constructor(){r(this,"mode");r(this,"constant");r(this,"constantMin");r(this,"constantMax");r(this,"curve");r(this,"curveMin");r(this,"curveMax");r(this,"curveMultiplier")}evaluate(A,e){const t=e===void 0?Math.random():e;switch(this.mode){case 0:return this.constant;case 1:return A=Ae.clamp01(A),this.curve.evaluate(A)*this.curveMultiplier;case 2:const g=A*this.curveMin.duration,I=A*this.curveMax.duration;return Ae.lerp(this.curveMin.evaluate(g),this.curveMax.evaluate(I),t%1)*this.curveMultiplier;case 3:return Ae.lerp(this.constantMin,this.constantMax,t%1);default:this.curveMax.evaluate(A)*this.curveMultiplier;break}return 0}getMax(){switch(this.mode){case 0:return this.constant;case 1:return this.getMaxFromCurve(this.curve)*this.curveMultiplier;case 2:return Math.max(this.getMaxFromCurve(this.curveMin),this.getMaxFromCurve(this.curveMax))*this.curveMultiplier;case 3:return Math.max(this.constantMin,this.constantMax);default:return 0}}getMaxFromCurve(A){if(!A)return 0;let e=Number.MIN_VALUE;for(let t=0;t<A.keys.length;t++){const g=A.keys[t];g.value>e&&(e=g.value)}return e}}Z([w()],se.prototype,"mode",2);Z([w()],se.prototype,"constant",2);Z([w()],se.prototype,"constantMin",2);Z([w()],se.prototype,"constantMax",2);Z([w(AB)],se.prototype,"curve",2);Z([w(AB)],se.prototype,"curveMin",2);Z([w(AB)],se.prototype,"curveMax",2);Z([w()],se.prototype,"curveMultiplier",2);var DD;const xo=(DD=class{constructor(){r(this,"mode");r(this,"color");r(this,"colorMin");r(this,"colorMax");r(this,"gradient");r(this,"gradientMin");r(this,"gradientMax")}evaluate(i,A){const e=A===void 0?Math.random():A;switch(this.mode){case 0:return this.color;case 1:return this.gradient.evaluate(i,xo._temp),xo._temp;case 2:return xo._temp.lerpColors(this.colorMin,this.colorMax,e);case 3:return this.gradientMin.evaluate(i,xo._temp),this.gradientMax.evaluate(i,xo._temp2),xo._temp.lerp(xo._temp2,e)}return xo._temp.set(16711935),xo._temp.alpha=1,xo._temp}},r(DD,"_temp",new Gt(0,0,0,1)),r(DD,"_temp2",new Gt(0,0,0,1)),DD);let yI=xo;Z([w(Gt)],yI.prototype,"color",2);Z([w(Gt)],yI.prototype,"colorMin",2);Z([w(Gt)],yI.prototype,"colorMax",2);Z([w(va)],yI.prototype,"gradient",2);Z([w(va)],yI.prototype,"gradientMin",2);Z([w(va)],yI.prototype,"gradientMax",2);class ug{constructor(){r(this,"cullingMode");r(this,"duration");r(this,"emitterVelocityMode");r(this,"flipRotation");r(this,"gravityModifier");r(this,"gravityModifierMultiplier");r(this,"loop");r(this,"maxParticles");r(this,"playOnAwake");r(this,"prewarm");r(this,"ringBufferLoopRange");r(this,"ringBufferMode");r(this,"scalingMode");r(this,"simulationSpace");r(this,"simulationSpeed");r(this,"startColor");r(this,"startDelay");r(this,"startDelayMultiplier");r(this,"startLifetime");r(this,"startLifetimeMultiplier");r(this,"startRotation");r(this,"startRotationMultiplier");r(this,"startRotation3D");r(this,"startRotationX");r(this,"startRotationXMultiplier");r(this,"startRotationY");r(this,"startRotationYMultiplier");r(this,"startRotationZ");r(this,"startRotationZMultiplier");r(this,"startSize");r(this,"startSize3D");r(this,"startSizeMultiplier");r(this,"startSizeX");r(this,"startSizeXMultiplier");r(this,"startSizeY");r(this,"startSizeYMultiplier");r(this,"startSizeZ");r(this,"startSizeZMultiplier");r(this,"startSpeed");r(this,"startSpeedMultiplier");r(this,"stopAction");r(this,"useUnscaledTime")}}Z([w(se)],ug.prototype,"gravityModifier",2);Z([w(yI)],ug.prototype,"startColor",2);Z([w(se)],ug.prototype,"startDelay",2);Z([w(se)],ug.prototype,"startLifetime",2);Z([w(se)],ug.prototype,"startRotation",2);Z([w(se)],ug.prototype,"startRotationX",2);Z([w(se)],ug.prototype,"startRotationY",2);Z([w(se)],ug.prototype,"startRotationZ",2);Z([w(se)],ug.prototype,"startSize",2);Z([w(se)],ug.prototype,"startSizeX",2);Z([w(se)],ug.prototype,"startSizeY",2);Z([w(se)],ug.prototype,"startSizeZ",2);Z([w(se)],ug.prototype,"startSpeed",2);class Bl{constructor(){r(this,"cycleCount");r(this,"maxCount");r(this,"minCount");r(this,"probability");r(this,"repeatInterval");r(this,"time");r(this,"count");r(this,"_performed",0)}reset(){this._performed=0}run(A){if(A<=this.time)return this.reset(),0;let e=0;if(this.cycleCount===0||this._performed<this.cycleCount){const t=this.time+this.repeatInterval*this._performed;if(A>=t&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:e=this.count.constant;break;case 3:e=Ae.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:e=this.count.curve.evaluate(Math.random());break;case 2:const g=Math.random();e=Ae.lerp(this.count.curveMin.evaluate(g),this.count.curveMax.evaluate(g),Math.random());break}}return e}}class ts{constructor(){r(this,"enabled");r(this,"bursts");r(this,"rateOverTime");r(this,"rateOverTimeMultiplier");r(this,"rateOverDistance");r(this,"rateOverDistanceMultiplier");r(this,"system")}get burstCount(){var A;return((A=this.bursts)==null?void 0:A.length)??0}reset(){var A;(A=this.bursts)==null||A.forEach(e=>e.reset())}getBurst(){let A=0;if(this.burstCount>0)for(let e=0;e<this.burstCount;e++){const t=this.bursts[e];t.time>=this.system.time&&t.reset(),A+=Math.round(t.run(this.system.time))}return A}}Z([w()],ts.prototype,"enabled",2);Z([w()],ts.prototype,"bursts",2);Z([w(se)],ts.prototype,"rateOverTime",2);Z([w()],ts.prototype,"rateOverTimeMultiplier",2);Z([w(se)],ts.prototype,"rateOverDistance",2);Z([w()],ts.prototype,"rateOverDistanceMultiplier",2);class Md{constructor(){r(this,"enabled");r(this,"color")}}Z([w(yI)],Md.prototype,"color",2);class xa{constructor(){r(this,"enabled");r(this,"separateAxes");r(this,"size");r(this,"sizeMultiplier");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier");r(this,"_time",0);r(this,"_temp",new k)}evaluate(A,e,t){if(e||(e=this._temp),!this.enabled)return e.x=e.y=e.z=1,e;if(this.separateAxes)e.x=this.x.evaluate(A,t)*this.xMultiplier,e.y=this.y.evaluate(A,t)*this.yMultiplier,e.z=this.z.evaluate(A,t)*this.zMultiplier;else{const g=this.size.evaluate(A,t)*this.sizeMultiplier;e.x=g}return e}}Z([w(se)],xa.prototype,"size",2);Z([w(se)],xa.prototype,"x",2);Z([w(se)],xa.prototype,"y",2);Z([w(se)],xa.prototype,"z",2);var pD;const jc=(pD=class{constructor(){r(this,"shapeType",5);r(this,"enabled",!0);r(this,"alignToDirection",!1);r(this,"angle",0);r(this,"arc",360);r(this,"arcSpread");r(this,"arcSpeedMultiplier");r(this,"arcMode");r(this,"boxThickness");r(this,"position");r(this,"rotation");r(this,"_rotation",new Ui);r(this,"scale");r(this,"radius");r(this,"radiusThickness");r(this,"sphericalDirectionAmount");r(this,"randomDirectionAmount");r(this,"randomPositionAmount");r(this,"system");r(this,"_space");r(this,"_worldSpaceMatrix",new OA);r(this,"_worldSpaceMatrixInverse",new OA);r(this,"_vector",new k(0,0,0));r(this,"_temp",new k(0,0,0));r(this,"_dir",new k);r(this,"_loopTime",0);r(this,"_loopDirection",1);ID&&console.log(this)}get type(){return I_[this.shapeType]}initialize(i){this.getPosition(),i.position.copy(this._vector)}toJSON(){return this}clone(){return new jc}update(i,A,e,t){this.system=i,this._space=e,e===1&&(this._worldSpaceMatrix.copy(t.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(i){const A=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return A&&(this._rotation.x=Ae.toRadians(this.rotation.x),this._rotation.y=Ae.toRadians(this.rotation.y),this._rotation.z=Ae.toRadians(this.rotation.z),this._rotation.order="ZYX",i.applyEuler(this._rotation)),A}get vector(){return this._vector}getPosition(){this._vector.set(0,0,0);const i=this._temp.copy(this.position),A=this._space===1;A&&i.applyQuaternion(this.system.worldQuaternion);let e=this.radius;if(A&&(e*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:ID&&KC.DrawBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(i);break;case 4:this.randomConePoint(this.position,this.angle,e,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,e,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,e,this.radiusThickness,this.arc,this._vector);break;default:this._vector.set(0,0,0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),A&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),ID&&KC.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(i){var A;if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const e=i.x,t=i.y,g=i.z;this._dir.set(e,t,g),(A=this.system)!=null&&A.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),ID&&(KC.DrawSphere(i,.01,8925952,.5,!0),KC.DrawDirection(i,this._dir,8925952,.5,!0)),this._dir}randomizePosition(i,A){if(A<=0)return;const e=jc._tempVec;e.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),e.x*=A*this.scale.x,e.y*=A*this.scale.y,e.z*=A*this.scale.z,i.add(e)}randomizeDirection(i,A){if(A===0)return;const e=jc._randomQuat,t=jc._tempVec;t.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),e.setFromAxisAngle(t,A*Math.random()*Math.PI),i.applyQuaternion(e)}spherizeDirection(i,A){if(A===0)return;const e=Math.random()*Math.PI*2,t=Math.acos(1-Math.random()*2),g=Math.sin(t)*Math.cos(e),I=Math.sin(t)*Math.sin(e),o=Math.cos(t),C=new k(g,I,o);i.lerp(C,A)}randomSpherePoint(i,A,e,t,g){const I=Math.random(),o=Math.random(),C=2*Math.PI*I*(t/360),s=Math.acos(2*o-1),n=Ae.lerp(1,1-Math.pow(1-Math.random(),Math.PI),e)*A,a=i.x+this.scale.x*(-n*Math.sin(s)*Math.cos(C)),B=i.y+this.scale.y*(n*Math.sin(s)*Math.sin(C)),Q=i.z+this.scale.z*(n*Math.cos(s));g.x=a,g.y=B,g.z=Q}randomCirclePoint(i,A,e,t,g){const I=Math.random(),o=2*Math.PI*I*(t/360),C=Ae.lerp(1,1-Math.pow(1-Math.random(),Math.PI),e)*A,s=i.x+this.scale.x*C*Math.cos(o),n=i.y+this.scale.y*C*Math.sin(o),a=i.z;g.x=s,g.y=n,g.z=a}randomConePoint(i,A,e,t,g,I,o){let C=0,s=0;switch(I){case 0:C=Math.random(),s=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:C=.5,s=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let n=2*Math.PI*C*(g/360);switch(I){case 2:case 1:n+=Math.PI+.5,n+=this._loopTime*Math.PI*2,n%=Ae.toRadians(g);break}const a=Math.acos(2*s-1),B=Ae.lerp(1,1-Math.pow(1-Math.random(),Math.PI),t)*e,Q=i.x+-B*Math.sin(a)*Math.cos(n),E=i.y+B*Math.sin(a)*Math.sin(n),c=i.z;o.x=Q*this.scale.x,o.y=E*this.scale.y,o.z=c*this.scale.z}},r(pD,"_randomQuat",new kA),r(pD,"_tempVec",new k),pD);let Di=jc;Z([w()],Di.prototype,"shapeType",2);Z([w()],Di.prototype,"enabled",2);Z([w()],Di.prototype,"alignToDirection",2);Z([w()],Di.prototype,"angle",2);Z([w()],Di.prototype,"arc",2);Z([w()],Di.prototype,"arcSpread",2);Z([w()],Di.prototype,"arcSpeedMultiplier",2);Z([w()],Di.prototype,"arcMode",2);Z([w(k)],Di.prototype,"boxThickness",2);Z([w(k)],Di.prototype,"position",2);Z([w(k)],Di.prototype,"rotation",2);Z([w(k)],Di.prototype,"scale",2);Z([w()],Di.prototype,"radius",2);Z([w()],Di.prototype,"radiusThickness",2);Z([w()],Di.prototype,"sphericalDirectionAmount",2);Z([w()],Di.prototype,"randomDirectionAmount",2);Z([w()],Di.prototype,"randomPositionAmount",2);class lt{constructor(){r(this,"damping");r(this,"enabled");r(this,"frequency");r(this,"octaveCount");r(this,"octaveMultiplier");r(this,"octaveScale");r(this,"positionAmount");r(this,"quality");r(this,"remap");r(this,"remapEnabled");r(this,"remapMultiplier");r(this,"remapX");r(this,"remapXMultiplier");r(this,"remapY");r(this,"remapYMultiplier");r(this,"remapZ");r(this,"remapZMultiplier");r(this,"scrollSpeedMultiplier");r(this,"separateAxes");r(this,"strengthMultiplier");r(this,"strengthX");r(this,"strengthXMultiplier");r(this,"strengthY");r(this,"strengthYMultiplier");r(this,"strengthZ");r(this,"strengthZMultiplier");r(this,"_noise");r(this,"_time",0);r(this,"_temp",new k)}update(A){this._time+=A.time.deltaTime*this.scrollSpeedMultiplier}apply(A,e,t,g,I,o){if(!this.enabled)return;this._noise||(this._noise=liA(()=>0));const C=this._temp.set(e.x,e.y,e.z).multiplyScalar(this.frequency),s=this._noise(C.x,C.y,C.z,this._time),n=this._noise(C.x,C.y,C.z,this._time+1e3*this.frequency),a=this._noise(C.x,C.y,C.z,this._time+2e3*this.frequency);this._temp.set(s,n,a).normalize();const B=I/o;let Q=this.positionAmount.evaluate(B);this.separateAxes?(this._temp.x*=Q*this.strengthXMultiplier,this._temp.y*=Q*this.strengthYMultiplier,this._temp.z*=Q*this.strengthZMultiplier):(this.strengthX&&(Q*=this.strengthX.evaluate(B)*1.5),this._temp.multiplyScalar(Q)),t.x+=this._temp.x,t.y+=this._temp.y,t.z+=this._temp.z}}Z([w()],lt.prototype,"damping",2);Z([w()],lt.prototype,"enabled",2);Z([w()],lt.prototype,"frequency",2);Z([w()],lt.prototype,"octaveCount",2);Z([w()],lt.prototype,"octaveMultiplier",2);Z([w()],lt.prototype,"octaveScale",2);Z([w(se)],lt.prototype,"positionAmount",2);Z([w()],lt.prototype,"quality",2);Z([w(se)],lt.prototype,"remap",2);Z([w()],lt.prototype,"remapEnabled",2);Z([w()],lt.prototype,"remapMultiplier",2);Z([w(se)],lt.prototype,"remapX",2);Z([w()],lt.prototype,"remapXMultiplier",2);Z([w(se)],lt.prototype,"remapY",2);Z([w()],lt.prototype,"remapYMultiplier",2);Z([w(se)],lt.prototype,"remapZ",2);Z([w()],lt.prototype,"remapZMultiplier",2);Z([w()],lt.prototype,"scrollSpeedMultiplier",2);Z([w()],lt.prototype,"separateAxes",2);Z([w()],lt.prototype,"strengthMultiplier",2);Z([w(se)],lt.prototype,"strengthX",2);Z([w()],lt.prototype,"strengthXMultiplier",2);Z([w(se)],lt.prototype,"strengthY",2);Z([w()],lt.prototype,"strengthYMultiplier",2);Z([w(se)],lt.prototype,"strengthZ",2);Z([w()],lt.prototype,"strengthZMultiplier",2);class _t{constructor(){r(this,"enabled");r(this,"attachRibbonToTransform",!1);r(this,"colorOverLifetime");r(this,"colorOverTrail");r(this,"dieWithParticles",!0);r(this,"inheritParticleColor",!0);r(this,"lifetime");r(this,"lifetimeMultiplier");r(this,"minVertexDistance",.2);r(this,"mode",0);r(this,"ratio",1);r(this,"ribbonCount",1);r(this,"shadowBias",0);r(this,"sizeAffectsLifetime",!1);r(this,"sizeAffectsWidth",!1);r(this,"splitSubEmitterRibbons",!1);r(this,"textureMode",0);r(this,"widthOverTrail");r(this,"widthOverTrailMultiplier");r(this,"worldSpace",!1)}getWidth(A,e,t){let g=this.widthOverTrail.evaluate(t);return t===0&&(g=A),A*=g,A}getColor(A,e,t){const g=this.colorOverTrail.evaluate(t),I=this.colorOverLifetime.evaluate(e);A.x*=g.r*I.r,A.y*=g.g*I.g,A.z*=g.b*I.b,A.w*=g.alpha*I.alpha}}Z([w()],_t.prototype,"enabled",2);Z([w()],_t.prototype,"attachRibbonToTransform",2);Z([w(yI)],_t.prototype,"colorOverLifetime",2);Z([w(yI)],_t.prototype,"colorOverTrail",2);Z([w()],_t.prototype,"dieWithParticles",2);Z([w()],_t.prototype,"inheritParticleColor",2);Z([w(se)],_t.prototype,"lifetime",2);Z([w()],_t.prototype,"lifetimeMultiplier",2);Z([w()],_t.prototype,"minVertexDistance",2);Z([w()],_t.prototype,"mode",2);Z([w()],_t.prototype,"ratio",2);Z([w()],_t.prototype,"ribbonCount",2);Z([w()],_t.prototype,"shadowBias",2);Z([w()],_t.prototype,"sizeAffectsLifetime",2);Z([w()],_t.prototype,"sizeAffectsWidth",2);Z([w()],_t.prototype,"splitSubEmitterRibbons",2);Z([w()],_t.prototype,"textureMode",2);Z([w(se)],_t.prototype,"widthOverTrail",2);Z([w()],_t.prototype,"widthOverTrailMultiplier",2);Z([w()],_t.prototype,"worldSpace",2);class zt{constructor(){r(this,"enabled");r(this,"space",0);r(this,"orbitalX");r(this,"orbitalY");r(this,"orbitalZ");r(this,"orbitalXMultiplier");r(this,"orbitalYMultiplier");r(this,"orbitalZMultiplier");r(this,"orbitalOffsetX");r(this,"orbitalOffsetY");r(this,"orbitalOffsetZ");r(this,"speedModifier");r(this,"speedModifierMultiplier");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier");r(this,"_system");r(this,"_temp",new k);r(this,"_temp2",new k);r(this,"_temp3",new k);r(this,"_hasOrbital",!1);r(this,"_index",0);r(this,"_orbitalMatrix",new OA)}update(A){this._system=A}init(A){this._index==0&&(A.debug=!0),this._index+=1,A.orbitx=this.orbitalX.evaluate(Math.random()),A.orbity=this.orbitalY.evaluate(Math.random()),A.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=A.orbitx!=0||A.orbity!=0||A.orbitz!=0}apply(A,e,t,g,I,o,C){var E;if(!this.enabled)return;const s=o/C,n=this.speedModifier.evaluate(s)*this.speedModifierMultiplier,a=this.x.evaluate(s),B=this.y.evaluate(s),Q=this.z.evaluate(s);if(this._temp.set(-a,B,Q),this._system,this._hasOrbital&&((E=this._system)==null?void 0:E.worldPos)){const h=this._temp2.set(t.x,t.y,t.z),l=this.orbitalXMultiplier,d=this.orbitalYMultiplier,p=this.orbitalZMultiplier,u=n*Math.PI*2*10,D=Math.cos(u*l),y=Math.sin(u*l),S=Math.cos(u*d),R=Math.sin(u*d),f=Math.cos(u*p),M=Math.sin(u*p),U=h.x*(S*f)+h.y*(S*M)+h.z*-R,J=h.x*(y*R*f-D*M)+h.y*(y*R*M+D*f)+h.z*(y*S),T=h.x*(D*R*f+y*M)+h.y*(D*R*M-y*f)+h.z*(D*S),Y=this._temp3.set(h.x-U,h.y-J,h.z-T);Y.normalize(),Y.multiplyScalar(.2/I*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),g.x+=Y.x,g.y+=Y.y,g.z+=Y.z}g.x+=this._temp.x,g.y+=this._temp.y,g.z+=this._temp.z,g.x*=n,g.y*=n,g.z*=n}}Z([w()],zt.prototype,"enabled",2);Z([w()],zt.prototype,"space",2);Z([w(se)],zt.prototype,"orbitalX",2);Z([w(se)],zt.prototype,"orbitalY",2);Z([w(se)],zt.prototype,"orbitalZ",2);Z([w()],zt.prototype,"orbitalXMultiplier",2);Z([w()],zt.prototype,"orbitalYMultiplier",2);Z([w()],zt.prototype,"orbitalZMultiplier",2);Z([w()],zt.prototype,"orbitalOffsetX",2);Z([w()],zt.prototype,"orbitalOffsetY",2);Z([w()],zt.prototype,"orbitalOffsetZ",2);Z([w(se)],zt.prototype,"speedModifier",2);Z([w()],zt.prototype,"speedModifierMultiplier",2);Z([w(se)],zt.prototype,"x",2);Z([w()],zt.prototype,"xMultiplier",2);Z([w(se)],zt.prototype,"y",2);Z([w()],zt.prototype,"yMultiplier",2);Z([w(se)],zt.prototype,"z",2);Z([w()],zt.prototype,"zMultiplier",2);class Dg{constructor(){r(this,"animation");r(this,"enabled");r(this,"cycleCount");r(this,"frameOverTime");r(this,"frameOverTimeMultiplier");r(this,"numTilesX");r(this,"numTilesY");r(this,"startFrame");r(this,"startFrameMultiplier");r(this,"rowMode");r(this,"rowIndex");r(this,"spriteCount");r(this,"timeMode")}sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:case 2:case 1:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?Math.random()*(this.numTilesX*this.numTilesY):0}evaluate(A){if(!this.sampleOnceAtStart())return this.getIndex(A)}getIndex(A){const e=this.numTilesX*this.numTilesY;A=A*this.cycleCount;let t=this.frameOverTime.evaluate(A%1);return t*=this.frameOverTimeMultiplier,t*=e,t=t%e,t=Math.floor(t),t}}Z([w()],Dg.prototype,"animation",2);Z([w()],Dg.prototype,"enabled",2);Z([w()],Dg.prototype,"cycleCount",2);Z([w(se)],Dg.prototype,"frameOverTime",2);Z([w()],Dg.prototype,"frameOverTimeMultiplier",2);Z([w()],Dg.prototype,"numTilesX",2);Z([w()],Dg.prototype,"numTilesY",2);Z([w(se)],Dg.prototype,"startFrame",2);Z([w()],Dg.prototype,"startFrameMultiplier",2);Z([w()],Dg.prototype,"rowMode",2);Z([w()],Dg.prototype,"rowIndex",2);Z([w()],Dg.prototype,"spriteCount",2);Z([w()],Dg.prototype,"timeMode",2);class Ro{constructor(){r(this,"enabled");r(this,"separateAxes");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier")}evaluate(A,e){return this.enabled?this.separateAxes?0:this.z.evaluate(A,e)*-1:0}}Z([w()],Ro.prototype,"enabled",2);Z([w()],Ro.prototype,"separateAxes",2);Z([w(se)],Ro.prototype,"x",2);Z([w()],Ro.prototype,"xMultiplier",2);Z([w(se)],Ro.prototype,"y",2);Z([w()],Ro.prototype,"yMultiplier",2);Z([w(se)],Ro.prototype,"z",2);Z([w()],Ro.prototype,"zMultiplier",2);class jI{constructor(){r(this,"enabled");r(this,"range");r(this,"separateAxes");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier")}evaluate(A,e){if(!this.enabled)return 0;if(!this.separateAxes){const t=Ae.lerp(this.range.x,this.range.y,e);return this.z.evaluate(t)*-1}return 0}}Z([w()],jI.prototype,"enabled",2);Z([w()],jI.prototype,"range",2);Z([w()],jI.prototype,"separateAxes",2);Z([w(se)],jI.prototype,"x",2);Z([w()],jI.prototype,"xMultiplier",2);Z([w(se)],jI.prototype,"y",2);Z([w()],jI.prototype,"yMultiplier",2);Z([w(se)],jI.prototype,"z",2);Z([w()],jI.prototype,"zMultiplier",2);class Ji{constructor(){r(this,"enabled");r(this,"dampen");r(this,"drag");r(this,"dragMultiplier");r(this,"limit");r(this,"limitMultiplier");r(this,"separateAxes");r(this,"limitX");r(this,"limitXMultiplier");r(this,"limitY");r(this,"limitYMultiplier");r(this,"limitZ");r(this,"limitZMultiplier");r(this,"multiplyDragByParticleSize",!1);r(this,"multiplyDragByParticleVelocity",!1);r(this,"space");r(this,"_temp",new k);r(this,"_temp2",new k)}apply(A,e,t,g,I,o,C){if(this.enabled){const s=this.limit.evaluate(I)*this.limitMultiplier;if(e.length()>s){this._temp.copy(e).normalize().multiplyScalar(s);let a=this.dampen*.5;e.x=Ae.lerp(e.x,this._temp.x,a),e.y=Ae.lerp(e.y,this._temp.y,a),e.z=Ae.lerp(e.z,this._temp.z,a),t.x=Ae.lerp(t.x,this._temp.x,a),t.y=Ae.lerp(t.y,this._temp.y,a),t.z=Ae.lerp(t.z,this._temp.z,a)}}}}Z([w()],Ji.prototype,"enabled",2);Z([w()],Ji.prototype,"dampen",2);Z([w(se)],Ji.prototype,"drag",2);Z([w()],Ji.prototype,"dragMultiplier",2);Z([w(se)],Ji.prototype,"limit",2);Z([w()],Ji.prototype,"limitMultiplier",2);Z([w()],Ji.prototype,"separateAxes",2);Z([w(se)],Ji.prototype,"limitX",2);Z([w()],Ji.prototype,"limitXMultiplier",2);Z([w(se)],Ji.prototype,"limitY",2);Z([w()],Ji.prototype,"limitYMultiplier",2);Z([w(se)],Ji.prototype,"limitZ",2);Z([w()],Ji.prototype,"limitZMultiplier",2);Z([w()],Ji.prototype,"multiplyDragByParticleSize",2);Z([w()],Ji.prototype,"multiplyDragByParticleVelocity",2);Z([w()],Ji.prototype,"space",2);class Ya{constructor(){r(this,"enabled");r(this,"curve");r(this,"curveMultiplier");r(this,"mode");r(this,"system");r(this,"_lastWorldPosition");r(this,"_velocity",new k);r(this,"_temp",new k)}update(A){this.enabled&&this.system.worldspace!==!1&&(this._lastWorldPosition?(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)):(this._velocity.set(0,0,0),this._lastWorldPosition=this.system.worldPos.clone()))}applyInitial(A){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const e=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(e),A.add(this._temp)}}applyCurrent(A,e,t){if(this.enabled&&this.system.worldspace!==!1&&this.mode===1){const g=this.curve.evaluate(e,t);this._temp.copy(this._velocity).multiplyScalar(g),A.add(this._temp)}}}Z([w()],Ya.prototype,"enabled",2);Z([w(se)],Ya.prototype,"curve",2);Z([w()],Ya.prototype,"curveMultiplier",2);Z([w()],Ya.prototype,"mode",2);class tI{constructor(){r(this,"enabled");r(this,"range");r(this,"separateAxes");r(this,"size");r(this,"sizeMultiplier");r(this,"x");r(this,"xMultiplier");r(this,"y");r(this,"yMultiplier");r(this,"z");r(this,"zMultiplier")}evaluate(A,e,t,g){const I=A.length(),o=Ae.remap(I,this.range.x,this.range.y,0,1),C=this.size.evaluate(o,t);return g*C}}Z([w()],tI.prototype,"enabled",2);Z([w(j)],tI.prototype,"range",2);Z([w()],tI.prototype,"separateAxes",2);Z([w(se)],tI.prototype,"size",2);Z([w()],tI.prototype,"sizeMultiplier",2);Z([w(se)],tI.prototype,"x",2);Z([w()],tI.prototype,"xMultiplier",2);Z([w(se)],tI.prototype,"y",2);Z([w()],tI.prototype,"yMultiplier",2);Z([w(se)],tI.prototype,"z",2);Z([w()],tI.prototype,"zMultiplier",2);class aB{constructor(){r(this,"enabled");r(this,"range");r(this,"color")}evaluate(A,e,t){const g=A.length(),I=Ae.remap(g,this.range.x,this.range.y,0,1),o=this.color.evaluate(I,e);t.x*=o.r,t.y*=o.g,t.z*=o.b,t.w*=o.alpha}}Z([w()],aB.prototype,"enabled",2);Z([w(j)],aB.prototype,"range",2);Z([w(yI)],aB.prototype,"color",2);function piA(i){const A=i.domElement.querySelector("link[rel='ar']");if(A)return A;const e=document.createElement("div");e.classList.add("menu"),e.classList.add("quicklook-menu"),e.style.display="none",e.style.visibility="hidden";const t=document.createElement("button");t.id="open-in-ar",t.innerText="Open in QuickLook",e.appendChild(t);const g=document.createElement("a");g.id="needle-usdz-link",g.style.display="none",g.rel="ar",g.href="",e.appendChild(g);const I=document.createElement("img");return I.id="button",g.appendChild(I),i.domElement.appendChild(e),g}function fiA(){var i=new Date;const A=i.getMonth()+1,e=i.getDate(),t=i.getHours(),g=i.getMinutes(),I=i.getSeconds(),o=(A<10?"0":"")+A,C=(e<10?"0":"")+e,s=(t<10?"0":"")+t,n=(g<10?"0":"")+g,a=(I<10?"0":"")+I;return i.getFullYear()+o+C+"-"+s+n+a}const oD=rA("debugusdz");function wiA(i,A){const e=[],t=eA.getComponentsInChildren(i,wI);let g=!1;oD&&console.log(t);for(const I of t){if(!I||!I.runtimeAnimatorController)continue;oD&&console.log(I);const o=[];for(const C of I.runtimeAnimatorController.enumerateActions()){oD&&console.log(C);const s=C.getClip();if(!g&&s.tracks.length>0){g=!0;const n=s.tracks[0],a=n.name.substring(0,n.name.lastIndexOf(".")),B=new _I(a+".position",[0,.01],[0,0,0,0,0,0]),Q=new _I(a+".quaternion",[0,.01],[0,0,0,1,0,0,0,1]);o.push(new So("rest",.01,[B,Q]))}o.includes(s)||o.push(s)}e.push({root:I.gameObject,clips:o})}oD&&console.log(e);for(const I of e)for(const o of I.clips)A.registerAnimation(I.root,o)}var yiA=Object.defineProperty,SiA=Object.getOwnPropertyDescriptor,hn=(i,A,e,t)=>{for(var g=t>1?void 0:t?SiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&yiA(A,e,g),g};const u0=rA("debugtext");var vi=(i=>(i[i.UpperLeft=0]="UpperLeft",i[i.UpperCenter=1]="UpperCenter",i[i.UpperRight=2]="UpperRight",i[i.MiddleLeft=3]="MiddleLeft",i[i.MiddleCenter=4]="MiddleCenter",i[i.MiddleRight=5]="MiddleRight",i[i.LowerLeft=6]="LowerLeft",i[i.LowerCenter=7]="LowerCenter",i[i.LowerRight=8]="LowerRight",i))(vi||{});class iI extends oB{constructor(){super(...arguments);r(this,"alignment",0);r(this,"verticalOverflow",0);r(this,"horizontalOverflow",0);r(this,"lineSpacing",1);r(this,"supportRichText",!1);r(this,"font");r(this,"fontStyle",0);r(this,"_text","");r(this,"_fontSize",12);r(this,"_textMeshUi",null);r(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(e){var t;super.setAlphaFactor(e),(t=this.uiObject)==null||t.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){var t;this._fontSize=e,(t=this.uiObject)==null||t.set({fontSize:e})}onColorChanged(){var e;(e=this.uiObject)==null||e.set({color:this.color,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeRender(){this.uiObject&&this.Root.screenspace&&this.updateOverflow()}updateOverflow(){var t;const e=(t=this.uiObject)==null?void 0:t._overflow;e&&(e._needsUpdate=!0,this.markDirty())}onCreate(e){u0&&console.log(this),this.horizontalOverflow==1&&(e.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,e.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,e.lineHeight=this.lineSpacing,delete e.backgroundOpacity,delete e.backgroundColor,u0&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),u0&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=t.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}getTextOpts(){let e=this.fontSize;const t={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.setFont(t,this.fontStyle),t}onEnable(){super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 0:case 3:case 6:e.textAlign="left";break;case 1:case 4:case 7:e.textAlign="center";break;case 2:case 5:case 8:e.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:e.alignItems="start";break;case 3:case 4:case 5:e.alignItems="center";break;case 6:case 7:case 8:e.alignItems="end";break}return e}feedText(e,t){var g,I,o;if(!this.uiObject)return null;if(this._textMeshUi||(this._textMeshUi=[]),!t||e.length===0)this.uiObject.textContent=e;else{let C=this.getNextTag(e);if(C)C.startIndex>0&&this.uiObject.add(new jD({textContent:e.substring(0,C.startIndex),color:"inherit"}));else return this.uiObject.textContent=e;const s=[];for(;C;){const n=this.getNextTag(e,C.endIndex),a={fontFamily:(g=this.uiObject)==null?void 0:g.get("fontFamily"),color:"inherit",textContent:""};n?(a.textContent=this.getText(e,C,n),this.handleTag(C,a,s),(I=this.uiObject)==null||I.add(new jD(a))):(a.textContent=e.substring(C.endIndex),this.handleTag(C,a,s),(o=this.uiObject)==null||o.add(new jD(a))),C=n}}return null}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,g={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let I=!1;if(this._textMeshUi)for(let o=0;o<this._textMeshUi.length;o++){if(e[o]===!0)continue;I=!0;const C=this._textMeshUi[o];C.textContent&&(tf(C,g),e[o]=!0)}if(!I)break;yield}}handleTag(e,t,g){if(e.isEndTag){if(g.length>0){const I=g.pop();if(I)for(const o in I.previousValues){const C=I.previousValues[o];t[o]=C}}}else if(e.type.includes("color")){const I=new D0(e,{color:t.color});if(g.push(I),e.type.length>6){const o=parseInt("0x"+e.type.substring(7));t.color=o}else t.color=new yA(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const I=new D0(e,{fontWeight:700});g.push(I)}else if(e.type=="i"){this.setFont(t,2);const I=new D0(e,{fontStyle:"italic"});g.push(I)}}getText(e,t,g){return e.substring(t.endIndex,g.startIndex)}getNextTag(e,t=0){const g=e.indexOf("<",t),I=e.indexOf(">",g);if(g>=0&&I>=0){const o=e.substring(g+1,I);return{type:o,startIndex:g,endIndex:I+1,isEndTag:o.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;let g=this.font,I=wG.getFontFamily(g);I||(I=wG.addFontFamily(g)),e.fontFamily=I;const o=g.toLowerCase();switch(t){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal",o.includes("-bold")||(g+="-bold");break;case 2:e.fontWeight=400,e.fontStyle="italic",o.includes("-italic")||(g+="-italic");break;case 3:e.fontStyle="italic",e.fontWeight=400,o.includes("-bold")||(g+="-bold"),o.includes("-italic")||(g+="-italic")}let C=I.getVariant(e.fontWeight,e.fontStyle);if(!C){let s=g;s!=null&&s.endsWith("-msdf.json")||(s+="-msdf.json");let n=g;n!=null&&n.endsWith(".png")||(n+=".png"),C=I.addVariant(e.fontWeight,e.fontStyle,s,n),C==null||C.addEventListener("ready",()=>{this.markDirty()})}}}hn([w()],iI.prototype,"alignment",2);hn([w()],iI.prototype,"verticalOverflow",2);hn([w()],iI.prototype,"horizontalOverflow",2);hn([w()],iI.prototype,"lineSpacing",2);hn([w()],iI.prototype,"supportRichText",2);hn([w(URL)],iI.prototype,"font",2);hn([w()],iI.prototype,"fontStyle",2);hn([w()],iI.prototype,"text",1);hn([w()],iI.prototype,"fontSize",1);class D0{constructor(A,e){r(this,"tag");r(this,"previousValues");this.tag=A,this.previousValues=e}}class ea{constructor(A){r(this,"id");r(this,"content","");r(this,"font",[]);r(this,"pointSize",144);r(this,"width");r(this,"height");r(this,"depth");r(this,"wrapMode");r(this,"horizontalAlignment");r(this,"verticalAlignment");r(this,"material");this.id=A}static getId(){return this.global_id++}setDepth(A){return this.depth=A,this}setPointSize(A){return this.pointSize=A,this}setHorizontalAlignment(A){return this.horizontalAlignment=A,this}setVerticalAlignment(A){return this.verticalAlignment=A,this}writeTo(A,e){var g;e.beginBlock(`def Preliminary_Text "${this.id}"`),this.content&&e.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(g=this.font)==null||g.push("sans-serif"));const t=this.font.map(I=>`"${I}"`).join(", ");e.appendLine(`string[] font = [ ${t} ]`),e.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&e.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&e.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&e.appendLine(`double depth = ${this.depth}`),this.wrapMode&&e.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&e.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&e.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&e.appendLine(`rel material:binding = </Materials/Material_${this.material.id}>`),e.closeBlock()}}r(ea,"global_id",0);class Zw{static singleLine(A,e,t){const g=new ea("text_"+ea.getId());return g.content=A,e&&(g.pointSize=e),t&&(g.depth=t),g}static multiLine(A,e,t,g,I,o){const C=new ea("text_"+ea.getId());return C.content=A,C.width=e,C.height=t,C.horizontalAlignment=g,C.verticalAlignment=I,o!==void 0&&(C.wrapMode=o),C}}const kiA=new OA().makeRotationY(Math.PI);class Xw{get extensionName(){return"text"}onExportObject(A,e,t){const g=eA.getComponent(A,iI);if(g){const I=eA.getComponent(A,Ug);let o=100,C=100;I&&(o=I.width,C=I.height);const s=e.clone();s.matrix=kiA.clone();const n=new yA().copySRGBToLinear(g.color);s.material=new jr({color:n,emissive:n}),e.add(s),s.addEventListener("serialize",(a,B)=>{const Q=Zw.multiLine(g.text,o,C,"center","bottom","flowing");this.setTextAlignment(Q,g.alignment),this.setOverflow(Q,g),s.material&&(Q.material=s.material),Q.pointSize=this.convertToTextSize(g.fontSize),Q.depth=.001,Q.writeTo(void 0,a)})}}convertToTextSize(A){return 1/.0502*144*A}setOverflow(A,e){e.horizontalOverflow?A.wrapMode="singleLine":A.wrapMode="flowing"}setTextAlignment(A,e){switch(e){case vi.LowerLeft:case vi.MiddleLeft:case vi.UpperLeft:A.horizontalAlignment="left";break;case vi.LowerCenter:case vi.MiddleCenter:case vi.UpperCenter:A.horizontalAlignment="center";break;case vi.LowerRight:case vi.MiddleRight:case vi.UpperRight:A.horizontalAlignment="right";break}switch(e){case vi.LowerLeft:case vi.LowerCenter:case vi.LowerRight:A.verticalAlignment="bottom";break;case vi.MiddleLeft:case vi.MiddleCenter:case vi.MiddleRight:A.verticalAlignment="middle";break;case vi.UpperLeft:case vi.UpperCenter:case vi.UpperRight:A.verticalAlignment="top";break}}}var GiA=Object.defineProperty,MiA=Object.getOwnPropertyDescriptor,Uo=(i,A,e,t)=>{for(var g=t>1?void 0:t?MiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&GiA(A,e,g),g};const hC=rA("debugusdz");class Ta{constructor(){r(this,"callToAction");r(this,"checkoutTitle");r(this,"checkoutSubtitle");r(this,"callToActionURL")}}Uo([w()],Ta.prototype,"callToAction",2);Uo([w()],Ta.prototype,"checkoutTitle",2);Uo([w()],Ta.prototype,"checkoutSubtitle",2);Uo([w()],Ta.prototype,"callToActionURL",2);class Fo extends MA{constructor(){super(...arguments);r(this,"objectToExport");r(this,"autoExportAnimations",!1);r(this,"exportFileName");r(this,"customUsdzFile");r(this,"customBranding");r(this,"anchoringType","plane");r(this,"planeAnchoringAlignment","horizontal");r(this,"interactive",!0);r(this,"extensions",[]);r(this,"link");r(this,"webxr");r(this,"webARSessionRoot");r(this,"lastCallback");r(this,"_quicklookButton");r(this,"_quicklookButtonContainer",null)}start(){var e,t,g,I;hC&&(console.log(this),console.log("Debug USDZ, press 't' to export"),window.addEventListener("keydown",o=>{switch(o.key){case"t":this.exportAsync();break}}),Wr()&&setTimeout(()=>{this.exportAsync()},2e3)),(e=document.getElementById("open-in-ar"))==null||e.addEventListener("click",o=>{o.preventDefault(),this.exportAsync()}),this.objectToExport||(this.objectToExport=this.gameObject),!((g=(t=this.objectToExport)==null?void 0:t.children)!=null&&g.length)&&!((I=this.objectToExport)!=null&&I.isMesh)&&(this.objectToExport=this.context.scene),this.interactive&&(this.extensions.push(new Pw),this.extensions.push(new _w),this.extensions.push(new Xw))}onEnable(){const e=Nh(),t=Gs();(hC||e&&t)&&(this.addQuicklookButton(),this.webARSessionRoot=eA.findObjectOfType(Na)??void 0,this.lastCallback=this.quicklookCallback.bind(this),this.link=piA(this.context),this.link.addEventListener("message",this.lastCallback)),hC&&eg("USDZ Exporter enabled: "+this.name)}onDisable(){var g;(g=this.link)==null||g.removeEventListener("message",this.lastCallback);const e=Nh(),t=Gs();(hC||e&&t)&&this.removeQuicklookButton(),hC&&eg("USDZ Exporter disabled: "+this.name)}async exportAsync(){var E;let e=this.exportFileName??((E=this.objectToExport)==null?void 0:E.name)??this.name;if(na()||(e+="-MadeWithNeedle"),e+="-"+fiA(),this.customUsdzFile){const c=this.buildQuicklookOverlay();hC&&console.log(c);const h=c.callToAction?encodeURIComponent(c.callToAction):"",l=c.checkoutTitle?encodeURIComponent(c.checkoutTitle):"",d=c.checkoutSubtitle?encodeURIComponent(c.checkoutSubtitle):"";this.link.href=this.customUsdzFile+`#callToAction=${h}&checkoutTitle=${l}&checkoutSubtitle=${d}&callToActionURL=${c.callToActionURL}`,console.log(this.link.href),this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=e+".usdz",this.link.click();return}if(!this.objectToExport)return;if(this.webARSessionRoot){const c=this.webARSessionRoot.gameObject,h=1/this.webARSessionRoot.arScale;c.matrix.makeScale(h,h,h),this.webARSessionRoot.invertForward&&c.matrix.multiply(new OA().makeRotationY(Math.PI))}const t=new xX,g=[...this.extensions],I=new Gw;g.push(I),this.autoExportAnimations&&wiA(this.objectToExport,I);const o={self:this,exporter:t,extensions:g,object:this.objectToExport};this.dispatchEvent(new CustomEvent("before-export",{detail:o})),t.debug=hC,this.anchoringType!=="plane"&&this.anchoringType!=="none"&&this.anchoringType!=="image"&&this.anchoringType!=="face"&&(this.anchoringType="plane"),this.planeAnchoringAlignment!=="horizontal"&&this.planeAnchoringAlignment!=="vertical"&&this.planeAnchoringAlignment!=="any"&&(this.planeAnchoringAlignment="horizontal");const C=await t.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:g,quickLookCompatible:!0}),s=new Blob([C],{type:"application/octet-stream"});this.dispatchEvent(new CustomEvent("after-export",{detail:o}));const n=this.buildQuicklookOverlay();hC&&console.log(n);const a=n.callToAction?encodeURIComponent(n.callToAction):"",B=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",Q=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=URL.createObjectURL(s)+`#callToAction=${a}&checkoutTitle=${B}&checkoutSubtitle=${Q}&callToActionURL=${n.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=e+".usdz",this.link.click()}quicklookCallback(e){if((e==null?void 0:e.data)=="_apple_ar_quicklook_button_tapped"){hC&&oC("Quicklook closed via call to action button");var t=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(t),!t.defaultPrevented){const g=new URLSearchParams(this.link.href);if(g){const I=g.get("callToActionURL");hC&&eg("Quicklook url: "+I),I&&(na()?globalThis.open(I,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",I))}}}}buildQuicklookOverlay(){var t,g,I;const e={};return this.customBranding&&Object.assign(e,this.customBranding),na()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),e.callToAction="Close",e.checkoutTitle="🌵 Made with Needle",e.checkoutSubtitle="_"),(t=e.callToAction)!=null&&t.length||(e.callToAction="Close"),(g=e.checkoutTitle)!=null&&g.length||(e.checkoutTitle="🌵 Made with Needle"),(I=e.checkoutSubtitle)!=null&&I.length||(e.checkoutSubtitle="_"),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:e})),e}async createQuicklookButton(){var e,t;if(!this.webxr)if(await Gl(1),this.webxr=eA.findObjectOfType(Se)??void 0,this.webxr)if(this.webxr.VRButton&&((e=this.webxr.VRButton.parentElement)==null||e.removeChild(this.webxr.VRButton)),this.webxr.ARButton&&this._quicklookButton!==this.webxr.ARButton){this._quicklookButton=this.webxr.ARButton;const g=(t=this.webxr.ARButton.parentElement)==null?void 0:t.querySelector("a");g&&(g.href=""),this.webxr.ARButton.innerText="Open in Quicklook",this.webxr.ARButton.disabled=!1,this.webxr.ARButton.addEventListener("click",I=>{I.preventDefault(),this.exportAsync()}),this.webxr.ARButton.classList.add("quicklook-ar-button"),this._quicklookButtonContainer=this.webxr.ARButton.parentElement,this.dispatchEvent(new CustomEvent("created-button",{detail:this.webxr.ARButton}))}else{this.webxr.createARButton=!1,this.webxr.createVRButton=!1;let g=window.document.querySelector(".webxr-buttons");g||(g=document.createElement("div"),g.classList.add("webxr-buttons"));const I=document.createElement("button");I.innerText="Open in Quicklook",I.addEventListener("click",()=>{this.exportAsync()}),I.classList.add("webxr-ar-button"),I.classList.add("webxr-button"),I.classList.add("quicklook-ar-button"),g.appendChild(I),this._quicklookButtonContainer=g,this.dispatchEvent(new CustomEvent("created-button",{detail:I}))}else console.warn("Could not find WebXR component: will not create Quicklook button",pe.Current)}async addQuicklookButton(){await this.createQuicklookButton(),this._quicklookButton&&this._quicklookButtonContainer&&this._quicklookButtonContainer.appendChild(this._quicklookButton)}removeQuicklookButton(){var e;(e=this._quicklookButton)==null||e.remove()}}Uo([w(UA)],Fo.prototype,"objectToExport",2);Uo([w()],Fo.prototype,"autoExportAnimations",2);Uo([w()],Fo.prototype,"exportFileName",2);Uo([w(URL)],Fo.prototype,"customUsdzFile",2);Uo([w(Ta)],Fo.prototype,"customBranding",2);Uo([w()],Fo.prototype,"anchoringType",2);Uo([w()],Fo.prototype,"planeAnchoringAlignment",2);Uo([w()],Fo.prototype,"interactive",2);const mJ=rA("debugdeletable");class $w extends Qo{}class GR extends MA{constructor(){super(...arguments);r(this,"deleteBoxes",[])}awake(){this.deleteBoxes=eA.findObjectsOfType($w,this.context)}update(){for(const e of this.deleteBoxes){const t=this.gameObject;if(e.isInBox(t)===!0){const I=eA.getComponentInParent(this.gameObject,FE);I?mJ&&console.warn("Can not delete object with usage marker",this.guid,I):(mJ&&console.log("DESTROY",this.gameObject),Bw(this.gameObject,this.context.connection))}}}}var miA=Object.defineProperty,RiA=Object.getOwnPropertyDescriptor,rB=(i,A,e,t)=>{for(var g=t>1?void 0:t?RiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&miA(A,e,g),g};class rC extends eI{constructor(){super(...arguments);r(this,"mode");r(this,"focusDistance");r(this,"focalLength");r(this,"aperture");r(this,"gaussianMaxRadius");r(this,"resolutionScale");r(this,"bokehScale")}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=t=>{const g=t/300,I=2;return Ae.lerp(I,.01,g)};const e=20;this.aperture.valueProcessor=t=>{const g=1-t/32;return Ae.lerp(1,e,g)}}onCreateEffect(){if(this.mode===0)return;const e=1/window.devicePixelRatio;if(this.resolutionScale===void 0){let g=1;Wr()&&(g=.6),this.resolutionScale=new ve(g*e)}const t=new Kx(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=g=>{t.circleOfConfusionMaterial.worldFocusDistance=g},this.focalLength.onValueChanged=g=>t.circleOfConfusionMaterial.worldFocusRange=g,this.aperture.onValueChanged=g=>t.bokehScale=g,this.resolutionScale&&(this.resolutionScale.onValueChanged=g=>t.resolution.scale=g),[t]}unapply(){}}rB([w()],rC.prototype,"mode",2);rB([w(ve)],rC.prototype,"focusDistance",2);rB([w(ve)],rC.prototype,"focalLength",2);rB([w(ve)],rC.prototype,"aperture",2);rB([w(ve)],rC.prototype,"gaussianMaxRadius",2);rB([w(ve)],rC.prototype,"resolutionScale",2);rB([w(ve)],rC.prototype,"bokehScale",2);$C("DepthOfField",rC);var UiA=Object.defineProperty,FiA=Object.getOwnPropertyDescriptor,NiA=(i,A,e,t)=>{for(var g=t>1?void 0:t?FiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&UiA(A,e,g),g};class Ay extends MA{constructor(){super(...arguments);r(this,"visibleOn")}onEnable(){this.apply()}apply(){this.test()||eA.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:KiA()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}NiA([w()],Ay.prototype,"visibleOn",2);let CD;function KiA(){if(CD===!0||CD===!1)return CD;let i=!1;return function(A){(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(A)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(A.substr(0,4)))&&(i=!0)}(navigator.userAgent||navigator.vendor||window.opera),CD=i,i}class MR{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(A){}}var o_=(i=>(i.SelectStart="selectstart",i.SelectEnd="selectend",i))(o_||{});const fs=class extends UE{constructor(){super();r(this,"transformSelf",!0);r(this,"orbit",null);r(this,"selectStartEventListener",[]);r(this,"selectEndEventListener",[]);r(this,"_dragHelper",null);r(this,"_draggingRigidbodies",[]);r(this,"_waitingForDragStart",null);r(this,"_isDragging",!1);r(this,"_marker",null);r(this,"_dragDelta");r(this,"_didDrag",!1);r(this,"_activePointerId");this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new j}static get HasAnySelected(){return this._active>0}addDragEventListener(e,t){switch(e){case"selectstart":this.selectStartEventListener.push(t);break;case"selectend":this.selectEndEventListener.push(t);break}}start(){this.orbit=eA.findObjectOfType(Bn,this.context)}allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||Se.IsInWebXR)return;const t=eA.getComponentInParent(e.object,fs);!t||t!==this||(fs.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){this.allowEdit(this.gameObject)&&(Se.IsInWebXR||fs.lastHovered===e.object&&(this.context.domElement.style.cursor="auto"))}onPointerDown(e){this.allowEdit(this.gameObject)&&(Se.IsInWebXR||(fs._active+=1,this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation(),this.orbit&&(this.orbit.enabled=!1)))}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&(fs._active>0&&(fs._active-=1),!Se.IsInWebXR&&(this.onDragEnd(e),e.StopPropagation(),this.orbit&&(this.orbit.enabled=!0)))}update(){var e;if(!Se.IsInWebXR){if(this._waitingForDragStart){if(!this._didDrag){const g=this.context.input.getPointerPositionDelta(0);if(g&&this._dragDelta.add(g),this._dragDelta.length()>2)this._didDrag=!0;else return}const t=this._waitingForDragStart;this._waitingForDragStart=null,this.onDragStart(t)}this._dragHelper&&this._dragHelper.hasSelected&&this.onUpdateDrag(),(((e=this._dragHelper)==null?void 0:e.hasSelected)===!1||this._activePointerId!==void 0&&this.context.input.getPointerPressed(this._activePointerId)===!1)&&this.onDragEnd(null)}}onDragStart(e){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new Ap(this.context.mainCamera);else return;if(!e||!e.object)return;const t=eA.getComponentInParent(e.object,fs);if(!t||t!==this)return;let g=e.object;this.transformSelf&&(g=this.gameObject);const I={selected:g,attached:g};for(const n of this.selectStartEventListener)n(this,I);if(this._activePointerId=e.pointerId,!I.attached)return;I.attached,g=I.attached,this._isDragging=!0,this._dragHelper.setSelected(g,this.context),this.orbit&&(this.orbit.enabled=!1);const o=eA.getComponentInChildren(g,da);o&&(o.fastMode=!0,o==null||o.requestOwnership()),this._marker=eA.addNewComponent(g,FE),this._draggingRigidbodies.length=0;const C=eA.getComponentsInChildren(g,jt);C&&this._draggingRigidbodies.push(...C);const s=cp();eA.invokeOnChildren(this._dragHelper.selected,s("onDragStart"))}onUpdateDrag(){if(this._dragHelper){this._dragHelper.onUpdate(this.context);for(const e of this._draggingRigidbodies)e.wakeUp(),e.resetVelocities()}}onDragEnd(e){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;for(const I of this._draggingRigidbodies)I.setVelocity(I.smoothedVelocity);this._draggingRigidbodies.length=0;const t=this._dragHelper.selected;if(this._dragHelper.setSelected(null,this.context),this.orbit&&(this.orbit.enabled=!0),e!=null&&e.object){const I=eA.getComponentInChildren(e.object,da);I&&(I.fastMode=!1)}this._marker&&this._marker.destroy();for(const I of this.selectEndEventListener)I(this);const g=cp();eA.invokeOnChildren(t,g("onDragEnd"))}};let ta=fs;r(ta,"_active",0),r(ta,"lastHovered");const vU=class{constructor(A){r(this,"_selected",null);r(this,"_context",null);r(this,"_camera");r(this,"_cameraPlane",new ro);r(this,"_hasGroundPlane",!1);r(this,"_groundPlane",new ro);r(this,"_groundOffset",new k);r(this,"_groundOffsetFactor",0);r(this,"_groundDistance",0);r(this,"_groundPlanePoint",new k);r(this,"_raycaster",new BE);r(this,"_cameraPlaneOffset",new k);r(this,"_intersection",new k);r(this,"_worldPosition",new k);r(this,"_inverseMatrix",new OA);r(this,"_rbs",[]);r(this,"_groundLine");r(this,"_groundMarker");r(this,"_groundOffsetVector",new k(0,1,0));r(this,"_requireUpdateGroundPlane",!0);r(this,"_didDragOnGroundPlaneLastFrame",!1);this._camera=A;const e=new Qi(vU.geometry),t=e.material;t.color=new yA(.4,.4,.4),e.layers.set(2),e.name="line",e.scale.y=1,this._groundLine=e;const g=new Go(.5,22,22),I=new wt({color:t.color}),o=new fA(g,I);o.visible=!1,o.layers.set(2),this._groundMarker=o}get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}setSelected(A,e){if(this._selected&&e)for(const t of this._rbs)t.wakeUp(),t.setVelocity(0,0,0);if(this._selected&&jg.Remove(e,this._selected),this._selected=A,this._context=e,this._rbs.length=0,A?(e.scene.add(this._groundLine),e.scene.add(this._groundMarker)):(this._groundLine.removeFromParent(),this._groundMarker.removeFromParent()),this._selected){if(!e){console.error("DragHelper: no context");return}jg.Add(e,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this.onUpdateScreenSpacePlane()}}onUpdate(A){var C,s,n,a,B;if(!this._context)return;const e="Space",t="KeyD",g=((C=this._context)==null?void 0:C.input.isKeyPressed(e))||((s=this._context)==null?void 0:s.input.isKeyPressed(t)),I=this._context.input.getTouchesPressedCount()>=2||g;if(I){const Q=this._context.input.getPointerPositionDelta(0);Q&&(this._groundOffsetVector.set(0,1,0),(n=this._selected)==null||n.rotateOnWorldAxis(this._groundOffsetVector,Q.x*this._context.time.deltaTime))}const o=this._context.input.getPointerPositionRC(0);if(o&&(this._raycaster.setFromCamera(o,this._camera),this._selected)){this._groundOffsetVector.set(0,1,0);const Q=ye(this._camera).clone().sub(ye(this._selected)).normalize(),E=Math.abs(Q.dot(this._groundOffsetVector)),c=((a=this._context)==null?void 0:a.input.isKeyPressed(e))||((B=this._context)==null?void 0:B.input.isKeyPressed(t)),h=!I&&E>.2&&!c&&this._context.input.getPointerPressedCount()<=1,l=this._didDragOnGroundPlaneLastFrame!==h;if(this._didDragOnGroundPlaneLastFrame=h,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!h||l)&&this.onUpdateGroundPlane(),this._requireUpdateGroundPlane=!1,this._hasGroundPlane)if(this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection)){const d=this._intersection.y;if(this._groundPlanePoint.copy(this._intersection).sub(this._groundOffset),this._groundPlanePoint.y=d,h){this._groundOffsetVector.set(0,1,0);const p=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(p,this._groundPlanePoint,!1),this.onDidUpdate();return}}else this._groundPlanePoint.set(0,99999,0);l&&this.onUpdateScreenSpacePlane(),this._requireUpdateGroundPlane=!0,this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&(this.onUpdateWorldPosition(this._intersection.sub(this._cameraPlaneOffset),this._groundPlanePoint,!0),this.onDidUpdate())}}onUpdateWorldPosition(A,e,t){if(this._selected){if(t){const g=ye(this._selected);g.y=A.y,A=g}if(hi(this._selected,A),hi(this._groundLine,A),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=e!==null,e){const g=ye(this._camera).distanceTo(e)*.01;this._groundMarker.scale.set(g,g,g),hi(this._groundMarker,e)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;const A=this._context.input.getPointerPositionRC(0);A&&(this._raycaster.setFromCamera(A,this._camera),this._cameraPlane.setFromNormalAndCoplanarPoint(this._camera.getWorldDirection(this._cameraPlane.normal),this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld)),this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&this._selected.parent&&(this._inverseMatrix.copy(this._selected.parent.matrixWorld).invert(),this._cameraPlaneOffset.copy(this._intersection).sub(this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld))))}onUpdateGroundPlane(){if(!this._selected||!this._context)return;const A=ye(this._selected),e=new on(new k(0,.1,0).add(A),new k(0,-1,0)),t=new CC;t.ignore=[this._selected];const g=this._context.physics.raycastFromRay(e,t);for(let I=0;I<g.length;I++){const o=g[I];if(!o.face||this.contains(this._selected,o.object))continue;const C=new k(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(C,o.point);break}this._hasGroundPlane=!0,this._groundPlane.setFromNormalAndCoplanarPoint(e.direction.multiplyScalar(-1),e.origin),this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection),this._groundDistance=this._intersection.distanceTo(A),this._groundOffset.copy(this._intersection).sub(A)}onDidUpdate(){dI.markDirty(this._selected);for(const A of this._rbs)A.wakeUp(),A.resetForcesAndTorques(),A.setAngularVelocity(0,0,0)}contains(A,e){if(A===e)return!0;if(A.children){for(const t of A.children)if(this.contains(t,e))return!0}return!1}};let Ap=vU;r(Ap,"geometry",new ue().setFromPoints([new k(0,0,0),new k(0,-1,0)]));function mR(i,A,e){console.warn("Adding components on object has been temporarily disabled")}var C_=(i=>(i.File_Spawned="file-spawned",i))(C_||{});class s_{constructor(A,e,t,g,I,o,C,s){r(this,"guid");r(this,"file_name");r(this,"file_hash");r(this,"file_size");r(this,"position");r(this,"seed");r(this,"sender");r(this,"serverUrl");r(this,"parentGuid");r(this,"boundsSize");this.seed=e,this.guid=t,this.file_name=g,this.file_hash=I,this.file_size=o,this.position=C,this.sender=A,this.serverUrl=s}}async function GG(i,A,e){const t=i.name;return t.endsWith(".gltf")||t.endsWith(".glb")?new Promise((g,I)=>{const o=new FileReader;o.readAsArrayBuffer(i),o.onloadend=async C=>{const s=o.result,n=Qw(),a=new Vg(n),B=await eC().parseSync(A,s,i.name,a);if(B&&B.scene){const Q=B.scene;if(!Q.guid){const E=new Vg(n);Q.guid=E.generateUUID()}e&&JiA(A.connection,i,n,Q,e),mR(),g(B)}}}):(console.warn("Unsupported file type: "+t),console.log(i),null)}async function n_(i,A){return new Promise(async(e,t)=>{const g=Qw(),I=new Vg(g),o=i.toString(),C=await eC().loadSync(A,o,o,I);C&&C.scene?(C.scene,mR(),e(C)):console.warn("Unsupported file type: "+i.toString())})}ii.registerCallback(LI.ContextCreated,i=>{a_(i.context)});function a_(i){i.connection.beginListen("file-spawned",async A=>{if(A.sender!==i.connection.connectionId){console.log("received file event",A),qiA(A,i);let e=null;try{e=await im(A.file_name,A.file_hash,A.file_size,A.serverUrl)}finally{biA(A)}if(e){const t=new Vg(A.seed),g=await eC().parseSync(i,e,null,t);if(g&&g.scene){const I=g.scene;if(mR(),A.parentGuid){const o=Xl(A.parentGuid,i.scene);"add"in o&&o.add(I)}I.parent||i.scene.add(I),A.position!==null&&I.position.copy(A.position)}}else console.error("download didnt return file")}})}async function JiA(i,A,e,t,g){if(!i.connectionId){console.error("Can not upload file - no connection id");return}if(!t.guid){console.error("Can not upload file - no guid",t,t.guid);return}const I=await Ox(A,g);if(!I)return;if(!I.filename){console.error("Can not send upload event - no filename",A.name);return}if(!I.hash){console.error("Can not send upload event - no hash",A.name);return}const o=new s_(i.connectionId,e,t.guid,I.filename,I.hash,A.size,t.position,I.url??g);t.parent&&(o.parentGuid=t.parent.guid),i.send("file-spawned",o)}const MG={};function qiA(i,A){const e=new Dt,t=new fA(e,new wt({color:65280})),g=new $f(t,5592405);if(MG[i.guid]=g,A.scene.add(g),i.parentGuid){const I=Xl(i.parentGuid,A.scene);I&&I.add(g)}i.position&&g.position.copy(i.position)}function biA(i,A){const e=i.guid,t=MG[e];t&&(delete MG[e],t.removeFromParent())}var LiA=Object.defineProperty,viA=Object.getOwnPropertyDescriptor,RR=(i,A,e,t)=>{for(var g=t>1?void 0:t?viA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&LiA(A,e,g),g};const xiA=rA("debugnet"),mG=class extends MA{constructor(){super(...arguments);r(this,"url",null);r(this,"urlParameterName",null);r(this,"localhost",null)}awake(){xiA&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let A=this.url?mG.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const I=rA(this.urlParameterName);I&&typeof I=="string"&&(A=I)}if(!A)return null;const t=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(A);return t!=null&&t.groups?(t==null?void 0:t.groups.socket_prefix)?A:"wss://"+(t==null?void 0:t.groups.url):null}static GetUrl(A,e){let t=A;const g=mG.IsLocalNetwork()&&e;return g&&(t=e),A!=null&&A.startsWith("/")&&(t=(g?t:window.location.origin)+A),t}static IsLocalNetwork(A=window.location.hostname){return zg(A)}};let BB=mG;RR([w()],BB.prototype,"url",2);RR([w()],BB.prototype,"urlParameterName",2);RR([w()],BB.prototype,"localhost",2);var YiA=Object.defineProperty,TiA=Object.getOwnPropertyDescriptor,r_=(i,A,e,t)=>{for(var g=t>1?void 0:t?TiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&YiA(A,e,g),g};class md extends MA{constructor(){super(...arguments);r(this,"filesBackendUrl");r(this,"localhost");r(this,"_dragOver");r(this,"_drop")}onEnable(){this.filesBackendUrl=this.filesBackendUrl?BB.GetUrl(this.filesBackendUrl,this.localhost):void 0,this._dragOver=this.onDrag.bind(this),this._drop=this.onDrop.bind(this),this.context.domElement.addEventListener("dragover",this._dragOver),this.context.domElement.addEventListener("drop",this._drop)}onDisable(){this.context.domElement.removeEventListener("dragover",this._dragOver),this.context.domElement.removeEventListener("drop",this._drop)}onDrag(e){e.preventDefault()}async addFiles(e){for(const t of e){if(!t)continue;console.log("Register file "+t.name+" to",this.filesBackendUrl,t);const g=await GG(t,this.context,this.filesBackendUrl);this.dispatchEvent(new CustomEvent("file-dropped",{detail:t})),g&&this.addObject(void 0,g)}}async onDrop(e){if(console.log(e),!e.dataTransfer)return;e.preventDefault();const t=e.dataTransfer.items;if(t)for(const g in t){const I=t[g];if(I.kind==="file"){const o=I.getAsFile();if(!o)continue;console.log("Register file "+o.name+" to",this.filesBackendUrl,o);const C=await GG(o,this.context,this.filesBackendUrl);this.dispatchEvent(new CustomEvent("file-dropped",{detail:o})),C&&this.addObject(e,C)}else I.kind==="string"&&I.type=="text/plain"&&I.getAsString(async o=>{console.log("dropped url",o);try{const C=new URL(o);if(!C)return;const s=await n_(C,this.context);s&&this.addObject(e,s)}catch{console.log("dropped string is not a valid URL!",o)}})}}async addObject(e,t){console.log("Dropped",t);const g=t.scene;if(e!==void 0){const I=new CC;I.setMask(16777215),I.screenPointFromOffset(e.offsetX,e.offsetY);const o=this.context.physics.raycast(I);if(o&&o.length>0)for(const C of o){g.position.copy(C.point);break}}this.gameObject.add(g),this.dispatchEvent(new CustomEvent("object-added",{detail:t}))}}r_([w()],md.prototype,"filesBackendUrl",2);r_([w()],md.prototype,"localhost",2);var HiA=Object.defineProperty,_iA=Object.getOwnPropertyDescriptor,ey=(i,A,e,t)=>{for(var g=t>1?void 0:t?_iA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&HiA(A,e,g),g};class QB extends UE{constructor(){super(...arguments);r(this,"parent",null);r(this,"object",null);r(this,"limitCount",10);r(this,"limitInterval",60);r(this,"_currentCount",0);r(this,"_startPosition",null);r(this,"_startQuaternion",null)}awake(){var t,g;if(this.object){if(this.object===this.gameObject){console.error("Can not duplicate self");return}this.object.visible=!1,this._startPosition=((t=this.object.position)==null?void 0:t.clone())??new k(0,0,0),this._startQuaternion=((g=this.object.quaternion)==null?void 0:g.clone())??new kA(0,0,0,1)}const e=eA.getComponentInParent(this.gameObject,ta);e?e.addDragEventListener(o_.SelectStart,(I,o)=>{if(this._currentCount>=this.limitCount){o.attached=null;return}const C=this.handleDuplication(o.selected);C&&(console.assert(C!==o.selected,"Duplicated object is original"),o.attached=C)}):console.warn("Could no find drag controls in parent",this.name),ti.addEventListener(Ss.SelectStart,(I,o)=>{if(this._currentCount>=this.limitCount){o.grab=null;return}const C=this.handleDuplication(o.selected);C&&(o.grab=C)}),this.cloneLimitIntervalFn()}cloneLimitIntervalFn(){this.destroyed||(this._currentCount>0&&(this._currentCount-=1),setTimeout(()=>{this.cloneLimitIntervalFn()},this.limitInterval/this.limitCount*1e3))}handleDuplication(e){var t;if(this._currentCount>=this.limitCount||!this.object)return null;if(e===this.gameObject||this.handleMultiObject(e)){if(this.object===this.gameObject)return null;this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);const g=new TC;this.parent||(this.parent=this.gameObject.parent),this.parent&&(g.parent=this.parent.guid??((t=this.parent.userData)==null?void 0:t.guid),g.keepWorldPosition=!0),g.position=this.worldPosition,g.rotation=this.worldQuaternion,g.context=this.context,this._currentCount+=1;const I=eA.instantiateSynced(this.object,g);return console.assert(I!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),I}return null}handleMultiObject(e){return this.gameObject.type==="Group"||this.gameObject.type==="Object3D"?this.isInChildren(this.gameObject,e):!1}isInChildren(e,t){if(!e)return!1;if(e===t)return!0;if(e.children){for(let g of e.children)if(this.isInChildren(g,t))return!0}return!1}}ey([w(UA)],QB.prototype,"parent",2);ey([w(UA)],QB.prototype,"object",2);ey([w()],QB.prototype,"limitCount",2);ey([w()],QB.prototype,"limitInterval",2);var IQ=(i=>(i[i.PointerEnter=0]="PointerEnter",i[i.PointerExit=1]="PointerExit",i[i.PointerDown=2]="PointerDown",i[i.PointerUp=3]="PointerUp",i[i.PointerClick=4]="PointerClick",i[i.Drag=5]="Drag",i[i.Drop=6]="Drop",i[i.Scroll=7]="Scroll",i[i.UpdateSelected=8]="UpdateSelected",i[i.Select=9]="Select",i[i.Deselect=10]="Deselect",i[i.Move=11]="Move",i[i.InitializePotentialDrag=12]="InitializePotentialDrag",i[i.BeginDrag=13]="BeginDrag",i[i.EndDrag=14]="EndDrag",i[i.Submit=15]="Submit",i[i.Cancel=16]="Cancel",i))(IQ||{}),OiA=Object.defineProperty,PiA=Object.getOwnPropertyDescriptor,UR=(i,A,e,t)=>{for(var g=t>1?void 0:t?PiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&OiA(A,e,g),g};class FR{constructor(){r(this,"eventID");r(this,"callback")}}UR([w()],FR.prototype,"eventID",2);UR([w(DI)],FR.prototype,"callback",2);class ty extends MA{constructor(){super(...arguments);r(this,"triggers")}invoke(e){if(this.triggers)for(const t of this.triggers)t.eventID===e&&t.callback.invoke()}onPointerClick(e){this.invoke(IQ.PointerClick)}onPointerEnter(e){this.invoke(IQ.PointerEnter)}onPointerExit(e){this.invoke(IQ.PointerExit)}onPointerDown(e){this.invoke(IQ.PointerDown)}onPointerUp(e){this.invoke(IQ.PointerUp)}}UR([w(FR)],ty.prototype,"triggers",2);var WiA=Object.defineProperty,ViA=Object.getOwnPropertyDescriptor,NR=(i,A,e,t)=>{for(var g=t>1?void 0:t?ViA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&WiA(A,e,g),g};class KR extends MA{constructor(){super(...arguments);r(this,"connectedBody");r(this,"_rigidBody",null)}get rigidBody(){return this._rigidBody}onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(jt)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.createJoint(this.rigidBody,this.connectedBody)}}NR([w(jt)],KR.prototype,"connectedBody",2);class JR extends KR{createJoint(A,e){var t;(t=this.context.physics.engine)==null||t.addFixedJoint(A,e)}}class Rd extends KR{constructor(){super(...arguments);r(this,"anchor");r(this,"axis")}createJoint(e,t){var g;this.axis&&this.anchor&&((g=this.context.physics.engine)==null||g.addHingeJoint(e,t,this.anchor,this.axis))}}NR([w(k)],Rd.prototype,"anchor",2);NR([w(k)],Rd.prototype,"axis",2);const jiA={type:"change"};let ziA=class extends Pi{constructor(A,e){super(),this.object=A,this.domElement=e,this.movementSpeed=1,this.rollSpeed=.005,this.dragToLook=!1,this.autoForward=!1;const t=this,g=1e-6,I=new kA,o=new k;this.tmpQuaternion=new kA,this.status=0,this.moveState={up:0,down:0,left:0,right:0,forward:0,back:0,pitchUp:0,pitchDown:0,yawLeft:0,yawRight:0,rollLeft:0,rollRight:0},this.moveVector=new k(0,0,0),this.rotationVector=new k(0,0,0),this.keydown=function(Q){if(!Q.altKey){switch(Q.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=.1;break;case"KeyW":this.moveState.forward=1;break;case"KeyS":this.moveState.back=1;break;case"KeyA":this.moveState.left=1;break;case"KeyD":this.moveState.right=1;break;case"KeyR":this.moveState.up=1;break;case"KeyF":this.moveState.down=1;break;case"ArrowUp":this.moveState.pitchUp=1;break;case"ArrowDown":this.moveState.pitchDown=1;break;case"ArrowLeft":this.moveState.yawLeft=1;break;case"ArrowRight":this.moveState.yawRight=1;break;case"KeyQ":this.moveState.rollLeft=1;break;case"KeyE":this.moveState.rollRight=1;break}this.updateMovementVector(),this.updateRotationVector()}},this.keyup=function(Q){switch(Q.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=1;break;case"KeyW":this.moveState.forward=0;break;case"KeyS":this.moveState.back=0;break;case"KeyA":this.moveState.left=0;break;case"KeyD":this.moveState.right=0;break;case"KeyR":this.moveState.up=0;break;case"KeyF":this.moveState.down=0;break;case"ArrowUp":this.moveState.pitchUp=0;break;case"ArrowDown":this.moveState.pitchDown=0;break;case"ArrowLeft":this.moveState.yawLeft=0;break;case"ArrowRight":this.moveState.yawRight=0;break;case"KeyQ":this.moveState.rollLeft=0;break;case"KeyE":this.moveState.rollRight=0;break}this.updateMovementVector(),this.updateRotationVector()},this.pointerdown=function(Q){if(this.dragToLook)this.status++;else{switch(Q.button){case 0:this.moveState.forward=1;break;case 2:this.moveState.back=1;break}this.updateMovementVector()}},this.pointermove=function(Q){if(!this.dragToLook||this.status>0){const E=this.getContainerDimensions(),c=E.size[0]/2,h=E.size[1]/2;this.moveState.yawLeft=-(Q.pageX-E.offset[0]-c)/c,this.moveState.pitchDown=(Q.pageY-E.offset[1]-h)/h,this.updateRotationVector()}},this.pointerup=function(Q){if(this.dragToLook)this.status--,this.moveState.yawLeft=this.moveState.pitchDown=0;else{switch(Q.button){case 0:this.moveState.forward=0;break;case 2:this.moveState.back=0;break}this.updateMovementVector()}this.updateRotationVector()},this.update=function(Q){const E=Q*t.movementSpeed,c=Q*t.rollSpeed;t.object.translateX(t.moveVector.x*E),t.object.translateY(t.moveVector.y*E),t.object.translateZ(t.moveVector.z*E),t.tmpQuaternion.set(t.rotationVector.x*c,t.rotationVector.y*c,t.rotationVector.z*c,1).normalize(),t.object.quaternion.multiply(t.tmpQuaternion),(o.distanceToSquared(t.object.position)>g||8*(1-I.dot(t.object.quaternion))>g)&&(t.dispatchEvent(jiA),I.copy(t.object.quaternion),o.copy(t.object.position))},this.updateMovementVector=function(){const Q=this.moveState.forward||this.autoForward&&!this.moveState.back?1:0;this.moveVector.x=-this.moveState.left+this.moveState.right,this.moveVector.y=-this.moveState.down+this.moveState.up,this.moveVector.z=-Q+this.moveState.back},this.updateRotationVector=function(){this.rotationVector.x=-this.moveState.pitchDown+this.moveState.pitchUp,this.rotationVector.y=-this.moveState.yawRight+this.moveState.yawLeft,this.rotationVector.z=-this.moveState.rollRight+this.moveState.rollLeft},this.getContainerDimensions=function(){return this.domElement!=document?{size:[this.domElement.offsetWidth,this.domElement.offsetHeight],offset:[this.domElement.offsetLeft,this.domElement.offsetTop]}:{size:[window.innerWidth,window.innerHeight],offset:[0,0]}},this.dispose=function(){this.domElement.removeEventListener("contextmenu",RJ),this.domElement.removeEventListener("pointerdown",s),this.domElement.removeEventListener("pointermove",C),this.domElement.removeEventListener("pointerup",n),window.removeEventListener("keydown",a),window.removeEventListener("keyup",B)};const C=this.pointermove.bind(this),s=this.pointerdown.bind(this),n=this.pointerup.bind(this),a=this.keydown.bind(this),B=this.keyup.bind(this);this.domElement.addEventListener("contextmenu",RJ),this.domElement.addEventListener("pointerdown",s),this.domElement.addEventListener("pointermove",C),this.domElement.addEventListener("pointerup",n),window.addEventListener("keydown",a),window.addEventListener("keyup",B),this.updateMovementVector(),this.updateRotationVector()}};function RJ(i){i.preventDefault()}class qR extends MA{constructor(){super(...arguments);r(this,"_controls",null)}onEnable(){var t;const e=(t=eA.getComponent(this.gameObject,Yt))==null?void 0:t.cam;this._controls=new ziA(e,this.context.renderer.domElement),this._controls.rollSpeed=.5,this._controls.movementSpeed=3,this._controls.dragToLook=!0}onDisable(){var e;(e=this._controls)==null||e.dispose(),this._controls=null}update(){this._controls&&this._controls.update(this.context.time.deltaTime)}}var ZiA=Object.defineProperty,XiA=Object.getOwnPropertyDescriptor,bR=(i,A,e,t)=>{for(var g=t>1?void 0:t?XiA(A,e):A,I=i.length-1,o;I>=0;I--)(o=i[I])&&(g=(t?o(A,e,g):o(g))||g);return t&&g&&ZiA(A,e,g),g};class jE extends MA{constructor(){super(...arguments);r(this,"_fog")}get fog(){return this._fog||(this._fog=new nM(0,0,50)),this._fog}get mode(){return 1}set near(e){this.fog.near=e}get near(){return this.fog.near}set far(e){this.fog.far=e}get far(){return this.fog.far}set color(e){this.fog.color.copy(e)}get color(){return this.fog.color}onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}bR([w()],jE.prototype,"near",1);bR([w()],jE.prototype,"far",1);bR([w(yA)],jE.prototype,"color",1);let p0,f0,PB,sD;function w0(i,A,e){f0||(f0=new og(2,2,1,1)),PB||(PB=new Ze({uniforms:{blitTexture:new SA(i)},vertexShader:`
4562
4562
  varying vec2 vUv;
4563
4563
  void main(){
4564
4564
  vUv = uv;