@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.
- package/CHANGELOG.md +4 -0
- package/dist/needle-engine.js +12 -12
- package/dist/needle-engine.light.js +4965 -4965
- package/dist/needle-engine.light.min.js +5 -5
- package/dist/needle-engine.light.umd.cjs +5 -5
- package/dist/needle-engine.min.js +5 -5
- package/dist/needle-engine.umd.cjs +5 -5
- package/lib/engine/engine_context.js +2 -2
- package/lib/engine/engine_context.js.map +1 -1
- package/lib/engine-components/Camera.js +0 -3
- package/lib/engine-components/Camera.js.map +1 -1
- package/lib/engine-components/OrbitControls.js +7 -3
- package/lib/engine-components/OrbitControls.js.map +1 -1
- package/package.json +1 -1
- package/plugins/vite/defines.js +5 -2
- package/src/engine/engine_context.ts +2 -2
- package/src/engine-components/Camera.ts +0 -4
- package/src/engine-components/OrbitControls.ts +6 -2
|
@@ -3333,11 +3333,11 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
|
|
|
3333
3333
|
isUnifiedPlanSupported:`).concat(this.isUnifiedPlanSupported())},i}()),zk={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"},y8=function(){function i(){this.CLOUD_HOST="0.peerjs.com",this.CLOUD_PORT=443,this.chunkedBrowsers={Chrome:1,chrome:1},this.chunkedMTU=16300,this.defaultConfig=zk,this.browser=sg.getBrowser(),this.browserVersion=sg.getVersion(),this.supports=function(){var e={browser:sg.isBrowserSupported(),webRTC:sg.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!e.webRTC)return e;var t;try{t=new RTCPeerConnection(zk),e.audioVideo=!0;var s=void 0;try{s=t.createDataChannel("_PEERJSTEST",{ordered:!0}),e.data=!0,e.reliable=!!s.ordered;try{s.binaryType="blob",e.binaryBlob=!sg.isIOS}catch{}}catch{}finally{s&&s.close()}}catch{}finally{t&&t.close()}return e}(),this.pack=qB.pack,this.unpack=qB.unpack,this._dataCount=1}return i.prototype.noop=function(){},i.prototype.validateId=function(e){return!e||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(e)},i.prototype.chunk=function(e){for(var t=[],s=e.size,r=Math.ceil(s/oi.chunkedMTU),n=0,o=0;o<s;){var a=Math.min(s,o+oi.chunkedMTU),l=e.slice(o,a),c={__peerData:this._dataCount,n,data:l,total:r};t.push(c),o=a,n++}return this._dataCount++,t},i.prototype.blobToArrayBuffer=function(e,t){var s=new FileReader;return s.onload=function(r){r.target&&t(r.target.result)},s.readAsArrayBuffer(e),s},i.prototype.binaryStringToArrayBuffer=function(e){for(var t=new Uint8Array(e.length),s=0;s<e.length;s++)t[s]=e.charCodeAt(s)&255;return t.buffer},i.prototype.randomToken=function(){return Math.random().toString(36).slice(2)},i.prototype.isSecure=function(){return location.protocol==="https:"},i}(),oi=new y8,Qk={};jo(Qk,"Peer",()=>i2,i=>i2=i);var rg={},b8=Object.prototype.hasOwnProperty,wr="~";function ng(){}Object.create&&(ng.prototype=Object.create(null),new ng().__proto__||(wr=!1));function _8(i,e,t){this.fn=i,this.context=e,this.once=t||!1}function jk(i,e,t,s,r){if(typeof t!="function")throw new TypeError("The listener must be a function");var n=new _8(t,s||i,r),o=wr?wr+e:e;return i._events[o]?i._events[o].fn?i._events[o]=[i._events[o],n]:i._events[o].push(n):(i._events[o]=n,i._eventsCount++),i}function Q0(i,e){--i._eventsCount===0?i._events=new ng:delete i._events[e]}function or(){this._events=new ng,this._eventsCount=0}or.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)b8.call(e,t)&&i.push(wr?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},or.prototype.listeners=function(i){var e=wr?wr+i:i,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var s=0,r=t.length,n=new Array(r);s<r;s++)n[s]=t[s].fn;return n},or.prototype.listenerCount=function(i){var e=wr?wr+i:i,t=this._events[e];return t?t.fn?1:t.length:0},or.prototype.emit=function(i,e,t,s,r,n){var o=wr?wr+i:i;if(!this._events[o])return!1;var a=this._events[o],l=arguments.length,c,u;if(a.fn){switch(a.once&&this.removeListener(i,a.fn,void 0,!0),l){case 1:return a.fn.call(a.context),!0;case 2:return a.fn.call(a.context,e),!0;case 3:return a.fn.call(a.context,e,t),!0;case 4:return a.fn.call(a.context,e,t,s),!0;case 5:return a.fn.call(a.context,e,t,s,r),!0;case 6:return a.fn.call(a.context,e,t,s,r,n),!0}for(u=1,c=new Array(l-1);u<l;u++)c[u-1]=arguments[u];a.fn.apply(a.context,c)}else{var d=a.length,p;for(u=0;u<d;u++)switch(a[u].once&&this.removeListener(i,a[u].fn,void 0,!0),l){case 1:a[u].fn.call(a[u].context);break;case 2:a[u].fn.call(a[u].context,e);break;case 3:a[u].fn.call(a[u].context,e,t);break;case 4:a[u].fn.call(a[u].context,e,t,s);break;default:if(!c)for(p=1,c=new Array(l-1);p<l;p++)c[p-1]=arguments[p];a[u].fn.apply(a[u].context,c)}}return!0},or.prototype.on=function(i,e,t){return jk(this,i,e,t,!1)},or.prototype.once=function(i,e,t){return jk(this,i,e,t,!0)},or.prototype.removeListener=function(i,e,t,s){var r=wr?wr+i:i;if(!this._events[r])return this;if(!e)return Q0(this,r),this;var n=this._events[r];if(n.fn)n.fn===e&&(!s||n.once)&&(!t||n.context===t)&&Q0(this,r);else{for(var o=0,a=[],l=n.length;o<l;o++)(n[o].fn!==e||s&&!n[o].once||t&&n[o].context!==t)&&a.push(n[o]);a.length?this._events[r]=a.length===1?a[0]:a:Q0(this,r)}return this},or.prototype.removeAllListeners=function(i){var e;return i?(e=wr?wr+i:i,this._events[e]&&Q0(this,e)):(this._events=new ng,this._eventsCount=0),this},or.prototype.off=or.prototype.removeListener,or.prototype.addListener=or.prototype.on,or.prefixed=wr,or.EventEmitter=or,rg=or;var et={};jo(et,"LogLevel",()=>zr,i=>zr=i),jo(et,"default",()=>Gk,i=>Gk=i);var zh=function(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var s=t.call(i),r,n=[],o;try{for(;(e===void 0||e-- >0)&&!(r=s.next()).done;)n.push(r.value)}catch(a){o={error:a}}finally{try{r&&!r.done&&(t=s.return)&&t.call(s)}finally{if(o)throw o.error}}return n},Qh=function(i,e,t){if(t||arguments.length===2)for(var s=0,r=e.length,n;s<r;s++)(n||!(s in e))&&(n||(n=Array.prototype.slice.call(e,0,s)),n[s]=e[s]);return i.concat(n||Array.prototype.slice.call(e))},w8="PeerJS: ",zr;(function(i){i[i.Disabled=0]="Disabled",i[i.Errors=1]="Errors",i[i.Warnings=2]="Warnings",i[i.All=3]="All"})(zr||(zr={}));var x8=function(){function i(){this._logLevel=zr.Disabled}return Object.defineProperty(i.prototype,"logLevel",{get:function(){return this._logLevel},set:function(e){this._logLevel=e},enumerable:!1,configurable:!0}),i.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logLevel>=zr.All&&this._print.apply(this,Qh([zr.All],zh(e),!1))},i.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logLevel>=zr.Warnings&&this._print.apply(this,Qh([zr.Warnings],zh(e),!1))},i.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logLevel>=zr.Errors&&this._print.apply(this,Qh([zr.Errors],zh(e),!1))},i.prototype.setLogFunction=function(e){this._print=e},i.prototype._print=function(e){for(var t=[],s=1;s<arguments.length;s++)t[s-1]=arguments[s];var r=Qh([w8],zh(t),!1);for(var n in r)r[n]instanceof Error&&(r[n]="("+r[n].name+") "+r[n].message);e>=zr.All?console.log.apply(console,Qh([],zh(r),!1)):e>=zr.Warnings?console.warn.apply(console,Qh(["WARNING"],zh(r),!1)):e>=zr.Errors&&console.error.apply(console,Qh(["ERROR"],zh(r),!1))},i}(),Gk=new x8,Hk={};jo(Hk,"Socket",()=>Vk,i=>Vk=i);var go;(function(i){i.Data="data",i.Media="media"})(go||(go={}));var Ji;(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"})(Ji||(Ji={}));var Ja;(function(i){i.Binary="binary",i.BinaryUTF8="binary-utf8",i.JSON="json"})(Ja||(Ja={}));var Ka;(function(i){i.Message="message",i.Disconnected="disconnected",i.Error="error",i.Close="close"})(Ka||(Ka={}));var js;(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"})(js||(js={}));var G1={};G1=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\xFCckler <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>","So\u0308ren 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 C8=function(){var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(s,r){s.__proto__=r}||function(s,r){for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(s[n]=r[n])},i(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");i(e,t);function s(){this.constructor=e}e.prototype=t===null?Object.create(t):(s.prototype=t.prototype,new s)}}(),S8=function(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var s=t.call(i),r,n=[],o;try{for(;(e===void 0||e-- >0)&&!(r=s.next()).done;)n.push(r.value)}catch(a){o={error:a}}finally{try{r&&!r.done&&(t=s.return)&&t.call(s)}finally{if(o)throw o.error}}return n},E8=function(i,e,t){if(t||arguments.length===2)for(var s=0,r=e.length,n;s<r;s++)(n||!(s in e))&&(n||(n=Array.prototype.slice.call(e,0,s)),n[s]=e[s]);return i.concat(n||Array.prototype.slice.call(e))},M8=function(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],s=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&s>=i.length&&(i=void 0),{value:i&&i[s++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},Vk=function(i){C8(e,i);function e(t,s,r,n,o,a){a===void 0&&(a=5e3);var l=i.call(this)||this;l.pingInterval=a,l._disconnected=!0,l._messagesQueue=[];var c=t?"wss://":"ws://";return l._baseUrl=c+s+":"+r+n+"peerjs?key="+o,l}return e.prototype.start=function(t,s){var r=this;this._id=t;var n="".concat(this._baseUrl,"&id=").concat(t,"&token=").concat(s);this._socket||!this._disconnected||(this._socket=new WebSocket(n+"&version="+G1.version),this._disconnected=!1,this._socket.onmessage=function(o){var a;try{a=JSON.parse(o.data),et.default.log("Server message received:",a)}catch{et.default.log("Invalid server message",o.data);return}r.emit(Ka.Message,a)},this._socket.onclose=function(o){r._disconnected||(et.default.log("Socket closed.",o),r._cleanup(),r._disconnected=!0,r.emit(Ka.Disconnected))},this._socket.onopen=function(){r._disconnected||(r._sendQueuedMessages(),et.default.log("Socket open"),r._scheduleHeartbeat())})},e.prototype._scheduleHeartbeat=function(){var t=this;this._wsPingTimer=setTimeout(function(){t._sendHeartbeat()},this.pingInterval)},e.prototype._sendHeartbeat=function(){if(!this._wsOpen()){et.default.log("Cannot send heartbeat, because socket closed");return}var t=JSON.stringify({type:js.Heartbeat});this._socket.send(t),this._scheduleHeartbeat()},e.prototype._wsOpen=function(){return!!this._socket&&this._socket.readyState===1},e.prototype._sendQueuedMessages=function(){var t,s,r=E8([],S8(this._messagesQueue),!1);this._messagesQueue=[];try{for(var n=M8(r),o=n.next();!o.done;o=n.next()){var a=o.value;this.send(a)}}catch(l){t={error:l}}finally{try{o&&!o.done&&(s=n.return)&&s.call(n)}finally{if(t)throw t.error}}},e.prototype.send=function(t){if(!this._disconnected){if(!this._id){this._messagesQueue.push(t);return}if(!t.type){this.emit(Ka.Error,"Invalid message");return}if(this._wsOpen()){var s=JSON.stringify(t);this._socket.send(s)}}},e.prototype.close=function(){this._disconnected||(this._cleanup(),this._disconnected=!0)},e.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)},e}(rg.EventEmitter),H1={};jo(H1,"MediaConnection",()=>Xk,i=>Xk=i);var V1={};jo(V1,"Negotiator",()=>Wk,i=>Wk=i);var j0=function(){return j0=Object.assign||function(i){for(var e,t=1,s=arguments.length;t<s;t++){e=arguments[t];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(i[r]=e[r])}return i},j0.apply(this,arguments)},G0=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(u){try{c(s.next(u))}catch(d){o(d)}}function l(u){try{c(s.throw(u))}catch(d){o(d)}}function c(u){u.done?n(u.value):r(u.value).then(a,l)}c((s=s.apply(i,e||[])).next())})},H0=function(i,e){var t={label:0,sent:function(){if(n[0]&1)throw n[1];return n[1]},trys:[],ops:[]},s,r,n,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(c){return function(u){return l([c,u])}}function l(c){if(s)throw new TypeError("Generator is already executing.");for(;t;)try{if(s=1,r&&(n=c[0]&2?r.return:c[0]?r.throw||((n=r.return)&&n.call(r),0):r.next)&&!(n=n.call(r,c[1])).done)return n;switch(r=0,n&&(c=[c[0]&2,n.value]),c[0]){case 0:case 1:n=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,r=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(n=t.trys,!(n=n.length>0&&n[n.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!n||c[1]>n[0]&&c[1]<n[3])){t.label=c[1];break}if(c[0]===6&&t.label<n[1]){t.label=n[1],n=c;break}if(n&&t.label<n[2]){t.label=n[2],t.ops.push(c);break}n[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(i,t)}catch(u){c=[6,u],r=0}finally{s=n=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}},Wk=function(){function i(e){this.connection=e}return i.prototype.startConnection=function(e){var t=this._startPeerConnection();if(this.connection.peerConnection=t,this.connection.type===go.Media&&e._stream&&this._addTracksToConnection(e._stream,t),e.originator){if(this.connection.type===go.Data){var s=this.connection,r={ordered:!!e.reliable},n=t.createDataChannel(s.label,r);s.initialize(n)}this._makeOffer()}else this.handleSDP("OFFER",e.sdp)},i.prototype._startPeerConnection=function(){et.default.log("Creating RTCPeerConnection.");var e=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(e),e},i.prototype._setupListeners=function(e){var t=this,s=this.connection.peer,r=this.connection.connectionId,n=this.connection.type,o=this.connection.provider;et.default.log("Listening for ICE candidates."),e.onicecandidate=function(a){!a.candidate||!a.candidate.candidate||(et.default.log("Received ICE candidates for ".concat(s,":"),a.candidate),o.socket.send({type:js.Candidate,payload:{candidate:a.candidate,type:n,connectionId:r},dst:s}))},e.oniceconnectionstatechange=function(){switch(e.iceConnectionState){case"failed":et.default.log("iceConnectionState is failed, closing connections to "+s),t.connection.emit("error",new Error("Negotiation of connection to "+s+" failed.")),t.connection.close();break;case"closed":et.default.log("iceConnectionState is closed, closing connections to "+s),t.connection.emit("error",new Error("Connection to "+s+" closed.")),t.connection.close();break;case"disconnected":et.default.log("iceConnectionState changed to disconnected on the connection with "+s);break;case"completed":e.onicecandidate=oi.noop;break}t.connection.emit("iceStateChanged",e.iceConnectionState)},et.default.log("Listening for data channel"),e.ondatachannel=function(a){et.default.log("Received data channel");var l=a.channel,c=o.getConnection(s,r);c.initialize(l)},et.default.log("Listening for remote stream"),e.ontrack=function(a){et.default.log("Received remote stream");var l=a.streams[0],c=o.getConnection(s,r);if(c.type===go.Media){var u=c;t._addStreamToMediaConnection(l,u)}}},i.prototype.cleanup=function(){et.default.log("Cleaning up PeerConnection to "+this.connection.peer);var e=this.connection.peerConnection;if(e){this.connection.peerConnection=null,e.onicecandidate=e.oniceconnectionstatechange=e.ondatachannel=e.ontrack=function(){};var t=e.signalingState!=="closed",s=!1;if(this.connection.type===go.Data){var r=this.connection,n=r.dataChannel;n&&(s=!!n.readyState&&n.readyState!=="closed")}(t||s)&&e.close()}},i.prototype._makeOffer=function(){return G0(this,void 0,Promise,function(){var e,t,s,r,n,o,a;return H0(this,function(l){switch(l.label){case 0:e=this.connection.peerConnection,t=this.connection.provider,l.label=1;case 1:return l.trys.push([1,7,,8]),[4,e.createOffer(this.connection.options.constraints)];case 2:s=l.sent(),et.default.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(s.sdp=this.connection.options.sdpTransform(s.sdp)||s.sdp),l.label=3;case 3:return l.trys.push([3,5,,6]),[4,e.setLocalDescription(s)];case 4:return l.sent(),et.default.log("Set localDescription:",s,"for:".concat(this.connection.peer)),r={sdp:s,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata,browser:oi.browser},this.connection.type===go.Data&&(n=this.connection,r=j0(j0({},r),{label:n.label,reliable:n.reliable,serialization:n.serialization})),t.socket.send({type:js.Offer,payload:r,dst:this.connection.peer}),[3,6];case 5:return o=l.sent(),o!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(t.emitError(Ji.WebRTC,o),et.default.log("Failed to setLocalDescription, ",o)),[3,6];case 6:return[3,8];case 7:return a=l.sent(),t.emitError(Ji.WebRTC,a),et.default.log("Failed to createOffer, ",a),[3,8];case 8:return[2]}})})},i.prototype._makeAnswer=function(){return G0(this,void 0,Promise,function(){var e,t,s,r,n;return H0(this,function(o){switch(o.label){case 0:e=this.connection.peerConnection,t=this.connection.provider,o.label=1;case 1:return o.trys.push([1,7,,8]),[4,e.createAnswer()];case 2:s=o.sent(),et.default.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(s.sdp=this.connection.options.sdpTransform(s.sdp)||s.sdp),o.label=3;case 3:return o.trys.push([3,5,,6]),[4,e.setLocalDescription(s)];case 4:return o.sent(),et.default.log("Set localDescription:",s,"for:".concat(this.connection.peer)),t.socket.send({type:js.Answer,payload:{sdp:s,type:this.connection.type,connectionId:this.connection.connectionId,browser:oi.browser},dst:this.connection.peer}),[3,6];case 5:return r=o.sent(),t.emitError(Ji.WebRTC,r),et.default.log("Failed to setLocalDescription, ",r),[3,6];case 6:return[3,8];case 7:return n=o.sent(),t.emitError(Ji.WebRTC,n),et.default.log("Failed to create answer, ",n),[3,8];case 8:return[2]}})})},i.prototype.handleSDP=function(e,t){return G0(this,void 0,Promise,function(){var s,r,n,o;return H0(this,function(a){switch(a.label){case 0:t=new RTCSessionDescription(t),s=this.connection.peerConnection,r=this.connection.provider,et.default.log("Setting remote description",t),n=this,a.label=1;case 1:return a.trys.push([1,5,,6]),[4,s.setRemoteDescription(t)];case 2:return a.sent(),et.default.log("Set remoteDescription:".concat(e," for:").concat(this.connection.peer)),e!=="OFFER"?[3,4]:[4,n._makeAnswer()];case 3:a.sent(),a.label=4;case 4:return[3,6];case 5:return o=a.sent(),r.emitError(Ji.WebRTC,o),et.default.log("Failed to setRemoteDescription, ",o),[3,6];case 6:return[2]}})})},i.prototype.handleCandidate=function(e){return G0(this,void 0,Promise,function(){var t,s,r,n,o,a;return H0(this,function(l){switch(l.label){case 0:et.default.log("handleCandidate:",e),t=e.candidate,s=e.sdpMLineIndex,r=e.sdpMid,n=this.connection.peerConnection,o=this.connection.provider,l.label=1;case 1:return l.trys.push([1,3,,4]),[4,n.addIceCandidate(new RTCIceCandidate({sdpMid:r,sdpMLineIndex:s,candidate:t}))];case 2:return l.sent(),et.default.log("Added ICE candidate for:".concat(this.connection.peer)),[3,4];case 3:return a=l.sent(),o.emitError(Ji.WebRTC,a),et.default.log("Failed to handleCandidate, ",a),[3,4];case 4:return[2]}})})},i.prototype._addTracksToConnection=function(e,t){if(et.default.log("add tracks from stream ".concat(e.id," to peer connection")),!t.addTrack)return et.default.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");e.getTracks().forEach(function(s){t.addTrack(s,e)})},i.prototype._addStreamToMediaConnection=function(e,t){et.default.log("add stream ".concat(e.id," to media connection ").concat(t.connectionId)),t.addStream(e)},i}(),W1={};jo(W1,"BaseConnection",()=>qk,i=>qk=i);var I8=function(){var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(s,r){s.__proto__=r}||function(s,r){for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(s[n]=r[n])},i(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");i(e,t);function s(){this.constructor=e}e.prototype=t===null?Object.create(t):(s.prototype=t.prototype,new s)}}(),qk=function(i){I8(e,i);function e(t,s,r){var n=i.call(this)||this;return n.peer=t,n.provider=s,n.options=r,n._open=!1,n.metadata=r.metadata,n}return Object.defineProperty(e.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),e}(rg.EventEmitter),T8=function(){var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(s,r){s.__proto__=r}||function(s,r){for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(s[n]=r[n])},i(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");i(e,t);function s(){this.constructor=e}e.prototype=t===null?Object.create(t):(s.prototype=t.prototype,new s)}}(),V0=function(){return V0=Object.assign||function(i){for(var e,t=1,s=arguments.length;t<s;t++){e=arguments[t];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(i[r]=e[r])}return i},V0.apply(this,arguments)},R8=function(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],s=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&s>=i.length&&(i=void 0),{value:i&&i[s++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},Xk=function(i){T8(e,i);function e(t,s,r){var n=i.call(this,t,s,r)||this;return n._localStream=n.options._stream,n.connectionId=n.options.connectionId||e.ID_PREFIX+oi.randomToken(),n._negotiator=new V1.Negotiator(n),n._localStream&&n._negotiator.startConnection({_stream:n._localStream,originator:!0}),n}return Object.defineProperty(e.prototype,"type",{get:function(){return go.Media},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localStream",{get:function(){return this._localStream},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteStream",{get:function(){return this._remoteStream},enumerable:!1,configurable:!0}),e.prototype.addStream=function(t){et.default.log("Receiving stream",t),this._remoteStream=t,i.prototype.emit.call(this,"stream",t)},e.prototype.handleMessage=function(t){var s=t.type,r=t.payload;switch(t.type){case js.Answer:this._negotiator.handleSDP(s,r.sdp),this._open=!0;break;case js.Candidate:this._negotiator.handleCandidate(r.candidate);break;default:et.default.warn("Unrecognized message type:".concat(s," from peer:").concat(this.peer));break}},e.prototype.answer=function(t,s){var r,n;if(s===void 0&&(s={}),this._localStream){et.default.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");return}this._localStream=t,s&&s.sdpTransform&&(this.options.sdpTransform=s.sdpTransform),this._negotiator.startConnection(V0(V0({},this.options._payload),{_stream:t}));var o=this.provider._getMessages(this.connectionId);try{for(var a=R8(o),l=a.next();!l.done;l=a.next()){var c=l.value;this.handleMessage(c)}}catch(u){r={error:u}}finally{try{l&&!l.done&&(n=a.return)&&n.call(a)}finally{if(r)throw r.error}}this._open=!0},e.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"))},e.ID_PREFIX="mc_",e}(W1.BaseConnection),q1={};jo(q1,"DataConnection",()=>Kk,i=>Kk=i);var Yk={};jo(Yk,"EncodingQueue",()=>Jk,i=>Jk=i);var P8=function(){var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(s,r){s.__proto__=r}||function(s,r){for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(s[n]=r[n])},i(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");i(e,t);function s(){this.constructor=e}e.prototype=t===null?Object.create(t):(s.prototype=t.prototype,new s)}}(),Jk=function(i){P8(e,i);function e(){var t=i.call(this)||this;return t.fileReader=new FileReader,t._queue=[],t._processing=!1,t.fileReader.onload=function(s){t._processing=!1,s.target&&t.emit("done",s.target.result),t.doNextTask()},t.fileReader.onerror=function(s){et.default.error("EncodingQueue error:",s),t._processing=!1,t.destroy(),t.emit("error",s)},t}return Object.defineProperty(e.prototype,"queue",{get:function(){return this._queue},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"size",{get:function(){return this.queue.length},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"processing",{get:function(){return this._processing},enumerable:!1,configurable:!0}),e.prototype.enque=function(t){this.queue.push(t),!this.processing&&this.doNextTask()},e.prototype.destroy=function(){this.fileReader.abort(),this._queue=[]},e.prototype.doNextTask=function(){this.size!==0&&(this.processing||(this._processing=!0,this.fileReader.readAsArrayBuffer(this.queue.shift())))},e}(rg.EventEmitter),B8=function(){var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(s,r){s.__proto__=r}||function(s,r){for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(s[n]=r[n])},i(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");i(e,t);function s(){this.constructor=e}e.prototype=t===null?Object.create(t):(s.prototype=t.prototype,new s)}}(),k8=function(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],s=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&s>=i.length&&(i=void 0),{value:i&&i[s++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},Kk=function(i){B8(e,i);function e(t,s,r){var n=i.call(this,t,s,r)||this;return n.stringify=JSON.stringify,n.parse=JSON.parse,n._buffer=[],n._bufferSize=0,n._buffering=!1,n._chunkedData={},n._encodingQueue=new Yk.EncodingQueue,n.connectionId=n.options.connectionId||e.ID_PREFIX+oi.randomToken(),n.label=n.options.label||n.connectionId,n.serialization=n.options.serialization||Ja.Binary,n.reliable=!!n.options.reliable,n._encodingQueue.on("done",function(o){n._bufferedSend(o)}),n._encodingQueue.on("error",function(){et.default.error("DC#".concat(n.connectionId,": Error occured in encoding from blob to arraybuffer, close DC")),n.close()}),n._negotiator=new V1.Negotiator(n),n._negotiator.startConnection(n.options._payload||{originator:!0}),n}return Object.defineProperty(e.prototype,"type",{get:function(){return go.Data},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dataChannel",{get:function(){return this._dc},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"bufferSize",{get:function(){return this._bufferSize},enumerable:!1,configurable:!0}),e.prototype.initialize=function(t){this._dc=t,this._configureDataChannel()},e.prototype._configureDataChannel=function(){var t=this;(!oi.supports.binaryBlob||oi.supports.reliable)&&(this.dataChannel.binaryType="arraybuffer"),this.dataChannel.onopen=function(){et.default.log("DC#".concat(t.connectionId," dc connection success")),t._open=!0,t.emit("open")},this.dataChannel.onmessage=function(s){et.default.log("DC#".concat(t.connectionId," dc onmessage:"),s.data),t._handleDataMessage(s)},this.dataChannel.onclose=function(){et.default.log("DC#".concat(t.connectionId," dc closed for:"),t.peer),t.close()}},e.prototype._handleDataMessage=function(t){var s=this,r=t.data,n=r.constructor,o=this.serialization===Ja.Binary||this.serialization===Ja.BinaryUTF8,a=r;if(o){if(n===Blob){oi.blobToArrayBuffer(r,function(c){var u=oi.unpack(c);s.emit("data",u)});return}else if(n===ArrayBuffer)a=oi.unpack(r);else if(n===String){var l=oi.binaryStringToArrayBuffer(r);a=oi.unpack(l)}}else this.serialization===Ja.JSON&&(a=this.parse(r));if(a.__peerData){this._handleChunk(a);return}i.prototype.emit.call(this,"data",a)},e.prototype._handleChunk=function(t){var s=t.__peerData,r=this._chunkedData[s]||{data:[],count:0,total:t.total};if(r.data[t.n]=t.data,r.count++,this._chunkedData[s]=r,r.total===r.count){delete this._chunkedData[s];var n=new Blob(r.data);this._handleDataMessage({data:n})}},e.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"))},e.prototype.send=function(t,s){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===Ja.JSON)this._bufferedSend(this.stringify(t));else if(this.serialization===Ja.Binary||this.serialization===Ja.BinaryUTF8){var r=oi.pack(t);if(!s&&r.size>oi.chunkedMTU){this._sendChunks(r);return}oi.supports.binaryBlob?this._bufferedSend(r):this._encodingQueue.enque(r)}else this._bufferedSend(t)},e.prototype._bufferedSend=function(t){(this._buffering||!this._trySend(t))&&(this._buffer.push(t),this._bufferSize=this._buffer.length)},e.prototype._trySend=function(t){var s=this;if(!this.open)return!1;if(this.dataChannel.bufferedAmount>e.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(function(){s._buffering=!1,s._tryBuffer()},50),!1;try{this.dataChannel.send(t)}catch(r){return et.default.error("DC#:".concat(this.connectionId," Error when sending:"),r),this._buffering=!0,this.close(),!1}return!0},e.prototype._tryBuffer=function(){if(this.open&&this._buffer.length!==0){var t=this._buffer[0];this._trySend(t)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}},e.prototype._sendChunks=function(t){var s,r,n=oi.chunk(t);et.default.log("DC#".concat(this.connectionId," Try to send ").concat(n.length," chunks..."));try{for(var o=k8(n),a=o.next();!a.done;a=o.next()){var l=a.value;this.send(l,!0)}}catch(c){s={error:c}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(s)throw s.error}}},e.prototype.handleMessage=function(t){var s=t.payload;switch(t.type){case js.Answer:this._negotiator.handleSDP(t.type,s.sdp);break;case js.Candidate:this._negotiator.handleCandidate(s.candidate);break;default:et.default.warn("Unrecognized message type:",t.type,"from peer:",this.peer);break}},e.ID_PREFIX="dc_",e.MAX_BUFFERED_AMOUNT=8388608,e}(W1.BaseConnection),Zk={};jo(Zk,"API",()=>t2,i=>t2=i);var $k=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(u){try{c(s.next(u))}catch(d){o(d)}}function l(u){try{c(s.throw(u))}catch(d){o(d)}}function c(u){u.done?n(u.value):r(u.value).then(a,l)}c((s=s.apply(i,e||[])).next())})},e2=function(i,e){var t={label:0,sent:function(){if(n[0]&1)throw n[1];return n[1]},trys:[],ops:[]},s,r,n,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(c){return function(u){return l([c,u])}}function l(c){if(s)throw new TypeError("Generator is already executing.");for(;t;)try{if(s=1,r&&(n=c[0]&2?r.return:c[0]?r.throw||((n=r.return)&&n.call(r),0):r.next)&&!(n=n.call(r,c[1])).done)return n;switch(r=0,n&&(c=[c[0]&2,n.value]),c[0]){case 0:case 1:n=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,r=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(n=t.trys,!(n=n.length>0&&n[n.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!n||c[1]>n[0]&&c[1]<n[3])){t.label=c[1];break}if(c[0]===6&&t.label<n[1]){t.label=n[1],n=c;break}if(n&&t.label<n[2]){t.label=n[2],t.ops.push(c);break}n[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(i,t)}catch(u){c=[6,u],r=0}finally{s=n=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}},t2=function(){function i(e){this._options=e}return i.prototype._buildRequest=function(e){var t=this._options.secure?"https":"http",s=this._options,r=s.host,n=s.port,o=s.path,a=s.key,l=new URL("".concat(t,"://").concat(r,":").concat(n).concat(o).concat(a,"/").concat(e));return l.searchParams.set("ts","".concat(Date.now()).concat(Math.random())),l.searchParams.set("version",G1.version),fetch(l.href,{referrerPolicy:this._options.referrerPolicy})},i.prototype.retrieveId=function(){return $k(this,void 0,Promise,function(){var e,t,s;return e2(this,function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,this._buildRequest("id")];case 1:if(e=r.sent(),e.status!==200)throw new Error("Error. Status:".concat(e.status));return[2,e.text()];case 2:throw t=r.sent(),et.default.error("Error retrieving ID",t),s="",this._options.path==="/"&&this._options.host!==oi.CLOUD_HOST&&(s=" 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."+s);case 3:return[2]}})})},i.prototype.listAllPeers=function(){return $k(this,void 0,Promise,function(){var e,t,s;return e2(this,function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,this._buildRequest("peers")];case 1:if(e=r.sent(),e.status!==200)throw e.status===401?(t="",this._options.host===oi.CLOUD_HOST?t="It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":t="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. "+t)):new Error("Error. Status:".concat(e.status));return[2,e.json()];case 2:throw s=r.sent(),et.default.error("Error retrieving list peers",s),new Error("Could not get list peers from the server."+s);case 3:return[2]}})})},i}(),D8=function(){var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(s,r){s.__proto__=r}||function(s,r){for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(s[n]=r[n])},i(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");i(e,t);function s(){this.constructor=e}e.prototype=t===null?Object.create(t):(s.prototype=t.prototype,new s)}}(),og=function(){return og=Object.assign||function(i){for(var e,t=1,s=arguments.length;t<s;t++){e=arguments[t];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(i[r]=e[r])}return i},og.apply(this,arguments)},ag=function(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],s=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&s>=i.length&&(i=void 0),{value:i&&i[s++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},O8=function(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var s=t.call(i),r,n=[],o;try{for(;(e===void 0||e-- >0)&&!(r=s.next()).done;)n.push(r.value)}catch(a){o={error:a}}finally{try{r&&!r.done&&(t=s.return)&&t.call(s)}finally{if(o)throw o.error}}return n},i2=function(i){D8(e,i);function e(t,s){var r=i.call(this)||this;r._id=null,r._lastServerId=null,r._destroyed=!1,r._disconnected=!1,r._open=!1,r._connections=new Map,r._lostMessages=new Map;var n;return t&&t.constructor==Object?s=t:t&&(n=t.toString()),s=og({debug:0,host:oi.CLOUD_HOST,port:oi.CLOUD_PORT,path:"/",key:e.DEFAULT_KEY,token:oi.randomToken(),config:oi.defaultConfig,referrerPolicy:"strict-origin-when-cross-origin"},s),r._options=s,r._options.host==="/"&&(r._options.host=window.location.hostname),r._options.path&&(r._options.path[0]!=="/"&&(r._options.path="/"+r._options.path),r._options.path[r._options.path.length-1]!=="/"&&(r._options.path+="/")),r._options.secure===void 0&&r._options.host!==oi.CLOUD_HOST?r._options.secure=oi.isSecure():r._options.host==oi.CLOUD_HOST&&(r._options.secure=!0),r._options.logFunction&&et.default.setLogFunction(r._options.logFunction),et.default.logLevel=r._options.debug||0,r._api=new Zk.API(s),r._socket=r._createServerConnection(),!oi.supports.audioVideo&&!oi.supports.data?(r._delayedAbort(Ji.BrowserIncompatible,"The current browser does not support WebRTC"),r):n&&!oi.validateId(n)?(r._delayedAbort(Ji.InvalidID,'ID "'.concat(n,'" is invalid')),r):(n?r._initialize(n):r._api.retrieveId().then(function(o){return r._initialize(o)}).catch(function(o){return r._abort(Ji.ServerError,o)}),r)}return Object.defineProperty(e.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"socket",{get:function(){return this._socket},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"connections",{get:function(){var t,s,r=Object.create(null);try{for(var n=ag(this._connections),o=n.next();!o.done;o=n.next()){var a=O8(o.value,2),l=a[0],c=a[1];r[l]=c}}catch(u){t={error:u}}finally{try{o&&!o.done&&(s=n.return)&&s.call(n)}finally{if(t)throw t.error}}return r},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"disconnected",{get:function(){return this._disconnected},enumerable:!1,configurable:!0}),e.prototype._createServerConnection=function(){var t=this,s=new Hk.Socket(this._options.secure,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval);return s.on(Ka.Message,function(r){t._handleMessage(r)}),s.on(Ka.Error,function(r){t._abort(Ji.SocketError,r)}),s.on(Ka.Disconnected,function(){t.disconnected||(t.emitError(Ji.Network,"Lost connection to server."),t.disconnect())}),s.on(Ka.Close,function(){t.disconnected||t._abort(Ji.SocketClosed,"Underlying socket is already closed.")}),s},e.prototype._initialize=function(t){this._id=t,this.socket.start(t,this._options.token)},e.prototype._handleMessage=function(t){var s,r,n=t.type,o=t.payload,a=t.src;switch(n){case js.Open:this._lastServerId=this.id,this._open=!0,this.emit("open",this.id);break;case js.Error:this._abort(Ji.ServerError,o.msg);break;case js.IdTaken:this._abort(Ji.UnavailableID,'ID "'.concat(this.id,'" is taken'));break;case js.InvalidKey:this._abort(Ji.InvalidKey,'API KEY "'.concat(this._options.key,'" is invalid'));break;case js.Leave:et.default.log("Received leave message from ".concat(a)),this._cleanupPeer(a),this._connections.delete(a);break;case js.Expire:this.emitError(Ji.PeerUnavailable,"Could not connect to peer ".concat(a));break;case js.Offer:var g=o.connectionId,m=this.getConnection(a,g);if(m&&(m.close(),et.default.warn("Offer received for existing Connection ID:".concat(g))),o.type===go.Media){var l=new H1.MediaConnection(a,this,{connectionId:g,_payload:o,metadata:o.metadata});m=l,this._addConnection(a,m),this.emit("call",l)}else if(o.type===go.Data){var c=new q1.DataConnection(a,this,{connectionId:g,_payload:o,metadata:o.metadata,label:o.label,serialization:o.serialization,reliable:o.reliable});m=c,this._addConnection(a,m),this.emit("connection",c)}else{et.default.warn("Received malformed connection type:".concat(o.type));return}var u=this._getMessages(g);try{for(var d=ag(u),p=d.next();!p.done;p=d.next()){var f=p.value;m.handleMessage(f)}}catch(v){s={error:v}}finally{try{p&&!p.done&&(r=d.return)&&r.call(d)}finally{if(s)throw s.error}}break;default:if(!o){et.default.warn("You received a malformed message from ".concat(a," of type ").concat(n));return}var g=o.connectionId,m=this.getConnection(a,g);m&&m.peerConnection?m.handleMessage(t):g?this._storeMessage(g,t):et.default.warn("You received an unrecognized message:",t);break}},e.prototype._storeMessage=function(t,s){this._lostMessages.has(t)||this._lostMessages.set(t,[]),this._lostMessages.get(t).push(s)},e.prototype._getMessages=function(t){var s=this._lostMessages.get(t);return s?(this._lostMessages.delete(t),s):[]},e.prototype.connect=function(t,s){if(s===void 0&&(s={}),this.disconnected){et.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(Ji.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}var r=new q1.DataConnection(t,this,s);return this._addConnection(t,r),r},e.prototype.call=function(t,s,r){if(r===void 0&&(r={}),this.disconnected){et.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(Ji.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}if(!s){et.default.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.");return}var n=new H1.MediaConnection(t,this,og(og({},r),{_stream:s}));return this._addConnection(t,n),n},e.prototype._addConnection=function(t,s){et.default.log("add connection ".concat(s.type,":").concat(s.connectionId," to peerId:").concat(t)),this._connections.has(t)||this._connections.set(t,[]),this._connections.get(t).push(s)},e.prototype._removeConnection=function(t){var s=this._connections.get(t.peer);if(s){var r=s.indexOf(t);r!==-1&&s.splice(r,1)}this._lostMessages.delete(t.connectionId)},e.prototype.getConnection=function(t,s){var r,n,o=this._connections.get(t);if(!o)return null;try{for(var a=ag(o),l=a.next();!l.done;l=a.next()){var c=l.value;if(c.connectionId===s)return c}}catch(u){r={error:u}}finally{try{l&&!l.done&&(n=a.return)&&n.call(a)}finally{if(r)throw r.error}}return null},e.prototype._delayedAbort=function(t,s){var r=this;setTimeout(function(){r._abort(t,s)},0)},e.prototype._abort=function(t,s){et.default.error("Aborting!"),this.emitError(t,s),this._lastServerId?this.disconnect():this.destroy()},e.prototype.emitError=function(t,s){et.default.error("Error:",s);var r;typeof s=="string"?r=new Error(s):r=s,r.type=t,this.emit("error",r)},e.prototype.destroy=function(){this.destroyed||(et.default.log("Destroy peer with ID:".concat(this.id)),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit("close"))},e.prototype._cleanup=function(){var t,s;try{for(var r=ag(this._connections.keys()),n=r.next();!n.done;n=r.next()){var o=n.value;this._cleanupPeer(o),this._connections.delete(o)}}catch(a){t={error:a}}finally{try{n&&!n.done&&(s=r.return)&&s.call(r)}finally{if(t)throw t.error}}this.socket.removeAllListeners()},e.prototype._cleanupPeer=function(t){var s,r,n=this._connections.get(t);if(n)try{for(var o=ag(n),a=o.next();!a.done;a=o.next()){var l=a.value;l.close()}}catch(c){s={error:c}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(s)throw s.error}}},e.prototype.disconnect=function(){if(!this.disconnected){var t=this.id;et.default.log("Disconnect peer with ID:".concat(t)),this._disconnected=!0,this._open=!1,this.socket.close(),this._lastServerId=t,this._id=null,this.emit("disconnected",t)}},e.prototype.reconnect=function(){if(this.disconnected&&!this.destroyed)et.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)et.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!"))}},e.prototype.listAllPeers=function(t){var s=this;t===void 0&&(t=function(r){}),this._api.listAllPeers().then(function(r){return t(r)}).catch(function(r){return s._abort(Ji.ServerError,r)})},e.DEFAULT_KEY="peerjs",e}(rg.EventEmitter),W0=Qk.Peer;class L8{constructor(){h(this,"_host"),h(this,"_client"),h(this,"_clientData"),this.onEnable()}get isHost(){return this._host!==void 0}onEnable(){const e="HOST-5980e65c-8438-453e-8b35-f13c736dcd81";this.trySetupHost(e)}trySetupHost(e){let t=new W0(e);t.on("error",s=>{console.error(s),this._host=void 0,this.trySetupClient(e)}),t.on("open",s=>{this._host=new U8(t)})}trySetupClient(e){this._client=new W0,this._client.on("error",t=>{console.error("Client error",t)}),this._client.on("open",t=>{console.log("client connected",t),this._clientData=this._client.connect(e,{metadata:{id:t}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",s=>{console.log("<<",s)})})}}class F8{constructor(e){h(this,"_peer"),this._peer=e}}class U8 extends F8{constructor(e){var t;super(e),h(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(s=>{var r;return(r=s.metadata)==null?void 0:r.id}).filter(s=>s!==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 s=this._peer.connections[t];if(s)if(Array.isArray(s))for(const r of s)r&&r.send(e);else console.warn(s)}}}}var Qr=(i=>(i[i.OnConnection=0]="OnConnection",i[i.OnRoomJoin=1]="OnRoomJoin",i[i.Queued=2]="Queued",i[i.Immediate=3]="Immediate",i))(Qr||{});const s2="https://urls.needle.tools/default-networking-backend/index";let dc="wss://needle-tiny-starter.glitch.me/socket";const xr=!!oe("debugnet"),lg=!!(xr||oe("debugowner"));var r2=(i=>(i.ConnectionInfo="connection-start-info",i))(r2||{}),Ni=(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))(Ni||{});class N8{constructor(){h(this,"room"),h(this,"viewId"),h(this,"allowEditing"),h(this,"inRoom")}}class z8{constructor(){h(this,"room")}}class Q8{constructor(){h(this,"userId")}}var n2=(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))(n2||{});class q0{constructor(e,t){h(this,"guid"),h(this,"connection"),h(this,"_hasOwnership",!1),h(this,"_isOwned"),h(this,"_gainSubscription"),h(this,"_lostSubscription"),h(this,"_hasOwnerResponse"),h(this,"_isWaitingForOwnershipResponseCallback",null),this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.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(e){e.guid===this.guid&&(this._isOwned=e.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(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(lg&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let s=0;const r=()=>{if(s++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):r()},100)};r()})}requestOwnership(){return lg&&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(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(lg&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(lg&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class o2{constructor(e){h(this,"context"),h(this,"_peer",null),h(this,"_usersInRoomCopy",[]),h(this,"_defaultMessagesBuffer",[]),h(this,"_defaultMessagesBufferArray",[]),h(this,"netWebSocketUrlProvider"),h(this,"_listeners",{}),h(this,"_listenersBinary",{}),h(this,"connected",!1),h(this,"channelId"),h(this,"_connectionId",null),h(this,"_ws"),h(this,"_waitingForSocket",{}),h(this,"_isInRoom",!1),h(this,"_currentRoomName",null),h(this,"_currentRoomViewId",null),h(this,"_currentRoomAllowEditing",!0),h(this,"_currentInRoom",[]),h(this,"_state",{}),h(this,"_currentDelay",-1),h(this,"_connectingToWebsocketPromise",null),this.context=e}get peer(){return this._peer||(this._peer=new L8),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return xr}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(e){return this._currentInRoom.indexOf(e)!==-1}usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(const t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){this.connect(),xr&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},Qr.OnConnection)}leaveRoom(e=null){if(e||(e=this.currentRoomName),!e){console.error("Can not leave unknown room");return}this.send("leave-room",{room:e})}send(e,t=null,s=Qr.Queued){if(t===null&&(t={}),s===Qr.Queued){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,s)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(e){var t;xr&&console.log("<< bin",e.length),(t=this._ws)==null||t.send(e)}sendBufferedMessagesNow(){var e;if(!this._ws)return;this._defaultMessagesBufferArray.length=0;const t=Object.keys(this._defaultMessagesBuffer).length;for(const r in this._defaultMessagesBuffer){const n=this._defaultMessagesBuffer[r];if(t<=1){this.sendWithWebsocket(n.key,n.value,Qr.Immediate);break}const o=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(o)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&xr&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const s=JSON.stringify(this._defaultMessagesBufferArray);(e=this._ws)==null||e.send(s)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){return this.stopListen(e,t)}stopListen(e,t){if(!t||!this._listeners[e])return;const s=this._listeners[e].indexOf(t);s>=0&&this._listeners[e].splice(s,1)}beginListenBinary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;const s=this._listenersBinary[e].indexOf(t);s>=0&&this._listenersBinary[e].splice(s,1)}registerProvider(e){this.netWebSocketUrlProvider=e}async connect(){var e;if(this.connected)return Promise.resolve(!0);xr&&console.log("connecting");const t=(e=this.netWebSocketUrlProvider)==null?void 0:e.getWebsocketUrl();return t?dc=t:JI()&&(dc="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){var e;(e=this._ws)==null||e.close(),this._ws=void 0}connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(e,t)=>{let s=!1;const r=o=>{s||(s=!0,e(o))};if(dc===void 0&&(console.log("Fetch default backend url: "+s2),dc=await(await fetch(s2)).text()),dc===void 0){r(!1);return}console.log(`\u22A1 Connecting to networking backend on
|
|
3334
3334
|
`+dc);const n=new UB.WebsocketBuilder(dc).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=n,this.connected=!0,console.log(`\u229E Connected to networking backend
|
|
3335
3335
|
`+dc),r(!0),this.onSendQueued(Qr.OnConnection)}).onClose(o=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,r(!1)}).onError((o,a)=>{console.error("\u22A0 Websocket error",o,a),r(!1)}).onMessage(this.onMessage.bind(this)).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build()})}onMessage(e,t){const s=t.data;try{if(typeof s!="string"){s.size&&this.handleIncomingBinaryMessage(s);return}const r=JSON.parse(s);if(Array.isArray(r))for(const n of r)this.handleIncomingStringMessage(n);else this.handleIncomingStringMessage(r);return}catch{xr&&s==="pong"&&console.log("<<",s)}}async handleIncomingBinaryMessage(e){const t=await e.arrayBuffer();var s=new Uint8Array(t);const r=new kv(s),n=r.getBufferIdentifier(),o=this._listenersBinary[n],a=e8(r),l=t8(a);if(l&&typeof l=="string"&&(this._state[l]=a),!o)return;const c=a??r;for(const u of o)u(c)}handleIncomingStringMessage(e){var t,s;if(xr&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){const a=e.data;a&&(console.assert(a.id!==void 0&&a.id!==null&&a.id.length>0,"server did not send connection id",a.id),console.log("Your id is: "+a.id,this.context.alias??""),this._connectionId=a.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(xr&&console.log(e),e){this._isInRoom=!0;const a=e;this._currentRoomName=a.room,this._currentRoomViewId=a.viewId,this._currentRoomAllowEditing=a.allowEditing??!0,console.log("Room view id",this._currentRoomViewId),this._currentInRoom.length=0,this._currentInRoom.push(...a.inRoom),xr&&console.log("joined room with",this._currentInRoom,this.context.alias??"")}this.onSendQueued(Qr.OnRoomJoin);break;case"left-room":e.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(e.data){const a=e.data;this._currentInRoom.push(a.userId),xr&&console.log(a.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){const a=e.data,l=this._currentInRoom.indexOf(a.userId);l>=0&&(console.log(a.userId+" left",this.context.alias??""),this._currentInRoom.splice(l,1)),a.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":xr&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const o=(t=e.data)==null?void 0:t.time;o&&(this._currentDelay=this.context.time.time-o),xr&&console.log("Current latency: "+this._currentDelay.toFixed(1)+" sec","Clients in room: "+((s=this._currentInRoom)==null?void 0:s.length));break}const r=this._listeners[e.key];if(r)for(const o of r)o(e.data);const n=e.data;n&&(this._state[n.guid]=n)}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,s=Qr.OnRoomJoin){if(!this._ws){const n=this._waitingForSocket[s]||[];n.push(()=>this.sendWithWebsocket(e,t,s)),this._waitingForSocket[s]=n;return}const r=JSON.stringify(this.toMessage(e,t));xr&&console.log(">>",e),this._ws.send(r)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const s of t)s();t.length=0}}}function wd(i,e){try{e?i(e):i()}catch(t){return console.error(t),!1}return!0}(0,eval)(`
|
|
3336
|
-
if(!globalThis[""
|
|
3337
|
-
globalThis[""
|
|
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 a2="null",j8="undefined",Za="needle_isActiveInHierarchy",jh="builtin_components",cg="needle_editor_guid",G8=/^(?:[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 H8(i){return typeof i=="string"&&G8.test(i)}const Gs=[];for(let i=0;i<256;++i)Gs.push((i+256).toString(16).slice(1));function V8(i,e=0){return(Gs[i[e+0]]+Gs[i[e+1]]+Gs[i[e+2]]+Gs[i[e+3]]+"-"+Gs[i[e+4]]+Gs[i[e+5]]+"-"+Gs[i[e+6]]+Gs[i[e+7]]+"-"+Gs[i[e+8]]+Gs[i[e+9]]+"-"+Gs[i[e+10]]+Gs[i[e+11]]+Gs[i[e+12]]+Gs[i[e+13]]+Gs[i[e+14]]+Gs[i[e+15]]).toLowerCase()}function W8(i){if(!H8(i))throw TypeError("Invalid UUID");let e;const t=new Uint8Array(16);return t[0]=(e=parseInt(i.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(i.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(i.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(i.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(i.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}function q8(i){i=unescape(encodeURIComponent(i));const e=[];for(let t=0;t<i.length;++t)e.push(i.charCodeAt(t));return e}const X8="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Y8="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function J8(i,e,t){function s(r,n,o,a){var l;if(typeof r=="string"&&(r=q8(r)),typeof n=="string"&&(n=W8(n)),((l=n)===null||l===void 0?void 0:l.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+r.length);if(c.set(n),c.set(r,n.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,o){a=a||0;for(let u=0;u<16;++u)o[a+u]=c[u];return o}return V8(c)}try{s.name=i}catch{}return s.DNS=X8,s.URL=Y8,s}function K8(i,e,t,s){switch(i){case 0:return e&t^~e&s;case 1:return e^t^s;case 2:return e&t^e&s^t&s;case 3:return e^t^s}}function X1(i,e){return i<<e|i>>>32-e}function Z8(i){const e=[1518500249,1859775393,2400959708,3395469782],t=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof i=="string"){const o=unescape(encodeURIComponent(i));i=[];for(let a=0;a<o.length;++a)i.push(o.charCodeAt(a))}else Array.isArray(i)||(i=Array.prototype.slice.call(i));i.push(128);const s=i.length/4+2,r=Math.ceil(s/16),n=new Array(r);for(let o=0;o<r;++o){const a=new Uint32Array(16);for(let l=0;l<16;++l)a[l]=i[o*64+l*4]<<24|i[o*64+l*4+1]<<16|i[o*64+l*4+2]<<8|i[o*64+l*4+3];n[o]=a}n[r-1][14]=(i.length-1)*8/Math.pow(2,32),n[r-1][14]=Math.floor(n[r-1][14]),n[r-1][15]=(i.length-1)*8&4294967295;for(let o=0;o<r;++o){const a=new Uint32Array(80);for(let f=0;f<16;++f)a[f]=n[o][f];for(let f=16;f<80;++f)a[f]=X1(a[f-3]^a[f-8]^a[f-14]^a[f-16],1);let l=t[0],c=t[1],u=t[2],d=t[3],p=t[4];for(let f=0;f<80;++f){const g=Math.floor(f/20),m=X1(l,5)+K8(g,c,u,d)+p+e[g]+a[f]>>>0;p=d,d=u,u=X1(c,30)>>>0,c=l,l=m}t[0]=t[0]+l>>>0,t[1]=t[1]+c>>>0,t[2]=t[2]+u>>>0,t[3]=t[3]+d>>>0,t[4]=t[4]+p>>>0}return[t[0]>>24&255,t[0]>>16&255,t[0]>>8&255,t[0]&255,t[1]>>24&255,t[1]>>16&255,t[1]>>8&255,t[1]&255,t[2]>>24&255,t[2]>>16&255,t[2]>>8&255,t[2]&255,t[3]>>24&255,t[3]>>16&255,t[3]>>8&255,t[3]&255,t[4]>>24&255,t[4]>>16&255,t[4]>>8&255,t[4]&255]}const $8=J8("v5",80,Z8),l2=$8;Gi.registerCallback(Cn.ContextCreated,i=>{const e=i.context;f2(e),p2(e)});const X0=oe("debugcomponents"),c2="eff8ba80-635d-11ec-90d6-0242ac120003";class Ur{constructor(e){h(this,"_originalSeed"),h(this,"_seed"),typeof e=="string"&&(e=Ur.hash(e)),this._originalSeed=e,this._seed=e}get seed(){return this._seed}set seed(e){this._seed=e}reset(){this._seed=this._originalSeed}generateUUID(e){if(typeof e=="string")return l2(e,c2);const t=this._seed;return this._seed-=1,l2(t.toString(),c2)}initialize(e){typeof e=="string"?this._seed=Ur.hash(e):this._seed=e}static createFromString(e){return new Ur(this.hash(e))}static hash(e){let t=0;for(let s=0;s<e.length;s++)t=e.charCodeAt(s)+((t<<5)-t);return t}}var h2=(i=>(i.NewInstanceCreated="new-instance-created",i.InstanceDestroyed="instance-destroyed",i))(h2||{});class u2{constructor(e){h(this,"guid"),this.guid=e}}function Y0(i,e,t=!0){if(!i)return;const s=i;if($a(i,t),!e){console.warn("Can not send destroy: No networking connection provided",i.guid);return}if(!e.isConnected){console.warn("Can not send destroy: not connected",i.guid);return}let r=i.guid;if(!r&&s.uuid&&(r=s.uuid),!r){console.warn("Can not send destroy: failed to find guid",i);return}const n=new u2(r);e.send("instance-destroyed",n,Qr.Queued)}function d2(i,e){const t=new u2(i);e.send("instance-destroyed",t,Qr.Queued)}function p2(i){i.connection.beginListen("instance-destroyed",e=>{X0&&console.log("[Remote] Destroyed",i.scene,e);const t=yg(e.guid,i.scene);t&&$a(t)})}class e9{constructor(e,t,s){h(this,"filename"),h(this,"hash"),h(this,"size"),this.filename=e,this.hash=t,this.size=s}}class t9{constructor(e,t){h(this,"guid"),h(this,"originalGuid"),h(this,"seed"),h(this,"visible"),h(this,"hostData"),h(this,"dontSave"),h(this,"parent"),h(this,"position"),h(this,"rotation"),h(this,"scale"),this.originalGuid=e,this.guid=t}}function Y1(i,e,t,s){var r;const n=i;if(!n.guid)return console.warn("Can not instantiate: No guid",n),null;if(e.context||(e.context=_t.Current),!e.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const o=e?{...e}:null,{instance:a,seed:l}=i9(n,e);if(a){const c=a;if(c.guid){X0&&console.log("[Local] new instance","gameobject:",a?.guid);const u=new t9(n.guid,c.guid);u.seed=l,o&&(o.position&&(u.position={x:o.position.x,y:o.position.y,z:o.position.z}),o.rotation&&(u.rotation={x:o.rotation.x,y:o.rotation.y,z:o.rotation.z,w:o.rotation.w}),o.scale&&(u.scale={x:o.scale.x,y:o.scale.y,z:o.scale.z})),u.position||(u.position={x:c.position.x,y:c.position.y,z:c.position.z}),u.rotation||(u.rotation={x:c.quaternion.x,y:c.quaternion.y,z:c.quaternion.z,w:c.quaternion.w}),u.scale||(u.scale={x:c.scale.x,y:c.scale.y,z:c.scale.z}),u.visible=n.visible,o!=null&&o.parent&&(typeof o.parent=="string"?u.parent=o.parent:u.parent=o.parent.guid),u.hostData=t,s===!1&&(u.dontSave=!0),(r=e?.context)==null||r.connection.send("new-instance-created",u)}else console.warn("Missing guid, can not send new instance event",c)}return a}function J0(){return Math.random()*9999999}function f2(i){i.connection.beginListen("new-instance-created",async e=>{const t=await s9(e.originalGuid,i.scene);if(!t){console.warn("could not find object that was instantiated: "+e.guid);return}const s=new Go;e.position&&(s.position=new S(e.position.x,e.position.y,e.position.z)),e.rotation&&(s.rotation=new xe(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w)),e.scale&&(s.scale=new S(e.scale.x,e.scale.y,e.scale.z)),s.parent=e.parent,e.seed&&(s.idProvider=new Ur(e.seed)),s.visible=e.visible,s.context=i,X0&&i.alias&&console.log("[Remote] instantiate in: "+i.alias);const r=bg(t,s);r&&(e.parent==="scene"&&i.scene.add(r),X0&&console.log("[Remote] new instance","gameobject:",r?.guid,t))})}function i9(i,e){const t=J0(),s=e??new Go;s.idProvider=new Ur(t);const r=bg(i,s);return{seed:t,instance:r}}const g2={};function m2(i,e){g2[i]=e}async function s9(i,e){const t=g2[i];if(t!=null){const s=await t(i);if(s)return s}return v2(i,e)}function v2(i,e){if(e===null||!i)return null;if(e.guid===i)return e;if(e.children)for(const t of e.children){const s=v2(i,t);if(s)return s}return null}const A2=new Map;function r9(i,e){if(!i)return;if(!e){console.warn("No prototype found",i,i.prototype,i.constructor);return}let t=A2.get(e);t&&t.apply(i)}function n9(i){const e=o9(i.prototype);A2.set(i,e)}function o9(i){return new a9(i)}class a9{constructor(e){h(this,"$symbol"),h(this,"extensions"),h(this,"descriptors"),this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(e),this.descriptors=new Array;for(let t=0;t<this.extensions.length;t++){const s=this.extensions[t],r=Object.getOwnPropertyDescriptor(e,s);r&&this.descriptors.push(r)}}apply(e){if(!e[this.$symbol]){e[this.$symbol]=!0;for(let t=0;t<this.extensions.length;t++){const s=this.extensions[t],r=this.descriptors[t];r&&Object.defineProperty(e,s,r)}}}}var hg=(i=>(i.Added="component-added",i.Removing="removing-component",i))(hg||{});const y2=oe("debugcomponentevents");class ug{static addComponentLifecylceEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.set(e,[]);let s=this.eventListeners.get(e);s||(s=[]),s.push(t),this.eventListeners.set(e,s),y2&&console.log("Added event listener for "+e,this.eventListeners)}static removeComponentLifecylceEventListener(e,t){const s=this.eventListeners.get(e);if(!s)return;const r=s.indexOf(t);r<0||s.splice(r,1)}static dispatchComponentLifecycleEvent(e,t){const s=this.eventListeners.get(e);if(y2&&console.log("Dispatching event "+e,s),!!s)for(const r of s)r(t)}}h(ug,"eventListeners",new Map);const J1=oe("debuggetcomponent");function l9(i){return i==null||i.isObject3D?i:i.object&&i.object.isObject3D?i.object:i}function K1(i,e){if(!i||!i.userData.components)return;const t=i.userData.components.indexOf(e);t<0||(ug.dispatchComponentLifecycleEvent(hg.Removing,e),e.gameObject=null,i.userData.components.splice(t,1))}function K0(i,e){const t=xd(i,e);if(t)return t;const s=new e;return Gh(i,s)}const b2=new Ur("addComponentIdProvider");function Gh(i,e,t=!0){i.userData||(i.userData={}),i.userData.components||(i.userData.components=[]),i.userData.components.push(e),e.gameObject=i,(e.guid===void 0||e.guid==="invalid")&&(e.guid=b2.generateUUID()),$0(i),yy(e);try{t&&e.__internalAwake&&(_g(i),e.__internalAwake()),ug.dispatchComponentLifecycleEvent(hg.Added,e)}catch(s){console.error(s)}return e}function Z1(i,e){if(e.gameObject===i)return e;if(e.gameObject&&e.gameObject.userData.components){const t=e.gameObject.userData.components.indexOf(e);e.gameObject.userData.components.splice(t,1)}if(!i.userData.components)i.userData.components=[];else if(i.userData.components.includes(e))return e;return i.userData.components.push(e),e.gameObject=i,(e.guid===void 0||e.guid==="invalid")&&(e.guid=b2.generateUUID()),yy(e),e}function _2(i){if(i.gameObject&&i.gameObject.userData.components){const e=i.gameObject.userData.components.indexOf(i);i.gameObject.userData.components.splice(e,1)}i.__internalDisable&&i.__internalDisable(),i.onDestroy&&i.onDestroy(),el(i,i.context??_t.Current),i.__internalDestroy(),i.gameObject=null}let w2=!1;function x2(i,e,t){var s;if(i!=null){if(!i.isObject3D){console.error("Object is not object3D");return}if(!((s=i?.userData)!=null&&s.components))return null;if(typeof e=="string"&&(w2||(w2=!0,console.warn(`Accessing components by name is not supported.
|
|
3340
|
+
`);const a2=NEEDLE_ENGINE_VERSION,j8="undefined",Za="needle_isActiveInHierarchy",jh="builtin_components",cg="needle_editor_guid",G8=/^(?:[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 H8(i){return typeof i=="string"&&G8.test(i)}const Gs=[];for(let i=0;i<256;++i)Gs.push((i+256).toString(16).slice(1));function V8(i,e=0){return(Gs[i[e+0]]+Gs[i[e+1]]+Gs[i[e+2]]+Gs[i[e+3]]+"-"+Gs[i[e+4]]+Gs[i[e+5]]+"-"+Gs[i[e+6]]+Gs[i[e+7]]+"-"+Gs[i[e+8]]+Gs[i[e+9]]+"-"+Gs[i[e+10]]+Gs[i[e+11]]+Gs[i[e+12]]+Gs[i[e+13]]+Gs[i[e+14]]+Gs[i[e+15]]).toLowerCase()}function W8(i){if(!H8(i))throw TypeError("Invalid UUID");let e;const t=new Uint8Array(16);return t[0]=(e=parseInt(i.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(i.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(i.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(i.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(i.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}function q8(i){i=unescape(encodeURIComponent(i));const e=[];for(let t=0;t<i.length;++t)e.push(i.charCodeAt(t));return e}const X8="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Y8="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function J8(i,e,t){function s(r,n,o,a){var l;if(typeof r=="string"&&(r=q8(r)),typeof n=="string"&&(n=W8(n)),((l=n)===null||l===void 0?void 0:l.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+r.length);if(c.set(n),c.set(r,n.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,o){a=a||0;for(let u=0;u<16;++u)o[a+u]=c[u];return o}return V8(c)}try{s.name=i}catch{}return s.DNS=X8,s.URL=Y8,s}function K8(i,e,t,s){switch(i){case 0:return e&t^~e&s;case 1:return e^t^s;case 2:return e&t^e&s^t&s;case 3:return e^t^s}}function X1(i,e){return i<<e|i>>>32-e}function Z8(i){const e=[1518500249,1859775393,2400959708,3395469782],t=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof i=="string"){const o=unescape(encodeURIComponent(i));i=[];for(let a=0;a<o.length;++a)i.push(o.charCodeAt(a))}else Array.isArray(i)||(i=Array.prototype.slice.call(i));i.push(128);const s=i.length/4+2,r=Math.ceil(s/16),n=new Array(r);for(let o=0;o<r;++o){const a=new Uint32Array(16);for(let l=0;l<16;++l)a[l]=i[o*64+l*4]<<24|i[o*64+l*4+1]<<16|i[o*64+l*4+2]<<8|i[o*64+l*4+3];n[o]=a}n[r-1][14]=(i.length-1)*8/Math.pow(2,32),n[r-1][14]=Math.floor(n[r-1][14]),n[r-1][15]=(i.length-1)*8&4294967295;for(let o=0;o<r;++o){const a=new Uint32Array(80);for(let f=0;f<16;++f)a[f]=n[o][f];for(let f=16;f<80;++f)a[f]=X1(a[f-3]^a[f-8]^a[f-14]^a[f-16],1);let l=t[0],c=t[1],u=t[2],d=t[3],p=t[4];for(let f=0;f<80;++f){const g=Math.floor(f/20),m=X1(l,5)+K8(g,c,u,d)+p+e[g]+a[f]>>>0;p=d,d=u,u=X1(c,30)>>>0,c=l,l=m}t[0]=t[0]+l>>>0,t[1]=t[1]+c>>>0,t[2]=t[2]+u>>>0,t[3]=t[3]+d>>>0,t[4]=t[4]+p>>>0}return[t[0]>>24&255,t[0]>>16&255,t[0]>>8&255,t[0]&255,t[1]>>24&255,t[1]>>16&255,t[1]>>8&255,t[1]&255,t[2]>>24&255,t[2]>>16&255,t[2]>>8&255,t[2]&255,t[3]>>24&255,t[3]>>16&255,t[3]>>8&255,t[3]&255,t[4]>>24&255,t[4]>>16&255,t[4]>>8&255,t[4]&255]}const $8=J8("v5",80,Z8),l2=$8;Gi.registerCallback(Cn.ContextCreated,i=>{const e=i.context;f2(e),p2(e)});const X0=oe("debugcomponents"),c2="eff8ba80-635d-11ec-90d6-0242ac120003";class Ur{constructor(e){h(this,"_originalSeed"),h(this,"_seed"),typeof e=="string"&&(e=Ur.hash(e)),this._originalSeed=e,this._seed=e}get seed(){return this._seed}set seed(e){this._seed=e}reset(){this._seed=this._originalSeed}generateUUID(e){if(typeof e=="string")return l2(e,c2);const t=this._seed;return this._seed-=1,l2(t.toString(),c2)}initialize(e){typeof e=="string"?this._seed=Ur.hash(e):this._seed=e}static createFromString(e){return new Ur(this.hash(e))}static hash(e){let t=0;for(let s=0;s<e.length;s++)t=e.charCodeAt(s)+((t<<5)-t);return t}}var h2=(i=>(i.NewInstanceCreated="new-instance-created",i.InstanceDestroyed="instance-destroyed",i))(h2||{});class u2{constructor(e){h(this,"guid"),this.guid=e}}function Y0(i,e,t=!0){if(!i)return;const s=i;if($a(i,t),!e){console.warn("Can not send destroy: No networking connection provided",i.guid);return}if(!e.isConnected){console.warn("Can not send destroy: not connected",i.guid);return}let r=i.guid;if(!r&&s.uuid&&(r=s.uuid),!r){console.warn("Can not send destroy: failed to find guid",i);return}const n=new u2(r);e.send("instance-destroyed",n,Qr.Queued)}function d2(i,e){const t=new u2(i);e.send("instance-destroyed",t,Qr.Queued)}function p2(i){i.connection.beginListen("instance-destroyed",e=>{X0&&console.log("[Remote] Destroyed",i.scene,e);const t=yg(e.guid,i.scene);t&&$a(t)})}class e9{constructor(e,t,s){h(this,"filename"),h(this,"hash"),h(this,"size"),this.filename=e,this.hash=t,this.size=s}}class t9{constructor(e,t){h(this,"guid"),h(this,"originalGuid"),h(this,"seed"),h(this,"visible"),h(this,"hostData"),h(this,"dontSave"),h(this,"parent"),h(this,"position"),h(this,"rotation"),h(this,"scale"),this.originalGuid=e,this.guid=t}}function Y1(i,e,t,s){var r;const n=i;if(!n.guid)return console.warn("Can not instantiate: No guid",n),null;if(e.context||(e.context=_t.Current),!e.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const o=e?{...e}:null,{instance:a,seed:l}=i9(n,e);if(a){const c=a;if(c.guid){X0&&console.log("[Local] new instance","gameobject:",a?.guid);const u=new t9(n.guid,c.guid);u.seed=l,o&&(o.position&&(u.position={x:o.position.x,y:o.position.y,z:o.position.z}),o.rotation&&(u.rotation={x:o.rotation.x,y:o.rotation.y,z:o.rotation.z,w:o.rotation.w}),o.scale&&(u.scale={x:o.scale.x,y:o.scale.y,z:o.scale.z})),u.position||(u.position={x:c.position.x,y:c.position.y,z:c.position.z}),u.rotation||(u.rotation={x:c.quaternion.x,y:c.quaternion.y,z:c.quaternion.z,w:c.quaternion.w}),u.scale||(u.scale={x:c.scale.x,y:c.scale.y,z:c.scale.z}),u.visible=n.visible,o!=null&&o.parent&&(typeof o.parent=="string"?u.parent=o.parent:u.parent=o.parent.guid),u.hostData=t,s===!1&&(u.dontSave=!0),(r=e?.context)==null||r.connection.send("new-instance-created",u)}else console.warn("Missing guid, can not send new instance event",c)}return a}function J0(){return Math.random()*9999999}function f2(i){i.connection.beginListen("new-instance-created",async e=>{const t=await s9(e.originalGuid,i.scene);if(!t){console.warn("could not find object that was instantiated: "+e.guid);return}const s=new Go;e.position&&(s.position=new S(e.position.x,e.position.y,e.position.z)),e.rotation&&(s.rotation=new xe(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w)),e.scale&&(s.scale=new S(e.scale.x,e.scale.y,e.scale.z)),s.parent=e.parent,e.seed&&(s.idProvider=new Ur(e.seed)),s.visible=e.visible,s.context=i,X0&&i.alias&&console.log("[Remote] instantiate in: "+i.alias);const r=bg(t,s);r&&(e.parent==="scene"&&i.scene.add(r),X0&&console.log("[Remote] new instance","gameobject:",r?.guid,t))})}function i9(i,e){const t=J0(),s=e??new Go;s.idProvider=new Ur(t);const r=bg(i,s);return{seed:t,instance:r}}const g2={};function m2(i,e){g2[i]=e}async function s9(i,e){const t=g2[i];if(t!=null){const s=await t(i);if(s)return s}return v2(i,e)}function v2(i,e){if(e===null||!i)return null;if(e.guid===i)return e;if(e.children)for(const t of e.children){const s=v2(i,t);if(s)return s}return null}const A2=new Map;function r9(i,e){if(!i)return;if(!e){console.warn("No prototype found",i,i.prototype,i.constructor);return}let t=A2.get(e);t&&t.apply(i)}function n9(i){const e=o9(i.prototype);A2.set(i,e)}function o9(i){return new a9(i)}class a9{constructor(e){h(this,"$symbol"),h(this,"extensions"),h(this,"descriptors"),this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(e),this.descriptors=new Array;for(let t=0;t<this.extensions.length;t++){const s=this.extensions[t],r=Object.getOwnPropertyDescriptor(e,s);r&&this.descriptors.push(r)}}apply(e){if(!e[this.$symbol]){e[this.$symbol]=!0;for(let t=0;t<this.extensions.length;t++){const s=this.extensions[t],r=this.descriptors[t];r&&Object.defineProperty(e,s,r)}}}}var hg=(i=>(i.Added="component-added",i.Removing="removing-component",i))(hg||{});const y2=oe("debugcomponentevents");class ug{static addComponentLifecylceEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.set(e,[]);let s=this.eventListeners.get(e);s||(s=[]),s.push(t),this.eventListeners.set(e,s),y2&&console.log("Added event listener for "+e,this.eventListeners)}static removeComponentLifecylceEventListener(e,t){const s=this.eventListeners.get(e);if(!s)return;const r=s.indexOf(t);r<0||s.splice(r,1)}static dispatchComponentLifecycleEvent(e,t){const s=this.eventListeners.get(e);if(y2&&console.log("Dispatching event "+e,s),!!s)for(const r of s)r(t)}}h(ug,"eventListeners",new Map);const J1=oe("debuggetcomponent");function l9(i){return i==null||i.isObject3D?i:i.object&&i.object.isObject3D?i.object:i}function K1(i,e){if(!i||!i.userData.components)return;const t=i.userData.components.indexOf(e);t<0||(ug.dispatchComponentLifecycleEvent(hg.Removing,e),e.gameObject=null,i.userData.components.splice(t,1))}function K0(i,e){const t=xd(i,e);if(t)return t;const s=new e;return Gh(i,s)}const b2=new Ur("addComponentIdProvider");function Gh(i,e,t=!0){i.userData||(i.userData={}),i.userData.components||(i.userData.components=[]),i.userData.components.push(e),e.gameObject=i,(e.guid===void 0||e.guid==="invalid")&&(e.guid=b2.generateUUID()),$0(i),yy(e);try{t&&e.__internalAwake&&(_g(i),e.__internalAwake()),ug.dispatchComponentLifecycleEvent(hg.Added,e)}catch(s){console.error(s)}return e}function Z1(i,e){if(e.gameObject===i)return e;if(e.gameObject&&e.gameObject.userData.components){const t=e.gameObject.userData.components.indexOf(e);e.gameObject.userData.components.splice(t,1)}if(!i.userData.components)i.userData.components=[];else if(i.userData.components.includes(e))return e;return i.userData.components.push(e),e.gameObject=i,(e.guid===void 0||e.guid==="invalid")&&(e.guid=b2.generateUUID()),yy(e),e}function _2(i){if(i.gameObject&&i.gameObject.userData.components){const e=i.gameObject.userData.components.indexOf(i);i.gameObject.userData.components.splice(e,1)}i.__internalDisable&&i.__internalDisable(),i.onDestroy&&i.onDestroy(),el(i,i.context??_t.Current),i.__internalDestroy(),i.gameObject=null}let w2=!1;function x2(i,e,t){var s;if(i!=null){if(!i.isObject3D){console.error("Object is not object3D");return}if(!((s=i?.userData)!=null&&s.components))return null;if(typeof e=="string"&&(w2||(w2=!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);}`,pD=class extends vo{constructor({blendFu
|
|
|
3833
3833
|
irradiance += 0.;
|
|
3834
3834
|
#else
|
|
3835
3835
|
irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
|
|
3836
|
-
#endif`),Xe.lightmap.lightmapScaleOffset={value:new it(1,1,0,0)};const G7=oe("debugplayerview");var Vo=(i=>(i.Browser="browser",i.Headset="headset",i.Handheld="handheld",i))(Vo||{});class DD{constructor(e,t){h(this,"userId"),h(this,"context"),h(this,"viewDevice","browser"),h(this,"removed",!1),h(this,"_object"),this.userId=e,this.context=t}get currentObject(){return this._object}set currentObject(e){this._object=e}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class OD{constructor(e){h(this,"context"),h(this,"playerViews",new Map),this.context=e}setPlayerView(e,t,s){let r=this.playerViews.get(e);r||(r=new DD(e,this.context),this.playerViews.set(e,r)),r.viewDevice=s,r.currentObject=t,r.removed=!1}getPlayerView(e){if(!!e){if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}}removePlayerView(e,t){const s=this.playerViews.get(e);s?.viewDevice===t&&(G7&&console.log("REMOVE",e),s.removed=!0,this.playerViews.delete(e))}}const bC=oe("debugSetup"),H7=oe("stats"),V7=oe("debugactive"),W7=oe("debugframerate"),q7=oe("debugcoroutine"),X7={};class Y7{constructor(e){h(this,"name"),h(this,"alias"),h(this,"domElement"),h(this,"renderer"),h(this,"hash"),this.domElement=e??document.body}}var dn=(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))(dn||{}),Eg=(i=>(i.ImmersiveVR="immersive-vr",i.ImmersiveAR="immersive-ar",i))(Eg||{});function yy(i,e){if(!i)return;const t=e?.new_scripts??_t.Current.new_scripts;t.includes(i)||t.push(i)}class _t{constructor(e){h(this,"name"),h(this,"alias"),h(this,"isManagedExternally",!1),h(this,"isPaused",!1),h(this,"runInBackground",!1),h(this,"targetFrameRate"),h(this,"hash"),h(this,"domElement"),h(this,"_resolutionScaleFactor",1),h(this,"_boundingClientRectFrame",-1),h(this,"_boundingClientRect",null),h(this,"_domX"),h(this,"_domY"),h(this,"xrSessionMode"),h(this,"_xrFrame",null),h(this,"_currentFrameEvent",-1),h(this,"scene"),h(this,"renderer"),h(this,"composer",null),h(this,"scripts",[]),h(this,"scripts_pausedChanged",[]),h(this,"scripts_earlyUpdate",[]),h(this,"scripts_update",[]),h(this,"scripts_lateUpdate",[]),h(this,"scripts_onBeforeRender",[]),h(this,"scripts_onAfterRender",[]),h(this,"scripts_WithCorroutines",[]),h(this,"coroutines",{}),h(this,"mainCameraComponent"),h(this,"post_setup_callbacks",[]),h(this,"pre_update_callbacks",[]),h(this,"pre_render_callbacks",[]),h(this,"post_render_callbacks",[]),h(this,"new_scripts",[]),h(this,"new_script_start",[]),h(this,"new_scripts_pre_setup_callbacks",[]),h(this,"new_scripts_post_setup_callbacks",[]),h(this,"application"),h(this,"time"),h(this,"input"),h(this,"physics"),h(this,"connection"),h(this,"assets"),h(this,"mainLight",null),h(this,"sceneLighting"),h(this,"addressables"),h(this,"lightmaps"),h(this,"players"),h(this,"_sizeChanged",!1),h(this,"_isCreated",!1),h(this,"_isCreating",!1),h(this,"_isVisible",!1),h(this,"_stats",H7?E7():null),h(this,"_intersectionObserver",null),h(this,"_disposeCallbacks",[]),h(this,"_cameraStack",[]),h(this,"_onBeforeRenderListeners",new Map),h(this,"_onAfterRenderListeners",new Map),h(this,"_requireDepthTexture",!1),h(this,"_requireColorTexture",!1),h(this,"_renderTarget"),h(this,"_isRendering",!1),h(this,"_accumulatedTime",0),h(this,"_framerateClock",new a0),h(this,"_dispatchReadyAfterFrame",!1),h(this,"_wasPaused",!1);var t,s;if(this.name=e?.name||"",this.alias=e?.alias,this.domElement=e?.domElement||document.body,this.hash=e?.hash,e!=null&&e.renderer)this.renderer=e.renderer,this.isManagedExternally=!0;else{const o={antialias:!0},a=(s=(t=e?.domElement)==null?void 0:t.shadowRoot)==null?void 0:s.querySelector("canvas");a&&(o.canvas=a),this.renderer=new ad(o),this.renderer.toneMappingExposure=1,this.renderer.toneMapping=vr,this.renderer.setClearColor(new _e("lightgrey"),0),this.renderer.antialias=!0,this.renderer.alpha=!1,this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=dw,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputEncoding=yt,this.renderer.physicallyCorrectLights=!0}this.scene=new an,Gi.register(this),this.application=new PD(this),this.time=new FB,this.input=new _B(this),this.physics=new OB(this),this.connection=new o2(this),this.assets=new T2,this.sceneLighting=new TD(this),this.addressables=new MD(this),this.lightmaps=new j7(this),this.players=new OD(this);const r=()=>this._sizeChanged=!0;window.addEventListener("resize",r),this._disposeCallbacks.push(()=>window.removeEventListener("resize",r));const n=new ResizeObserver(o=>this._sizeChanged=!0);n.observe(this.domElement),this._disposeCallbacks.push(()=>n.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 a2}static get Current(){return Gi.Current}static set Current(e){Gi.Current=e}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(e){if(e!==this._resolutionScaleFactor&&typeof e=="number"){if(e<=0){console.error("Invalid resolution scale factor",e);return}this._resolutionScaleFactor=e,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 e;return((e=this.renderer.xr)==null?void 0:e.isPresenting)||!1}get isInVR(){return this.xrSessionMode==="immersive-vr"}get isInAR(){return this.xrSessionMode==="immersive-ar"}get xrSession(){var e;return(e=this.renderer.xr)==null?void 0:e.getSession()}get xrFrame(){return this._xrFrame}get arOverlayElement(){const e=this.domElement;return typeof e.getAROverlayContainer=="function"?e.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}get mainCamera(){if(this.mainCameraComponent){const e=this.mainCameraComponent;return e.cam||e.buildCamera(),e.cam}return null}get rendererData(){return this.sceneLighting}get isCreated(){return this._isCreated}internalOnUpdateVisible(){var e,t;(e=this._intersectionObserver)==null||e.disconnect(),(t=this._intersectionObserver)==null||t.observe(this.domElement)}updateSize(){var e,t,s;if(!this.isManagedExternally&&((e=this.renderer.xr)==null?void 0:e.isPresenting)===!1){this._sizeChanged=!1;const r=this.resolutionScaleFactor,n=this.domWidth*r,o=this.domHeight*r,a=this.mainCamera;this.updateAspect(a),this.renderer.setSize(n,o),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.composer&&((t=this.composer.setSize)==null||t.call(this.composer,n,o),"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&((s=this.composer.setPixelRatio)==null||s.call(this.composer,window.devicePixelRatio)))}}updateAspect(e,t,s){if(!e)return;t===void 0&&(t=this.domWidth),s===void 0&&(s=this.domHeight);const r=e.aspect;e.aspect=t/s,r!==e.aspect&&e.updateProjectionMatrix()}async onCreate(e,t){try{return this._isCreating=!0,await this.internalOnCreate(e,t)}finally{this._isCreating=!1}}clear(){var e;(e=this.scene)!=null&&e.children.length&&($a(this.scene,!0,!0),this.scene=new an),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear())}dispose(){this.internalOnDestroy()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){var e,t,s;this.clear(),(e=this.renderer)==null||e.setAnimationLoop(null),this.isManagedExternally||(t=this.renderer)==null||t.dispose();for(const r of this._disposeCallbacks)try{r()}catch(n){console.error("Error in on dispose callback:",n,r)}(s=this.domElement)!=null&&s.parentElement&&this.domElement.parentElement.removeChild(this.domElement),Gi.dispatchCallback(Cn.ContextDestroyed,this),Gi.unregister(this)}registerCoroutineUpdate(e,t,s){return this.coroutines[s]||(this.coroutines[s]=[]),this.coroutines[s].push({comp:e,main:t}),t}unregisterCoroutineUpdate(e,t){if(!this.coroutines[t])return;const s=this.coroutines[t].findIndex(r=>r.main===e);s>=0&&this.coroutines[t].splice(s,1)}stopAllCoroutinesFrom(e){for(const t in this.coroutines){const s=this.coroutines[t];for(let r=s.length-1;r>=0;r--)s[r].comp===e&&s.splice(r,1)}}setCurrentCamera(e){var t;if(!e)return;if(e.cam||e.buildCamera(),!e.cam){console.warn("Camera component is missing camera",e);return}const s=this._cameraStack.indexOf(e);s>=0&&this._cameraStack.splice(s,1),this._cameraStack.push(e),this.mainCameraComponent=e;const r=e.cam;r.isPerspectiveCamera&&this.updateAspect(r),(t=this.mainCameraComponent)==null||t.applyClearFlagsIfIsActiveCamera()}removeCamera(e){if(!e)return;const t=this._cameraStack.indexOf(e);if(t>=0&&this._cameraStack.splice(t,1),this.mainCameraComponent===e&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){const s=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(s)}}addBeforeRenderListener(e,t){var s;this._onBeforeRenderListeners.has(e.uuid)||(this._onBeforeRenderListeners.set(e.uuid,[]),e.onBeforeRender=this._createRenderCallbackWrapper(e,this._onBeforeRenderListeners)),(s=this._onBeforeRenderListeners.get(e.uuid))==null||s.push(t)}removeBeforeRenderListener(e,t){if(this._onBeforeRenderListeners.has(e.uuid)){const s=this._onBeforeRenderListeners.get(e.uuid),r=s.indexOf(t);r>=0&&s.splice(r,1)}}addAfterRenderListener(e,t){var s;this._onAfterRenderListeners.has(e.uuid)||(this._onAfterRenderListeners.set(e.uuid,[]),e.onAfterRender=this._createRenderCallbackWrapper(e,this._onAfterRenderListeners)),(s=this._onAfterRenderListeners.get(e.uuid))==null||s.push(t)}removeAfterRenderListener(e,t){if(this._onAfterRenderListeners.has(e.uuid)){const s=this._onAfterRenderListeners.get(e.uuid),r=s.indexOf(t);r>=0&&s.splice(r,1)}}_createRenderCallbackWrapper(e,t){return(s,r,n,o,a,l)=>{const c=t.get(e.uuid);if(c)for(let u=0;u<c.length;u++){const d=c[u];d(s,r,n,o,a,l)}}}get isRendering(){return this._isRendering}setRequireDepth(e){this._requireDepthTexture=e}setRequireColor(e){this._requireColorTexture=e}get depthTexture(){var e;return((e=this._renderTarget)==null?void 0:e.depthTexture)||null}get opaqueColorTexture(){var e;return((e=this._renderTarget)==null?void 0:e.texture)||null}get isVisibleToUser(){if(this.isInXR)return!0;if(!this._isVisible)return!1;const e=getComputedStyle(this.domElement);return e.visibility!=="hidden"&&e.display!=="none"&&e.opacity!=="0"}async internalOnCreate(e,t){var s;this.clear(),(s=this.renderer)==null||s.setAnimationLoop(null),await pf(1),_t.Current=this,await Gi.dispatchCallback(Cn.ContextCreationStart,this);let r=!0;try{_t.Current=this,e&&await e(this,t)}catch(n){console.error(n),r=!1}if(!r)return!1;this.internalOnUpdateVisible(),!this.isManagedExternally&&!this.domElement.shadowRoot&&this.domElement.prepend(this.renderer.domElement),_t.Current=this,_t.Current=this;for(let n=0;n<this.new_scripts.length;n++){const o=this.new_scripts[n];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 a=o.gameObject.userData.components;a.includes(o)||a.push(o)}}if(this.post_setup_callbacks)for(let n=0;n<this.post_setup_callbacks.length;n++)_t.Current=this,await this.post_setup_callbacks[n](this);if(!this.mainCamera){_t.Current=this;let n=null;Hh(this.scene,o=>{const a=o;if(a!=null&&a.isCamera){if(_g(a.gameObject),!a.activeAndEnabled)return;if(a.tag==="MainCamera")return n=a,!0;n=a}}),n?this.setCurrentCamera(n):(Gi.dispatchCallback(Cn.MissingCamera,this),!this.mainCamera&&!this.isManagedExternally&&console.warn("Missing camera in main scene",this))}if(_t.Current=this,ny(this),!this.isManagedExternally&&this.composer&&this.mainCamera){const n=new py(this.scene,this.mainCamera);this.renderer.setSize(this.domWidth,this.domHeight),this.composer.addPass(n),this.composer.setSize(this.domWidth,this.domHeight)}return this._sizeChanged=!0,this._stats&&(this._stats.showPanel(1),this.domElement.appendChild(this._stats.dom)),bC&&S0(this.scene,!0),this._isCreating=!1,this.restartRenderLoop(),this._dispatchReadyAfterFrame=!0,Gi.dispatchCallback(Cn.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 e=this.render.bind(this);return this.renderer.setAnimationLoop(e),!0}render(e,t){if(_r()||bC||C9())try{this.internalRender(e,t)}catch(s){(_r()||bC)&&s instanceof Error&&Rs("Exception during render-loop.<br/>See console for details.",so.Error),console.error(s),console.warn("Stopping render loop due to error"),this.renderer.setAnimationLoop(null),this.domElement.dispatchEvent(new CustomEvent("error",{detail:s}))}else this.internalRender(e,t)}internalRender(e,t){var s,r;if(this._xrFrame=t,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((s=this._stats)==null||s.begin(),_t.Current=this,!this.onHandlePaused()){for(_t.Current=this,this.time.update(),W7&&console.log("FPS",this.time.smoothedFps.toFixed(0)),ny(this),oy(this.scene),G2(this);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const n=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(n)}if(this.pre_update_callbacks)for(const n in this.pre_update_callbacks)this.pre_update_callbacks[n]();this._currentFrameEvent=0;for(let n=0;n<this.scripts_earlyUpdate.length;n++){const o=this.scripts_earlyUpdate[n];o.activeAndEnabled&&o.earlyUpdate!==void 0&&(_t.Current=this,o.earlyUpdate())}if(this.executeCoroutines(0),!this.onHandlePaused()){this._currentFrameEvent=1;for(let n=0;n<this.scripts_update.length;n++){const o=this.scripts_update[n];o.activeAndEnabled&&o.update!==void 0&&(_t.Current=this,o.update())}if(this.executeCoroutines(1),!this.onHandlePaused()){this._currentFrameEvent=2;for(let n=0;n<this.scripts_lateUpdate.length;n++){const o=this.scripts_lateUpdate[n];o.activeAndEnabled&&o.lateUpdate!==void 0&&(_t.Current=this,o.lateUpdate())}if(this.executeCoroutines(2),!this.onHandlePaused()){if(this.physics.engine){const n=this.time.deltaTime/1;for(let o=0;o<1;o++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.engine.step(n),this._currentFrameEvent=10,this.executeCoroutines(10);this.physics.engine.postStep()}if(!this.onHandlePaused()){if(this.isVisibleToUser){this._currentFrameEvent=3;for(let n=0;n<this.scripts_onBeforeRender.length;n++){const o=this.scripts_onBeforeRender[n];o.activeAndEnabled&&o.onBeforeRender!==void 0&&(_t.Current=this,o.onBeforeRender(t))}if(this.executeCoroutines(3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(const n in this.pre_render_callbacks)this.pre_render_callbacks[n]();this.isManagedExternally||(M9(this),this._currentFrameEvent=-1,this.renderNow(),this._currentFrameEvent=4);for(let n=0;n<this.scripts_onAfterRender.length;n++){const o=this.scripts_onAfterRender[n];o.activeAndEnabled&&o.onAfterRender!==void 0&&(_t.Current=this,o.onAfterRender())}if(this.executeCoroutines(4),this.post_render_callbacks)for(const n in this.post_render_callbacks)this.post_render_callbacks[n]()}this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),(r=this._stats)==null||r.end(),this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")))}}}}}}renderNow(e){return!e&&(e=this.mainCamera,!e)?!1:(this._isRendering=!0,this.renderRequiredTextures(),this.composer&&!this.isInXR?this.composer.render(this.time.deltaTime):e&&this.renderer.render(this.scene,e),this._isRendering=!1,!0)}onHandlePaused(){const e=this.evaluatePaused();if(this._wasPaused!==e){V7&&console.log("Paused?",e,"context:"+this.alias);for(let t=0;t<this.scripts_pausedChanged.length;t++){const s=this.scripts_pausedChanged[t];s.activeAndEnabled&&s.onPausedChanged!==void 0&&(_t.Current=this,s.onPausedChanged(e,this._wasPaused))}}return this._wasPaused=e,e}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 ri(this.domWidth,this.domHeight),this._requireDepthTexture){const s=new DA(this.domWidth,this.domHeight);this._renderTarget.depthTexture=s}this._requireColorTexture&&(this._renderTarget.texture=new Nt,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=Zt,this._renderTarget.texture.magFilter=Zt,this._renderTarget.texture.format=wi)}const e=this._renderTarget;e.texture&&(e.texture.encoding=this.renderer.outputEncoding);const t=this.renderer.getRenderTarget();this.renderer.setRenderTarget(e),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(t)}executeCoroutines(e){if(this.coroutines[e]){const s=this.coroutines[e];for(let r=0;r<s.length;r++)try{const n=s[r];if(!n.comp||n.comp.destroyed||!n.main||n.comp.enabled===!1){q7&&console.log("Removing coroutine",n.comp,n.comp.enabled),s.splice(r,1),--r;continue}const o=n.chained;if(o&&o.length>0){const c=o[o.length-1].next();if(c.done&&o.pop(),t(c)&&(n.chained||(n.chained=[]),n.chained.push(c.value)),!c.done)continue}const a=n.main.next();if(a.done===!0){s.splice(r,1),--r;continue}const l=a.value;if(t(l)){if(l.next().done)continue;n.chained||(n.chained=[]),n.chained.push(l)}}catch(n){console.error(n)}}function t(s){return!!(s&&s.next&&s.return)}}}const J7=oe("debugaroverlay"),Wh="ar",LD="quit-ar";class K7{constructor(){h(this,"arContainer",null),h(this,"closeARCallback"),h(this,"currentSession",null),h(this,"registeredCloseEventElements",[]),h(this,"_createdAROnlyElements",[]),h(this,"_reparentedObjects",[]),this.closeARCallback=this.onRequestedEndAR.bind(this)}get ARContainer(){return this.arContainer}requestEndAR(){this.onRequestedEndAR()}onBegin(e,t,s){this.currentSession=s,this.arContainer=t,e.domElement.querySelectorAll(`.${Wh}`).forEach(n=>{var o;n&&n!==this.arContainer&&(this._reparentedObjects.push({el:n,previousParent:n.parentElement}),(o=this.arContainer)==null||o.appendChild(n))});const r=t.getElementsByClassName(LD);if(!r||r.length<=0)console.warn(`Missing quit AR elements, creating fallback X button. Use class name '${LD}' to override.`),this.createFallbackCloseARButton(this.arContainer);else for(let n=0;n<r.length;n++){const o=r[n];o&&(o.addEventListener("click",this.closeARCallback),this.registeredCloseEventElements.push(o))}}onEnd(e){var t;for(const s of this._createdAROnlyElements)s.remove&&s.remove();for(const s of this._reparentedObjects){const r=s.el;(t=s.previousParent)==null||t.appendChild(r)}this._reparentedObjects.length=0,nw()&&setTimeout(()=>{const s=e.renderer.domElement;s&&e.domElement.insertBefore(s,e.domElement.firstChild);const r=document.querySelectorAll("*");for(var n=0;n<r.length;n++){const o=r[n];o&&o._displayChanged!==void 0&&o._displayWas!==void 0&&(o.style.display=o._displayWas)}},10)}findOrCreateARContainer(e){if(e.classList.contains(Wh))return e;if(e.children)for(let r=0;r<e.children.length;r++){const n=e.children[r];if(!(!n||!n.classList)&&n.classList.contains(Wh))return n}const t=document.getElementsByClassName(Wh);if(t&&t.length>0)return t[0];J7&&console.log("No overlay container found in document - generating new ony");const s=document.createElement("div");return s.classList.add(Wh),s.style.position="absolute",s.style.width="100%",s.style.height="100%",s.style.display="flex",s.style.visibility="visible",e.appendChild(s)}onRequestedEndAR(){if(this.currentSession){this.currentSession.end(),this.currentSession=null;for(const e of this.registeredCloseEventElements)e.removeEventListener("click",this.closeARCallback);this.registeredCloseEventElements.length=0}}createFallbackCloseARButton(e){var t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("width","38px"),t.setAttribute("height","38px"),t.style.position="absolute",t.style.right="20px",t.style.top="40px",t.style.zIndex="9999",t.style.pointerEvents="auto",t.addEventListener("click",this.closeARCallback),e.appendChild(t),this._createdAROnlyElements.push(t);var s=document.createElementNS("http://www.w3.org/2000/svg","path");s.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),s.setAttribute("stroke","#ddd"),s.setAttribute("stroke-width","3px"),t.appendChild(s),this._createdAROnlyElements.push(s)}}class $ extends Me{constructor(){super(...arguments),h(this,"guid")}static isDestroyed(e){return eC(e)}static setActive(e,t,s=!0){e&&(Ag(e,t),oy(e),t&&s&&G2(_t.Current,e))}static isActiveSelf(e){return Sd(e)}static isActiveInHierarchy(e){return O2(e)}static markAsInstancedRendered(e,t){L2(e,t)}static isUsingInstancing(e){return ry(e)}static foreachComponent(e,t,s=!0){return Hh(e,t,s)}static instantiateSynced(e,t){return e?Y1(e,t):null}static instantiate(e,t=null){return bg(e,t)}static destroySynced(e,t,s=!0){if(!e)return;const r=e;t=t??_t.Current,Y0(r,t.connection,s)}static destroy(e,t=!0,s=!0){return $a(e,t,s)}static add(e,t,s){if(!(!e||!t)){if(e===t){console.warn("Can not add object to self",e);return}s||(s=_t.Current),t.add(e),Ag(e,!0),oy(e),s?$.foreachComponent(e,r=>{iC(r,s),!r.__internalDidAwakeAndStart&&s.new_script_start.includes(r)===!1&&s.new_script_start.push(r)},!0):console.warn("Missing context")}}static remove(e){var t;e&&((t=e.parent)==null||t.remove(e),Ag(e,!1),oy(e),$.foreachComponent(e,s=>{S9(s)},!0))}static invokeOnChildren(e,t,...s){this.invoke(e,t,!0,s)}static invoke(e,t,s=!1,...r){e&&this.foreachComponent(e,n=>{const o=n[t];o&&typeof o=="function"&&o?.call(n,...r)},s)}static addNewComponent(e,t,s=!0){const r=new t;return Gh(e,r,s),r}static addComponent(e,t){return this.moveComponent(e,t)}static moveComponent(e,t){return Z1(e,t)}static removeComponent(e){return K1(e.gameObject,e),e}static getOrAddComponent(e,t){return K0(e,t)}static getComponent(e,t){return e===null?null:xd(e,t)}static getComponents(e,t,s=null){return e===null?s??[]:dg(e,t,s)}static findByGuid(e,t){return yg(e,t)}static findObjectOfType(e,t,s=!0){return C2(e,t??_t.Current,s)}static findObjectsOfType(e,t){const s=[];return S2(e,s,t),s}static getComponentInChildren(e,t){return Cd(e,t)}static getComponentsInChildren(e,t,s=null){return pg(e,t,s??void 0)}static getComponentInParent(e,t){return fg(e,t)}static getComponentsInParent(e,t,s=null){return Z0(e,t,s)}static getAllComponents(e){var t;return[...(t=e.userData)==null?void 0:t.components]}static*iterateComponents(e){var t;const s=(t=e?.userData)==null?void 0:t.components;if(s&&Array.isArray(s))for(let r=0;r<s.length;r++)yield s[r]}}var ns;let vc=(ns=class{constructor(){h(this,"__context"),h(this,"__name"),h(this,"gameObject"),h(this,"guid","invalid"),h(this,"sourceId"),h(this,"__didAwake",!1),h(this,"__didStart",!1),h(this,"__didEnable",!1),h(this,"__isEnabled"),h(this,"__destroyed",!1),h(this,"_worldPosition"),h(this,"_worldQuaternion"),h(this,"_worldEuler"),h(this,"_worldRotation"),h(this,"_eventListeners",new Map),this.__internalNewInstanceCreated()}get isComponent(){return!0}get context(){return this.__context??_t.Current}set context(i){this.__context=i}get scene(){return this.context.scene}get layer(){var i,e;return(e=(i=this.gameObject)==null?void 0:i.userData)==null?void 0:e.layer}get name(){var i,e;return(i=this.gameObject)!=null&&i.name?this.gameObject.name:(e=this.gameObject)==null?void 0:e.userData.name}set name(i){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=i,this.__name=i):this.__name=i}get tag(){var i;return(i=this.gameObject)==null?void 0:i.userData.tag}set tag(i){this.gameObject&&(this.gameObject.userData.tag=i)}get static(){var i;return(i=this.gameObject)==null?void 0:i.userData.static}get hideFlags(){var i;return(i=this.gameObject)==null?void 0:i.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 i=this.gameObject[Za];return i===void 0?!0:i}set __isActiveInHierarchy(i){this.gameObject&&(this.gameObject[Za]=i)}awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(i,e=dn.Update){return this.context.registerCoroutineUpdate(this,i,e)}stopCoroutine(i,e=dn.Update){this.context.unregisterCoroutineUpdate(i,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(i){return this.__destroyed?(_r()&&console.warn("[Needle Engine Dev] Trying to enable destroyed component"),!1):this.__didAwake?this.__didEnable?(i!==!0&&(this.__isEnabled=!0),!1):(this.__didEnable=!0,this.__isEnabled=!0,this.onEnable(),!0):!1}__internalDisable(i){if(this.__didAwake){if(!this.__didEnable){i!==!0&&(this.__isEnabled=!1);return}this.__didEnable=!1,this.__isEnabled=!1,this.onDisable()}}__internalDestroy(){var i;this.__destroyed||(this.__destroyed=!0,(i=this.destroy)==null||i.call(this),this.dispatchEvent(new CustomEvent("destroyed",{detail:this})),_2(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(i){if(this.__destroyed){_r()&&console.warn(`[Needle Engine Dev] Trying to ${i?"enable":"disable"} destroyed component`);return}if(typeof i=="number"&&(i>=.5?i=!0:i=!1),!this.__didAwake){this.__isEnabled=i;return}i?this.__internalEnable():this.__internalDisable()}get worldPosition(){return this._worldPosition||(this._worldPosition=new S),wt(this.gameObject,this._worldPosition),this._worldPosition}set worldPosition(i){Yi(this.gameObject,i)}setWorldPosition(i,e,t){ns._worldPositionBuffer.set(i,e,t),this.worldPosition=ns._worldPositionBuffer}get worldQuaternion(){return this._worldQuaternion||(this._worldQuaternion=new xe),ws(this.gameObject,this._worldQuaternion)}set worldQuaternion(i){Nr(this.gameObject,i)}setWorldQuaternion(i,e,t,s){ns._worldQuaternionBuffer.set(i,e,t,s),this.worldQuaternion=ns._worldQuaternionBuffer}get worldEuler(){return this._worldEuler||(this._worldEuler=new fs),this._worldEuler.setFromQuaternion(this.worldQuaternion),this._worldEuler}set worldEuler(i){var e;this._worldQuaternion||(this._worldQuaternion=new xe),(e=this._worldQuaternion)==null||e.setFromEuler(i),this.worldQuaternion=this._worldQuaternion}get worldRotation(){const i=this.worldEuler;this._worldRotation||(this._worldRotation=new S);const e=this._worldRotation;return e.set(i.x,i.y,i.z),e.x=Je.toDegrees(e.x),e.y=Je.toDegrees(e.y),e.z=Je.toDegrees(e.z),e}set worldRotation(i){this.setWorldRotation(i.x,i.y,i.z,!0)}setWorldRotation(i,e,t,s=!0){s&&(i=Je.toRadians(i),e=Je.toRadians(e),t=Je.toRadians(t)),ns._worldEulerBuffer.set(i,e,t),ns._worldQuaternionBuffer.setFromEuler(ns._worldEulerBuffer),this.worldQuaternion=ns._worldQuaternionBuffer}get forward(){return ns._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}get right(){return ns._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}get up(){return ns._up.set(0,1,0).applyQuaternion(this.worldQuaternion)}addEventListener(i,e){this._eventListeners[i]=this._eventListeners[i]||[],this._eventListeners[i].push(e)}removeEventListener(i,e){if(!this._eventListeners[i])return;const t=this._eventListeners[i].indexOf(e);t>=0&&this._eventListeners[i].splice(t,1)}dispatchEvent(i){if(!this._eventListeners[i.type])return!1;const e=this._eventListeners[i.type];for(let t=0;t<e.length;t++)e[t](i);return!1}},h(ns,"_worldPositionBuffer",new S),h(ns,"_worldQuaternionBuffer",new xe),h(ns,"_worldEulerBuffer",new fs),h(ns,"_tempQuaternionBuffer2",new xe),h(ns,"_forward",new S),h(ns,"_right",new S),h(ns,"_up",new S),ns);class Ee extends vc{}const Z7=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:Ee,Component:vc,GameObject:$},Symbol.toStringTag,{value:"Module"})),$7='<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>',eq=new Blob([$7],{type:"image/svg+xml;charset=utf-8"}),tq=URL.createObjectURL(eq),FD=tq,qh=oe("debuglicense"),_C="basic";qh&&console.log("License Type: "+_C);function Ac(){switch(_C){case"pro":case"enterprise":return!0}return!1}function UD(){switch(_C){case"indie":return!0}return!1}function ND(){return Ac()||UD()}Gi.registerCallback(Cn.ContextRegistered,i=>{iq(i.context)});async function iq(i){try{if(Ac()!==!0)return CC(i)}catch(e){return qh&&console.log("License check failed",e),CC(i)}qh&&CC(i)}const zD="needle-license-element",wC=5e3,xC=200;function CC(i){rq(),i.domElement.addEventListener("ready",()=>{setTimeout(()=>{sq(i)},1e3)}),aq()}function sq(i){const e=nq(),t=oq(),s=setInterval(()=>{if(!e)return;const l=i.domElement.shadowRoot||i.domElement;e.parentNode!==l&&(l.appendChild(e),t&&l.appendChild(t))},100);let r=`<img class="logo" src="${FD}" style="width: 40px; height: 40px; margin-right: 2px; vertical-align: middle; margin-bottom: 2px;"/>`;const n=document.createElement("div");n.innerHTML=r,n.classList.add("logo"),e.appendChild(n);const o=document.createElement("div");o.classList.add("text"),e.appendChild(o),e.title="Needle Engine",ND()||(e.title+=" non commercial version"),e.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")});const a=wC+xC;setTimeout(()=>{clearInterval(s),e?.remove(),t?.remove()},a)}let QD=0;async function rq(i){const e=Date.now();if(e-QD<2e3)return;QD=e,console.log("%c Needle Engine \u2014 non commercial version",`
|
|
3836
|
+
#endif`),Xe.lightmap.lightmapScaleOffset={value:new it(1,1,0,0)};const G7=oe("debugplayerview");var Vo=(i=>(i.Browser="browser",i.Headset="headset",i.Handheld="handheld",i))(Vo||{});class DD{constructor(e,t){h(this,"userId"),h(this,"context"),h(this,"viewDevice","browser"),h(this,"removed",!1),h(this,"_object"),this.userId=e,this.context=t}get currentObject(){return this._object}set currentObject(e){this._object=e}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class OD{constructor(e){h(this,"context"),h(this,"playerViews",new Map),this.context=e}setPlayerView(e,t,s){let r=this.playerViews.get(e);r||(r=new DD(e,this.context),this.playerViews.set(e,r)),r.viewDevice=s,r.currentObject=t,r.removed=!1}getPlayerView(e){if(!!e){if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}}removePlayerView(e,t){const s=this.playerViews.get(e);s?.viewDevice===t&&(G7&&console.log("REMOVE",e),s.removed=!0,this.playerViews.delete(e))}}const bC=oe("debugSetup"),H7=oe("stats"),V7=oe("debugactive"),W7=oe("debugframerate"),q7=oe("debugcoroutine"),X7={};class Y7{constructor(e){h(this,"name"),h(this,"alias"),h(this,"domElement"),h(this,"renderer"),h(this,"hash"),this.domElement=e??document.body}}var dn=(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))(dn||{}),Eg=(i=>(i.ImmersiveVR="immersive-vr",i.ImmersiveAR="immersive-ar",i))(Eg||{});function yy(i,e){if(!i)return;const t=e?.new_scripts??_t.Current.new_scripts;t.includes(i)||t.push(i)}class _t{constructor(e){h(this,"name"),h(this,"alias"),h(this,"isManagedExternally",!1),h(this,"isPaused",!1),h(this,"runInBackground",!1),h(this,"targetFrameRate"),h(this,"hash"),h(this,"domElement"),h(this,"_resolutionScaleFactor",1),h(this,"_boundingClientRectFrame",-1),h(this,"_boundingClientRect",null),h(this,"_domX"),h(this,"_domY"),h(this,"xrSessionMode"),h(this,"_xrFrame",null),h(this,"_currentFrameEvent",-1),h(this,"scene"),h(this,"renderer"),h(this,"composer",null),h(this,"scripts",[]),h(this,"scripts_pausedChanged",[]),h(this,"scripts_earlyUpdate",[]),h(this,"scripts_update",[]),h(this,"scripts_lateUpdate",[]),h(this,"scripts_onBeforeRender",[]),h(this,"scripts_onAfterRender",[]),h(this,"scripts_WithCorroutines",[]),h(this,"coroutines",{}),h(this,"mainCameraComponent"),h(this,"post_setup_callbacks",[]),h(this,"pre_update_callbacks",[]),h(this,"pre_render_callbacks",[]),h(this,"post_render_callbacks",[]),h(this,"new_scripts",[]),h(this,"new_script_start",[]),h(this,"new_scripts_pre_setup_callbacks",[]),h(this,"new_scripts_post_setup_callbacks",[]),h(this,"application"),h(this,"time"),h(this,"input"),h(this,"physics"),h(this,"connection"),h(this,"assets"),h(this,"mainLight",null),h(this,"sceneLighting"),h(this,"addressables"),h(this,"lightmaps"),h(this,"players"),h(this,"_sizeChanged",!1),h(this,"_isCreated",!1),h(this,"_isCreating",!1),h(this,"_isVisible",!1),h(this,"_stats",H7?E7():null),h(this,"_intersectionObserver",null),h(this,"_disposeCallbacks",[]),h(this,"_cameraStack",[]),h(this,"_onBeforeRenderListeners",new Map),h(this,"_onAfterRenderListeners",new Map),h(this,"_requireDepthTexture",!1),h(this,"_requireColorTexture",!1),h(this,"_renderTarget"),h(this,"_isRendering",!1),h(this,"_accumulatedTime",0),h(this,"_framerateClock",new a0),h(this,"_dispatchReadyAfterFrame",!1),h(this,"_wasPaused",!1);var t,s;if(this.name=e?.name||"",this.alias=e?.alias,this.domElement=e?.domElement||document.body,this.hash=e?.hash,e!=null&&e.renderer)this.renderer=e.renderer,this.isManagedExternally=!0;else{const o={antialias:!0},a=(s=(t=e?.domElement)==null?void 0:t.shadowRoot)==null?void 0:s.querySelector("canvas");a&&(o.canvas=a),this.renderer=new ad(o),this.renderer.toneMappingExposure=1,this.renderer.toneMapping=vr,this.renderer.setClearColor(new _e("lightgrey"),0),this.renderer.antialias=!0,this.renderer.alpha=!1,this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=dw,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputEncoding=yt,this.renderer.physicallyCorrectLights=!0}this.scene=new an,Gi.register(this),this.application=new PD(this),this.time=new FB,this.input=new _B(this),this.physics=new OB(this),this.connection=new o2(this),this.assets=new T2,this.sceneLighting=new TD(this),this.addressables=new MD(this),this.lightmaps=new j7(this),this.players=new OD(this);const r=()=>this._sizeChanged=!0;window.addEventListener("resize",r),this._disposeCallbacks.push(()=>window.removeEventListener("resize",r));const n=new ResizeObserver(o=>this._sizeChanged=!0);n.observe(this.domElement),this._disposeCallbacks.push(()=>n.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 a2}static get Current(){return Gi.Current}static set Current(e){Gi.Current=e}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(e){if(e!==this._resolutionScaleFactor&&typeof e=="number"){if(e<=0){console.error("Invalid resolution scale factor",e);return}this._resolutionScaleFactor=e,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 e;return((e=this.renderer.xr)==null?void 0:e.isPresenting)||!1}get isInVR(){return this.xrSessionMode==="immersive-vr"}get isInAR(){return this.xrSessionMode==="immersive-ar"}get xrSession(){var e;return(e=this.renderer.xr)==null?void 0:e.getSession()}get xrFrame(){return this._xrFrame}get arOverlayElement(){const e=this.domElement;return typeof e.getAROverlayContainer=="function"?e.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}get mainCamera(){if(this.mainCameraComponent){const e=this.mainCameraComponent;return e.cam||e.buildCamera(),e.cam}return null}get rendererData(){return this.sceneLighting}get isCreated(){return this._isCreated}internalOnUpdateVisible(){var e,t;(e=this._intersectionObserver)==null||e.disconnect(),(t=this._intersectionObserver)==null||t.observe(this.domElement)}updateSize(){var e,t,s;if(!this.isManagedExternally&&((e=this.renderer.xr)==null?void 0:e.isPresenting)===!1){this._sizeChanged=!1;const r=this.resolutionScaleFactor,n=this.domWidth*r,o=this.domHeight*r,a=this.mainCamera;this.updateAspect(a),this.renderer.setSize(n,o),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.composer&&((t=this.composer.setSize)==null||t.call(this.composer,n,o),"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&((s=this.composer.setPixelRatio)==null||s.call(this.composer,window.devicePixelRatio)))}}updateAspect(e,t,s){if(!e)return;t===void 0&&(t=this.domWidth),s===void 0&&(s=this.domHeight);const r=e.aspect;e.aspect=t/s,r!==e.aspect&&e.updateProjectionMatrix()}async onCreate(e,t){try{return this._isCreating=!0,await this.internalOnCreate(e,t)}finally{this._isCreating=!1}}clear(){var e;(e=this.scene)!=null&&e.children.length&&($a(this.scene,!0,!0),this.scene=new an),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear())}dispose(){this.internalOnDestroy()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){var e,t,s;this.clear(),(e=this.renderer)==null||e.setAnimationLoop(null),this.isManagedExternally||(t=this.renderer)==null||t.dispose();for(const r of this._disposeCallbacks)try{r()}catch(n){console.error("Error in on dispose callback:",n,r)}(s=this.domElement)!=null&&s.parentElement&&this.domElement.parentElement.removeChild(this.domElement),Gi.dispatchCallback(Cn.ContextDestroyed,this),Gi.unregister(this)}registerCoroutineUpdate(e,t,s){return this.coroutines[s]||(this.coroutines[s]=[]),this.coroutines[s].push({comp:e,main:t}),t}unregisterCoroutineUpdate(e,t){if(!this.coroutines[t])return;const s=this.coroutines[t].findIndex(r=>r.main===e);s>=0&&this.coroutines[t].splice(s,1)}stopAllCoroutinesFrom(e){for(const t in this.coroutines){const s=this.coroutines[t];for(let r=s.length-1;r>=0;r--)s[r].comp===e&&s.splice(r,1)}}setCurrentCamera(e){var t;if(!e)return;if(e.cam||e.buildCamera(),!e.cam){console.warn("Camera component is missing camera",e);return}const s=this._cameraStack.indexOf(e);s>=0&&this._cameraStack.splice(s,1),this._cameraStack.push(e),this.mainCameraComponent=e;const r=e.cam;r.isPerspectiveCamera&&this.updateAspect(r),(t=this.mainCameraComponent)==null||t.applyClearFlagsIfIsActiveCamera()}removeCamera(e){if(!e)return;const t=this._cameraStack.indexOf(e);if(t>=0&&this._cameraStack.splice(t,1),this.mainCameraComponent===e&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){const s=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(s)}}addBeforeRenderListener(e,t){var s;this._onBeforeRenderListeners.has(e.uuid)||(this._onBeforeRenderListeners.set(e.uuid,[]),e.onBeforeRender=this._createRenderCallbackWrapper(e,this._onBeforeRenderListeners)),(s=this._onBeforeRenderListeners.get(e.uuid))==null||s.push(t)}removeBeforeRenderListener(e,t){if(this._onBeforeRenderListeners.has(e.uuid)){const s=this._onBeforeRenderListeners.get(e.uuid),r=s.indexOf(t);r>=0&&s.splice(r,1)}}addAfterRenderListener(e,t){var s;this._onAfterRenderListeners.has(e.uuid)||(this._onAfterRenderListeners.set(e.uuid,[]),e.onAfterRender=this._createRenderCallbackWrapper(e,this._onAfterRenderListeners)),(s=this._onAfterRenderListeners.get(e.uuid))==null||s.push(t)}removeAfterRenderListener(e,t){if(this._onAfterRenderListeners.has(e.uuid)){const s=this._onAfterRenderListeners.get(e.uuid),r=s.indexOf(t);r>=0&&s.splice(r,1)}}_createRenderCallbackWrapper(e,t){return(s,r,n,o,a,l)=>{const c=t.get(e.uuid);if(c)for(let u=0;u<c.length;u++){const d=c[u];d(s,r,n,o,a,l)}}}get isRendering(){return this._isRendering}setRequireDepth(e){this._requireDepthTexture=e}setRequireColor(e){this._requireColorTexture=e}get depthTexture(){var e;return((e=this._renderTarget)==null?void 0:e.depthTexture)||null}get opaqueColorTexture(){var e;return((e=this._renderTarget)==null?void 0:e.texture)||null}get isVisibleToUser(){if(this.isInXR)return!0;if(!this._isVisible)return!1;const e=getComputedStyle(this.domElement);return e.visibility!=="hidden"&&e.display!=="none"&&e.opacity!=="0"}async internalOnCreate(e,t){var s;this.clear(),(s=this.renderer)==null||s.setAnimationLoop(null),await pf(1),_t.Current=this,await Gi.dispatchCallback(Cn.ContextCreationStart,this);let r=!0;try{_t.Current=this,e&&await e(this,t)}catch(n){console.error(n),r=!1}if(!r)return!1;this.internalOnUpdateVisible(),!this.isManagedExternally&&!this.domElement.shadowRoot&&this.domElement.prepend(this.renderer.domElement),_t.Current=this,_t.Current=this;for(let n=0;n<this.new_scripts.length;n++){const o=this.new_scripts[n];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 a=o.gameObject.userData.components;a.includes(o)||a.push(o)}}if(this.post_setup_callbacks)for(let n=0;n<this.post_setup_callbacks.length;n++)_t.Current=this,await this.post_setup_callbacks[n](this);if(!this.mainCamera){_t.Current=this;let n=null;Hh(this.scene,o=>{const a=o;if(a!=null&&a.isCamera){if(_g(a.gameObject),!a.activeAndEnabled)return;if(a.tag==="MainCamera")return n=a,!0;n=a}}),n?this.setCurrentCamera(n):!Gi.dispatchCallback(Cn.MissingCamera,this)&&!this.mainCamera&&!this.isManagedExternally&&console.warn("Missing camera in main scene",this)}if(_t.Current=this,ny(this),!this.isManagedExternally&&this.composer&&this.mainCamera){const n=new py(this.scene,this.mainCamera);this.renderer.setSize(this.domWidth,this.domHeight),this.composer.addPass(n),this.composer.setSize(this.domWidth,this.domHeight)}return this._sizeChanged=!0,this._stats&&(this._stats.showPanel(1),this.domElement.appendChild(this._stats.dom)),bC&&S0(this.scene,!0),this._isCreating=!1,this.restartRenderLoop(),this._dispatchReadyAfterFrame=!0,Gi.dispatchCallback(Cn.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 e=this.render.bind(this);return this.renderer.setAnimationLoop(e),!0}render(e,t){if(_r()||bC||C9())try{this.internalRender(e,t)}catch(s){(_r()||bC)&&s instanceof Error&&Rs("Exception during render-loop.<br/>See console for details.",so.Error),console.error(s),console.warn("Stopping render loop due to error"),this.renderer.setAnimationLoop(null),this.domElement.dispatchEvent(new CustomEvent("error",{detail:s}))}else this.internalRender(e,t)}internalRender(e,t){var s,r;if(this._xrFrame=t,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((s=this._stats)==null||s.begin(),_t.Current=this,!this.onHandlePaused()){for(_t.Current=this,this.time.update(),W7&&console.log("FPS",this.time.smoothedFps.toFixed(0)),ny(this),oy(this.scene),G2(this);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const n=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(n)}if(this.pre_update_callbacks)for(const n in this.pre_update_callbacks)this.pre_update_callbacks[n]();this._currentFrameEvent=0;for(let n=0;n<this.scripts_earlyUpdate.length;n++){const o=this.scripts_earlyUpdate[n];o.activeAndEnabled&&o.earlyUpdate!==void 0&&(_t.Current=this,o.earlyUpdate())}if(this.executeCoroutines(0),!this.onHandlePaused()){this._currentFrameEvent=1;for(let n=0;n<this.scripts_update.length;n++){const o=this.scripts_update[n];o.activeAndEnabled&&o.update!==void 0&&(_t.Current=this,o.update())}if(this.executeCoroutines(1),!this.onHandlePaused()){this._currentFrameEvent=2;for(let n=0;n<this.scripts_lateUpdate.length;n++){const o=this.scripts_lateUpdate[n];o.activeAndEnabled&&o.lateUpdate!==void 0&&(_t.Current=this,o.lateUpdate())}if(this.executeCoroutines(2),!this.onHandlePaused()){if(this.physics.engine){const n=this.time.deltaTime/1;for(let o=0;o<1;o++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.engine.step(n),this._currentFrameEvent=10,this.executeCoroutines(10);this.physics.engine.postStep()}if(!this.onHandlePaused()){if(this.isVisibleToUser){this._currentFrameEvent=3;for(let n=0;n<this.scripts_onBeforeRender.length;n++){const o=this.scripts_onBeforeRender[n];o.activeAndEnabled&&o.onBeforeRender!==void 0&&(_t.Current=this,o.onBeforeRender(t))}if(this.executeCoroutines(3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(const n in this.pre_render_callbacks)this.pre_render_callbacks[n]();this.isManagedExternally||(M9(this),this._currentFrameEvent=-1,this.renderNow(),this._currentFrameEvent=4);for(let n=0;n<this.scripts_onAfterRender.length;n++){const o=this.scripts_onAfterRender[n];o.activeAndEnabled&&o.onAfterRender!==void 0&&(_t.Current=this,o.onAfterRender())}if(this.executeCoroutines(4),this.post_render_callbacks)for(const n in this.post_render_callbacks)this.post_render_callbacks[n]()}this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),(r=this._stats)==null||r.end(),this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")))}}}}}}renderNow(e){return!e&&(e=this.mainCamera,!e)?!1:(this._isRendering=!0,this.renderRequiredTextures(),this.composer&&!this.isInXR?this.composer.render(this.time.deltaTime):e&&this.renderer.render(this.scene,e),this._isRendering=!1,!0)}onHandlePaused(){const e=this.evaluatePaused();if(this._wasPaused!==e){V7&&console.log("Paused?",e,"context:"+this.alias);for(let t=0;t<this.scripts_pausedChanged.length;t++){const s=this.scripts_pausedChanged[t];s.activeAndEnabled&&s.onPausedChanged!==void 0&&(_t.Current=this,s.onPausedChanged(e,this._wasPaused))}}return this._wasPaused=e,e}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 ri(this.domWidth,this.domHeight),this._requireDepthTexture){const s=new DA(this.domWidth,this.domHeight);this._renderTarget.depthTexture=s}this._requireColorTexture&&(this._renderTarget.texture=new Nt,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=Zt,this._renderTarget.texture.magFilter=Zt,this._renderTarget.texture.format=wi)}const e=this._renderTarget;e.texture&&(e.texture.encoding=this.renderer.outputEncoding);const t=this.renderer.getRenderTarget();this.renderer.setRenderTarget(e),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(t)}executeCoroutines(e){if(this.coroutines[e]){const s=this.coroutines[e];for(let r=0;r<s.length;r++)try{const n=s[r];if(!n.comp||n.comp.destroyed||!n.main||n.comp.enabled===!1){q7&&console.log("Removing coroutine",n.comp,n.comp.enabled),s.splice(r,1),--r;continue}const o=n.chained;if(o&&o.length>0){const c=o[o.length-1].next();if(c.done&&o.pop(),t(c)&&(n.chained||(n.chained=[]),n.chained.push(c.value)),!c.done)continue}const a=n.main.next();if(a.done===!0){s.splice(r,1),--r;continue}const l=a.value;if(t(l)){if(l.next().done)continue;n.chained||(n.chained=[]),n.chained.push(l)}}catch(n){console.error(n)}}function t(s){return!!(s&&s.next&&s.return)}}}const J7=oe("debugaroverlay"),Wh="ar",LD="quit-ar";class K7{constructor(){h(this,"arContainer",null),h(this,"closeARCallback"),h(this,"currentSession",null),h(this,"registeredCloseEventElements",[]),h(this,"_createdAROnlyElements",[]),h(this,"_reparentedObjects",[]),this.closeARCallback=this.onRequestedEndAR.bind(this)}get ARContainer(){return this.arContainer}requestEndAR(){this.onRequestedEndAR()}onBegin(e,t,s){this.currentSession=s,this.arContainer=t,e.domElement.querySelectorAll(`.${Wh}`).forEach(n=>{var o;n&&n!==this.arContainer&&(this._reparentedObjects.push({el:n,previousParent:n.parentElement}),(o=this.arContainer)==null||o.appendChild(n))});const r=t.getElementsByClassName(LD);if(!r||r.length<=0)console.warn(`Missing quit AR elements, creating fallback X button. Use class name '${LD}' to override.`),this.createFallbackCloseARButton(this.arContainer);else for(let n=0;n<r.length;n++){const o=r[n];o&&(o.addEventListener("click",this.closeARCallback),this.registeredCloseEventElements.push(o))}}onEnd(e){var t;for(const s of this._createdAROnlyElements)s.remove&&s.remove();for(const s of this._reparentedObjects){const r=s.el;(t=s.previousParent)==null||t.appendChild(r)}this._reparentedObjects.length=0,nw()&&setTimeout(()=>{const s=e.renderer.domElement;s&&e.domElement.insertBefore(s,e.domElement.firstChild);const r=document.querySelectorAll("*");for(var n=0;n<r.length;n++){const o=r[n];o&&o._displayChanged!==void 0&&o._displayWas!==void 0&&(o.style.display=o._displayWas)}},10)}findOrCreateARContainer(e){if(e.classList.contains(Wh))return e;if(e.children)for(let r=0;r<e.children.length;r++){const n=e.children[r];if(!(!n||!n.classList)&&n.classList.contains(Wh))return n}const t=document.getElementsByClassName(Wh);if(t&&t.length>0)return t[0];J7&&console.log("No overlay container found in document - generating new ony");const s=document.createElement("div");return s.classList.add(Wh),s.style.position="absolute",s.style.width="100%",s.style.height="100%",s.style.display="flex",s.style.visibility="visible",e.appendChild(s)}onRequestedEndAR(){if(this.currentSession){this.currentSession.end(),this.currentSession=null;for(const e of this.registeredCloseEventElements)e.removeEventListener("click",this.closeARCallback);this.registeredCloseEventElements.length=0}}createFallbackCloseARButton(e){var t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("width","38px"),t.setAttribute("height","38px"),t.style.position="absolute",t.style.right="20px",t.style.top="40px",t.style.zIndex="9999",t.style.pointerEvents="auto",t.addEventListener("click",this.closeARCallback),e.appendChild(t),this._createdAROnlyElements.push(t);var s=document.createElementNS("http://www.w3.org/2000/svg","path");s.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),s.setAttribute("stroke","#ddd"),s.setAttribute("stroke-width","3px"),t.appendChild(s),this._createdAROnlyElements.push(s)}}class $ extends Me{constructor(){super(...arguments),h(this,"guid")}static isDestroyed(e){return eC(e)}static setActive(e,t,s=!0){e&&(Ag(e,t),oy(e),t&&s&&G2(_t.Current,e))}static isActiveSelf(e){return Sd(e)}static isActiveInHierarchy(e){return O2(e)}static markAsInstancedRendered(e,t){L2(e,t)}static isUsingInstancing(e){return ry(e)}static foreachComponent(e,t,s=!0){return Hh(e,t,s)}static instantiateSynced(e,t){return e?Y1(e,t):null}static instantiate(e,t=null){return bg(e,t)}static destroySynced(e,t,s=!0){if(!e)return;const r=e;t=t??_t.Current,Y0(r,t.connection,s)}static destroy(e,t=!0,s=!0){return $a(e,t,s)}static add(e,t,s){if(!(!e||!t)){if(e===t){console.warn("Can not add object to self",e);return}s||(s=_t.Current),t.add(e),Ag(e,!0),oy(e),s?$.foreachComponent(e,r=>{iC(r,s),!r.__internalDidAwakeAndStart&&s.new_script_start.includes(r)===!1&&s.new_script_start.push(r)},!0):console.warn("Missing context")}}static remove(e){var t;e&&((t=e.parent)==null||t.remove(e),Ag(e,!1),oy(e),$.foreachComponent(e,s=>{S9(s)},!0))}static invokeOnChildren(e,t,...s){this.invoke(e,t,!0,s)}static invoke(e,t,s=!1,...r){e&&this.foreachComponent(e,n=>{const o=n[t];o&&typeof o=="function"&&o?.call(n,...r)},s)}static addNewComponent(e,t,s=!0){const r=new t;return Gh(e,r,s),r}static addComponent(e,t){return this.moveComponent(e,t)}static moveComponent(e,t){return Z1(e,t)}static removeComponent(e){return K1(e.gameObject,e),e}static getOrAddComponent(e,t){return K0(e,t)}static getComponent(e,t){return e===null?null:xd(e,t)}static getComponents(e,t,s=null){return e===null?s??[]:dg(e,t,s)}static findByGuid(e,t){return yg(e,t)}static findObjectOfType(e,t,s=!0){return C2(e,t??_t.Current,s)}static findObjectsOfType(e,t){const s=[];return S2(e,s,t),s}static getComponentInChildren(e,t){return Cd(e,t)}static getComponentsInChildren(e,t,s=null){return pg(e,t,s??void 0)}static getComponentInParent(e,t){return fg(e,t)}static getComponentsInParent(e,t,s=null){return Z0(e,t,s)}static getAllComponents(e){var t;return[...(t=e.userData)==null?void 0:t.components]}static*iterateComponents(e){var t;const s=(t=e?.userData)==null?void 0:t.components;if(s&&Array.isArray(s))for(let r=0;r<s.length;r++)yield s[r]}}var ns;let vc=(ns=class{constructor(){h(this,"__context"),h(this,"__name"),h(this,"gameObject"),h(this,"guid","invalid"),h(this,"sourceId"),h(this,"__didAwake",!1),h(this,"__didStart",!1),h(this,"__didEnable",!1),h(this,"__isEnabled"),h(this,"__destroyed",!1),h(this,"_worldPosition"),h(this,"_worldQuaternion"),h(this,"_worldEuler"),h(this,"_worldRotation"),h(this,"_eventListeners",new Map),this.__internalNewInstanceCreated()}get isComponent(){return!0}get context(){return this.__context??_t.Current}set context(i){this.__context=i}get scene(){return this.context.scene}get layer(){var i,e;return(e=(i=this.gameObject)==null?void 0:i.userData)==null?void 0:e.layer}get name(){var i,e;return(i=this.gameObject)!=null&&i.name?this.gameObject.name:(e=this.gameObject)==null?void 0:e.userData.name}set name(i){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=i,this.__name=i):this.__name=i}get tag(){var i;return(i=this.gameObject)==null?void 0:i.userData.tag}set tag(i){this.gameObject&&(this.gameObject.userData.tag=i)}get static(){var i;return(i=this.gameObject)==null?void 0:i.userData.static}get hideFlags(){var i;return(i=this.gameObject)==null?void 0:i.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 i=this.gameObject[Za];return i===void 0?!0:i}set __isActiveInHierarchy(i){this.gameObject&&(this.gameObject[Za]=i)}awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(i,e=dn.Update){return this.context.registerCoroutineUpdate(this,i,e)}stopCoroutine(i,e=dn.Update){this.context.unregisterCoroutineUpdate(i,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(i){return this.__destroyed?(_r()&&console.warn("[Needle Engine Dev] Trying to enable destroyed component"),!1):this.__didAwake?this.__didEnable?(i!==!0&&(this.__isEnabled=!0),!1):(this.__didEnable=!0,this.__isEnabled=!0,this.onEnable(),!0):!1}__internalDisable(i){if(this.__didAwake){if(!this.__didEnable){i!==!0&&(this.__isEnabled=!1);return}this.__didEnable=!1,this.__isEnabled=!1,this.onDisable()}}__internalDestroy(){var i;this.__destroyed||(this.__destroyed=!0,(i=this.destroy)==null||i.call(this),this.dispatchEvent(new CustomEvent("destroyed",{detail:this})),_2(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(i){if(this.__destroyed){_r()&&console.warn(`[Needle Engine Dev] Trying to ${i?"enable":"disable"} destroyed component`);return}if(typeof i=="number"&&(i>=.5?i=!0:i=!1),!this.__didAwake){this.__isEnabled=i;return}i?this.__internalEnable():this.__internalDisable()}get worldPosition(){return this._worldPosition||(this._worldPosition=new S),wt(this.gameObject,this._worldPosition),this._worldPosition}set worldPosition(i){Yi(this.gameObject,i)}setWorldPosition(i,e,t){ns._worldPositionBuffer.set(i,e,t),this.worldPosition=ns._worldPositionBuffer}get worldQuaternion(){return this._worldQuaternion||(this._worldQuaternion=new xe),ws(this.gameObject,this._worldQuaternion)}set worldQuaternion(i){Nr(this.gameObject,i)}setWorldQuaternion(i,e,t,s){ns._worldQuaternionBuffer.set(i,e,t,s),this.worldQuaternion=ns._worldQuaternionBuffer}get worldEuler(){return this._worldEuler||(this._worldEuler=new fs),this._worldEuler.setFromQuaternion(this.worldQuaternion),this._worldEuler}set worldEuler(i){var e;this._worldQuaternion||(this._worldQuaternion=new xe),(e=this._worldQuaternion)==null||e.setFromEuler(i),this.worldQuaternion=this._worldQuaternion}get worldRotation(){const i=this.worldEuler;this._worldRotation||(this._worldRotation=new S);const e=this._worldRotation;return e.set(i.x,i.y,i.z),e.x=Je.toDegrees(e.x),e.y=Je.toDegrees(e.y),e.z=Je.toDegrees(e.z),e}set worldRotation(i){this.setWorldRotation(i.x,i.y,i.z,!0)}setWorldRotation(i,e,t,s=!0){s&&(i=Je.toRadians(i),e=Je.toRadians(e),t=Je.toRadians(t)),ns._worldEulerBuffer.set(i,e,t),ns._worldQuaternionBuffer.setFromEuler(ns._worldEulerBuffer),this.worldQuaternion=ns._worldQuaternionBuffer}get forward(){return ns._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}get right(){return ns._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}get up(){return ns._up.set(0,1,0).applyQuaternion(this.worldQuaternion)}addEventListener(i,e){this._eventListeners[i]=this._eventListeners[i]||[],this._eventListeners[i].push(e)}removeEventListener(i,e){if(!this._eventListeners[i])return;const t=this._eventListeners[i].indexOf(e);t>=0&&this._eventListeners[i].splice(t,1)}dispatchEvent(i){if(!this._eventListeners[i.type])return!1;const e=this._eventListeners[i.type];for(let t=0;t<e.length;t++)e[t](i);return!1}},h(ns,"_worldPositionBuffer",new S),h(ns,"_worldQuaternionBuffer",new xe),h(ns,"_worldEulerBuffer",new fs),h(ns,"_tempQuaternionBuffer2",new xe),h(ns,"_forward",new S),h(ns,"_right",new S),h(ns,"_up",new S),ns);class Ee extends vc{}const Z7=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:Ee,Component:vc,GameObject:$},Symbol.toStringTag,{value:"Module"})),$7='<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>',eq=new Blob([$7],{type:"image/svg+xml;charset=utf-8"}),tq=URL.createObjectURL(eq),FD=tq,qh=oe("debuglicense"),_C="basic";qh&&console.log("License Type: "+_C);function Ac(){switch(_C){case"pro":case"enterprise":return!0}return!1}function UD(){switch(_C){case"indie":return!0}return!1}function ND(){return Ac()||UD()}Gi.registerCallback(Cn.ContextRegistered,i=>{iq(i.context)});async function iq(i){try{if(Ac()!==!0)return CC(i)}catch(e){return qh&&console.log("License check failed",e),CC(i)}qh&&CC(i)}const zD="needle-license-element",wC=5e3,xC=200;function CC(i){rq(),i.domElement.addEventListener("ready",()=>{setTimeout(()=>{sq(i)},1e3)}),aq()}function sq(i){const e=nq(),t=oq(),s=setInterval(()=>{if(!e)return;const l=i.domElement.shadowRoot||i.domElement;e.parentNode!==l&&(l.appendChild(e),t&&l.appendChild(t))},100);let r=`<img class="logo" src="${FD}" style="width: 40px; height: 40px; margin-right: 2px; vertical-align: middle; margin-bottom: 2px;"/>`;const n=document.createElement("div");n.innerHTML=r,n.classList.add("logo"),e.appendChild(n);const o=document.createElement("div");o.classList.add("text"),e.appendChild(o),e.title="Needle Engine",ND()||(e.title+=" non commercial version"),e.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")});const a=wC+xC;setTimeout(()=>{clearInterval(s),e?.remove(),t?.remove()},a)}let QD=0;async function rq(i){const e=Date.now();if(e-QD<2e3)return;QD=e,console.log("%c Needle Engine \u2014 non commercial version",`
|
|
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",e,!0),this._newLineBreakability=null}update(e,t){this._needsProcess=!0}process(e){const t=e._whiteSpace._newLineBreakability;if(e._inlines._value)for(let s=0;s<e._inlines._value.length;s++){const r=e._inlines._value[s],n=r.char;let o=null;n!==void 0&&(t!=="nowrap"&&(this._value.includes(n)||n.match(/\s/g))&&(o="possible"),n.match(/\n/g)&&(o=t)),r.lineBreak=o}}get value(){return this._value}}class wF extends ci{constructor(){super("layouter",null,!1),this._value=null}update(e,t){this._value=e._parent.find(s=>s.isUI&&s.isText),this._needsProcess=!0}process(e){this._value&&(this._value._layouter._needsProcess=!0)}}class E$ extends $g{constructor(e){super("backgroundColor",e,!1),this._allowsInherit=!1,this._input=0}computeOutputValue(e){this._input==="inherit"?this._value.set(this.getInheritedInput(e)):this._value.set(this._input)}}class xF extends v3{constructor(){super(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}}class CF extends A3{constructor(){super()}computeOutputValue(e){const t=this.getInheritedInput(e),s=M$[t];s?this._value=s:this._value=t}}const M$={light:"100",normal:"400",bold:"700",bolder:"900"};class SF extends S3{constructor(){super("fontFamily","inherit",!0),this._input="inherit",this._needsUpdate=!0,this._allowsInherit=!1}computeOutputValue(e){let t=this._inheritedInput;if(t==="inherit"&&(t=this.getInheritedInput(e)),t instanceof ab)this._value=t,e._font._needsUpdate=!0;else if(typeof t=="string"){const s=tu.getFontFamily(t);s?(this._value=s,e._font._needsUpdate=!0):console.warn(`(.style) fontFamily, the font '${t}' is not registered. Aborted.`)}else console.warn("(.style) fontFamily requires a registered fontFamily instance, or the id of a registered fontFamily."),console.warn("If you want to set a specific font, please use .font property instead.")}get value(){return this._value}}class EE extends M3{constructor(){super(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited,this._whiteSpacedContent="",this._stringCollapser=this.emptyStrategyLogic,this._inlineCollapser=this.emptyStrategyLogic,this._inlineWrapper=this.emptyStrategyLogic}_computeFromInherited(e){switch(super._computeFromInherited(e),this._newLineBreakability=I$(this._value),this._value){case"nowrap":case"normal":this._stringCollapser=T$;break;case"pre-line":this._stringCollapser=MF;break;default:this._stringCollapser=R$}switch(this._value){case"pre-line":case"nowrap":case"normal":this._inlineCollapser=O$;break;case"pre-wrap":this._inlineCollapser=D$;break;default:this._inlineCollapser=L$}switch(this._value){case"pre-line":case"pre-wrap":case"normal":this._inlineWrapper=P$;break;case"pre":this._inlineWrapper=B$;break;default:this._inlineWrapper=k$}this._needsProcess=!0}process(e){e.isInline&&!e.isInlineBlock&&(this._whiteSpacedContent=this._stringCollapser(e._textContent._value),e._glyphs._needsProcess=!0)}}const EF={" ":" ","\n":`
|
|
4559
4559
|
`,"\r":"\r"," ":" "},I$=function(i){switch(i){case"pre":case"pre-wrap":case"pre-line":return"mandatory"}return null};function T$(i){return MF(i.replace(/\n/g," "))}function MF(i){return i.replace(/[ ]{2,}/g," ")}function R$(i){return i}function P$(i,e,t,s){const r=i[e];if(r.lineBreak==="mandatory"||t+r.xadvance+r.xoffset+r.kerning>s.INNER_WIDTH)return!0;const n=RF(i,e,s);return F$(i[e-1],t,n,s)}function B$(i,e,t,s){return i[e].lineBreak==="mandatory"}function k$(){return!1}function D$(i){if(!i[0])return 0;const e=i[0],t=i[i.length-1];return e.char&&e.char===`
|
|
4560
4560
|
`&&i.length>1&&TF([e],i[1]),t.char&&t.char===`
|
|
4561
|
-
`&&i.length>1&&IF([t],i[i.length-2]),e.offsetX}function O$(i){if(!i[0])return 0;let e=[],t;for(let s=0;s<i.length;s++){const r=i[s];if(r.char&&EF[r.char]&&i.length>s){e.push(r),t=i[s+1];continue}break}TF(e,t),e=[],t=null;for(let s=i.length-1;s>0;s--){const r=i[s];if(r.char&&EF[r.char]&&s>0){e.push(r),t=i[s-1];continue}break}return IF(e,t),i[0].offsetX}function L$(i){return i[0]?i[0].offsetX:0}function IF(i,e){if(e)for(let t=0;t<i.length;t++){const s=i[t];s.fontFactor=0,s.offsetX=e.offsetX+e.cumulativeWidth,s.cumulativeWidth=0}}function TF(i,e){if(e)for(let t=0;t<i.length;t++){const s=i[t];s.fontFactor=0,s.offsetX=e.offsetX,s.cumulativeWidth=0}}function RF(i,e,t,s){if(s=s||0,!i[e])return s;const r=i[e];return r.lineBreak?s+r.xadvance:RF(i,e+1,t,s+r.xadvance+r.xoffset+r.kerning+t.LETTERSPACING)}function F$(i,e,t,s){return!i||!i.char||e+t<s.INNER_WIDTH?!1:s.BREAKON.indexOf(i.char)>-1}class PF extends I3{constructor(){super(),this._input="inherit",this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}_computeFromInherited(e){super._computeFromInherited(e),e._fontSize._needsProcess=!0,e._layouter._needsProcess=!0}}class BF extends Si{constructor(){super("fontSize","inherit",!0),this._allowsInherit=!1}computeOutputValue(e){this._value=this._inheritedInput,e._font._fontVariant&&(e._bounds._needsProcess=!0,e._layouter._needsProcess=!0)}process(e){if(!e._font._fontVariant||!e._font._fontVariant.isReady)return;const t=this._value/e._font._fontVariant.typographic.size,s=e._inlines._value;for(let r=0;r<s.length;r++){const n=s[r];n.resetOffsets(),n.fontSize=this._value,n.fontFactor=t}}get value(){return this._value}}class kF extends T3{constructor(){super("segments",1,!1),this._notInheritedValue=void 0}update(e,t){this._notInheritedValue=this._value,this._notInheritedValue==="inherit"&&(this._notInheritedValue=this.getInheritedInput(e)),e._layouter._needsUpdate=!0}set value(e){this._value!==e&&(this._value=e,this._needsUpdate=!0)}get value(){return this._value==="inherit"?this._notInheritedValue:this._value}}class U$ extends kF{constructor(){super(),this._value="inherit"}}class N$ extends cb{constructor(){super(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}_computeFromInherited(e){super._computeFromInherited(e),e._parent._value._layouter._needsProcess=!1}process(e){if(this._value!=="none"){const t=e._whiteSpace._whiteSpacedContent,s=e._inlines._value;for(let r=1;r<s.length;r++){const n=t[r-1]+t[r];s[r].kerning=e._font._fontVariant.getKerningAmount(n)}}}}class DF extends ci{constructor(){super("children",null,!1),this._uis=[]}update(e,t){}process(e){}_compute(e){}dispose(){}}function z$(i,e=!1){const t=i[0].index!==null,s=new Set(Object.keys(i[0].attributes)),r=new Set(Object.keys(i[0].morphAttributes)),n={},o={},a=i[0].morphTargetsRelative,l=new Ke.BufferGeometry;let c=0;for(let u=0;u<i.length;++u){const d=i[u];let p=0;if(t!==(d.index!==null))return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+u+". All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them."),null;for(const f in d.attributes){if(!s.has(f))return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+u+'. All geometries must have compatible attributes; make sure "'+f+'" attribute exists among all geometries, or in none of them.'),null;n[f]===void 0&&(n[f]=[]),n[f].push(d.attributes[f]),p++}if(p!==s.size)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+u+". Make sure all geometries have the same number of attributes."),null;if(a!==d.morphTargetsRelative)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+u+". .morphTargetsRelative must be consistent throughout all geometries."),null;for(const f in d.morphAttributes){if(!r.has(f))return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+u+". .morphAttributes must be consistent throughout all geometries."),null;o[f]===void 0&&(o[f]=[]),o[f].push(d.morphAttributes[f])}if(l.userData.mergedUserData=l.userData.mergedUserData||[],l.userData.mergedUserData.push(d.userData),e){let f;if(t)f=d.index.count;else if(d.attributes.position!==void 0)f=d.attributes.position.count;else return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+u+". The geometry must have either an index or a position attribute"),null;l.addGroup(c,f,u),c+=f}}if(t){let u=0;const d=[];for(let p=0;p<i.length;++p){const f=i[p].index;for(let g=0;g<f.count;++g)d.push(f.getX(g)+u);u+=i[p].attributes.position.count}l.setIndex(d)}for(const u in n){const d=OF(n[u]);if(!d)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the "+u+" attribute."),null;l.setAttribute(u,d)}for(const u in o){const d=o[u][0].length;if(d===0)break;l.morphAttributes=l.morphAttributes||{},l.morphAttributes[u]=[];for(let p=0;p<d;++p){const f=[];for(let m=0;m<o[u].length;++m)f.push(o[u][m][p]);const g=OF(f);if(!g)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the "+u+" morphAttribute."),null;l.morphAttributes[u].push(g)}}return l}function OF(i){let e,t,s,r=0;for(let a=0;a<i.length;++a){const l=i[a];if(l.isInterleavedBufferAttribute)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. InterleavedBufferAttributes are not supported."),null;if(e===void 0&&(e=l.array.constructor),e!==l.array.constructor)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes."),null;if(t===void 0&&(t=l.itemSize),t!==l.itemSize)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes."),null;if(s===void 0&&(s=l.normalized),s!==l.normalized)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes."),null;r+=l.array.length}const n=new e(r);let o=0;for(let a=0;a<i.length;++a)n.set(i[a].array,o),o+=i[a].array.length;return new Ke.BufferAttribute(n,t,s)}class Q$ extends ci{constructor(){super("renderer")}render(e){if(!e._inlines._value||!e._inlines._value.length)return;const t=e._inlines._value.map(r=>e._font._fontVariant.getGeometricGlyph(r,e).translate(r.offsetX,r.offsetY,0)),s=z$(t);e.setFontMesh(new Ke.Mesh(s,e.fontMaterial)),e._fontMesh.renderOrder=1/0}}class j$ extends qS{constructor(){super(),this._allowsInherit=!1,this._needsUpdate=!1}computeOutputValue(e){this._value=this._inheritedInput,e._layouter._needsProcess=!0}}class cf extends om{constructor(e={}){const t={};cf.definePropertiesValues(t,e),super(t,e),h(this,"_rebuildParentUI",()=>{super._rebuildParentUI(),this._layouter._needsUpdate=!0}),cf.init(this)}add(e){const t=[];for(let s=0;s<arguments.length;s++){const r=arguments[s];!r.isUI||r.isInline?(t.push(r),r.position.z=.005):console.warn("Block element can only contain Box elements.",r)}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=DF),e.textContent||(e.textContent=w$),e.glyphs||(e.glyphs=C$),e.inlines||(e.inlines=x$),e.layouter||(e.layouter=wF),e.renderer||(e.renderer=Q$),e.fontFamily||(e.fontFamily=SF),e.fontWeight||(e.fontWeight=CF),e.fontStyle||(e.fontStyle=xF),e.fontSize||(e.fontSize=BF),e.color||(e.color=S$),e.backgroundColor||(e.backgroundColor=E$),e.lineBreak||(e.lineBreak=_F),e.letterSpacing||(e.letterSpacing=PF),e.whiteSpace||(e.whiteSpace=EE),e.segments||(e.segments=U$),e.textAlign||(e.textAlign=j$),e.fontKerning||(e.fontKerning=N$)}static init(e){Object.defineProperties(e,{isInline:{configurable:!1,enumerable:!0,value:!0}})}}class G$ extends m3{constructor(){super("textContent",null,!1),this._needsUpdate=!1}set value(e){this._value!==e&&(this._value=e,this._needsUpdate=!0)}update(e,t){this._needsUpdate=!1;for(let s=e.children.length-1;s>=0;s--){const r=e.children[s];r.isUI&&(e.remove(r),r.clear())}e._children._uis=[],this._value&&e.add(new cf({name:"anonymousInline",textContent:this._value}))}}class H$ extends Array{constructor(...e){super(...e),this.width=0,this.height=0}}class V$ extends ci{constructor(){super("layouter",null,!1),this._value=null}update(e,t){}process(e){let t=e._width._value;e._width._auto?t=1/0:t=e._bounds._innerWidth;const s=e._lineHeight._value,r=new H$(new bF);let n=0;e._children._inlines.forEach(d=>{if(!d._inlines.value)return;this._resetInlines(d);const p=d._fontSize._value,f=d._letterSpacing._value*p,g=d._whiteSpace._value,m=d._lineBreak._value,v={WHITESPACE:g,LETTERSPACING:f,BREAKON:m,INNER_WIDTH:t},A=d._whiteSpace._inlineWrapper;n+=d._margin._value.w+d._padding._value.w,d._inlines.value.forEach((b,y,_)=>{const x=r[r.length-1];if(A(_,y,n,v)){if(r.push(new bF(b)),b.offsetX=b.xoffset,b.width===0){n=0;return}b.cumulativeWidth=b.xadvance+f,n=b.cumulativeWidth;return}r[r.length-1].push(b),b.offsetX=n+b.xoffset+b.kerning,b.cumulativeWidth=b.xadvance+b.kerning+f,n+=b.cumulativeWidth,x.length-1===1&&x[x.length-2].width===0&&(b.offsetX-=b.xoffset,n-=b.xoffset)}),n+=d._margin._value.y+d._padding._value.y});const o=e._whiteSpace._inlineCollapser;let a=0,l=0,c=0;r.forEach((d,p)=>{const f=o(d);let g=0,m=0;if(d.forEach(v=>{g=Math.max(g,v.lineHeight),m=Math.max(m,v.lineBase),v.offsetX-=f}),d.lineHeight=g,d.lineBase=m,p===0?c=-(g*s-g)*.5:c-=r[p-1].lineHeight*s,d.y=c,d.x=0,d.forEach(v=>{v.offsetY=c-v.anchor,v.lineHeight<d.lineHeight&&(v.offsetY-=d.lineBase-v.lineBase)}),l+=d.lineHeight*s,d.width=0,d[0]){const v=d[d.length-1];d.width=v.offsetX+v.cumulativeWidth+v.paddingRight+v.marginRight+d[0].offsetX,a=Math.max(a,d.width)}}),r.height=l,r.width=a,this._value=r,t===1/0&&e._bounds.setChildrenWidth(e,r.width),e._height._auto&&e._bounds.setChildrenHeight(e,r.height);const u=e._parent._value;u&&(u._autoSize._needsProcess=!0,u._flexDirection._needsProcess=!0),e._inlineJustificator._needsProcess=!0,e._textAlign._needsProcess=!0,e._overflow._needsUpdate=!0}_resetInlines(e){e._fontSize.process(e)}}class W$ extends qS{constructor(){super(),this._allowsInherit=!1,this._needsUpdate=!0}computeOutputValue(e){this._value=this._inheritedInput,this._needsProcess=!0}process(e){q$(e),e._renderer._needsRender=!0}}function q$(i){const e=i._layouter._value,t=i._textAlign._value,s=i._bounds._innerWidth;for(let r=0;r<e.length;r++){const n=e[r],o=X$(i,n,r===e.length-1),a=i._padding._value,l=i._borderWidth._value,c=(-a.w+a.y)/2+(-l.w+l.y)/2;n.x+=o;for(let u=0;u<n.length;u++)n[u].offsetX+=o-c}if(t.indexOf("justify")===0)for(let r=0;r<e.length;r++){const n=e[r];if(t.indexOf("-")!==-1&&r===e.length-1)return;const o=s-n.width;if(o<=0)return;let a=0;for(let d=1;d<n.length-1;d++)a+=n[d].char===" "?1:0;const l=o/a;let c=1;t==="justify-right"&&(n.reverse(),c=-1);let u=0;for(let d=1;d<=n.length-1;d++){const p=n[d];p.offsetX+=u*c,u+=p.char===" "?l:0}t==="justify-right"&&n.reverse()}}function X$(i,e,t){switch(i._textAlign._value){case"justify-left":case"justify":case"left":return-i._bounds._innerWidth/2;case"justify-right":case"right":return-e.width+i._bounds._innerWidth/2;case"center":return-e.width/2;case"justify-center":return t?-e.width/2:-i._bounds._innerWidth/2;default:console.warn(`textAlign: '${i._textAlign._value}' is not valid`)}}class Y$ extends XS{constructor(){super(),this._value=this._input="column",this._allowsInherit=!1,this._needsUpdate=!0}computeOutputValue(e){this._value=this._inheritedInput}}class J$ extends E3{constructor(){super(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}}class K$ extends cb{constructor(){super(),this._value=this._input=this.getDefaultValue(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}_computeFromInherited(e){super._computeFromInherited(e)}}class Z$ extends mF{constructor(){super(),this._innerWidth=1/0,this._innerHeight=0}}class $$ extends ci{constructor(){super("children",null,!1),h(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 eee extends ci{constructor(){super("autosize")}process(e){if(e._layouter._value&&e._layouter._value.length){const t=e._layouter._value,s=e._padding._value,r=e._borderWidth._value;e._width._auto&&e._bounds.setOffsetWidth(e,t.width+s.w+s.y+r.w+r.y),e._height._auto&&e._bounds.setOffsetHeight(e,t.height+s.x+s.z+r.x+r.z)}}}class tee extends yF{constructor(){super("renderer"),this._needsUpdate=!1}render(e){super.render(e);for(const t of e._children._inlines)t._renderer.render(t);e.performAfterUpdate()}}class Uv extends Lv{constructor(e={},t={}){Uv.definePropertiesValues(t,e),super(t,e),Uv.init(this)}add(e){const t=[];let s=!1;for(let r=0;r<arguments.length;r++){const n=arguments[r];!n.isUI||n.isInline?(n.isInline&&(s=!0),t.push(n)):console.warn("Block element can only contain Box elements.",n)}return t.length>0&&super.add(...t),s&&(this._children._needsUpdate=!0,this._layouter._needsProcess=!0),this}set textContent(e){this._textContent.value=e}get textContent(){return super.textContent}set invertAlpha(e){this._invertAlpha.value=e}get invertAlpha(){return this._invertAlpha._value}get lines(){return this._layouter._value}static definePropertiesValues(e,t){e.flexDirection=Y$,e.justifyContent=YS,e.alignItems=WS,e.bounds=Z$,e.autoSize=eee,e.renderer=tee,e.children||(e.children=$$),e.textContent||(e.textContent=G$),e.layouter||(e.layouter=V$),e.lineHeight||(e.lineHeight=J$),e.textAlign||(e.textAlign=W$),e.whiteSpace||(e.whiteSpace=EE),e.fontKerning||(e.fontKerning=K$),e.segments||(e.segments=kF),t.width||(t.width="100%"),t.fontSide||(t.fontSide=0)}static init(e){Object.defineProperties(e,{isText:{configurable:!1,enumerable:!0,value:!0}})}}class iee extends ci{constructor(){super("inlines",null,!1),this._value=[]}process(e){this._value[0].paddingLeft=e._padding._value.w,this._value[0].marginLeft=e._margin._value.w;const t=this._value.length-1;this._value[t].paddingRight=e._padding._value.y,this._value[t].marginRight=e._margin._value.y}}class see extends ci{constructor(){super("renderer")}render(e){e._backgroundMesh||e.setBackgroundMesh(new AF(e)),e._backgroundMesh.position.x=e._inlines._value[0].offsetX+e._inlines._value[0].width/2,e._backgroundMesh.position.y=e._inlines._value[0].offsetY+e._inlines._value[0].lineBase/2,e._bounds.render(e)}}class ree extends ci{constructor(){super("bounds",null,!1),this._size=new Ke.Vector3(1,1,1),this._offsetWidth=0,this._offsetHeight=0,this._innerWidth=0,this._innerHeight=0}update(e,t){this.output(t),this._needsProcess=!0}process(e){this._offsetWidth=this._innerWidth=e._inlines._value[0].width,this._offsetHeight=this._innerHeight=e._inlines._value[0].height,this._needsRender=!0,e._borderWidth._needsRender=!0,e._borderRadius._needsRender=!0}render(e){this._size.x=this._offsetWidth,this._size.y=this._offsetHeight}output(e){e.size=this._size}}class Nv extends om{constructor(e={}){const t={};Nv.definePropertiesValues(t,e),super(t,e),Nv.init(this)}clear(){for(const e of this._inlines._value)e.clear();return super.clear()}bindBackgroundMeshProperties(){this._backgroundMesh.raycast=()=>{},this._bounds._size=this._backgroundMesh.scale,this._bounds._needsUpdate=!0}unbindBackgroundMeshProperties(){this._bounds._size=new Ke.Vector3(1,1,1),this._bounds._needsUpdate=!0}add(e){const t=[];for(let s=0;s<arguments.length;s++){const r=arguments[s];r.isUI?console.warn("ThreeMeshUI::InlineBlockElement cannot contains UI Elements.",r):(t.push(r),r.position.z=.005)}return super.add(...t)}static definePropertiesValues(e,t){e.children||(e.children=DF),e.bounds||(e.bounds=ree),e.inlines||(e.inlines=iee),e.layouter||(e.layouter=wF),e.renderer||(e.renderer=see),e.fontFamily||(e.fontFamily=SF),e.fontWeight||(e.fontWeight=CF),e.fontStyle||(e.fontStyle=xF),e.fontSize||(e.fontSize=BF),e.backgroundColor||(e.backgroundColor=p3),e.lineBreak||(e.lineBreak=_F),e.letterSpacing||(e.letterSpacing=PF),e.whiteSpace||(e.whiteSpace=EE),e.fontKerning||(e.fontKerning=cb),t.backgroundSize||(t.backgroundSize="cover"),t.width||(t.width="100%"),t.height||(t.height="100%"),t.boxSizing||(t.boxSizing="border-box")}static init(e){Object.defineProperties(e,{isInline:{configurable:!1,enumerable:!0,value:!0},isInlineBlock:{configurable:!1,enumerable:!0,value:!0}}),e._inlines._value=[new nee(e)],e.backgroundMaterial=new gF,e._renderer.render(e)}}class nee extends _3{constructor(e){super(),this._uiElement=e}get xadvance(){const e=this._uiElement._padding._value,t=this._uiElement._width;return t._relative?t._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):e.w+e.y+t.value}get width(){const e=this._uiElement._width;return e._relative?e._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):e.value}get height(){const e=this._uiElement._height;return e._relative?e._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):e.value}get anchor(){return this.height}get lineHeight(){const e=this._uiElement._height;return e._relative?e._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):e.value}get lineBase(){const e=this._uiElement._height;return e._relative?e._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):e.value}clear(){this._uiElement=null}}class LF{constructor(e){this._subject=e}attach(){console.error(`Behavior::attach() - Is abstract and therefore should be overridden in ${this.constructor.name}`)}act(){throw new Error(`Behavior::act() - Is abstract and therefore should be overridden in ${this.constructor.name}`)}detach(){console.error(`Behavior::detach() - Is abstract and therefore should be overridden in ${this.constructor.name}`)}clear(){}}const FF=()=>Ab.update(),UF={BaseProperty:ci,Block:Fv,Text:Uv,Inline:cf,InlineBlock:Nv,MeshUIBaseElement:om,FontLibrary:tu,update:FF,MSDFFontMaterialUtils:io,ShaderChunkUI:fF,Behavior:LF,FontVariant:Zg};typeof global<"u"&&(global.ThreeMeshUI=UF);const oee=UF;var aee=ls.w8,NF=ls.cg,ME=ls.gO,lee=ls.wb,IE=ls.zV,cee=ls.HS,hee=ls.Ec,bb=ls.gF,uee=ls.ol,dee=ls.pz,pee=ls.tx,fee=ls.hj,gee=ls.FV,mee=ls.sV,zF=ls.xv,vee=ls.mx,Aee=ls.gE,yee=ls.ZP,QF=ls.Vx;const jF=Object.freeze(Object.defineProperty({__proto__:null,BaseProperty:aee,Behavior:NF,Block:ME,DefaultValues:lee,FontLibrary:IE,FontVariant:cee,InheritableProperty:hee,Inline:bb,InlineBlock:uee,InlineGlyph:dee,MSDFFontMaterialUtils:pee,MaterialTransformers:fee,MeshUIBaseElement:gee,ShaderChunkUI:mee,Text:zF,TypographicFont:vee,TypographicGlyph:Aee,default:yee,update:QF},Symbol.toStringTag,{value:"Module"}));ME.prototype.interactable={get(){return this.interactive},set(i){this.interactable=i}};const yl=Symbol("shadowDomOwner");class Bo extends Ee{constructor(){super(...arguments),h(this,"shadowComponent",null),h(this,"_controlsChildLayout",!0),h(this,"_root"),h(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(){Wn.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=$.getComponentInParent(this.gameObject,am)),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 s;this.removeShadowComponent();const r=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=$.getComponentInParent(r,Bo),!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[yl]=this,this.setShadowComponentOwner(e);let n=!1;if(((s=this.Root)==null?void 0:s.gameObject)===this.gameObject)this.gameObject.add(e);else{let o=this._parentComponent.shadowComponent;o&&(o?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),Zf&&e.add(new Ad(.5)),this.onAfterAddedToScene(),n&&QF()}set(e){}setShadowComponentOwner(e){if(e&&(e[yl]===void 0||e[yl]===this)&&(e[yl]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,s){if(e&&e[yl]===t){s(e);for(const r of e.children)this.traverseOwnedShadowComponents(r,t,s)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class am extends Bo{awake(){super.awake()}}class up{static getObject(e){const t=e[yl];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const s=this.tryFindCanvasGroup(e);if(s?.isCanvasGroup===!0&&(t&&(t.canvasGroup=s),s.blocksRaycasts===!1||s.interactable===!1))return!1;const r=Hh(e,n=>{if(n.isGraphic===!0)return n},!1);return t&&r?.isGraphic===!0&&(t.graphic=r),!(r?.raycastTarget===!1||r?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=Hh(e,s=>{const r=s;if(r.blocksRaycasts!==void 0&&r.interactable!==void 0)return r},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}const lm=oe("debugwebxrcontroller");var dp=(i=>(i[i.PhysicalDevice=0]="PhysicalDevice",i[i.Touch=1]="Touch",i))(dp||{}),bl=(i=>(i.SelectStart="select-start",i.SelectEnd="select-end",i.Update="update",i))(bl||{});class _b extends Ee{}const Hs=class extends Ee{constructor(){super(...arguments),h(this,"webXR"),h(this,"index",-1),h(this,"controllerModel"),h(this,"controller"),h(this,"controllerGrip"),h(this,"hand"),h(this,"handPointerModel"),h(this,"grabbed",null),h(this,"input",null),h(this,"type",0),h(this,"showRaycastLine",!0),h(this,"_wristQuaternion",null),h(this,"movementVector",new S),h(this,"worldRot",new xe),h(this,"joystick",new W),h(this,"didRotate",!1),h(this,"didTeleport",!1),h(this,"didChangeScale",!1),h(this,"lastHit",null),h(this,"raycastLine",null),h(this,"_raycastHitPoint",null),h(this,"_connnectedCallback",null),h(this,"_disconnectedCallback",null),h(this,"_selectStartEvt",null),h(this,"_selectEndEvt",null),h(this,"_selectionPressed",!1),h(this,"_selectionPressedLastFrame",!1),h(this,"_selectionStartTime",0),h(this,"_selectionEndTime",0),h(this,"_useSmoothing",!0),h(this,"_isConnected",!1),h(this,"rayRotation",new xe),h(this,"_pinchStartTime"),h(this,"selectStartCallback",null),h(this,"lastSelectStartObject",null),h(this,"_didNotEndSelection",!1),h(this,"closeGrabBoundingBoxHelper")}static CreateRaycastLine(){const i=new qi(this.geometry),e=i.material;return e.color=this.raycastColor,i.layers.set(2),i.name="line",i.scale.z=1,i}static CreateRaycastHitPoint(){const i=new to(.5,22,22),e=new di({color:this.raycastColor}),t=new ye(i,e);return t.visible=!1,t.layers.set(2),t}static Create(i,e,t,s){const r=t?$.addNewComponent(t,Hs,!1):new Hs;r.webXR=i,r.index=e,r.type=s;const n=i.context;r.controller=n.renderer.xr.getController(e),r.controllerGrip=n.renderer.xr.getControllerGrip(e),r.controllerModel=this.Factory.createControllerModel(r.controller),r.controllerGrip.add(r.controllerModel),r.hand=n.renderer.xr.getHand(e);const o=new Bd;Rg(o,n),r.webXR.handModelPath&&r.webXR.handModelPath!==""?o.setPath(zl(i.sourceId,r.webXR.handModelPath)):o.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/");const a=new WY(r.hand,o);return r.hand.add(a),r.hand.traverse(l=>l.layers.set(2)),r.handPointerModel=new $Y(r.hand,r.controller),r.controller.addEventListener("connected",l=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),r.setControllerLayers(r.hand,2),setTimeout(()=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),r.setControllerLayers(r.hand,2)},1e3)}),r.hand.addEventListener("connected",l=>{var c;if(l.data.hand){i.Rig&&i.Rig.add(r.hand),r.type=0,r.handPointerModel.traverse(d=>d.layers.set(2)),(c=r.handPointerModel.pointerObject)==null||c.traverse(d=>d.layers.set(2));const u=r.hand.joints;if(u)for(const d of Object.keys(u)){const p=u[d];p.parent||r.hand.add(p)}}}),r}static addEventListener(i,e){const t=this.eventSubs[i]??[];t.push(e),this.eventSubs[i]=t}static removeEventListener(i,e){if(!e)return;const t=this.eventSubs[i]??[],s=t.indexOf(e);s>=0&&t.splice(s,1),this.eventSubs[i]=t}get isUsingHands(){var i;return((i=this.input)==null?void 0:i.hand)!=null}get wrist(){if(!this.hand)return null;const i=this.hand.joints;return i?i.wrist:null}getWristQuaternion(){const i=this.wrist;return i?(this._wristQuaternion||(this._wristQuaternion=new xe),ws(i).multiply(this._wristQuaternion.setFromEuler(new fs(-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 i,e,t;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)),(i=this.hand)==null||i.clear(),(e=this.controllerGrip)==null||e.clear(),(t=this.controller)==null||t.clear()}onEnable(){var i,e,t,s,r;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=Hs.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=Hs.CreateRaycastHitPoint()),(i=this.webXR.Rig)==null||i.add(this.hand),(e=this.webXR.Rig)==null||e.add(this.controllerGrip),(t=this.webXR.Rig)==null||t.add(this.controller),(s=this.webXR.Rig)==null||s.add(this.raycastLine),(r=this.raycastLine)==null||r.add(this._raycastHitPoint),this._raycastHitPoint.visible=!1,this.hand.add(this.handPointerModel),lm&&console.log("ADDED TO RIG",this.webXR.Rig)}onDisable(){var i,e,t,s,r;(i=this.hand)==null||i.removeFromParent(),(e=this.controllerGrip)==null||e.removeFromParent(),(t=this.controller)==null||t.removeFromParent(),(s=this.raycastLine)==null||s.removeFromParent(),(r=this._raycastHitPoint)==null||r.removeFromParent();const n=this.webXR.Controllers.indexOf(this);n>=0&&this.webXR.Controllers.splice(n,1)}onSourceConnected(i){if(this._isConnected){console.warn("Received connected event for controller that is already connected",this.index,i);return}this._isConnected=!0,this.input=i.data,this.type===1&&(this.onSelectStart(),this.createPointerEvent("down"))}onSourceDisconnected(i){if(!this._isConnected){console.warn("Received discnnected event for controller that is not connected",i);return}this._isConnected=!1,this.type===1&&(this.onSelectEnd(),this.createPointerEvent("up")),this.input=null}createPointerEvent(i){switch(i){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 i=Hs.eventSubs.update;if(i&&i.length>0)for(const s of i)s(this);let e=1;this.type===0?e=this.context.time.deltaTime/.1:this.isUsingHands&&this.handPointerModel.pinched&&(e=this.context.time.deltaTime/.3),this.rayRotation.slerp(ws(this.controller),this.useSmoothing?e:1);const t=wt(this.controller);if(this.isUsingHands&&this.handPointerModel.cursorObject&&(this.handPointerModel.cursorObject.visible=!1),this.raycastLine){const s=this.showRaycastLine&&this.type!==1;if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed&&s,Yi(this.raycastLine,t);const r=this.hand.joints;if(r&&r.wrist&&this.grabbed&&this.grabbed.isCloseGrab){const n=this.getWristQuaternion();n&&this.rayRotation.copy(n)}Nr(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=s,Nr(this.raycastLine,this.rayRotation),Yi(this.raycastLine,t)}this.lastHit=this.updateLastHit(),this.grabbed&&this.grabbed.update(),this._selectionPressedLastFrame=this._selectionPressed,this.selectStartCallback&&this.selectStartCallback()}onUpdate(i){var e,t;if(this.lastHit=null,!i||i.inputSources.length<=this.index){this.input=null;return}if(this.type===0&&(this.input=i.inputSources[this.index]),!this.input)return;const s=this.webXR.Rig;if(!s)return;this._didNotEndSelection&&!this.handPointerModel.pinched&&(this._didNotEndSelection=!1,this.onSelectEnd()),this.updateStick(this.input);const r=(t=(e=this.input)==null?void 0:e.gamepad)==null?void 0:t.buttons;switch(this.input.handedness){case"left":const n=3*Hs.MovementSpeedFactor,o=2,a=Je.clamp01(this.joystick.length()*2),l=this.joystick.x>0?1:-1;let c=Math.pow(this.joystick.x,o);c*=l,c*=a;const u=this.joystick.y>0?1:-1;let d=Math.pow(this.joystick.y,o);d*=u,c*=a,s.getWorldQuaternion(this.worldRot),this.movementVector.set(c,0,d),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),this.movementVector.multiplyScalar(n*this.context.time.deltaTime),s.position.add(this.movementVector),this.isUsingHands&&this.runTeleport(s,r);break;case"right":const p=this.joystick.x,f=Math.abs(p);if(f<.4)this.didRotate=!1;else if(f>.5&&!this.didRotate){const g=p>0?-1:1;s.rotateY(Je.toRadians(30*g)),this.didRotate=!0}this.runTeleport(s,r);break}}runTeleport(i,e){var t,s,r;let n=-this.joystick.y;if((t=this.hand)!=null&&t.visible&&!this.grabbed){const c=this.handPointerModel.isPinched();c&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),c&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(n=this.handPointerModel.isPinched()?1:0),c||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;let o=n>.5&&this.webXR.IsInVR,a=this.webXR.Rig?((r=(s=this.webXR.Rig)==null?void 0:s.scale)==null?void 0:r.x)<.999:!1,l=null;if(e&&this.input&&!this.input.hand)for(let c=0;c<e.length;c++){const u=e[c];if(c===4)if(u.pressed&&!this.didChangeScale&&this.webXR.IsInVR){this.didChangeScale=!0;const d=this.webXR.Rig;if(d)if(a){a=!1,d.scale.set(1,1,1),l=1,Hs.MovementSpeedFactor=1;const p=this.context.mainCamera;Hs.PreviousCameraFarDistance&&(p.far=Hs.PreviousCameraFarDistance)}else{a=!0,o=!0,l=.1,Hs.MovementSpeedFactor=l*2;const p=this.context.mainCamera;Hs.PreviousCameraFarDistance=p.far,p.far/=l}}else u.pressed||(this.didChangeScale=!1)}if(o){if(!this.didTeleport){const c=this.raycast();if(this.didTeleport=!0,c&&c.length>0){const u=c[0];if(a||this.isValidTeleportTarget(u.object)){const d=u.point;Yi(i,d)}}}}else n<.1&&(this.didTeleport=!1);l!==null&&(i.scale.set(l,l,l),i.updateMatrixWorld())}isValidTeleportTarget(i){return $.getComponentInParent(i,_b)!=null}updateStick(i){var e;!i||!i.gamepad||((e=i.gamepad.axes)==null?void 0:e.length)<4||(this.joystick.x=i.gamepad.axes[2],this.joystick.y=i.gamepad.axes[3])}updateLastHit(){var i;const e=this.raycast(),t=e?e[0]:null;this.lastHit=t;let s=1;if(this.webXR.Rig&&(s/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=s*(((i=this.lastHit)==null?void 0:i.distance)??9999);const r=this.raycastLine.material;t!=null?r.color=Hs.raycastColor:r.color=Hs.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;const r=Je.clamp(this.lastHit.distance*.01*s,.015,.1);this._raycastHitPoint.scale.set(r,r,r)}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 i=null,e=!1;if(this.isUsingHands?(i=this.overlap(),i.length<=0?(i=this.raycast(),e=!1):e=!0):i=this.raycast(),lm&&console.log("onHandleSelectStart","close grab? "+e,"intersections",i),i&&i.length>0)for(const t of i){const s=t.object;this.lastSelectStartObject=s;const r={selected:s,grab:s},n=Hs.eventSubs["select-start"];if(n&&n.length>0)for(const o of n)o(this,r);r.grab!==s&&lm&&console.log("Grabbed object changed","original",s,"new",r.grab),r.grab&&(this.grabbed=na.TryTake(this,r.grab,t,e));break}else{const t=Hs.eventSubs["select-start"],s={selected:null,grab:null};if(t&&t.length>0)for(const r of t)r(this,s)}}onSelectEnd(){var i;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:((i=this.grabbed)==null?void 0:i.selected)??this.lastSelectStartObject},t=Hs.eventSubs["select-end"];if(t&&t.length>0)for(const s of t)s(this,e);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(i){return!(!i||$.isActiveInHierarchy(i)===!1||up.isInteractable(i)===!1)}setControllerLayers(i,e){var t,s;if(i&&(i.layers.set(e),i.children))for(const r of i.children)((t=this.grabbed)==null?void 0:t.selected)===r||((s=this.grabbed)==null?void 0:s.selectedMesh)===r||this.setControllerLayers(r,e)}getRay(){const i=new za;return i.origin.copy(wt(this.controller)),i.direction.set(0,0,-1).applyQuaternion(this.rayRotation),i}overlap(){const i=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(lm&&(!this.closeGrabBoundingBoxHelper&&i&&(this.closeGrabBoundingBoxHelper=new g0(i,16776960),this.scene.add(this.closeGrabBoundingBoxHelper)),this.closeGrabBoundingBoxHelper&&i&&this.closeGrabBoundingBoxHelper.setFromObject(i)),!i)return new Array;const e=wt(i).clone();return this.context.physics.sphereOverlap(e,.02)}raycast(){const i=new fo;i.layerMask=new Mn,i.layerMask.enableAll(),i.layerMask.disable(2),i.ray=this.getRay();const e=this.context.physics.raycast(i);for(let t=0;t<e.length;t++){const s=e[t],r=s.object;if(!this.testIsVisible(r)){e.splice(t,1),t--;continue}s.object=up.getObject(r);break}return e}};let cs=Hs;h(cs,"Factory",new uJ),h(cs,"raycastColor",new _e(.9,.3,.3)),h(cs,"raycastNoHitColor",new _e(.6,.6,.6)),h(cs,"geometry",new At().setFromPoints([new S(0,0,0),new S(0,0,-1)])),h(cs,"handModels",{}),h(cs,"eventSubs",{}),h(cs,"PreviousCameraFarDistance"),h(cs,"MovementSpeedFactor",1);var wb=(i=>(i.WillTake="WillTake",i.DidTake="DidTake",i.WillFree="WillFree",i.DidFree="DidFree",i))(wb||{});const Yr=class{constructor(){h(this,"sync",null),h(this,"selected",null),h(this,"selectedParent",null),h(this,"selectedMesh",null),h(this,"controller",null),h(this,"grabTime",0),h(this,"grabUUID",""),h(this,"isCloseGrab",!1),h(this,"originalMaterial",null),h(this,"usageMarker",null),h(this,"rigidbodies",null),h(this,"didReparent",!1),h(this,"grabDistance",0),h(this,"interactable",null),h(this,"positionSource",null),h(this,"grabPoint",new S),h(this,"localPositionOffsetToGrab",null),h(this,"localPositionOffsetToGrab_worldSpace",new S),h(this,"localQuaternionToGrab",new xe(0,0,0,1)),h(this,"targetDir",null),h(this,"quaternionLerp",null),h(this,"controllerDir",new S),h(this,"controllerWorldPos",new S),h(this,"lastControllerWorldPos",new S),h(this,"controllerPosDelta",new S),h(this,"totalChangeAlongDirection",0),h(this,"rigPositionLastFrame",new S)}static AddEventListener(i,e){return Yr.Events[i]||(Yr.Events[i]=[]),Yr.Events[i].push(e),e}static RemoveEventListener(i,e){if(!e||!Yr.Events[i])return;const t=Yr.Events[i].indexOf(e);t>=0&&Yr.Events[i].splice(t,1)}static Register(i){this.Current.find(e=>e===i)||this.Current.push(i)}static Remove(i){const e=this.Current.indexOf(i);e>=0&&this.Current.splice(e,1)}static TryTake(i,e,t,s){const r=$.getComponentInParent(e,sp);if(r)e=r.gameObject;else return lm&&console.warn("Prevented taking object that is not interactable",e),null;let n=e;const o=$.getComponentInParent(e,Uc);o&&(o.requestOwnership(),n=o.gameObject);for(const l of this.Current)if(l.selected===n)return l.controller===i||(l.free(),l.Take(i,n,e,o,r,t,s)),l;const a=new Yr;return a.Take(i,n,e,o,r,t,s),a}Take(i,e,t,s,r,n,o){var a,l;if(console.assert(e!==null,"Expected object to be taken but was",e),i.isUsingHands?this.positionSource=o?i.wrist:i.controller:this.positionSource=i.controller,!this.positionSource)return console.warn("No position source"),this;const c={controller:i,take:e,hit:t,sync:s,interactable:r};(a=Yr.Events.WillTake)==null||a.forEach(g=>g(this,c));const u=t;u!=null&&u.material&&(this.originalMaterial=u.material,Array.isArray(u.material)||(u.material=u.material.clone(),u.material&&u.material.emissive&&(u.material.emissive.b=.2))),this.selected=e,this.selectedParent||(this.selectedParent=e.parent),this.selectedMesh=u,this.controller=i,this.interactable=r,this.isCloseGrab=o,this.didReparent=!1,this.sync=s,this.grabTime=i.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=$.addNewComponent(this.selected,rp),this.rigidbodies=$.getComponentsInChildren(this.selected,Li),wt(this.positionSource,this.lastControllerWorldPos);const d=()=>o?this.lastControllerWorldPos.clone():n.point.clone();this.grabDistance=d().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(d());const p=i.isUsingHands&&o?this.controller.getWristQuaternion().clone():i.rayRotation.clone();ws(this.selected,this.localQuaternionToGrab).premultiply(p.invert());const f=this.controller.webXR.Rig;return f&&this.rigPositionLastFrame.copy(wt(f)),Pr.Add(i.context,this.selected),Yr.Register(this),this.sync&&(this.sync.fastMode=!0),(l=Yr.Events.DidTake)==null||l.forEach(g=>g(this,c)),this}free(){var i,e,t,s;if(!this.selected)return;const r={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};(i=Yr.Events.WillFree)==null||i.forEach(a=>a(this,r)),Pr.Remove(this.controller.context,this.selected),Yr.Remove(this),this.sync&&(this.sync.fastMode=!1);const n=this.selectedMesh;n&&this.originalMaterial&&n.material&&(n.material=this.originalMaterial);const o=this.selected;if(this.didReparent&&o.parent){const a=this.selectedParent;a?a.attach(o):(e=this.controller)==null||e.context.scene.attach(o)}if((t=this.usageMarker)==null||t.destroy(),this.controller&&(this.controller.grabbed=null),this.selected=null,this.selectedParent=null,this.selectedMesh=null,this.sync=null,this.rigidbodies)for(const a of this.rigidbodies)a.wakeUp(),a.setVelocity(a.smoothedVelocity);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,(s=Yr.Events.DidFree)==null||s.forEach(a=>a(this,r))}controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),wt(this.positionSource,this.controllerWorldPos),this.controllerPosDelta.copy(this.controllerWorldPos),this.controllerPosDelta.sub(this.lastControllerWorldPos),this.lastControllerWorldPos.copy(this.controllerWorldPos);const i=this.controller.webXR.Rig;if(i){const e=wt(i),t=this.rigPositionLastFrame.sub(e);this.controllerPosDelta.add(t),this.rigPositionLastFrame.copy(e)}return this.controllerDir.dot(this.controllerPosDelta)}update(){var i;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=((i=this.controller.webXR.Rig)==null?void 0:i.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 S),this.targetDir.set(0,0,-this.grabDistance*t);const s=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),r=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=r.clone()),this.quaternionLerp.slerp(r,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),Nr(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(s),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(wt(this.selected)),s.sub(this.localPositionOffsetToGrab_worldSpace)),Yi(this.selected,s)}if(this.rigidbodies!=null)for(const e of this.rigidbodies)e.wakeUp();en.markDirty(this.selected,!0)}}};let na=Yr;h(na,"Events",{}),h(na,"Current",[]);var bee=Object.defineProperty,_ee=Object.getOwnPropertyDescriptor,TE=(i,e,t,s)=>{for(var r=s>1?void 0:s?_ee(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&bee(e,t,r),r};class su extends Ee{constructor(){super(...arguments),h(this,"objectBounds",!1),h(this,"color"),h(this,"isGizmo",!0),h(this,"_gizmoObject",null),h(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!Zf||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new g0(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=_L(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),dn.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(var e;this._boxHelper;)(e=this._boxHelper)==null||e.update(),yield}}TE([w()],su.prototype,"objectBounds",2),TE([w(_e)],su.prototype,"color",2),TE([w()],su.prototype,"isGizmo",2);const wee=oe("debugrig");class xb extends Ee{awake(){if(wee){const e=new Me;e.position.y+=.5,this.gameObject.add(e);const t=e.addNewComponent(su);t&&(t.isGizmo=!1)}}}class pp{constructor(){h(this,"bb",null),h(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}w(){return this.bb.readFloat32(this.bb_pos+12)}static sizeOf(){return 16}static createVec4(e,t,s,r,n){return e.prep(4,16),e.writeFloat32(n),e.writeFloat32(r),e.writeFloat32(s),e.writeFloat32(t),e.offset()}}class pr{constructor(){h(this,"bb",null),h(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsVrUserStateBuffer(e,t){return(t||new pr).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+D0),(t||new pr).__init(e.readInt32(e.position())+e.position(),e)}guid(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}time(){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}avatarId(e){const t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__string(this.bb_pos+t,e):null}position(e){const t=this.bb.__offset(this.bb_pos,10);return t?(e||new pn).__init(this.bb_pos+t,this.bb):null}rotation(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new pp).__init(this.bb_pos+t,this.bb):null}scale(){const e=this.bb.__offset(this.bb_pos,14);return e?this.bb.readFloat32(this.bb_pos+e):0}posLeftHand(e){const t=this.bb.__offset(this.bb_pos,16);return t?(e||new pn).__init(this.bb_pos+t,this.bb):null}posRightHand(e){const t=this.bb.__offset(this.bb_pos,18);return t?(e||new pn).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){const t=this.bb.__offset(this.bb_pos,20);return t?(e||new pp).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){const t=this.bb.__offset(this.bb_pos,22);return t?(e||new pp).__init(this.bb_pos+t,this.bb):null}static startVrUserStateBuffer(e){e.startObject(10)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addTime(e,t){e.addFieldInt64(1,t,e.createLong(0,0))}static addAvatarId(e,t){e.addFieldOffset(2,t,0)}static addPosition(e,t){e.addFieldStruct(3,t,0)}static addRotation(e,t){e.addFieldStruct(4,t,0)}static addScale(e,t){e.addFieldFloat32(5,t,0)}static addPosLeftHand(e,t){e.addFieldStruct(6,t,0)}static addPosRightHand(e,t){e.addFieldStruct(7,t,0)}static addRotLeftHand(e,t){e.addFieldStruct(8,t,0)}static addRotRightHand(e,t){e.addFieldStruct(9,t,0)}static endVrUserStateBuffer(e){return e.endObject()}static finishVrUserStateBufferBuffer(e,t){e.finish(t)}static finishSizePrefixedVrUserStateBufferBuffer(e,t){e.finish(t,void 0,!0)}}const GF=oe("debugxr"),cm=oe("debugavatar"),RE="VRUS";k1(RE,pr.getRootAsVrUserStateBuffer);function PE(){return new Date().getTime()}function xee(i){let e=i&4294967295,t=i/Math.pow(2,32)&1048575;return Ma.create(e,t)}const Cb=class{constructor(i){h(this,"guid"),h(this,"time"),h(this,"avatarId"),h(this,"position",new S),h(this,"rotation",new it),h(this,"scale",1),h(this,"posLeftHand",new S),h(this,"posRightHand",new S),h(this,"rotLeftHand",new xe),h(this,"rotRightHand",new xe),this.guid=i}update(i,e,t,s,r){var n,o,a,l,c,u;this.time=PE(),this.avatarId=r,this.position.set(e.x,e.y,e.z),i&&this.position.applyMatrix4(i.matrixWorld);let d=Cb.quat0;const p=Cb.quat1;d.set(t.x,t.y,t.z,t.w),d=d.multiplyQuaternions(d,Cb.invertRotation),i&&(i.getWorldQuaternion(p),d.multiplyQuaternions(p,d)),this.rotation.set(d.x,d.y,d.z,d.w),this.scale=i.scale.x;const f=(n=s.LeftController)==null?void 0:n.controllerGrip;f&&(f.getWorldPosition(this.posLeftHand),f.getWorldQuaternion(this.rotLeftHand));const g=(o=s.RightController)==null?void 0:o.controllerGrip;if(g&&(g.getWorldPosition(this.posRightHand),g.getWorldQuaternion(this.rotRightHand)),(l=(a=s.LeftController)==null?void 0:a.hand)!=null&&l.visible){const m=s.LeftController.wrist;m&&(m.getWorldPosition(this.posLeftHand),m.getWorldQuaternion(this.rotLeftHand))}if((u=(c=s.RightController)==null?void 0:c.hand)!=null&&u.visible){const m=s.RightController.wrist;m&&(m.getWorldPosition(this.posRightHand),m.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(i,e){i.clear();const t=i.createString(this.guid),s=i.createString(this.avatarId);pr.startVrUserStateBuffer(i),pr.addGuid(i,t),pr.addTime(i,xee(this.time)),pr.addAvatarId(i,s),pr.addPosition(i,pn.createVec3(i,this.position.x,this.position.y,this.position.z)),pr.addRotation(i,pp.createVec4(i,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),pr.addScale(i,this.scale),pr.addPosLeftHand(i,pn.createVec3(i,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),pr.addPosRightHand(i,pn.createVec3(i,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),pr.addRotLeftHand(i,pp.createVec4(i,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),pr.addRotRightHand(i,pp.createVec4(i,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));const r=pr.endVrUserStateBuffer(i);i.finish(r,RE);const n=i.asUint8Array();e.sendBinary(n)}setFromBuffer(i,e){if(!i)return;this.guid=i,this.time=e.time().toFloat64();const t=e.avatarId();t&&(this.avatarId=t);const s=e.position();s&&this.position.set(s.x(),s.y(),s.z());const r=e.rotation();r&&this.rotation.set(r.x(),r.y(),r.z(),r.w());const n=e.posLeftHand();n&&this.posLeftHand.set(n.x(),n.y(),n.z());const o=e.posRightHand();o&&this.posRightHand.set(o.x(),o.y(),o.z());const a=e.rotLeftHand();a&&this.rotLeftHand.set(a.x(),a.y(),a.z(),a.w());const l=e.rotRightHand();l&&this.rotRightHand.set(l.x(),l.y(),l.z(),l.w()),this.scale=e.scale()}};let _l=Cb;h(_l,"invertRotation",new xe().setFromAxisAngle(new S(0,1,0),Math.PI)),h(_l,"quat0",new xe),h(_l,"quat1",new xe);class hm extends Ee{constructor(){super(...arguments),h(this,"webXR",null),h(this,"debugAvatarUser",null),h(this,"voip",null),h(this,"tempState",new _l("")),h(this,"_removeAvatarsList",[]),h(this,"eventSub_ConnectionEvent",null),h(this,"eventSub_WebXRStartEvent",null),h(this,"eventSub_WebXREndEvent",null),h(this,"eventSub_WebXRUpdateEvent",null),h(this,"avatars",{}),h(this,"localAvatar",null),h(this,"k_LocalAvatarNoNetworkingGuid","local"),h(this,"ownership",null),h(this,"xrState",null),h(this,"builder",new af(1024))}async awake(){if(this.webXR||(this.webXR=$.getComponent(this.gameObject,xt)),this.webXR||(this.webXR=$.findObjectOfType(xt,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=$.findObjectOfType(xt,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=$.findObjectOfType(Fl,this.context)),cm){const e="debug-avatar-"+cm,t=new Lc(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof cm=="string"&&cm.length>0)if(await t.setAvatarOverride(cm)){const s=new _l(e);s.position.y+=1;const r=.5;s.posLeftHand.y+=r,s.posLeftHand.x+=r,s.posRightHand.y+=r,s.posRightHand.x-=r,t.tryUpdate(s,0)}else t.destroy()}}onEnable(){if(!this.webXR&&(this.webXR=$.getComponent(this.gameObject,xt),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),xt.addEventListener(_i.XRStarted,this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),xt.addEventListener(_i.XRUpdate,this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),xt.addEventListener(_i.XRStopped,this.eventSub_WebXREndEvent),this.eventSub_ConnectionEvent=this.onConnected.bind(this),this.context.connection.beginListen(Ni.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 s=this.avatars[e.id];s?.destroy(),this.avatars[e.id]=void 0}}),this.context.connection.beginListenBinary(RE,e=>{const t=e.guid();if(!t)return;const s=e.time().toFloat64(),r=this.tempState;r.setFromBuffer(t,e);const n=this.onTryGetAvatar(t,s);n?.tryUpdate(r,s)}),this.context.connection.beginListen("vr-session-update",e=>{const t=e.guid,s=e.time,r=this.onTryGetAvatar(t,s);r?.tryUpdate(e,s)})}onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;const s=new Date().getTime()-t;if(s>5e3)return GF&&console.log("old data",s,e),null;let r=this.avatars[e];if(r===void 0)try{console.log("create new avatar");const n=new Lc(this.context,e,this.webXR);r=n,this.avatars[e]=n}catch(n){this.avatars[e]=null,console.error(n)}return r}onDisable(){this.eventSub_ConnectionEvent&&this.context.connection.stopListen(Ni.JoinedRoom,this.eventSub_ConnectionEvent),xt.removeEventListener(_i.XRStarted,this.eventSub_WebXRStartEvent),xt.removeEventListener(_i.XRUpdate,this.eventSub_WebXRUpdateEvent),xt.removeEventListener(_i.XRStopped,this.eventSub_WebXREndEvent)}update(){const e=PE();this.debugAvatarUser&&(this.debugAvatarUser.lastUpdate=e),this.detectPotentiallyDisconnectedAvatarsAndRemove();for(const t in this.avatars){const s=this.avatars[t];s&&s.update()}}detectPotentiallyDisconnectedAvatarsAndRemove(){const e=PE();for(const t in this.avatars){const s=this.avatars[t];if(!s){this._removeAvatarsList.push(t);continue}e-s.lastUpdate>1e4&&(console.log("avatar timed out (didnt receive any updates in a while) - destroying it now"),s.destroy(),this.avatars[t]=void 0)}for(const t of this._removeAvatarsList)delete this.avatars[t];this._removeAvatarsList.length=0}buildLocalAvatar(){var e;if(this.localAvatar)return;const t=((e=this.context.connection)==null?void 0:e.connectionId)??this.k_LocalAvatarNoNetworkingGuid;this.localAvatar=new Lc(this.context,t,this.webXR),this.localAvatar.isLocalAvatar=!0,this.localAvatar.setAvatarOverride(this.getAvatarId()),this.avatars[this.localAvatar.guid]=this.localAvatar}onConnected(){var e,t,s;GF&&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,(s=this.ownership)==null||s.freeOwnership(),this.ownership=null)}onXRSessionStart(e){var t,s,r;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,(s=this.ownership)==null||s.freeOwnership(),this.ownership=null,this.avatars)for(const n in this.avatars)(r=this.avatars[n])==null||r.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 _l(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid)),this.ownership??(this.ownership=new q0(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:s,rig:r}=e,n=t.getViewerPose(s.getReferenceSpace());if(!n)return;const o=n?.transform,a=o.position,l=o.orientation;this.xrState.update(r,a,l,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 oe("avatar")??null}}var Cee=Object.defineProperty,See=Object.getOwnPropertyDescriptor,fp=(i,e,t,s)=>{for(var r=s>1?void 0:s?See(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Cee(e,t,r),r};async function HF(){return nw()?!0:"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function VF(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}let Sb=!1,Eb=!1;HF().then(i=>Sb=i),VF().then(i=>Eb=i);var _i=(i=>(i.XRStarted="xrStarted",i.XRStopped="xrStopped",i.XRUpdate="xrUpdate",i.RequestVRSession="requestVRSession",i.ModifyAROptions="modify-ar-options",i))(_i||{}),gp;const Ss=(gp=class extends Ee{constructor(){super(...arguments),h(this,"enableVR",!0),h(this,"enableAR",!0),h(this,"defaultAvatar"),h(this,"handModelPath",""),h(this,"createVRButton",!0),h(this,"createARButton",!0),h(this,"controllers",[]),h(this,"rig"),h(this,"isInit",!1),h(this,"_requestedAR",!1),h(this,"_requestedVR",!1),h(this,"_isInAR",!1),h(this,"_isInVR",!1),h(this,"_arButton"),h(this,"_vrButton"),h(this,"webAR",null),h(this,"_transformOrientation",new xe),h(this,"_currentHeadPose",null),h(this,"_originalCameraParent",null),h(this,"_originalCameraPosition",new S),h(this,"_originalCameraRotation",new xe),h(this,"_originalXRRigParent",null),h(this,"_originalXRRigPosition",new S),h(this,"_originalXRRigRotation",new xe),h(this,"xrMirrorWindow",null)}static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(Sb||Eb)}static get IsARSupported(){return Sb}static get IsVRSupported(){return Eb}static get OptionalFeatures_VR(){return this._optionalFeatures_VR}static get OptionalFeatures_AR(){return this._optionalFeatures_AR}static addEventListener(i,e){return this.events.addEventListener(i,e),e}static removeEventListener(i,e){return this.events.removeEventListener(i,e),e}static dispatchEvent(i,e){this.events.dispatchEvent({type:i,detail:e})}static createVRButton(i,e){Ss.XRSupported?i.__internalAwake():console.warn("WebXR is not supported on this device");const t={optionalFeatures:Ss.OptionalFeatures_VR},s=FS.createButton(i.context.renderer,t);return s.classList.add("webxr-ar-button"),s.classList.add("webxr-button"),this.resetButtonStyles(s),(e?.registerClick??!0)&&s.addEventListener("click",i.onClickedVRButton.bind(i)),s}static createARButton(i,e){var t;i.__internalAwake();const s=(t=i.webAR)==null?void 0:t.getAROverlayContainer(),r={optionalFeatures:[...this.OptionalFeatures_AR]};s?(r.domOverlay={root:s},r.optionalFeatures.push("dom-overlay"),r.optionalFeatures.push("hit-test")):console.warn("No dom overlay root found, HTML overlays on top of screen-based AR will not work.");const n=OY.createButton(i.context.renderer,r,this.onModifyAROptions.bind(this));return n.classList.add("webxr-ar-button"),n.classList.add("webxr-button"),Ss.resetButtonStyles(n),(e?.registerClick??!0)&&n.addEventListener("click",i.onClickedARButton.bind(i)),n}static onModifyAROptions(i){Ss.dispatchEvent("modify-ar-options",i)}static resetButtonStyles(i){i&&(i.style.position="",i.style.bottom="",i.style.left="")}endSession(){const i=this.context.renderer.xr.getSession();i&&i.end()}get Rig(){return this.rig||this.ensureRig(),this.rig}get Controllers(){return this.controllers}get LeftController(){var i,e;return this.controllers.length>0&&((i=this.controllers[0].input)==null?void 0:i.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 i,e;return this.controllers.length>0&&((i=this.controllers[0].input)==null?void 0:i.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=lr.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!$.findObjectOfType(hm,this.context)){const i=$.addNewComponent(this.gameObject,hm,!1);i.webXR=this}this.webAR=new dm(this)}start(){location.protocol=="http:"&&location.host.indexOf("localhost")<0&&(uo("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,Ss.XRSupported;let i,e;const t=document.createElement("div");t.classList.add("webxr-buttons"),this.context.domElement.append(t),this.enableAR&&this.createARButton&&Sb&&(i=Ss.createARButton(this),this._arButton=i,t.appendChild(i)),this.createVRButton&&this.enableVR&&Eb&&(e=Ss.createVRButton(this),this._vrButton=e,t.appendChild(e)),setTimeout(()=>{Ss.resetButtonStyles(e),Ss.resetButtonStyles(i)},1e3)}get TransformOrientation(){return this._transformOrientation}get HeadPose(){return this._currentHeadPose}onBeforeRender(i){var e;if(!i)return;const t=this.context.renderer.xr.getSession();if(t){const s=i.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(!s)return;this._currentHeadPose=s;const r=s?.transform;r&&this._transformOrientation.set(r.orientation.x,r.orientation.y,r.orientation.z,r.orientation.w),Ss._isInXr===!1&&t&&this.onEnterXR(t,i);for(const n of this.controllers)n.onUpdate(t);this._isInAR&&((e=this.webAR)==null||e.onUpdate(t,i))}Ss.events.dispatchEvent({type:"xrUpdate",frame:i,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 i=0;i<2;i++)cs.Create(this,i,this.gameObject,dp.PhysicalDevice);Ss.events.dispatchEvent({type:"requestVRSession"})}}captureStateBeforeXR(){this.context.mainCamera&&(this._originalCameraPosition.copy(wt(this.context.mainCamera)),this._originalCameraRotation.copy(ws(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 i=$.findObjectOfType(xb,this.context);i?this.rig=i.gameObject:(this.rig=new Rn,this.rig.rotateY(Math.PI),this.rig.name="XRRig",this.context.scene.add(this.rig))}}onEnterXR(i,e){var t,s;console.log("[XR] session begin",i),Ss._isInXr=!0,this.ensureRig();const r=this.context.renderer.xr.getReferenceSpace();if(r&&this.rig){const a=e.getViewerPose(r),l=a?.transform.orientation;if(l){const c=new xe(l.x,l.y,l.z,l.w),u=new fs().setFromQuaternion(c);this.rig.rotateY(u.y)}}const n=this.context.renderer.xr;if(this.context.mainCamera){const a=n.getCamera(this.context.mainCamera),l=(t=this.context.mainCameraComponent)==null?void 0:t.cullingMask;if(l!==void 0){for(const c of a.cameras)c.layers.mask=l;a.layers.mask=l}else{for(const c of a.cameras)c.layers.enableAll();a.layers.enableAll()}this.rig.add(this.context.mainCamera),this._requestedAR&&this.context.scene.add(this.rig)}const o=this._requestedAR?as.AR:as.VR;switch($o.Global.Set(o),o){case as.AR:this.context.xrSessionMode=Eg.ImmersiveAR,this._isInAR=!0,(s=this.webAR)==null||s.onBegin(i);break;case as.VR:this.context.xrSessionMode=Eg.ImmersiveVR,this._isInVR=!0,this.onEnterVR(i);break}i.addEventListener("end",()=>{console.log("[XR] session end"),Ss._isInXr=!1,this.onExitXR(i)}),this.onEnterXR_HandleMirrorWindow(i),Ss.events.dispatchEvent({type:"xrStarted",session:i})}onExitXR(i){var e,t,s;const r=this._isInAR;this._isInAR&&i&&((e=this.webAR)==null||e.onEnd(i)),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&&((t=this._originalCameraParent)==null||t.add(this.context.mainCamera),Yi(this.context.mainCamera,this._originalCameraPosition),Nr(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),r&&((s=this._originalXRRigParent)==null||s.add(this.rig),this.rig.position.copy(this._originalXRRigPosition),this.rig.quaternion.copy(this._originalXRRigRotation)),$o.Global.Set(as.Browser|as.ThirdPerson),Ss.events.dispatchEvent({type:"xrStopped",session:i})}onEnterVR(i){}destroyControllers(){var i;for(let e=this.controllers.length-1;e>=0;e-=1)(i=this.controllers[e])==null||i.destroy();this.controllers.length=0}onEnterXR_HandleMirrorWindow(i){oe("mirror")&&setTimeout(()=>{if(!Ss.IsInWebXR)return;const e=new URL(window.location.href);df(e.searchParams,Yy,1),df(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=()=>{Ss.IsInWebXR&&i.end()})})},1e3)}},h(gp,"_isInXr",!1),h(gp,"events",new vs),h(gp,"_optionalFeatures_VR",["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]),h(gp,"_optionalFeatures_AR",["anchors","local-floor","hand-tracking","layers"]),gp);let xt=Ss;fp([w()],xt.prototype,"enableVR",2),fp([w()],xt.prototype,"enableAR",2),fp([w(lr)],xt.prototype,"defaultAvatar",2),fp([w()],xt.prototype,"handModelPath",2),fp([w()],xt.prototype,"createVRButton",2),fp([w()],xt.prototype,"createARButton",2);const um=class{constructor(i){h(this,"_webxr"),h(this,"reticle",null),h(this,"reticleParent",null),h(this,"hitTestSource",null),h(this,"reticleActive",!0),h(this,"previousBackground",null),h(this,"previousEnvironment",null),h(this,"sessionRoot",null),h(this,"_previousParent",null),h(this,"arDomOverlay",null),h(this,"arOverlayElement",null),h(this,"noHitTestAvailable",!1),h(this,"didPlaceARSessionRoot",!1),this._webxr=i}get webxr(){return this._webxr}get context(){return this.webxr.context}getAROverlayContainer(){this.arDomOverlay=this.webxr.context.domElement;const i=this.arDomOverlay;return i.getAROverlayContainer?this.arOverlayElement=i.getAROverlayContainer():this.arOverlayElement=this.arDomOverlay,this.arOverlayElement}setReticleActive(i){this.reticleActive=i}async onBegin(i){var e,t,s,r;const n=this.webxr.context;this.reticleActive=!0,this.didPlaceARSessionRoot=!1,this.getAROverlayContainer();const o=(e=navigator.userAgent)!=null&&e.includes("OculusBrowser")?dp.PhysicalDevice:dp.Touch,a=o===dp.Touch?4:2;for(let c=0;c<a;c++)cs.Create(this.webxr,c,this.webxr.gameObject,o);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=$.findObjectOfType(Dc,n)),this.previousBackground=n.scene.background,this.previousEnvironment=n.scene.environment,n.scene.background=null,i.requestReferenceSpace("viewer").then(c=>{var u,d;(d=(u=i.requestHitTestSource)==null?void 0:u.call(i,{space:c}))==null||d.then(p=>{this.hitTestSource=p}).catch(p=>{this.noHitTestAvailable=!0,console.warn("WebXR: Hit test not supported",p)})}),!this.reticle&&this.sessionRoot&&(this.reticle=new ye(new of(.07,.09,32).rotateX(-Math.PI/2),new di),this.reticle.name="AR Placement reticle",this.reticle.matrixAutoUpdate=!1,this.reticle.visible=!1,this.reticleParent=new Me,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,um.tempWebXRObject||(um.tempWebXRObject=new Me),this.context.scene.add(um.tempWebXRObject),$.addComponent(um.tempWebXRObject,this.webxr),this.sessionRoot?(this.sessionRoot.webAR=this,(t=this.sessionRoot)==null||t.onBegin(i)):console.warn("No WebARSessionRoot found in scene");const l=this.context.domElement;(s=l?.onEnterAR)==null||s.call(l,i,this.arOverlayElement),(r=this.context.mainCameraComponent)==null||r.applyClearFlagsIfIsActiveCamera()}onEnd(i){var e,t;this._previousParent&&($.addComponent(this._previousParent,this.webxr),this._previousParent=null),this.hitTestSource=null;const s=this.webxr.context;s.scene.background=this.previousBackground,s.scene.environment=this.previousEnvironment,this.sessionRoot&&this.sessionRoot.onEnd(this.webxr.Rig,i);const r=this.context.domElement;(e=r.onExitAR)==null||e.call(r,i),(t=this.context.mainCameraComponent)==null||t.applyClearFlagsIfIsActiveCamera()}onUpdate(i,e){var t,s;if(this.noHitTestAvailable===!0){if(this.reticle&&(this.reticle.visible=!1),!this.didPlaceARSessionRoot){this.didPlaceARSessionRoot=!0;const n=this.webxr.Rig,o=Eee.clone();(t=this.sessionRoot)==null||t.placeAt(n,o)}return}if(!this.hitTestSource)return;const r=e.getHitTestResults(this.hitTestSource);if(r.length){const n=r[0],o=this.webxr.context.renderer.xr.getReferenceSpace();if(o){const a=n.getPose(o);if(this.sessionRoot){const l=this.sessionRoot.onUpdate(this.webxr.Rig,i,a);this.didPlaceARSessionRoot=l}if(this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&a)){const l=a.transform.matrix;this.reticle.matrix.fromArray(l),this.webxr.Rig&&this.reticle.matrix.premultiply(this.webxr.Rig.matrix)}}}else(s=this.sessionRoot)==null||s.onUpdate(this.webxr.Rig,i,null),this.reticle&&(this.reticle.visible=!1)}};let dm=um;h(dm,"tempWebXRObject");const Eee=new Qe().identity().makeTranslation(0,0,0);class ru{constructor(e,t){h(this,"used",!1),h(this,"inputSource"),h(this,"object"),h(this,"pointerId"),h(this,"isDown"),h(this,"isUp"),h(this,"isPressed"),h(this,"isClicked"),h(this,"input"),h(this,"event"),this.event=t,this.input=e}use(){this.used=!0,this.pointerId!==void 0&&this.input.setPointerUsed(this.pointerId)}stopPropagation(){var e;(e=this.event)==null||e.stopImmediatePropagation()}Use(){this.use()}StopPropagation(){var e;(e=this.event)==null||e.stopImmediatePropagation()}}class mp extends Ee{awake(){Wn.createIfNoneExists(this.context)}onEnable(){var e;(e=Wn.get(this.context))==null||e.register(this)}onDisable(){var e;(e=Wn.get(this.context))==null||e.unregister(this)}performRaycast(e=null){return null}}class nu extends mp{constructor(){super(...arguments),h(this,"targets",null),h(this,"raycastHits",[])}start(){this.targets=[this.gameObject]}performRaycast(e=null){return this.targets?(e??(e=new fo),e.targets=this.targets,e.results=this.raycastHits,this.context.physics.raycast(e)):null}}class BE extends nu{}const pm=oe("debugeventsystem");var kE=(i=>(i.BeforeHandleInput="BeforeHandleInput",i.AfterHandleInput="AfterHandleInput",i))(kE||{});const wl=class extends Ee{constructor(){super(),h(this,"raycaster",[]),h(this,"_selectStartFn"),h(this,"_selectEndFn"),h(this,"_selectUpdateFn"),h(this,"_handleEventFn"),h(this,"lastPointerEvent",null),h(this,"objectsHoveredThisFrame",[]),h(this,"objectsHoveredLastFrame",[]),h(this,"raisedPointerDownEvents",[]),h(this,"raisedPointerDownObjects",[]),h(this,"_didMove",!1),h(this,"_tempComponentsArray",[]),h(this,"_sortedHits",[]),h(this,"_sortingBuffer",[]),h(this,"_noDepthTestingResults",[]),h(this,"handleEventsArray",[]),h(this,"out",{}),h(this,"currentActiveMeshUIComponents",[]),wl.systems.push(this)}static createIfNoneExists(i){this.didSearchEventSystem||(this.didSearchEventSystem=!0,wl.systems.length<=0&&wl.systems.push(...$.findObjectsOfType(wl,i)));for(const t of wl.systems)if(t.context===i)return;const e=new Me;$.addNewComponent(e,wl),i.scene.add(e)}static get systems(){const i=_t.Current;return this._eventSystemMap.has(i)||this._eventSystemMap.set(i,[]),this._eventSystemMap.get(i)}static get(i){const e=this._eventSystemMap.get(i);return e&&e.length>0?e[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(i,e){xl.update(i,e)}static markUIDirty(i){xl.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.objectsHoveredThisFrame.length>0}onDestroy(){wl.systems.splice(wl.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!$.findObjectOfType(mp,this.context)){const i=$.addNewComponent(this.context.scene,nu);this.raycaster.push(i),_r()&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found",this)}}register(i){var e;i&&this.raycaster&&!this.raycaster.includes(i)&&((e=this.raycaster)==null||e.push(i))}unregister(i){var e,t;const s=(e=this.raycaster)==null?void 0:e.indexOf(i);s!==void 0&&s!==-1&&((t=this.raycaster)==null||t.splice(s,1))}onEnable(){const i=new Map;this._selectStartFn??(this._selectStartFn=(t,s)=>{if(!s.grab)return;xl.resetLastSelected();const r=new ru(this.context.input);r.inputSource=t,r.isDown=t.selectionDown,r.isUp=t.selectionUp,r.isPressed=t.selectionPressed,r.isClicked=!1,i.set(t,s.grab),s.grab&&!this.handleEvents(s.grab,r)&&(s.grab=null)}),this._selectEndFn??(this._selectEndFn=(t,s)=>{var r;if(!s.grab)return;const n=new ru(this.context.input);n.inputSource=t,n.isDown=t.selectionDown,n.isUp=t.selectionUp,n.isPressed=t.selectionPressed,n.isClicked=t.selectionClick,this.handleEvents(s.grab,n);const o=i.get(t);if(i.set(t,null),o)for(let a=0;a<this.raisedPointerDownEvents.length;a++){const l=this.raisedPointerDownEvents[a];this.raisedPointerDownObjects[a]===o&&l&&((r=l.onPointerUp)==null||r.call(l,n),this.raisedPointerDownEvents.splice(a,1),this.raisedPointerDownObjects.splice(a,1),a--)}});const e=new fo;this._selectUpdateFn??(this._selectUpdateFn=t=>{e.ray=t.getRay();const s=this.performRaycast(e);if(!s)return;const r=new ru(this.context.input);r.inputSource=t,this.handleIntersections(s,r)}),cs.addEventListener(bl.SelectStart,this._selectStartFn),cs.addEventListener(bl.SelectEnd,this._selectEndFn),cs.addEventListener(bl.Update,this._selectUpdateFn),this._handleEventFn??(this._handleEventFn=this.onHandleEvents.bind(this)),this.context.pre_update_callbacks.push(this._handleEventFn)}onDisable(){cs.removeEventListener(bl.SelectStart,this._selectStartFn),cs.removeEventListener(bl.SelectEnd,this._selectEndFn),cs.removeEventListener(bl.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(),xt.IsInWebXR||this.context.input.isKeyPressed("AltLeft")||this.context.input.isKeyPressed("AltRight"))return;if(!this._didMove){const n=this.context.input.getPointerPositionRC(0);if(n&&n.x===0&&n.y===0)return;this._didMove=!0}let i=0;for(const n of this.context.input.foreachPointerId()){const o=this.context.input.getPointerDown(n),a=this.context.input.getPointerUp(n);if(o||a){i=n;break}}const e=this.context.input.getPointerEvent(i),t=new ru(this.context.input,e);t.inputSource=this.context.input,t.pointerId=i,t.isClicked=this.context.input.getPointerClicked(i),t.isDown=this.context.input.getPointerDown(i),t.isUp=this.context.input.getPointerUp(i),t.isPressed=this.context.input.getPointerPressed(i),pm&&t.isClicked&&console.log("CLICK",i);const s=this.performRaycast(null);if(!s)return;this.lastPointerEvent=t;const r={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};pm&&t.isClicked&&Rs("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown),this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:r})),this.handleIntersections(s,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:r}))}onBeforeRender(){if(this.lastPointerEvent)this.lastPointerEvent.used=!1;else return;if(this.lastPointerEvent.isUp){for(const e of this.raisedPointerDownEvents)e.onPointerUp&&e.onPointerUp(this.lastPointerEvent);this.raisedPointerDownEvents.length=0,this.raisedPointerDownObjects.length=0}for(const e of this.objectsHoveredLastFrame)if(this.objectsHoveredThisFrame.indexOf(e)<0){this._tempComponentsArray.length=0;const t=$.getComponentsInParent(e,Ee,this._tempComponentsArray);this.lastPointerEvent.object=e;for(let s=0;s<t.length;s++){const r=t[s];if(!r.gameObject||r.destroyed)continue;const n=r;n.onPointerExit&&n.onPointerExit(this.lastPointerEvent)}}const i=this.objectsHoveredLastFrame;this.objectsHoveredLastFrame=this.objectsHoveredThisFrame,this.objectsHoveredThisFrame=i}performRaycast(i){if(!this.raycaster)return null;this._sortedHits.length=0;for(const e of this.raycaster){if(!e.activeAndEnabled)continue;const t=e.performRaycast(i);t&&t.length>0&&this._sortedHits.push(...t)}return this._sortedHits.sort((e,t)=>e.distance-t.distance),this._sortedHits}handleIntersections(i,e){if(!i||i.length<=0)return!1;i=this.sortCandidates(i);for(const t of i){const{object:s}=t;if(this.handleEvents(s,e))return!0}return!1}sortCandidates(i){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let e=0;e<i.length;e++){const t=i[e],s=t.object;if(s.material&&s.material.depthTest===!1){this._noDepthTestingResults.push(t);continue}this._sortingBuffer.push(t)}for(const e of this._sortingBuffer)this._noDepthTestingResults.push(e);return this._noDepthTestingResults}handleEvents(i,e){if(!this.testIsVisible(i))return e.isClicked&&pm&&console.log("not allowed",i),!1;const t=i;e.object=i,this.lastPointerEvent=e;const s=i.parent;let r=!1;const n=e.isClicked??!1;let o=null;if(s&&s.isUI){const a=(e.isPressed||e.isClicked)??!1;if(s[yl]){const l=s[yl].gameObject;if(l){if(!up.isInteractable(l,this.out))return!1;o=this.out.canvasGroup??null,this.handleMeshUIIntersection(i,a),i=l,r=!0}}if(!r&&this.handleMeshUiObjectWithoutShadowDom(s,a))return!0}if(n&&pm&&console.log(this.context.time.frame,i),this.objectsHoveredThisFrame.push(i),o===null||o.interactable){const a=this.objectsHoveredLastFrame.indexOf(i)>=0;this.handleEventsArray.length=0;const l=$.getComponentsInParent(i,Ee,this.handleEventsArray);for(let c=0;c<l.length;c++){if(e.used)return!0;if(l[c].destroyed)continue;const u=l[c];if(u.interactable!==!1){if(u.onPointerEnter&&(a||u.onPointerEnter(e)),u.onPointerMove&&u.onPointerMove(e),e.isDown&&u.onPointerDown&&!this.raisedPointerDownEvents.includes(u)&&(u.onPointerDown(e),this.raisedPointerDownEvents.push(u),this.raisedPointerDownObjects.push(t)),e.isUp&&u.onPointerUp){const d=this.raisedPointerDownEvents.indexOf(u);d!==-1&&this.raisedPointerDownEvents.splice(d,1),u.onPointerUp(e)}e.isClicked&&u.onPointerClick&&u.onPointerClick(e)}}}return!0}handleMeshUiObjectWithoutShadowDom(i,e){return!i||!i.isUI?!0:this.handleMeshUIIntersection(i,e)}handleMeshUIIntersection(i,e){const t=xl.updateState(i,e);return t&&this.currentActiveMeshUIComponents.push(t),t!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&xl.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let i=0;i<this.currentActiveMeshUIComponents.length;i++){const e=this.currentActiveMeshUIComponents[i];xl.resetState(e)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(i){return i?$.isActiveSelf(i)?this.testIsVisible(i.parent):!1:!0}};let Wn=wl;h(Wn,"_eventSystemMap",new Map),h(Wn,"didSearchEventSystem",!1);class xl{static markDirty(){this.needsUpdate=!0}static update(e,t){const s=t.time.frameCount;for(const r of this.lastUpdateFrame)if(r.context===t){if(s===r.frame)return;r.frame=s;let n=this.needsUpdate||s<1;r.nextUpdate===t.time.frameCount&&(n=!0),n&&(pm&&console.log("Update threemeshui"),this.needsUpdate=!1,e.update());return}this.lastUpdateFrame=[{context:t,frame:s,nextUpdate:s}],e.update()}static updateState(e,t){let s=null;if(e&&(s=this.findBlockInParent(e),s&&s!==this.lastSelected)){if(s.interactable===!1)return null;this.needsUpdate=!0}return s}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockInParent(e){return e?e.isBlock?e:this.findBlockInParent(e.parent):null}}h(xl,"lastSelected",null),h(xl,"lastUpdateFrame",[]),h(xl,"needsUpdate",!1);const Mb=Symbol("cameraController");function Mee(i){return i[Mb]}function WF(i,e,t){t?i[Mb]=e:i[Mb]===e&&(i[Mb]=null)}var Iee=Object.defineProperty,Tee=Object.getOwnPropertyDescriptor,Ree=(i,e,t,s)=>{for(var r=s>1?void 0:s?Tee(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Iee(e,t,r),r};const Ib=oe("freecam"),qF=oe("debugcamerafit"),Pee={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let DE;class Cl extends Ee{constructor(){super(...arguments),h(this,"autoRotate",!1),h(this,"autoRotateSpeed",1),h(this,"enableKeys",!0),h(this,"enableDamping",!0),h(this,"dampingFactor",.1),h(this,"enableZoom",!0),h(this,"minZoom",0),h(this,"maxZoom",1/0),h(this,"enablePan",!0),h(this,"lookAtConstraint",null),h(this,"lookAtConstraint01",1),h(this,"middleClickToFocus",!0),h(this,"doubleClickToFocus",!0),h(this,"useSlerp",!0),h(this,"debugLog",!1),h(this,"targetLerpSpeed",5),h(this,"_lookTargetPosition"),h(this,"_controls",null),h(this,"_cameraObject",null),h(this,"_lerpToTargetPosition",!1),h(this,"_lerpCameraToTarget",!1),h(this,"_cameraTargetPosition",null),h(this,"_inputs",0),h(this,"_enableTime",0),h(this,"_startedListeningToKeyEvents",!1),h(this,"_eventSystem"),h(this,"_afterHandleInputFn"),h(this,"_camera",null),h(this,"_syncedTransform"),h(this,"targetElement",null),h(this,"_shouldDisable",!1),h(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 S,this._startedListeningToKeyEvents=!1}start(){if(this._controls){const e=$.getComponent(this.gameObject,Mi);if(e&&!this.setFromTargetPosition()){this.debugLog&&console.log("NO TARGET");const t=wt(e.cam).length(),s=new S(0,0,-t).applyMatrix4(e.cam.matrixWorld);this.setTarget(s,!0)}}this.startCoroutine(this.startRaycastDelayed()),this._eventSystem=Wn.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(kE.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var e,t;(e=this._controls)==null||e.dispose(),(t=this._eventSystem)==null||t.removeEventListener(kE.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._enableTime=this.context.time.time;const e=$.getComponent(this.gameObject,Mi);this._camera=e;const t=e?.cam;if(t&&WF(t,this,!0),!this._controls){console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t);const s=this.targetElement??this.context.domElement;this._controls=new DY(t,s),DE===void 0&&(DE={...this._controls.keys})}this._controls&&(Ib&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,lh()&&(this.doubleClickToFocus=!0)),this._controls.enableDamping=this.enableDamping,this._controls.keys=this.enableKeys?DE:Pee,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.addEventListener("start",this.onControlsChangeStarted.bind(this)),t?.type==="PerspectiveCamera"?Ib||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):Ib||(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=$.getComponent(this.gameObject,Uc)??void 0}onDisable(){var e;(e=this._camera)!=null&&e.cam&&WF(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 fo;e.screenPoint=new W(0,0),e.lineThreshold=.1;const t=this.context.physics.raycast(e);t.length>0&&this.setTarget(t[0].point,!0)}}onBeforeRender(){var e,t,s;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 r=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(r||(r=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3),r?this.setTargetFromRaycast():(this.context.input.getPointerDown(0)||this.context.input.mouseWheelChanged)&&(this._lerpToTargetPosition=!1,this._lerpCameraToTarget=!1),this._lerpToTargetPosition||this._lerpCameraToTarget){const n=this.context.time.deltaTime*this.targetLerpSpeed;if(this._lerpCameraToTarget&&this._cameraTargetPosition&&this._cameraObject){if(this.useSlerp){const o=(e=this._cameraObject)==null?void 0:e.position;wB(o,this._cameraTargetPosition,n)}else(t=this._cameraObject)==null||t.position.lerp(this._cameraTargetPosition,n);this._cameraObject.position.distanceTo(this._cameraTargetPosition)<1e-4&&(this._lerpCameraToTarget=!1)}this._lerpToTargetPosition&&(this.lerpTarget(this._lookTargetPosition,n),this._lookTargetPosition.distanceTo(this._controls.target)<1e-5&&(this._lerpToTargetPosition=!1))}!Ib&&(s=this.lookAtConstraint)!=null&&s.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 s;e?(this._lerpCameraToTarget=!0,this._cameraTargetPosition=e.clone(),t&&this._cameraTargetPosition&&((s=this.controllerObject)==null||s.position.copy(this._cameraTargetPosition))):this._lerpCameraToTarget=!1}setFromTargetPosition(e=0,t=1){var s;if(!this._controls)return!1;const r=(s=this.lookAtConstraint)==null?void 0:s.sources;if(r&&r.length>0){const n=r[e];if(n)return n.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 e,t;if(!this.controls)return;const s=this.context.physics.raycast();for(const r of s)if(r.distance>0&&$.isActiveInHierarchy(r.object)){if(this._lookTargetPosition.copy(r.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;const n=wt(this.context.mainCamera);this._cameraTargetPosition=n.clone().sub(this.controls.target).add(this._lookTargetPosition),(t=(e=this._cameraObject)==null?void 0:e.parent)==null||t.worldToLocal(this._cameraTargetPosition)}break}}fitCamera(e,t=1.1){const s=this._cameraObject,r=this._controls;if(e!=null&&e.length||(e=this.context.scene.children),!s||!r)return;const n=new S,o=new S,a=new ir;a.makeEmpty();for(const m of e)m instanceof f1||a.expandByObject(m,!0);s.updateMatrixWorld(),s.updateProjectionMatrix(),a.getCenter(o),a.applyMatrix4(s.matrixWorldInverse),a.getSize(n),a.setFromCenterAndSize(o,n);const l=s.fov,c=2*Math.atan(Math.tan(l*Math.PI/360/2)*s.aspect)/Math.PI*360,u=n.y/(2*Math.atan(Math.PI*l/360)),d=n.x/(2*Math.atan(Math.PI*c/360)),p=t*Math.max(u,d)+n.z/2;qF&&console.log("Fit camera to objects",u,d,"distance",p);const f=wt(s),g=r.target.clone().sub(f).normalize().multiplyScalar(p);if(r.maxDistance=p*10,r.minDistance=p*.01,r.target.copy(o),s.near=p/100,s.far=p*100,s.updateMatrixWorld(),s.updateProjectionMatrix(),Yi(s,r.target.clone().sub(g)),qF){const m=new f1(a);this.context.scene.add(m),RB(m,x0(s)),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",v=>{v.code==="KeyF"&&this.fitCamera(e)}))}r.update()}}Ree([w(qg)],Cl.prototype,"lookAtConstraint",2);var Bee=Object.defineProperty,kee=Object.getOwnPropertyDescriptor,qn=(i,e,t,s)=>{for(var r=s>1?void 0:s?kee(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Bee(e,t,r),r},XF=(i=>(i[i.Skybox=1]="Skybox",i[i.SolidColor=2]="SolidColor",i[i.Uninitialized=4]="Uninitialized",i))(XF||{});const fm=oe("debugcam"),YF=oe("debugscreenpointtoray");var Tb;const gm=(Tb=class extends Ee{constructor(){super(...arguments),h(this,"_nearClipPlane",.1),h(this,"_farClipPlane",1e3),h(this,"orthographic",!1),h(this,"orthographicSize",5),h(this,"ARBackgroundAlpha",0),h(this,"_cullingMask",4294967295),h(this,"_backgroundBlurriness"),h(this,"_backgroundIntensity"),h(this,"_targetTexture",null),h(this,"_backgroundColor"),h(this,"_fov"),h(this,"_cam",null),h(this,"_clearFlags",2),h(this,"_skybox")}get isCamera(){return!0}get aspect(){return this._cam instanceof Xt?this._cam.aspect:this.context.domWidth/this.context.domHeight}get fieldOfView(){return this._cam instanceof Xt?this._cam.fov:this._fov}set fieldOfView(i){const e=this._fov!=i;if(this._fov=i,e&&this._cam&&this._cam instanceof Xt){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(i){const e=this._nearClipPlane!=i;this._nearClipPlane=i,this._cam&&e&&(this._cam.near=i,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(i){const e=this._farClipPlane!=i;this._farClipPlane=i,this._cam&&e&&(this._cam.far=i,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(i){i!==this._clearFlags&&(this._clearFlags=i,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(i){this._cullingMask=i,this._cam&&(this._cam.layers.mask=i)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set backgroundBlurriness(i){i!==this._backgroundBlurriness&&(i===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(i,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(i){i!==this._backgroundIntensity&&(i===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(i,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(i){if(i){if(this._backgroundColor)this._backgroundColor.copy(i);else{if(!i.clone)return;this._backgroundColor=i.clone()}i.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(i){this._targetTexture=i}get targetTexture(){return this._targetTexture}get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(i,e,t){let s=this.cam;const r=gm._origin;r.set(i,e,-1),this.context.input.convertScreenspaceToRaycastSpace(r),YF&&console.log("screenPointToRay",i.toFixed(2),e.toFixed(2),"now:",r.x.toFixed(2),r.y.toFixed(2),"isInXR:"+this.context.isInXR),r.z=-1,r.unproject(s);const n=gm._direction.set(r.x,r.y,r.z),o=wt(s);return n.sub(o),n.normalize(),t?(t.set(o,n),t):new za(o.clone(),n.clone())}awake(){this.sourceId||console.warn("Camera has no source - the camera should be exported inside a gltf",this.name),YF&&window.addEventListener("pointerdown",i=>{const e=i.clientX,t=i.clientY;console.log("touch",e.toFixed(2),t.toFixed(2));const s=this.screenPointToRay(e,t),r="#"+Math.floor(Math.random()*16777215).toString(16);Jo.DrawRay(s.origin,s.direction,r,10)})}onEnable(){fm&&console.log(this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),Oee(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 i=this.context.renderer;i&&this._targetTexture.render(this.context.scene,this._cam,i)}}buildCamera(){if(this._cam)return;const i=this.gameObject.isCamera;let e=null;if(i?(e=this.gameObject,e?.layers.enableAll(),e instanceof Xt&&(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 Xt(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 sd(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){fm&&console.log("Camera does not exist (apply clear flags)");return}switch(fm&&Rs("apply Camera clear flags: "+this._clearFlags),this._clearFlags){case 1:if(gm.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 i=this._backgroundColor.alpha;gm.backgroundShouldBeTransparent(this.context)&&(i=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,i)}break;case 4:this.context.scene.background=null,this.context.renderer.setClearColor(0,0);break}}enableSkybox(){this._skybox||(this._skybox=new Dee(this)),this._skybox.enable()}static backgroundShouldBeTransparent(i){var e,t,s,r;const n=(e=i.renderer.xr)==null?void 0:e.getSession();if(!n)return!1;const o=n.environmentBlendMode;fm&&Rs("Environment blend mode: "+o+" on "+navigator.userAgent);const a=o==="additive"||o==="alpha-blend";return i.xrSessionMode===Eg.ImmersiveAR&&o==="opaque"&&((t=navigator.userAgent)!=null&&t.includes("OculusBrowser")||(s=navigator.userAgent)!=null&&s.includes("Mozilla")&&(r=navigator.userAgent)!=null&&r.includes("Mobile WebXRViewer/v2"))?!0:a}},h(Tb,"_origin",new S),h(Tb,"_direction",new S),Tb);let Mi=gm;qn([w()],Mi.prototype,"fieldOfView",1),qn([w()],Mi.prototype,"nearClipPlane",1),qn([w()],Mi.prototype,"farClipPlane",1),qn([w()],Mi.prototype,"clearFlags",1),qn([w()],Mi.prototype,"orthographic",2),qn([w()],Mi.prototype,"orthographicSize",2),qn([w()],Mi.prototype,"ARBackgroundAlpha",2),qn([w()],Mi.prototype,"cullingMask",1),qn([w()],Mi.prototype,"backgroundBlurriness",1),qn([w()],Mi.prototype,"backgroundIntensity",1),qn([w(vi)],Mi.prototype,"backgroundColor",1),qn([w(Yd)],Mi.prototype,"targetTexture",1);class Dee{constructor(e){h(this,"_camera"),h(this,"_skybox"),this._camera=e}get context(){var e;return(e=this._camera)==null?void 0:e.context}enable(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?this.context.scene.background!==this._skybox&&(fm&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=yt,this._skybox.mapping=Sn,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this._camera.sourceId,this.context.lightmaps)}}function Oee(i){oe("freecam")&&i.context.mainCameraComponent===i&&$.getOrAddComponent(i.gameObject,Cl)}class vp extends Ee{constructor(){super(...arguments),h(this,"_listener",null)}get listener(){return this._listener==null&&(this._listener=new l1),this._listener}awake(){os.registerWaitForAllowAudio(()=>{if(this.destroyed)return;const e=this.listener;if(e==null||e.parent)return;const t=$.getComponentInParent(this.gameObject,Mi);t?t.cam.add(e):this.gameObject.add(e)})}}var Lee=Object.defineProperty,Fee=Object.getOwnPropertyDescriptor,Rb=(i,e,t,s)=>{for(var r=s>1?void 0:s?Fee(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Lee(e,t,r),r};class mm{constructor(){h(this,"guid")}}Rb([w()],mm.prototype,"guid",2);class Ap{constructor(){h(this,"signal"),h(this,"reaction")}}Rb([w(mm)],Ap.prototype,"signal",2),Rb([w(Vr)],Ap.prototype,"reaction",2);var OE;const Sl=(OE=class extends Ee{constructor(){super(...arguments),h(this,"events")}static invoke(i){if(Sl.receivers[i]){const e=Sl.receivers[i];if(!e)return;for(const t of e)t.invoke(i)}}onEnable(){if(this.events)for(const i of this.events)Sl.receivers[i.signal.guid]||(Sl.receivers[i.signal.guid]=[]),Sl.receivers[i.signal.guid].push(this)}onDisable(){if(this.events){for(const i of this.events)if(Sl.receivers[i.signal.guid]){const e=Sl.receivers[i.signal.guid].indexOf(this);e>=0&&Sl.receivers[i.signal.guid].splice(e,1)}}}invoke(i){if(!this.events||!Array.isArray(this.events))return;let e=typeof i=="object"?i.guid:i;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(s){console.error(s)}}},h(OE,"receivers",{}),OE);let yp=Sl;Rb([w(Ap)],yp.prototype,"events",2);var fn=(i=>(i.Activation="ActivationTrack",i.Animation="AnimationTrack",i.Audio="AudioTrack",i.Control="ControlTrack",i.Marker="MarkerTrack",i.Signal="SignalTrack",i))(fn||{}),Qc=(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))(Qc||{}),LE=(i=>(i.Signal="SignalEmitter",i))(LE||{});const vm=oe("debugtimeline"),FE=class extends Ee{constructor(){super(...arguments),h(this,"playableAsset"),h(this,"playOnAwake"),h(this,"extrapolationMode",1),h(this,"waitForAudio",!0),h(this,"_visibilityChangeEvt"),h(this,"_clonedPlayableAsset",!1),h(this,"_speed",1),h(this,"_guidsMap"),h(this,"_isPlaying",!1),h(this,"_internalUpdateRoutine"),h(this,"_isPaused",!1),h(this,"_time",0),h(this,"_duration",0),h(this,"_weight",1),h(this,"_animationTracks",[]),h(this,"_audioTracks",[]),h(this,"_signalTracks",[]),h(this,"_controlTracks",[]),h(this,"_customTracks",[]),h(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks])}static registerCreateTrack(i,e){this.createTrackFunctions[i]=e}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(i){typeof i=="number"&&!Number.isNaN(i)?this._time=i:(vm||gr())&&console.error("INVALID TIMELINE.TIME VALUE",i,this.name)}get duration(){return this._duration}set duration(i){this._duration=i}get weight(){return this._weight}set weight(i){this._weight=i}get speed(){return this._speed}set speed(i){this._speed=i}awake(){var i,e,t;vm&&console.log(this,(i=this.playableAsset)==null?void 0:i.tracks),this.rebuildGraph(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,(e=this.playableAsset)==null?void 0:e.tracks,Array.isArray((t=this.playableAsset)==null?void 0:t.tracks),this)}onEnable(){var i,e;for(const t of this._audioTracks)(i=t.onEnable)==null||i.call(t);for(const t of this._customTracks)(e=t.onEnable)==null||e.call(t);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 i,e;this.stop();for(const t of this._audioTracks)(i=t.onDisable)==null||i.call(t);for(const t of this._customTracks)(e=t.onDisable)==null||e.call(t);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var i;for(const e of this._allTracks)for(const t of e)(i=t.onDestroy)==null||i.call(t)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const i=this._isPaused==!0;if(this._isPaused=!1,i&&this.invokePauseChangedMethodsOnTracks(),!this._isPlaying){if(this._isPlaying=!0,this.waitForAudio){const e=[];for(const t of this._audioTracks){const s=t.loadAudio(this._time,1,0);s&&e.push(s)}if(e.length>0&&(await Promise.all(e),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!os.userInteractionRegistered&&this.waitForAudio;)await pf(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 t of this._audioTracks)t.stop();const i=this._isPaused==!0,e=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.evaluate(),i&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,i&&!e&&this.invokePauseChangedMethodsOnTracks(),this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null}evaluate(){if(!this.isValid())return;let i=this._time;switch(this.extrapolationMode){case 0:this._speed>0?i=Math.min(i,this._duration):this._speed<0&&(i=Math.max(i,0)),this._time=i;break;case 1:i%=this._duration,this._time=i;break;case 2:if(i>this._duration){this.stop();return}break}this.internalEvaluate(i)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(const i of this._allTracks)for(const e of i)yield e}get audioTracks(){return this._audioTracks}resolveGuids(i){this._guidsMap=i}invokePauseChangedMethodsOnTracks(){var i;for(const e of this.forEachTrack())(i=e.onPauseChanged)==null||i.call(e)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.evaluate()),yield}internalEvaluate(i){for(const e of this.playableAsset.tracks)if(!e.muted)switch(e.type){case fn.Activation:for(let t=0;t<e.outputs.length;t++){const s=e.outputs[t];if(typeof s=="object"){let r=!1;for(const o of e.clips)o.start<=i&&i<=o.end&&(r=!0);const n=s;n.visible!==void 0&&(n.visible=r)}}break}for(const e of this._animationTracks)e.evaluate(i);for(const e of this._audioTracks)e.evaluate(i);for(const e of this._signalTracks)e.evaluate(i);for(const e of this._controlTracks)e.evaluate(i);for(const e of this._customTracks)e.evaluate(i)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Qv(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const i=this.findRoot(this.gameObject);for(const e of this.playableAsset.tracks){for(let t=e.outputs.length-1;t>=0;t--){let s=e.outputs[t];if(typeof s=="string"){this._guidsMap&&this._guidsMap[s]&&(s=this._guidsMap[s]);const r=$.findByGuid(s,i);r===null||typeof r!="object"?(e.outputs.splice(t,1),console.warn("Failed to resolve binding",s,e.name,e.type)):(vm&&console.log("Resolved binding",s,"to",r),e.outputs[t]=r)}else if(s===null){if(e.outputs.splice(t,1),FE.createTrackFunctions[e.type])continue;e.type!==fn.Audio&&e.type!==fn.Control&&e.type!==fn.Marker&&e.type!==fn.Signal&&console.warn("Missing binding",s,e.name,e.type,this.name,this.playableAsset.name)}}if(e.type===fn.Control)for(let t=0;t<e.clips.length;t++){const s=e.clips[t];let r=s.asset.sourceObject;if(typeof r=="string"){this._guidsMap&&this._guidsMap[r]&&(r=this._guidsMap[r]);const n=$.findByGuid(r,i);n===null||typeof n!="object"?console.warn("Failed to resolve sourceObject binding",r,e.name,s):(vm&&console.log("Resolved binding",r,"to",n),s.asset.sourceObject=n)}}}}findRoot(i){return i.parent?this.findRoot(i.parent):i}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const i of this.playableAsset.tracks)if(i.muted!==!0){for(const e of i.clips)e.end>this._duration&&(this._duration=e.end);for(const e of i.markers)e.time>this._duration&&(this._duration=e.time+.001)}}}setupAndCreateTrackHandlers(){var i,e;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;const t=$.findObjectOfType(vp,this.context);for(const s of this.playableAsset.tracks){const r=s.type,n=FE.createTrackFunctions[r];if(n!=null){const o=n(this,s);if(typeof o.evaluate=="function"){o.director=this,o.track=s,this._customTracks.push(o);continue}}if(s.type===fn.Animation){if(s.clips.length<=0){vm&&console.warn("Animation track has no clips",s);continue}for(let o=s.outputs.length-1;o>=0;o--){let a=s.outputs[o];if(a instanceof Me){const c=$.getOrAddComponent(a,Gr);c&&(a=c)}const l=(i=a?.gameObject)==null?void 0:i.animations;if(l){const c=new Pb;c.trackOffset=s.trackOffset,c.director=this,c.track=s;for(let u=0;u<s.clips.length;u++){const d=s.clips[u],p=d.asset;if(!p){console.error("MISSING anim model?","clip#"+u,d,s,this.playableAsset,this.name);continue}const f=p.clip;let g=f;if((typeof g=="string"||typeof g=="number")&&(g=l.find(v=>v.name===f)),!g){console.warn("Could not find animationClip for model",d,s.name,this.name,(e=this.playableAsset)==null?void 0:e.name);continue}c.mixer||(c.mixer=new c0(a.gameObject)),c.clips.push(g),c.mixer.uncacheAction(g),c.createHooks(d.asset,g);const m=c.mixer.clipAction(g);c.actions.push(m),c.models.push(d)}this._animationTracks.push(c)}}}else if(s.type===fn.Audio){if(s.clips.length<=0)continue;const o=new _m;if(o.director=this,o.track=s,this._audioTracks.push(o),!t)continue;o.listener=t.listener;for(let a=0;a<s.clips.length;a++){const l=s.clips[a];o.addModel(l)}}else if(s.type===fn.Marker){const o=new wm;o.director=this,o.track=s;for(const a of s.markers)switch(a.type){case LE.Signal:o.models.push(a),o.didTrigger.push(!1);break}if(o!==null&&o.models.length>0){const a=$.getComponent(this.gameObject,yp);a&&(o.receivers.push(a),this._signalTracks.push(o))}}else if(s.type===fn.Signal){const o=new wm;o.director=this,o.track=s;for(const a of s.markers)o.models.push(a),o.didTrigger.push(!1);for(const a of s.outputs)o.receivers.push(a);this._signalTracks.push(o)}else if(s.type===fn.Control){const o=new Bb;o.director=this,o.track=s;for(const a of s.clips)o.models.push(a);o.resolveSourceObjects(this.context),this._controlTracks.push(o)}}}setAudioTracksAllowPlaying(i){for(const e of this._audioTracks)e.onAllowAudioChanged(i)}};let Am=FE;h(Am,"createTrackFunctions",{});const ou=oe("debugtimeline");class ym{constructor(){h(this,"director"),h(this,"track")}get muted(){return this.track.muted}set muted(e){var t;e!==this.track.muted&&(this.track.muted=e,(t=this.onMuteChanged)==null||t.call(this))}*forEachClip(e=!1){var t;if((t=this.track)!=null&&t.clips)if(e)for(let s=this.track.clips.length-1;s>=0;s--)yield this.track.clips[s];else for(const s of this.track.clips)yield s}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,s,r=!0){if(t<0||t>=s.length)return 0;const n=s[t];if(r||e>=n.start&&e<=n.end){let o=1,a=!1;if(n.easeInDuration>0){const l=Math.min((e-n.start)/n.easeInDuration,1);o*=l}if(n.easeOutDuration>0&&!a){const l=Math.min((n.end-e)/n.easeOutDuration,1);o*=l}return o}return 0}}class Uee{constructor(e){h(this,"clip"),h(this,"rootPositionOffset"),h(this,"rootQuaternionOffset"),h(this,"rootStartPosition"),h(this,"rootEndPosition"),h(this,"rootStartQuaternion"),h(this,"rootEndQuaternion");const t=e.getClip();this.clip=t;const s=e.getRoot(),r=s.name+".position",n=s.name+".quaternion";ou&&console.log(t.name,t.tracks,r);for(const o of t.tracks)if(!(o.times.length<=0)){if(o.name.endsWith(r))this.rootStartPosition=new S().fromArray(o.values,0),this.rootEndPosition=new S().fromArray(o.values,o.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),ou&&console.log(this.rootPositionOffset);else if(o.name.endsWith(n)&&(this.rootStartQuaternion=new xe().fromArray(o.values,0),this.rootEndQuaternion=new xe().fromArray(o.values,o.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),ou)){const a=new fs().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",a)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class Pb extends ym{constructor(){super(...arguments),h(this,"models",[]),h(this,"trackOffset"),h(this,"target"),h(this,"mixer"),h(this,"clips",[]),h(this,"actions",[]),h(this,"_actionOffsets",[]),h(this,"_didBind",!1),h(this,"_animator",null),h(this,"_animatorWasEnabled",!1),h(this,"_useclipOffsets",!0),h(this,"_totalOffsetPosition",new S),h(this,"_totalOffsetRotation",new xe),h(this,"_totalOffsetPosition2",new S),h(this,"_totalOffsetRotation2",new xe),h(this,"_summedPos",new S),h(this,"_tempPos",new S),h(this,"_summedRot",new xe),h(this,"_tempRot",new xe),h(this,"_clipRotQuat",new xe)}onPauseChanged(){this._animator&&this._animatorWasEnabled!==void 0&&(this._animator.enabled=this.director.isPlaying===!1?this._animatorWasEnabled:!1)}createHooks(e,t){var s,r;if(((s=t.tracks)==null?void 0:s.length)<=0){console.warn("No tracks in AnimationClip",t);return}const n=t.tracks[0].name.split("."),o=n[n.length-2],a=o+".position",l=o+".quaternion";let c=!1,u=!1;for(const d of t.tracks)d.name.endsWith(a)?(c=!0,this.createPositionInterpolant(t,e,d)):d.name.endsWith(l)&&(u=!0,this.createRotationInterpolant(t,e,d));if(!c||!u){const d=(r=this.mixer)==null?void 0:r.getRoot(),p=t.tracks[0],f=p.name.lastIndexOf("."),g=p.name.substring(0,f),m=g.substring(g.lastIndexOf(".")+1),v=d.getObjectByName(m);if(v)if(c){if(!u){const A=t.tracks[0].name.substring(0,f)+".quaternion";ou&&console.warn("Create quaternion track",m,v);const b=v.quaternion,y=new Fo(A,[0,t.duration],[b.x,b.y,b.z,b.w,b.x,b.y,b.z,b.w]);t.tracks.push(y),this.createRotationInterpolant(t,e,y)}}else{const A=g+".position";ou&&console.warn("Create position track",m,v);const b=v.position,y=new nc(A,[0,t.duration],[b.x,b.y,b.z,b.x,b.y,b.z]);t.tracks.push(y),this.createPositionInterpolant(t,e,y)}}}bind(){if(!this._didBind){this._didBind=!0,ou&&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 Uee(e);this._actionOffsets.push(t)}this.target&&(this._animator=$.getComponent(this.target,Gr)??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,s=t.position,r=t.rotation;s&&s.x!==void 0&&(s.isVector3||(t.position=new S(s.x,s.y,s.z)),r.isQuaternion||(t.rotation=new xe(r.x,r.y,r.z,r.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new S(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new xe(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,s=0,r=!1,n=!1;for(let o=0;o<this.clips.length;o++){const a=this.models[o],l=this.actions[o],c=a.asset;l.weight=0;const u=e>=a.start&&e<=a.end,d=a.preExtrapolationMode,p=a.postExtrapolationMode,f=o<this.clips.length-1?this.models[o+1]:null;let g=u,m=!1;if(!g&&!r&&a.end<e&&p!==Qc.None?(!f||f.start>e)&&(g=!0,r=!0):o==0&&!g&&!n&&a.start>e&&d!==Qc.None&&(!f||f.start<e)&&(g=!0,m=!0,n=!0),g){let v=1;v*=this.evaluateWeight(e,o,this.models,g),v*=this.director.weight;let A=u;m&&d!==Qc.Hold&&(e+=a.start,A=!0);let b=this.getClipTime(e,a),y=0;const _=c.duration;if(m&&d===Qc.Hold&&(b=0),A){if(c.loop)for(y+=Math.floor(b/(_+1e-6));b>_;)b-=_}else if(!u)switch(p){case Qc.Loop:b%=_;break;case Qc.PingPong:const M=Math.floor(b/_)%2!==0;b%=_,M&&(b=_-b);break}a.reversed===!0?l.time=l.getClip().duration-b:l.time=b,l.timeScale=0;const x=v;if(l.weight=x,l.clampWhenFinished=!0,l.isRunning()||l.play(),this._useclipOffsets){const M=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,P=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(s=1-v),t+=1;const C=this._summedPos.set(0,0,0),R=this._tempPos.set(0,0,0),T=this._summedRot.identity(),z=this._tempRot.identity(),G=c.rotation;G&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(G,v));const N=this._actionOffsets[o];if(N.hasOffsets)for(let F=0;F<y;F++)N.rootPositionOffset?R.copy(N.rootPositionOffset):R.set(0,0,0),R.applyQuaternion(T),this._clipRotQuat&&R.applyQuaternion(this._clipRotQuat),N.rootQuaternionOffset&&(z.copy(N.rootQuaternionOffset),T.multiply(z)),C.add(R);this._clipRotQuat&&P.multiply(this._clipRotQuat),P.multiply(T),c.position&&C.add(c.position),M.add(C)}}}this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,s),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,s)),this.mixer.update(e)}createRotationInterpolant(e,t,s){var r;const n=s.createInterpolant.bind(s),o=new xe;this.ensureTrackOffsets();const a=(r=this.trackOffset)==null?void 0:r.rotation;s.createInterpolant=()=>{const l=n(),c=l.evaluate.bind(l);return l.evaluate=u=>{const d=c(u);return o.set(d[0],d[1],d[2],d[3]),o.premultiply(this._totalOffsetRotation),a&&o.premultiply(a),d[0]=o.x,d[1]=o.y,d[2]=o.z,d[3]=o.w,d},l}}createPositionInterpolant(e,t,s){var r,n;const o=s.createInterpolant.bind(s),a=new S;this.ensureTrackOffsets();const l=(r=this.trackOffset)==null?void 0:r.rotation,c=(n=this.trackOffset)==null?void 0:n.position;let u;s.createInterpolant=()=>{const d=o(),p=d.evaluate.bind(d);return d.evaluate=f=>{var g,m;const v=p(f);return a.set(v[0],v[1],v[2]),t.removeStartOffset&&(u===void 0?(u=null,u=(m=(g=this._actionOffsets.find(A=>A.clip===e))==null?void 0:g.rootStartPosition)==null?void 0:m.clone()):u!=null&&u.isVector3&&a.sub(u)),a.applyQuaternion(this._totalOffsetRotation),a.add(this._totalOffsetPosition),l&&a.applyQuaternion(l),c&&(a.x-=c.x,a.y+=c.y,a.z+=c.z),v[0]=a.x,v[1]=a.y,v[2]=a.z,v},d}}}const Nee=oe("mutetimeline"),bm=class extends ym{constructor(){super(...arguments),h(this,"models",[]),h(this,"listener"),h(this,"audio",[]),h(this,"audioContextTimeOffset",[]),h(this,"lastTime",0),h(this,"_audioLoader",null)}getAudioFilePath(i){const e=this.director.sourceId;return zl(e,i)}onAllowAudioChanged(i){for(let e=0;e<this.models.length;e++){const t=this.models[e];this.audio[e].setVolume(i?t.asset.volume:0)}}addModel(i){const e=new l0(this.listener);this.audio.push(e),this.models.push(i)}onDisable(){for(const i of this.audio)i.isPlaying&&i.stop()}onMuteChanged(){if(this.muted)for(let i=0;i<this.audio.length;i++){const e=this.audio[i];e!=null&&e.isPlaying&&e.stop()}}stop(){for(let i=0;i<this.audio.length;i++){const e=this.audio[i];e!=null&&e.isPlaying&&e.stop()}}evaluate(i){if(Nee||this.track.muted||this.director.speed<0)return;const e=this.director.context.application.muted,t=e?.1:0;for(let s=0;s<this.models.length;s++){const r=this.models[s],n=this.audio[s];if((!n||!n.buffer)&&this.isInTimeRange(r,i-1,i+1)&&this.handleAudioLoading(r,n),os.userInteractionRegistered!==!1&&!(n===null||!n.buffer))if(n.playbackRate=this.director.context.time.timeScale,n.loop=r.asset.loop,i>=r.start&&i<=r.end&&i<this.director.duration){if(this.director.isPlaying==!1){if(n.isPlaying&&n.stop(),this.lastTime===i)continue}else if(!n.isPlaying)n.offset=r.clipIn+(i-r.start)*r.timeScale,n.play(t);else{const a=r.clipIn+(i-r.start)*r.timeScale,l=n.context.currentTime-n._startedAt+n.offset;Math.abs(a-l)>.3&&(n.offset=a,n.stop(),n.play(t))}let o=r.asset.volume;if(e&&(o=0),r.easeInDuration>0){const a=Math.min((i-r.start)/r.easeInDuration,1);o*=a}if(r.easeOutDuration>0){const a=Math.min((r.end-i)/r.easeOutDuration,1);o*=a}n.setVolume(o*this.director.weight)}else n.isPlaying&&n.stop()}this.lastTime=i}loadAudio(i,e=0,t=0){let s=null;const r=i-t,n=i+e;for(const o of this.models)if(this.isInTimeRange(o,r,n)){const a=this.audio[this.models.indexOf(o)],l=this.handleAudioLoading(o,a);l!==null&&(s===null&&(s=[]),s.push(l))}return s!==null?Promise.all(s):null}isInTimeRange(i,e,t){return e<=i.start&&t>=i.end||e>=i.start&&e<=i.end||t>=i.start&&t<=i.end}static dispose(){bm._currentlyLoading.clear()}handleAudioLoading(i,e){this._audioLoader||(this._audioLoader=new o0);const t=this.getAudioFilePath(i.asset.clip);if(bm._currentlyLoading.get(t)){const r=bm._currentlyLoading.get(t);return r.then(n=>{n&&e.setBuffer(n)}),r}ou&&console.warn("LOAD audio track",t,this.director.sourceId);const s=new Promise((r,n)=>{this._audioLoader.load(t,o=>{e.setBuffer(o),r(o)},void 0,o=>{console.error("Error loading audio",o),r(null)})});return bm._currentlyLoading.set(t,s),s}};let _m=bm;h(_m,"_currentlyLoading",new Map);class wm extends ym{constructor(){super(...arguments),h(this,"models",[]),h(this,"didTrigger",[]),h(this,"receivers",[])}evaluate(e){var t;if(!this.track.muted)for(let s=0;s<this.models.length;s++){const r=this.models[s],n=this.didTrigger[s],o=r.time-e;let a=!1;if(r.retroActive)a=o<=1e-6;else{const l=Math.abs(o);l>=1e-5&&l<.1&&(a=!0)}if(a){if(!n)if(this.didTrigger[s]=!0,((t=this.receivers)==null?void 0:t.length)<=0)yp.invoke(r.asset);else for(const l of this.receivers)l&&l.invoke(r.asset)}else r.emitOnce||(this.didTrigger[s]=!1)}}}class Bb extends ym{constructor(){super(...arguments),h(this,"models",[]),h(this,"timelines",[]),h(this,"_previousActiveModel",null)}resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const s=this.models[t].asset;if(!s.sourceObject||typeof s.sourceObject!="object"){console.log("no source object, removing model",t,s),this.models.splice(t,1);continue}else{const r=$.getComponent(s.sourceObject,Am);this.timelines.push(r),r&&s.updateDirector&&(r.playOnAwake=!1)}}}evaluate(e){var t;this._previousActiveModel=null;for(let s=0;s<this.models.length;s++){const r=this.models[s],n=r.asset;if(e>=r.start&&e<=r.end){this._previousActiveModel=r;const o=this.getClipTime(e,r);if(n.controlActivation){const a=n.sourceObject;a.visible=!0}if(n.updateDirector){const a=this.timelines[s];a&&(a.isPlaying&&a.pause(),a.time=o,a.evaluate())}}else{const o=(t=this._previousActiveModel)==null?void 0:t.asset;if(n.controlActivation){const a=n.sourceObject;o?.sourceObject!==a&&(a.visible=!1)}}}}}var zee=Object.defineProperty,Qee=Object.getOwnPropertyDescriptor,JF=(i,e,t,s)=>{for(var r=s>1?void 0:s?Qee(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&zee(e,t,r),r};class Dt{constructor(e){h(this,"_active",!0),h(this,"_value"),h(this,"_valueRaw"),h(this,"_defaultValue"),h(this,"valueProcessor"),h(this,"onValueChanged"),this._value=e,this._defaultValue=e}get overrideState(){return this._active}set overrideState(e){if(this._active===e)return;this._active=e;const t=e?this._valueRaw:this._defaultValue;this.processValue(t,!0)}get value(){return this._valueRaw}set value(e){this.processValue(e,!1)}set defaultValue(e){this._defaultValue=e}__init(){this.processValue(this._valueRaw,!0)}processValue(e,t){if(e==null||!t&&this.testIfValueChanged(e)===!1)return;const s=this._value;!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,e=this._defaultValue,this._valueRaw=e):(this._valueRaw=e,this._active&&this.valueProcessor&&(e=this.valueProcessor(e)),this._value=e),this.onValueChanged&&this.onValueChanged(e,s,this)}testIfValueChanged(e){return this._valueRaw!==e}}JF([w()],Dt.prototype,"overrideState",1),JF([w()],Dt.prototype,"value",1);var jee=Object.defineProperty,Gee=Object.getOwnPropertyDescriptor,Hee=(i,e,t,s)=>{for(var r=s>1?void 0:s?Gee(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&jee(e,t,r),r};const Vee=oe("debugpost");class kr extends vc{constructor(){super(...arguments),h(this,"active",!0),h(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(){Vee&&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 s=this[t];s instanceof Dt&&s.__init()}}onAfterDeserialize(e,t){if(typeof e=="object"){const s=this.$serializedTypes;if(s){for(const r of Object.keys(s))if(s[r]===Dt){const n=e[r];if(n!==void 0){const o=this[r];o.value=n}}}}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof Dt){const s=e.value;return this[t].value=s,!0}}}Hee([w()],kr.prototype,"active",2);var Wee=Object.defineProperty,qee=Object.getOwnPropertyDescriptor,Xee=(i,e,t,s)=>{for(var r=s>1?void 0:s?qee(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Wee(e,t,r),r};const Yee=oe("debugpost"),UE={};function oa(i,e){UE[i]=e}function Jee(i){return i.__type in UE?UE[i.__type]:(Yee&&i.__type&&console.warn("Unknown postprocessing type",i.__type,i),kr)}class xm{constructor(){h(this,"components")}init(){var e;(e=this.components)==null||e.forEach(t=>t.init())}}Xee([Pd([i=>Jee(i),kr])],xm.prototype,"components",2);var Kee=Object.defineProperty,Zee=Object.getOwnPropertyDescriptor,$ee=(i,e,t,s)=>{for(var r=s>1?void 0:s?Zee(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Kee(e,t,r),r};class Cm extends kr{constructor(){super(...arguments),h(this,"preset")}get typeName(){return"Antialiasing"}onCreateEffect(){const e=new b7({preset:Id.HIGH,edgeDetectionMode:aC.DEPTH});return this.preset.onValueChanged=t=>{e.applyPreset(t)},e}}$ee([w(Dt)],Cm.prototype,"preset",2),oa("Antialiasing",Cm);class kb{constructor(){h(this,"files",[])}get extensionName(){return"Audio"}onExportObject(e,t,s){const r=$.getComponents(e,os);if(r.length)for(const n of r){if(!n.playOnAwake)continue;const o=n.clip.split("/").pop();this.files.includes(n.clip)||this.files.push(n.clip),t.addEventListener("serialize",(a,l)=>{a.appendLine(),a.beginBlock(`def SpatialAudio "${t.name}"`),a.appendLine(`uniform asset filePath = @audio/${o}@`),a.appendLine(`uniform token auralMode = "${n.spatialBlend>0?"spatial":"nonSpatial"}"`),a.appendLine(`uniform token playbackMode = "${n.loop?"loopFromStage":"onceFromStart"}"`),a.appendLine(`uniform float gain = ${n.volume}`),a.closeBlock()})}}async onAfterSerialize(e){console.warn("onAfterSerialize",this);for(const t of this.files){const s=t.split("/").pop(),r=await(await(await fetch(t)).blob()).arrayBuffer(),n=new Uint8Array(r);e.files["audio/"+s]=n}}}var ete=Object.defineProperty,tte=Object.getOwnPropertyDescriptor,KF=(i,e,t,s)=>{for(var r=s>1?void 0:s?tte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&ete(e,t,r),r};const ite=oe("debugmouth");class Sm extends Ee{constructor(){super(...arguments),h(this,"idle",[]),h(this,"talking",[]),h(this,"marker",null),h(this,"voip",null),h(this,"lastMouthChangeTime",0),h(this,"mouthChangeLength",0)}awake(){setTimeout(()=>{this.voip=$.findObjectOfType(Fl,this.context),this.marker||(this.marker=$.getComponentInParent(this.gameObject,hr))},3e3)}update(){var e;if(!this.voip||this.context.time.frameCount%10!==0)return;let t=((e=this.marker)==null?void 0:e.connectionId)??null;if(!t){ite&&(t=null);return}const s=this.voip.getFrequency(t)??0;this.updateLips(s)}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(s=>s.visible=!1):this.talking.map(s=>s.visible=!1);for(let s=0;s<e.length;s++){const r=e[s];r&&(r.visible=s===t)}}}}KF([w(Me)],Sm.prototype,"idle",2),KF([w(Me)],Sm.prototype,"talking",2);class NE extends Ee{constructor(){super(...arguments),h(this,"voip",null),h(this,"marker",null),h(this,"_startPosition",null)}awake(){this.voip=$.findObjectOfType(Fl,this.context),this.marker=$.getComponentInParent(this.gameObject,hr)}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 s=t/100;this.gameObject.position.y=this._startPosition.y+s*.07}}var ste=Object.defineProperty,rte=Object.getOwnPropertyDescriptor,Db=(i,e,t,s)=>{for(var r=s>1?void 0:s?rte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&ste(e,t,r),r};class au extends Ee{constructor(){super(...arguments),h(this,"eyes",[]),h(this,"lastBlinkTime",0),h(this,"blinkLength",0),h(this,"eyesOpen",!0),h(this,"state",null)}awake(){this.state=$.getComponentInParent(this.gameObject,Rr)}update(){if(!(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)&&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 e of this.eyes)e&&(e.visible=this.eyesOpen)}}}Db([w(Me)],au.prototype,"eyes",2),Db([w()],au.prototype,"lastBlinkTime",2),Db([w()],au.prototype,"blinkLength",2),Db([w()],au.prototype,"eyesOpen",2);var nte=Object.defineProperty,ote=Object.getOwnPropertyDescriptor,zE=(i,e,t,s)=>{for(var r=s>1?void 0:s?ote(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&nte(e,t,r),r},QE;const ZF=(QE=class extends Ee{constructor(){super(...arguments),h(this,"head",null),h(this,"eyes",null),h(this,"target",null),h(this,"brain",null),h(this,"vec",new S),h(this,"currentTargetPoint",new S)}awake(){this.brain||(this.brain=$.getComponentInParent(this.gameObject,Jg)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=$.addNewComponent(this.gameObject,Jg)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}update(){const i=this.target;if(i&&this.head){const e=this.eyes;if(e){const t=wt(i);this.currentTargetPoint.lerp(t,this.context.time.deltaTime/.1);const s=wt(this.head),r=this.vec.copy(this.currentTargetPoint).sub(s).normalize();if(r.length()<.1)return;const n=ZF.forward;if(n.set(0,0,1),n.applyQuaternion(ws(this.head)),n.dot(r)>.45)for(let o=0;o<e.length;o++)e[o].lookAt(this.currentTargetPoint)}}}},h(QE,"forward",new S(0,0,1)),QE);let bp=ZF;zE([w(Me)],bp.prototype,"head",2),zE([w(Me)],bp.prototype,"eyes",2),zE([w(Me)],bp.prototype,"target",2);var ate=Object.defineProperty,lte=Object.getOwnPropertyDescriptor,jE=(i,e,t,s)=>{for(var r=s>1?void 0:s?lte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&ate(e,t,r),r};class _p extends Ee{constructor(){super(...arguments),h(this,"length",1),h(this,"depthTest",!0),h(this,"isGizmo",!0),h(this,"_axes",null)}onEnable(){if(this.isGizmo&&!Zf)return;this._axes||(this._axes=new Ad(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)}}jE([w()],_p.prototype,"length",2),jE([w()],_p.prototype,"depthTest",2),jE([w()],_p.prototype,"isGizmo",2);class GE extends Ee{constructor(){super(...arguments),h(this,"from"),h(this,"to"),h(this,"hint"),h(this,"desiredDistance",1)}onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=wt(this.to).clone(),t=wt(this.from).clone(),s=e.distanceTo(t),r=e.clone();r.sub(t);let n=t.clone();n.add(e),n.multiplyScalar(.5);let o=wt(this.hint).clone();o.sub(n);let a=new S;a.crossVectors(o,r),a.crossVectors(r,a),a.normalize();let l=s*.5,c=Math.max(this.desiredDistance,l),u=Math.sqrt(c*c-l*l),d=a.clone();d.multiplyScalar(u),d.add(n),Yi(this.gameObject,d);let p=n.clone();p.sub(a),this.gameObject.lookAt(p)}}class Ob{constructor(){h(this,"behaviours",[]),h(this,"behaviourComponents",[]),h(this,"behaviourComponentsCopy",[])}get extensionName(){return"Behaviour"}addBehavior(e){this.behaviours.push(e)}onBeforeBuildDocument(e){e.root.traverse(t=>{$.foreachComponent(t,s=>{var r;const n=s;(typeof n.createBehaviours=="function"||typeof n.beforeCreateDocument=="function"||typeof n.afterCreateDocument=="function")&&(this.behaviourComponents.push(n),(r=n.beforeCreateDocument)==null||r.call(n,this,e))},!1)})}onExportObject(e,t,s){var r;for(const n of this.behaviourComponents)(r=n.createBehaviours)==null||r.call(n,this,t,s)}onAfterBuildDocument(e){for(const t of this.behaviourComponents)typeof t.afterCreateDocument=="function"&&t.afterCreateDocument(this,e);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0}onAfterHierarchy(e,t){var s;if((s=this.behaviours)!=null&&s.length){t.beginBlock('def Scope "Behaviors"');for(const r of this.behaviours)r.writeTo(this,e.document,t);t.closeBlock()}}async onAfterSerialize(e){console.log("onAfterSerialize",this.behaviourComponentsCopy);for(const t of this.behaviourComponentsCopy)console.log("behaviour",t),typeof t.afterSerialize=="function"&&(console.log("beh has afterSerialize",t),t.afterSerialize.constructor.name==="AsyncFunction"?await t.afterSerialize(this,e):t.afterSerialize(this,e))}}var cte=Object.defineProperty,hte=Object.getOwnPropertyDescriptor,HE=(i,e,t,s)=>{for(var r=s>1?void 0:s?hte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&cte(e,t,r),r};class lu extends kr{constructor(){super(...arguments),h(this,"threshold"),h(this,"intensity"),h(this,"scatter"),h(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 lD(this.context.scene,this.context.mainCamera,{blendFunction:kt.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,intensity:this.intensity.value});t.inverted=!0}else e=new pC;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}}HE([w(Dt)],lu.prototype,"threshold",2),HE([w(Dt)],lu.prototype,"intensity",2),HE([w(Dt)],lu.prototype,"scatter",2),oa("Bloom",lu);var ute=Object.defineProperty,dte=Object.getOwnPropertyDescriptor,Mo=(i,e,t,s)=>{for(var r=s>1?void 0:s?dte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&ute(e,t,r),r};class aa extends Ee{constructor(){super(...arguments),h(this,"attachedRigidbody",null),h(this,"isTrigger",!1),h(this,"sharedMaterial")}get isCollider(){return!0}awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Li))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Li))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Li))}onDisable(){var e;(e=this.context.physics.engine)==null||e.removeBody(this)}}Mo([w(Li)],aa.prototype,"attachedRigidbody",2),Mo([w()],aa.prototype,"isTrigger",2),Mo([w()],aa.prototype,"sharedMaterial",2);class Em extends aa{constructor(){super(...arguments),h(this,"radius",.5),h(this,"center",new S(0,0,0))}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addSphereCollider(this,this.center,this.radius)}}Mo([w()],Em.prototype,"radius",2),Mo([w(S)],Em.prototype,"center",2);class Mm extends aa{constructor(){super(...arguments),h(this,"size",new S(1,1,1)),h(this,"center",new S(0,0,0))}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addBoxCollider(this,this.center,this.size)}}Mo([w(S)],Mm.prototype,"size",2),Mo([w(S)],Mm.prototype,"center",2);class Im extends aa{constructor(){super(...arguments),h(this,"sharedMesh"),h(this,"convex",!1)}onEnable(){var e,t,s,r,n;if(super.onEnable(),(e=this.sharedMesh)!=null&&e.isMesh||this.gameObject instanceof ye&&(this.sharedMesh=this.gameObject),(t=this.sharedMesh)!=null&&t.isMesh)(s=this.context.physics.engine)==null||s.addMeshCollider(this,this.sharedMesh,this.convex,Ns(this.gameObject));else{const o=this.sharedMesh;if(o!=null&&o.isGroup){console.warn(`MeshCollider mesh is a group "${(r=this.sharedMesh)==null?void 0:r.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);for(const a in o.children){const l=o.children[a];l.isMesh&&((n=this.context.physics.engine)==null||n.addMeshCollider(this,l,this.convex,Ns(this.gameObject)))}}}}}Mo([w()],Im.prototype,"convex",2);class jc extends aa{constructor(){super(...arguments),h(this,"center",new S(0,0,0)),h(this,"radius",.5),h(this,"height",2)}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addCapsuleCollider(this,this.center,this.height,this.radius)}}Mo([w(S)],jc.prototype,"center",2),Mo([w()],jc.prototype,"radius",2),Mo([w()],jc.prototype,"height",2);function VE(i){return i[yl]||(i.parent?VE(i.parent):null)}function Lb(i,e){if(!i)return;const t=i.material;if(t?.isMaterial===!0){const s=i.parent;s&&s.isText,t.side=e.doubleSided??!0?bi:mr,t.shadowSide=e.doubleSided?bi:mr,i.castShadow=e.castShadows?e.castShadows:!1,i.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const s of i.children)Lb(s,e)}function wp(i,e,t){i[e]===void 0&&console.warn("Field",e,"is undefined on",i);const s=Proxy.revocable(i[e],{set(o,a,l,c){const u=o[a],d=Reflect.set(o,a,l,c);return t(l,u),d}}),r=s.revoke,n=i[e];return s.revoke=()=>{i[e]=n,r()},i[e]=s.proxy,s}const $F=Symbol("Scheduled action");function pte(i,e,t=dn.OnBeforeRender){let s=i[$F];s||(s=i[$F]={});const r=e.name;s[t]||(s[t]={});const n=s[t];if(n[r])return;function*o(){e?.call(i),n[r]=null}const a=i.startCoroutine(o(),t);n[r]=a}var fte=Object.defineProperty,gte=Object.getOwnPropertyDescriptor,cu=(i,e,t,s)=>{for(var r=s>1?void 0:s?gte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&fte(e,t,r),r};const WE=oe("debugui"),qE=oe("debuguilayout");class XE{constructor(){h(this,"width"),h(this,"height")}}class YE{constructor(){h(this,"x"),h(this,"y"),h(this,"width"),h(this,"height")}}const la=new S,Tm=new Qe,Fb=new xe,eU=class extends Bo{constructor(){super(...arguments),h(this,"offset",.01),h(this,"_anchoredPosition"),h(this,"sizeDelta",new W(100,100)),h(this,"pivot",new W(.5,.5)),h(this,"anchorMin",new W(0,0)),h(this,"anchorMax",new W(1,1)),h(this,"offsetMin",new W(0,0)),h(this,"offsetMax",new W(0,0)),h(this,"lastMatrix"),h(this,"rectBlock"),h(this,"_transformNeedsUpdate",!1),h(this,"_initialPosition"),h(this,"_parentRectTransform"),h(this,"_lastUpdateFrame",-1),h(this,"_lastAnchoring"),h(this,"_createdBlocks",[]),h(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 W),this._anchoredPosition}set anchoredPosition(i){this._anchoredPosition=i}get width(){if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const i=this._parentRectTransform.width,e=this.anchorMax.x-this.anchorMin.x;let t=i*e;return t+=this.sizeDelta.x,t}return this.sizeDelta.x}get height(){if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const i=this._parentRectTransform.height,e=this.anchorMax.y-this.anchorMin.y;let t=i*e;return t+=this.sizeDelta.y,t}return this.sizeDelta.y}awake(){super.awake(),this._anchoredPosition||(this._anchoredPosition=new W),this.lastMatrix=new Qe,this.rectBlock=new Me,this.rectBlock.position.z=.1,this.rectBlock.name=this.name,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this.onApplyTransform("RectTransform awake"),wp(this,"_anchoredPosition",()=>{this.markDirty()}),wp(this,"sizeDelta",()=>{this.markDirty()}),wp(this,"pivot",()=>{this.markDirty()}),wp(this,"anchorMin",()=>{this.markDirty()}),wp(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var i;super.onEnable(),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(i=this.Canvas)==null||i.registerTransform(this)}onDisable(){var i;super.onDisable(),this.removeShadowComponent(),(i=this.Canvas)==null||i.unregisterTransform(this)}onParentRectTransformChanged(i){this._transformNeedsUpdate||this.onApplyTransform(qE?`${i.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(qE&&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(i){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=$.getComponentInParent(this.gameObject.parent,eU):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,qE&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+i),this.isRoot()?this.Root.screenspace||(e.rotation.y=Math.PI):(e.matrix.identity(),e.matrixAutoUpdate=!1,la.set(0,0,0),this.applyPivot(la),e.matrix.setPosition(la.x,la.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(Fb.copy(this.gameObject.quaternion),Fb.x*=-1,Fb.z*=-1,Tm.makeRotationFromQuaternion(Fb),e.matrix.premultiply(Tm)),la.set(0,0,0),this.applyAnchoring(la),la.z+=this.offset,Tm.identity(),Tm.setPosition(la.x,la.y,la.z),e.matrix.premultiply(Tm),e.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const t=!0;for(const s of tC(this.gameObject,Bo,t,1)){if(s===this||!s.activeAndEnabled)continue;const r=s;r.onParentRectTransformChanged&&r.onParentRectTransformChanged(this)}}applyAnchoring(i){this._lastAnchoring||(this._lastAnchoring=new W);const e=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=e.x,this.gameObject.position.y+=e.y,this._lastAnchoring.copy(this._anchoredPosition),i.x+=this._initialPosition.x-this.gameObject.position.x,i.y+=this._initialPosition.y-this.gameObject.position.y,i.z+=this._initialPosition.z-this.gameObject.position.z;const t=this._parentRectTransform;if(t){let s=0;const r=1-this.anchorMax.y-this.anchorMin.y;s-=t.height*.5*r,i.y+=s;let n=0;const o=1-this.anchorMax.x-this.anchorMin.x;n-=t.width*.5*o,i.x+=n}}applyPivot(i){if(this.pivot&&!this.isRoot()){const e=this.pivot.x-.5;i.x-=e*this.sizeDelta.x*this.gameObject.scale.x;const t=this.pivot.y-.5;i.y-=t*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const i={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:this.offset,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(i),i}ensureValidSize(i,e=1e-4){return i.width<=0&&(i.width=e),i.height<=0&&(i.height=1e-4),i}createNewBlock(i){i={...this.getBasicOptions(),...i},WE&&console.log(this.name,i);const e=new ME(i);return this._createdBlocks.push(e),e}createNewText(i){WE&&console.log(i),i={...this.getBasicOptions(),...i},WE&&console.log(this.name,i);const e=new zF(i);return this._createdTextBlocks.push(e),e}};let ur=eU;cu([w(W)],ur.prototype,"anchoredPosition",1),cu([w(W)],ur.prototype,"sizeDelta",2),cu([w(W)],ur.prototype,"pivot",2),cu([w(W)],ur.prototype,"anchorMin",2),cu([w(W)],ur.prototype,"anchorMax",2),cu([w(W)],ur.prototype,"offsetMin",2),cu([w(W)],ur.prototype,"offsetMax",2);class mte extends NF{constructor(e,t={}){super(e),e._simpleState__activeStates=[],e._simpleState__normalStyles={},e._simpleState__states=t,e._simpleState__statesProperties={};for(const s in t)for(const r in t[s])e._simpleState__statesProperties[r]||(e._simpleState__statesProperties[r]=[]),e._simpleState__statesProperties[r].push(s);for(const s of e._components)e._simpleState__statesProperties[s.id]&&(e._simpleState__normalStyles[s.id]=s.inline?s.inline:s._value);e.__overridedSet=e.set,e.set=this.storeSet.bind(e),e.renderStates=this.renderStates.bind(e),e.setupState=this.setupState.bind(e),e.setState=this.setState.bind(e),e.activatePseudoState=this.activatePseudoState.bind(e),e.deactivatePseudoState=this.deactivatePseudoState.bind(e),e.togglePseudoState=this.togglePseudoState.bind(e)}act(){}attach(){}detach(){}setupState(e,t){this._simpleState__states[e]=t;const s=[];for(const r in t)this._simpleState__statesProperties[r]||(this._simpleState__statesProperties[r]=[],s.push(r)),this._simpleState__statesProperties[r].push(e);for(const r of this._components)s.indexOf(r.id)>-1&&(this._simpleState__normalStyles[r.id]=r.inline?r.inline:r._value)}renderStates(){let e={...this._simpleState__normalStyles};for(const t in this._simpleState__states)this._simpleState__activeStates.indexOf(t)>-1&&(e={...e,...this._simpleState__states[t]});this.set(e,!1)}storeSet(e,t=!0){if(t)for(const s in e)this._simpleState__statesProperties[s]&&(this._simpleState__normalStyles[s]=e[s]);this.__overridedSet(e)}activatePseudoState(e){this._simpleState__activeStates.indexOf(e)===-1&&(this._simpleState__activeStates.push(e),this.renderStates())}deactivatePseudoState(e){const t=this._simpleState__activeStates.indexOf(e);t>-1&&(this._simpleState__activeStates.splice(t,1),this.renderStates())}togglePseudoState(e){const t=this._simpleState__activeStates.indexOf(e);t>-1?this._simpleState__activeStates.splice(t,1):this._simpleState__activeStates.push(e),this.renderStates()}setState(e){Array.isArray(e)?this._simpleState__activeStates=e:this._simpleState__activeStates=[e],this.renderStates()}}var vte=Object.defineProperty,Ate=Object.getOwnPropertyDescriptor,tU=(i,e,t,s)=>{for(var r=s>1?void 0:s?Ate(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&vte(e,t,r),r};class xp extends Ee{constructor(){super(...arguments),h(this,"effectColor"),h(this,"effectDistance")}}tU([w(vi)],xp.prototype,"effectColor",2),tU([w(W)],xp.prototype,"effectDistance",2);var yte=Object.defineProperty,bte=Object.getOwnPropertyDescriptor,iU=(i,e,t,s)=>{for(var r=s>1?void 0:s?bte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&yte(e,t,r),r};const Ub={backgroundColor:new _e(1,1,1),backgroundOpacity:1,borderColor:new _e(1,1,1),borderOpacity:1};var JE;const Nb=(JE=class extends Bo{constructor(){super(...arguments),h(this,"_alphaFactor",1),h(this,"raycastTarget",!0),h(this,"uiObject",null),h(this,"_color",null),h(this,"_rect",null),h(this,"_stateManager",null),h(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new vi(1,1,1,1)),this._color}set color(i){(!this._color||this._color.r!==i.r||this._color.g!==i.g||this._color.b!==i.b||this._color.alpha!==i.alpha)&&(this._color||(this._color=new vi(1,1,1,1)),this._color.copy(i))}setAlphaFactor(i){this._alphaFactor=i,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(Ub.backgroundColor=this._color,Ub.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(Ub,this._alphaFactor),this.uiObject.set(Ub),this.markDirty())}get m_Color(){return this._color}get rectTransform(){return this._rect||(this._rect=$.getComponent(this.gameObject,ur)),this._rect}onParentRectTransformChanged(){var i;(i=this.uiObject)==null||i.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(i){this.makePanel(),this.uiObject&&(this.uiObject.setState(i),this==null||this.markDirty())}setupState(i){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new mte(this.uiObject)),this.uiObject.setupState(i.state,i.attributes))}setOptions(i){this.makePanel(),this.uiObject&&this.uiObject.set(i)}awake(){super.awake(),this.makePanel(),wp(this,"_color",()=>pte(this,this.onColorChanged))}onEnable(){var i;super.onEnable(),this.uiObject&&((i=this.rectTransform.shadowComponent)==null||i.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 i={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:1};this.onBeforeCreate(i),this.applyEffects(i),this.onCreate(i),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated()}onBeforeCreate(i){}onCreate(i){this.uiObject=this.rectTransform.createNewBlock(i),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(i,e=1){var t;const s=(t=this.gameObject)==null?void 0:t.getComponent(xp);s&&(s.effectDistance&&(i.borderWidth=Math.max(Math.abs(s.effectDistance.x),Math.abs(s.effectDistance.y))),s.effectColor&&(i.borderColor=s.effectColor,i.borderOpacity=s.effectColor.alpha*e))}async setTexture(i){if(this.setOptions({backgroundOpacity:0}),i){if(i.encoding===yt)if(Nb.textureCache.has(i))i=Nb.textureCache.get(i);else{const e=i.clone();e.encoding=Hi,Nb.textureCache.set(i,e),i=e}this.setOptions({backgroundImage:i,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)}},h(JE,"textureCache",new Map),JE);let hu=Nb;iU([w(vi)],hu.prototype,"color",1),iU([w()],hu.prototype,"raycastTarget",2);class Rm extends hu{constructor(){super(...arguments),h(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var _te=Object.defineProperty,wte=Object.getOwnPropertyDescriptor,zb=(i,e,t,s)=>{for(var r=s>1?void 0:s?wte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&_te(e,t,r),r};let KE=class{constructor(){h(this,"texture",null),h(this,"rect")}};zb([w(Nt)],KE.prototype,"texture",2);let Cp=class extends Rm{constructor(){super(...arguments),h(this,"_sprite"),h(this,"pixelsPerUnitMultiplier",1)}set image(i){this.sprite?this.sprite.texture=i:(this.sprite=new KE,this.sprite.texture=i),this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(i){this._sprite!==i&&(this._sprite=i,this.onAfterCreated())}isBuiltinSprite(){var i,e,t,s,r,n,o,a;switch((e=(i=this.sprite)==null?void 0:i.texture)==null?void 0:e.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return((r=(s=(t=this.sprite)==null?void 0:t.texture)==null?void 0:s.image)==null?void 0:r.width)===32&&((a=(o=(n=this.sprite)==null?void 0:n.texture)==null?void 0:o.image)==null?void 0:a.height)===32}onBeforeCreate(i){var e,t;super.onBeforeCreate(i),this.isBuiltinSprite()&&(i.borderRadius=5/this.pixelsPerUnitMultiplier,((t=(e=this.sprite)==null?void 0:e.texture)==null?void 0:t.name)==="Knob"&&(i.borderRadius=999))}onAfterCreated(){var i;this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture((i=this.sprite)==null?void 0:i.texture))}};zb([w(KE)],Cp.prototype,"sprite",1),zb([w()],Cp.prototype,"pixelsPerUnitMultiplier",2);class Qb extends Rm{constructor(){super(...arguments),h(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))}}zb([w(Nt)],Qb.prototype,"mainTexture",1);var xte=Object.defineProperty,Cte=Object.getOwnPropertyDescriptor,gn=(i,e,t,s)=>{for(var r=s>1?void 0:s?Cte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&xte(e,t,r),r};const Sp=oe("debugbutton");class uu{constructor(){h(this,"colorMultiplier"),h(this,"disabledColor"),h(this,"fadeDuration"),h(this,"highlightedColor"),h(this,"normalColor"),h(this,"pressedColor"),h(this,"selectedColor")}}gn([w()],uu.prototype,"colorMultiplier",2),gn([w(vi)],uu.prototype,"disabledColor",2),gn([w()],uu.prototype,"fadeDuration",2),gn([w(vi)],uu.prototype,"highlightedColor",2),gn([w(vi)],uu.prototype,"normalColor",2),gn([w(vi)],uu.prototype,"pressedColor",2),gn([w(vi)],uu.prototype,"selectedColor",2);class El extends Ee{constructor(){super(...arguments),h(this,"onClick"),h(this,"_isHovered",!1),h(this,"colors"),h(this,"transition"),h(this,"animationTriggers"),h(this,"animator"),h(this,"_interactable",!0),h(this,"_requestedAnimatorTrigger"),h(this,"_isInit",!1),h(this,"_image")}onPointerEnter(e){var t,s;Sp&&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&&((s=this._image)==null||s.setState("hovered")),this.context.input.setCursorPointer())}onPointerExit(){var e,t;Sp&&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,s;Sp&&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&&((s=this._image)==null||s.setState("pressed")))}onPointerUp(e){var t,s;Sp&&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&&((s=this._image)==null||s.setState(this._isHovered?"hovered":"normal")))}onPointerClick(e){var t;this.interactable&&(Sp&&(console.warn("Button Click",this.onClick),Rs("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(),Sp&&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=$.getComponent(this.gameObject,Cp),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){var t,s,r,n,o;e.setInteractable(this.interactable);const a=this.getFinalColor(e.color,(t=this.colors)==null?void 0:t.normalColor),l={state:"normal",attributes:{backgroundColor:a,backgroundOpacity:a.alpha}};e.setupState(l);const c=this.getFinalColor(e.color,(s=this.colors)==null?void 0:s.highlightedColor),u={state:"hovered",attributes:{backgroundColor:c,backgroundOpacity:c.alpha}};e.setupState(u);const d=this.getFinalColor(e.color,(r=this.colors)==null?void 0:r.pressedColor),p={state:"pressed",attributes:{backgroundColor:d,backgroundOpacity:d.alpha}};e.setupState(p);const f=this.getFinalColor(e.color,(n=this.colors)==null?void 0:n.selectedColor),g={state:"selected",attributes:{backgroundColor:f,backgroundOpacity:f.alpha}};e.setupState(g);const m=this.getFinalColor(e.color,(o=this.colors)==null?void 0:o.disabledColor),v={state:"disabled",attributes:{backgroundColor:m,backgroundOpacity:m.alpha}};e.setupState(v)}getFinalColor(e,t){return t?e.clone().multiply(t):e.clone()}}gn([w(Vr)],El.prototype,"onClick",2),gn([w()],El.prototype,"colors",2),gn([w()],El.prototype,"transition",2),gn([w()],El.prototype,"animationTriggers",2),gn([w(Gr)],El.prototype,"animator",2),gn([w()],El.prototype,"interactable",1);var Ste=Object.defineProperty,Ete=Object.getOwnPropertyDescriptor,hs=(i,e,t,s)=>{for(var r=s>1?void 0:s?Ete(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Ste(e,t,r),r};const sU=oe("debuguilayout");class Gc{constructor(){h(this,"left",0),h(this,"right",0),h(this,"top",0),h(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}hs([w()],Gc.prototype,"left",2),hs([w()],Gc.prototype,"right",2),hs([w()],Gc.prototype,"top",2),hs([w()],Gc.prototype,"bottom",2);class mn extends Ee{constructor(){super(...arguments),h(this,"_rectTransform",null),h(this,"_needsUpdate",!1),h(this,"childAlignment",0),h(this,"reverseArrangement",!1),h(this,"spacing",0),h(this,"padding"),h(this,"minWidth",0),h(this,"minHeight",0),h(this,"flexibleHeight",0),h(this,"flexibleWidth",0),h(this,"preferredHeight",0),h(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&&(sU&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){sU&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(ur);const e=this.gameObject.getComponentInParent(dr);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(dr);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}hs([w()],mn.prototype,"childAlignment",2),hs([w()],mn.prototype,"reverseArrangement",2),hs([w()],mn.prototype,"spacing",2),hs([w(Gc)],mn.prototype,"padding",2),hs([w()],mn.prototype,"minWidth",2),hs([w()],mn.prototype,"minHeight",2),hs([w()],mn.prototype,"flexibleHeight",2),hs([w()],mn.prototype,"flexibleWidth",2),hs([w()],mn.prototype,"preferredHeight",2),hs([w()],mn.prototype,"preferredWidth",2);class Hc extends mn{constructor(){super(...arguments),h(this,"childControlHeight",!0),h(this,"childControlWidth",!0),h(this,"childForceExpandHeight",!1),h(this,"childForceExpandWidth",!1),h(this,"childScaleHeight",!1),h(this,"childScaleWidth",!1)}onCalculateLayout(e){var t;const s=this.primaryAxis,r=e.width;let n=r;const o=e.height;let a=o;n-=this.padding.horizontal,a-=this.padding.vertical,s==="x"?this.padding.horizontal:this.padding.vertical;const l=s==="x",c=l?"y":"x",u=l?this.childControlWidth:this.childControlHeight,d=l?this.childControlHeight:this.childControlWidth,p=l?this.childForceExpandWidth:this.childForceExpandHeight,f=l?this.childForceExpandHeight:this.childForceExpandWidth,g=l?a:n,m=l?r:o,v=.5*(l?this.childAlignment%3:Math.floor(this.childAlignment/3));let A=0;l?A+=this.padding.left:A+=this.padding.top;let b=0,y=0;for(let C=0;C<this.gameObject.children.length;C++){const R=this.gameObject.children[C],T=$.getComponent(R,ur);T!=null&&T.activeAndEnabled&&(y+=1,l?b+=T.width:b+=T.height)}let _=0;const x=this.spacing*(y-1);if(p||u){let C=0;l?C=n-=x:C=a-=x,y>0&&(_=C/y)}let M=0;M+=this.padding.left,M-=this.padding.right,v!==0&&(A=m-b,A*=v,A-=x*v,l?(A-=this.padding.right*v,A+=this.padding.left*(1-v),A<this.padding.left&&(A=this.padding.left)):(A-=this.padding.bottom*v,A+=this.padding.top*(1-v),A<this.padding.top&&(A=this.padding.top)));let P=1;for(let C=0;C<this.gameObject.children.length;C++){const R=this.gameObject.children[C],T=$.getComponent(R,ur);if(T!=null&&T.activeAndEnabled){(t=T.pivot)==null||t.set(.5,.5),T.anchorMin.set(0,1),T.anchorMax.set(0,1);const z=r*.5+M*.5;T.anchoredPosition.x!==z&&(T.anchoredPosition.x=z);const G=o*-.5;T.anchoredPosition.y!==G&&(T.anchoredPosition.y=G),f&&d&&T.sizeDelta[c]!==g&&(T.sizeDelta[c]=g),p&&u&&T.sizeDelta[s]!==_&&(T.sizeDelta[s]=_);const N=l?T.width:T.height;let F=N*.5;if(A+=F,p){let te=_*P-_*.5;te>A&&(A=te-_*.5+N+this.padding.left,A-=F)}let X=A;s==="y"&&(X=-X),T.anchoredPosition[s]!==X&&(T.anchoredPosition[s]=X),A+=F,A+=this.spacing,P+=1}}}}hs([w()],Hc.prototype,"childControlHeight",2),hs([w()],Hc.prototype,"childControlWidth",2),hs([w()],Hc.prototype,"childForceExpandHeight",2),hs([w()],Hc.prototype,"childForceExpandWidth",2),hs([w()],Hc.prototype,"childScaleHeight",2),hs([w()],Hc.prototype,"childScaleWidth",2);class ZE extends Hc{get primaryAxis(){return"y"}}class $E extends Hc{get primaryAxis(){return"x"}}class eM extends mn{onCalculateLayout(){}}var Mte=Object.defineProperty,Ite=Object.getOwnPropertyDescriptor,ca=(i,e,t,s)=>{for(var r=s>1?void 0:s?Ite(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Mte(e,t,r),r};const tM=oe("debuguilayout"),rU=class extends am{constructor(){super(...arguments),h(this,"_renderOnTop"),h(this,"_depthWrite",!1),h(this,"_doubleSided",!0),h(this,"_castShadows",!1),h(this,"_receiveShadows",!1),h(this,"_renderMode",-1),h(this,"_rootCanvas"),h(this,"_scaleFactor",1),h(this,"worldCamera"),h(this,"planeDistance",-1),h(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this)),h(this,"previousParent",null),h(this,"_lastMatrixWorld",null),h(this,"_rectTransforms",[]),h(this,"_layoutGroups",new Map),h(this,"onBeforeRenderRoutine",()=>{var i,e;this.previousParent=this.gameObject.parent,this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(i=this.shadowComponent)==null||i.updateMatrixWorld(!0),(e=this.shadowComponent)==null||e.updateWorldMatrix(!0,!0),Wn.ensureUpdateMeshUI(jF,this.context))}),h(this,"onAfterRenderRoutine",()=>{var i,e;if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const t=this.context.mainCamera;t?.add(this.gameObject)}else this.previousParent.add(this.gameObject);this.context.renderer.autoClear=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(i=this.shadowComponent)==null||i.updateMatrixWorld(!0),Wn.ensureUpdateMeshUI(jF,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)}),h(this,"_updateRenderSettingsRoutine"),h(this,"_activeRenderMode",-1),h(this,"_lastWidth",-1),h(this,"_lastHeight",-1)}get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(i){i!==this._renderOnTop&&(this._renderOnTop=i,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(i){this._depthWrite!==i&&(this._depthWrite=i,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(i){this._doubleSided!==i&&(this._doubleSided=i,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(i){this._castShadows!==i&&(this._castShadows=i,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(i){this._receiveShadows!==i&&(this._receiveShadows=i,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(i){this._renderMode!==i&&(this._renderMode=i,this.onRenderSettingsChanged())}set rootCanvas(i){this._rootCanvas instanceof rU||(this._rootCanvas=i)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(i){this._scaleFactor=i}awake(){var i;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,tM&&console.log("Canvas.Awake()",((i=this.previousParent)==null?void 0:i.name)+"/"+this.gameObject.name),super.awake()}start(){this.onUpdateRenderMode()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new Qe,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 i=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);i!==-1&&this.context.pre_render_callbacks.splice(i,1);const e=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);e!==-1&&this.context.post_render_callbacks.splice(e,1)}registerTransform(i){this._rectTransforms.push(i)}unregisterTransform(i){const e=this._rectTransforms.indexOf(i);e!==-1&&this._rectTransforms.splice(e,1)}registerLayoutGroup(i){const e=i.gameObject;this._layoutGroups.set(e,i)}unregisterLayoutGroup(i){const e=i.gameObject;this._layoutGroups.delete(e)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new Qe);const i=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);tM&&i&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);let e=!1;for(const t of this._rectTransforms){i&&t.markDirty();let s=this._layoutGroups.get(t.gameObject);t.isDirty&&!s&&(s=t.gameObject.getComponentInParent(mn)),(t.isDirty||s!=null&&s.isDirty)&&(tM&&!e&&console.log("CANVAS UPDATE ### "+t.name+" ##################################### "+this.context.time.frame),s?.updateLayout(),t.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),dn.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),Lb(this.shadowComponent,this);for(const i of $.getComponentsInChildren(this.gameObject,Bo))Lb(i.shadowComponent,this)}}onUpdateRenderMode(i=!1){if(!i&&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=Je.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 s=t+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-s,this.gameObject.quaternion.identity();const r=this.gameObject.getComponent(ur);let n=!1;r.sizeDelta.x!==this.context.domWidth&&(n=!0),r.sizeDelta.y!==this.context.domHeight&&(n=!0);const o=e.fieldOfView*Math.PI/180,a=2*Math.tan(o/2)*Math.abs(s);this.gameObject.scale.x=a/this.context.domHeight,this.gameObject.scale.y=a/this.context.domHeight,this.gameObject.scale.z=.01,n&&(r.sizeDelta.x=this.context.domWidth,r.sizeDelta.y=this.context.domHeight,r?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};let dr=rU;ca([w()],dr.prototype,"renderOnTop",1),ca([w()],dr.prototype,"depthWrite",1),ca([w()],dr.prototype,"doubleSided",1),ca([w()],dr.prototype,"castShadows",1),ca([w()],dr.prototype,"receiveShadows",1),ca([w()],dr.prototype,"renderMode",1),ca([w(dr)],dr.prototype,"rootCanvas",1),ca([w()],dr.prototype,"scaleFactor",1),ca([w(Mi)],dr.prototype,"worldCamera",2),ca([w()],dr.prototype,"planeDistance",2);var Tte=Object.defineProperty,Rte=Object.getOwnPropertyDescriptor,iM=(i,e,t,s)=>{for(var r=s>1?void 0:s?Rte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Tte(e,t,r),r};class Ep extends Ee{constructor(){super(...arguments),h(this,"_alpha",1),h(this,"interactable",!0),h(this,"blocksRaycasts",!0),h(this,"_isDirty",!1),h(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(),dn.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){for(const e of $.getComponentsInChildren(this.gameObject,Bo,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}iM([w()],Ep.prototype,"alpha",1),iM([w()],Ep.prototype,"interactable",2),iM([w()],Ep.prototype,"blocksRaycasts",2);var Pte=Object.defineProperty,Bte=Object.getOwnPropertyDescriptor,Ii=(i,e,t,s)=>{for(var r=s>1?void 0:s?Bte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Pte(e,t,r),r};class du extends Ee{constructor(){super(...arguments),h(this,"object"),h(this,"target"),h(this,"duration",1),h(this,"relativeMotion",!1),h(this,"coroutine",null),h(this,"targetPos",new S),h(this,"targetRot",new xe),h(this,"targetScale",new S)}*moveToTarget(){if(!this.target||!this.object)return;const e=wt(this.object).clone(),t=wt(this.target).clone(),s=ws(this.object).clone(),r=ws(this.target).clone(),n=Ns(this.object).clone(),o=Ns(this.target).clone(),a=e.distanceTo(t),l=s.angleTo(r),c=n.distanceTo(o);if(a<.01&&l<.01&&c<.01){Yi(this.object,t),Nr(this.object,r),I1(this.object,o),this.coroutine=null;return}let u=0,d=0;for(;u<1;)u+=this.context.time.deltaTime/this.duration,u>1&&(u=1),d=u<.5?4*u*u*u:1-Math.pow(-2*u+2,3)/2,this.targetPos.lerpVectors(e,t,d),this.targetRot.slerpQuaternions(s,r,d),this.targetScale.lerpVectors(n,o,d),Yi(this.object,this.targetPos),Nr(this.object,this.targetRot),I1(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(),s=this.object.scale.clone(),r=this.target.position.clone(),n=this.target.quaternion.clone(),o=this.target.scale.clone();r.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(r),this.targetRot.copy(this.object.quaternion).multiply(n),this.targetScale.copy(this.object.scale).multiply(o);let a=0,l=0;for(;a<1;)a+=this.context.time.deltaTime/this.duration,a>1&&(a=1),l=a<.5?4*a*a*a:1-Math.pow(-2*a+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,l),this.object.quaternion.slerpQuaternions(t,this.targetRot,l),this.object.scale.lerpVectors(s,this.targetScale,l),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 s=new Tr("Move to "+((t=this.target)==null?void 0:t.name),Wr.tapTrigger(this.gameObject),ni.transformAction(this.object,this.target,this.duration,this.relativeMotion?RS.Relative:RS.Absolute));e.addBehavior(s)}}}Ii([w(Me)],du.prototype,"object",2),Ii([w(Me)],du.prototype,"target",2),Ii([w()],du.prototype,"duration",2),Ii([w()],du.prototype,"relativeMotion",2);var sM;const Mp=(sM=class extends Ee{constructor(){super(...arguments),h(this,"materialToSwitch"),h(this,"variantMaterial"),h(this,"_objectsWithThisMaterial",[]),h(this,"selfModel"),h(this,"targetModels",[])}awake(){if(this.variantMaterial&&this.materialToSwitch){const i=$.findObjectsOfType(zi);for(const e of i)e.sharedMaterial===this.materialToSwitch&&this._objectsWithThisMaterial.push(e)}}onPointerClick(){if(this.variantMaterial)for(const i of this._objectsWithThisMaterial)i.sharedMaterial=this.variantMaterial}createBehaviours(i,e,t){this._objectsWithThisMaterial.find(s=>s.gameObject.uuid===e.uuid)&&this.targetModels.push(e),this.gameObject.uuid===e.uuid&&(this.selfModel=e,this.materialToSwitch&&(Mp._materialTriggersPerId[this.materialToSwitch.uuid]||(Mp._materialTriggersPerId[this.materialToSwitch.uuid]=[]),Mp._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(i,e){if(!this.materialToSwitch)return;const t=Mp._materialTriggersPerId[this.materialToSwitch.uuid];if(t){const s={};for(const n of t){const o=n.createVariants();o&&o.length>0&&(s[n.selfModel.uuid]=o)}const r=[];for(const n of t){for(const o in s)o!==n.selfModel.uuid&&r.push(s[o]);n.createAndAttachBehaviors(i,s[n.selfModel.uuid],r)}}delete Mp._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(i,e,t){const s=[],r=[];for(const n of this.targetModels){const o=ni.fadeAction(n,0,!1);r.push(o)}for(const n of t)r.push(ni.fadeAction(n,0,!1));for(const n of e)s.push(ni.fadeAction(n,0,!1)),r.push(ni.fadeAction(n,0,!0));i.addBehavior(new Tr("Select "+this.selfModel.name,Wr.tapTrigger(this.selfModel),ni.parallel(...r))),i.addBehavior(new Tr("Start hidden "+this.selfModel.name,Wr.sceneStartTrigger(),ni.parallel(...s)))}createVariants(){if(!this.variantMaterial)return null;const i=[];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())&&Zo.createEmptyParent(e),e.parent&&e.parent.add(t),i.push(t)}return i}},h(sM,"_materialTriggersPerId",{}),sM);let Pm=Mp;Ii([w(Tt)],Pm.prototype,"materialToSwitch",2),Ii([w(Tt)],Pm.prototype,"variantMaterial",2);class Ip extends Ee{constructor(){super(...arguments),h(this,"target"),h(this,"toggleOnClick",!1),h(this,"targetState",!0),h(this,"hideSelf",!0),h(this,"selfModel"),h(this,"otherModel"),h(this,"toggleModel"),h(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,s){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 s=this.hideSelf;this.targetState,this.toggleOnClick&&(s=!0,this.target.visible,(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&DL.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.clone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel));const r=[];if(s&&r.push(ni.fadeAction(this.selfModel,0,!1)),this.toggleModel&&r.push(ni.fadeAction(this.toggleModel,0,!0)),r.push(ni.fadeAction(this.otherModel,0,this.targetState)),e.addBehavior(new Tr("Toggle_"+this.selfModel.name+"_hideSelf",Wr.tapTrigger(this.selfModel),ni.sequence(...r))),this.toggleOnClick&&this.toggleModel){const n=[];n.push(ni.fadeAction(this.toggleModel,0,!1)),n.push(ni.fadeAction(this.selfModel,0,!0)),n.push(ni.fadeAction(this.otherModel,0,!this.targetState)),e.addBehavior(new Tr("Toggle_"+this.selfModel.name+"_toggleSelf",Wr.tapTrigger(this.toggleModel),ni.sequence(...n))),e.addBehavior(new Tr("HideOnStart_"+this.gameObject.name,Wr.sceneStartTrigger(),ni.fadeAction(this.toggleModel,0,!1)))}}this.gameObject.visible=this.stateBeforeCreatingDocument}}}Ii([w(Me)],Ip.prototype,"target",2),Ii([w()],Ip.prototype,"targetState",2),Ii([w()],Ip.prototype,"hideSelf",2);class rM extends Ee{start(){this.gameObject.visible=!1}createBehaviours(e,t,s){t.uuid===this.gameObject.uuid&&e.addBehavior(new Tr("HideOnStart_"+this.gameObject.name,Wr.sceneStartTrigger(),ni.fadeAction(t,0,!1)))}beforeCreateDocument(){this.gameObject.visible=!0}afterCreateDocument(){this.gameObject.visible=!1}}class Tp extends Ee{constructor(){super(...arguments),h(this,"target"),h(this,"duration",.5),h(this,"motionType",TS.bounce)}beforeCreateDocument(){}createBehaviours(e,t,s){if(this.target&&t.uuid===this.gameObject.uuid){const r=new Tr("emphasize "+this.name,Wr.tapTrigger(this.gameObject),ni.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(r)}}afterCreateDocument(e,t){}}Ii([w()],Tp.prototype,"target",2),Ii([w()],Tp.prototype,"duration",2),Ii([w()],Tp.prototype,"motionType",2);class Rp extends Ee{constructor(){super(...arguments),h(this,"target"),h(this,"clip",""),h(this,"toggleOnClick",!1)}onPointerClick(){if(!(!this.target&&!this.clip)){if(!this.target){const e=this.gameObject.addNewComponent(os);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,s){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const r=this.clip?this.clip:this.target?this.target.clip:void 0;if(!r)return;const n=this.target?this.target.gameObject:this.gameObject,o=r.split("/").pop(),a=this.target?this.target.volume:1,l=this.target&&this.target.spatialBlend==0?BS.NonSpatial:BS.Spatial,c=new Tr("playAudio "+this.name,Wr.tapTrigger(this.gameObject),ni.playAudioAction(n,"audio/"+o,qL.Play,a,l));e.addBehavior(c)}}async afterSerialize(e,t){if(!this.target&&!this.clip)return;const s=this.clip?this.clip:this.target?this.target.clip:void 0;if(!s)return;const r=s.split("/").pop(),n=await(await(await fetch(this.clip)).blob()).arrayBuffer(),o=new Uint8Array(n);t.files["audio/"+r]=o}}Ii([w(os)],Rp.prototype,"target",2),Ii([w(URL)],Rp.prototype,"clip",2),Ii([w()],Rp.prototype,"toggleOnClick",2);var nM;const Pp=(nM=class extends Ee{constructor(){super(...arguments),h(this,"target"),h(this,"animator"),h(this,"stateName"),h(this,"stateNameAfterPlaying"),h(this,"loopAfterPlaying",!1),h(this,"selfModel"),h(this,"stateAnimationModel"),h(this,"stateAnimation"),h(this,"stateAfterPlayingAnimationModel"),h(this,"stateAfterPlayingAnimation")}onPointerClick(){var i;this.target&&this.stateName&&((i=this.animator)==null||i.play(this.stateName,0,0,.1))}createBehaviours(i,e,t){e.uuid===this.gameObject.uuid&&(this.selfModel=e)}onAfterHierarchy(){Pp.animationActions=[]}afterCreateDocument(i,e){!this.stateAnimation||!this.stateAnimationModel||e.document.traverse(t=>{var s,r;if(t.uuid===((s=this.target)==null?void 0:s.uuid)&&this.stateAnimation){const n=[];let o=Pp.animationActions.find(l=>l.affectedObjects==t&&l.start==this.stateAnimation.start&&l.duration==this.stateAnimation.duration);if(o||(o=ni.startAnimationAction(t,this.stateAnimation.start,this.stateAnimation.duration),Pp.animationActions.push(o)),n.push(o),this.stateAfterPlayingAnimation&&this.stateAfterPlayingAnimationModel){let l=Pp.animationActions.find(u=>u.affectedObjects==t&&u.start==this.stateAfterPlayingAnimation.start&&u.duration==this.stateAfterPlayingAnimation.duration);l||(l=ni.startAnimationAction(t,this.stateAfterPlayingAnimation.start,this.stateAfterPlayingAnimation.duration),Pp.animationActions.push(l));const c=ni.sequence(l);this.loopAfterPlaying&&c.makeLooping(),n.push(c)}const a=new Tr("tap "+this.name+" for "+this.stateName+" on "+((r=this.target)==null?void 0:r.name),Wr.tapTrigger(this.selfModel),ni.sequence(...n));i.addBehavior(a)}})}createAnimation(i,e,t){var s,r,n,o;if(this.target&&this.animator){const a=(r=(s=this.animator)==null?void 0:s.runtimeAnimatorController)==null?void 0:r.findState(this.stateName);this.stateAnimationModel=e,this.stateAnimation=i.registerAnimation(this.target,a?.motion.clip);const l=(o=(n=this.animator)==null?void 0:n.runtimeAnimatorController)==null?void 0:o.findState(this.stateNameAfterPlaying);this.stateAfterPlayingAnimationModel=e,this.stateAfterPlayingAnimation=i.registerAnimation(this.target,l?.motion.clip)}}},h(nM,"animationActions",[]),nM);let Vc=Pp;Ii([w(Me)],Vc.prototype,"target",2),Ii([w(Gr)],Vc.prototype,"animator",2),Ii([w()],Vc.prototype,"stateName",2),Ii([w()],Vc.prototype,"stateNameAfterPlaying",2),Ii([w()],Vc.prototype,"loopAfterPlaying",2);class Bp extends Ee{constructor(){super(...arguments),h(this,"target")}getType(){}getDuration(){}}Ii([w(Me)],Bp.prototype,"target",2);class Bm extends Ee{constructor(){super(...arguments),h(this,"target")}}Ii([w(Bp)],Bm.prototype,"target",2);class km extends Bp{constructor(){super(...arguments),h(this,"type",1),h(this,"duration",1)}getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Ii([w()],km.prototype,"type",2),Ii([w()],km.prototype,"duration",2);class oM extends Bm{}var kte=Object.defineProperty,Dte=Object.getOwnPropertyDescriptor,Ml=(i,e,t,s)=>{for(var r=s>1?void 0:s?Dte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&kte(e,t,r),r};class pu extends Ee{constructor(){super(...arguments),h(this,"center",new S(0,0,0)),h(this,"radius",.5),h(this,"height",2),h(this,"_rigidbody",null),h(this,"_activeGroundCollisions",new Set)}get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(Li),this._rigidbody||(this._rigidbody=this.gameObject.addNewComponent(Li)),this.rigidbody)}onEnable(){let e=this.rigidbody,t=this.gameObject.getComponent(jc);t||(t=this.gameObject.addNewComponent(jc)),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}}Ml([w(S)],pu.prototype,"center",2),Ml([w()],pu.prototype,"radius",2),Ml([w()],pu.prototype,"height",2);class Il extends Ee{constructor(){super(...arguments),h(this,"controller"),h(this,"movementSpeed",2),h(this,"rotationSpeed",2),h(this,"jumpForce",1),h(this,"doubleJumpForce",2),h(this,"animator"),h(this,"lookForward",!0),h(this,"_currentSpeed",new S(0,0,0)),h(this,"_currentAngularSpeed",new S(0,0,0)),h(this,"_temp",new S(0,0,0)),h(this,"_jumpCount",0),h(this,"_currentRotation"),h(this,"_raycastOptions",new fo)}awake(){this._currentRotation=new xe}update(){var e,t,s,r,n,o,a,l,c,u,d;(e=this.controller)!=null&&e.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&((t=this.animator)==null||t.setBool("doubleJump",!1)));const p=this.context.input.isKeyPressed("w"),f=this.context.input.isKeyPressed("s"),g=this.context.input.isKeyPressed("a"),m=this.context.input.isKeyPressed("d"),v=this.context.input.isKeyDown(" "),A=(p?1:0)+(f?-1:0);this._currentSpeed.z+=A*this.movementSpeed*this.context.time.deltaTime,(s=this.animator)==null||s.setBool("running",A!=0),(n=this.animator)==null||n.setBool("jumping",((r=this.controller)==null?void 0:r.isGrounded)===!0&&v),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 b=(g?1:0)+(m?-1:0);if(this._currentAngularSpeed.y+=Je.toRadians(b*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const y=this.context.mainCameraComponent.forward;y.y=0,y.normalize(),this._currentRotation.setFromUnitVectors(new S(0,0,1),y),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&&v&&this.jumpForce>0){let y=(o=this.controller)==null?void 0:o.isGrounded;if(this.doubleJumpForce>0&&!((a=this.controller)!=null&&a.isGrounded)&&this._jumpCount===1&&(y=!0,(l=this.animator)==null||l.setBool("doubleJump",!0)),y){this._jumpCount+=1;const _=this.controller.rigidbody,x=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;_.applyImpulse(new S(0,1,0).multiplyScalar(x))}}if(this.controller){const y=(c=this.controller)==null?void 0:c.rigidbody.getVelocity().y;if(y<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new za),this._raycastOptions.ray.origin.copy(wt(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const _=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const x=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(_),(x.length&&x[0].distance>2||y<-10)&&((u=this.animator)==null||u.setBool("falling",!0))}else(d=this.animator)==null||d.setBool("falling",!1)}}}Ml([w(pu)],Il.prototype,"controller",2),Ml([w()],Il.prototype,"movementSpeed",2),Ml([w()],Il.prototype,"rotationSpeed",2),Ml([w()],Il.prototype,"jumpForce",2),Ml([w()],Il.prototype,"doubleJumpForce",2),Ml([w(Gr)],Il.prototype,"animator",2);var Ote=Object.defineProperty,Lte=Object.getOwnPropertyDescriptor,Fte=(i,e,t,s)=>{for(var r=s>1?void 0:s?Lte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Ote(e,t,r),r};class Dm extends kr{constructor(){super(...arguments),h(this,"intensity")}get typeName(){return"ChromaticAberration"}init(){this.intensity.defaultValue=0}onCreateEffect(){const e=new rD;return e.offset=new W(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}}Fte([w(Dt)],Dm.prototype,"intensity",2),oa("ChromaticAberration",Dm);var Ute=Object.defineProperty,Nte=Object.getOwnPropertyDescriptor,jb=(i,e,t,s)=>{for(var r=s>1?void 0:s?Nte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Ute(e,t,r),r};class Wc extends kr{constructor(){super(...arguments),h(this,"postExposure"),h(this,"contrast"),h(this,"hueShift"),h(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===vr&&this.postExposure.overrideState&&(this.context.renderer.toneMapping=Af);const e=new sD;this.postExposure.onValueChanged=s=>{this.context.renderer.toneMapping===vr&&(this.context.renderer.toneMapping=Af),this.context.renderer.toneMappingExposure=s},this.contrast.onValueChanged=s=>{e.contrast=s};const t=new oD;return this.hueShift.onValueChanged=s=>t.hue=s,this.saturation.onValueChanged=s=>t.saturation=s,[t,e]}}jb([w(Dt)],Wc.prototype,"postExposure",2),jb([w(Dt)],Wc.prototype,"contrast",2),jb([w(Dt)],Wc.prototype,"hueShift",2),jb([w(Dt)],Wc.prototype,"saturation",2),oa("ColorAdjustments",Wc);const zte=(Math.sqrt(5)-1)/4,Vs=(5-Math.sqrt(5))/20,Gb=i=>Math.floor(i)|0,Hb=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 Qte(i=Math.random){const e=jte(i),t=new Float64Array(e).map(o=>Hb[o%32*4]),s=new Float64Array(e).map(o=>Hb[o%32*4+1]),r=new Float64Array(e).map(o=>Hb[o%32*4+2]),n=new Float64Array(e).map(o=>Hb[o%32*4+3]);return function(o,a,l,c){let u,d,p,f,g;const m=(o+a+l+c)*zte,v=Gb(o+m),A=Gb(a+m),b=Gb(l+m),y=Gb(c+m),_=(v+A+b+y)*Vs,x=v-_,M=A-_,P=b-_,C=y-_,R=o-x,T=a-M,z=l-P,G=c-C;let N=0,F=0,X=0,te=0;R>T?N++:F++,R>z?N++:X++,R>G?N++:te++,T>z?F++:X++,T>G?F++:te++,z>G?X++:te++;const re=N>=3?1:0,Z=F>=3?1:0,fe=X>=3?1:0,ae=te>=3?1:0,Oe=N>=2?1:0,Se=F>=2?1:0,ie=X>=2?1:0,ce=te>=2?1:0,Re=N>=1?1:0,K=F>=1?1:0,je=X>=1?1:0,Ne=te>=1?1:0,Be=R-re+Vs,ve=T-Z+Vs,de=z-fe+Vs,Ae=G-ae+Vs,pe=R-Oe+2*Vs,Ue=T-Se+2*Vs,Pe=z-ie+2*Vs,ct=G-ce+2*Vs,me=R-Re+3*Vs,ht=T-K+3*Vs,ut=z-je+3*Vs,Pt=G-Ne+3*Vs,ii=R-1+4*Vs,U=T-1+4*Vs,D=z-1+4*Vs,le=G-1+4*Vs,Te=v&255,ke=A&255,Ge=b&255,st=y&255;let Q=.6-R*R-T*T-z*z-G*G;if(Q<0)u=0;else{const ge=Te+e[ke+e[Ge+e[st]]];Q*=Q,u=Q*Q*(t[ge]*R+s[ge]*T+r[ge]*z+n[ge]*G)}let J=.6-Be*Be-ve*ve-de*de-Ae*Ae;if(J<0)d=0;else{const ge=Te+re+e[ke+Z+e[Ge+fe+e[st+ae]]];J*=J,d=J*J*(t[ge]*Be+s[ge]*ve+r[ge]*de+n[ge]*Ae)}let Ve=.6-pe*pe-Ue*Ue-Pe*Pe-ct*ct;if(Ve<0)p=0;else{const ge=Te+Oe+e[ke+Se+e[Ge+ie+e[st+ce]]];Ve*=Ve,p=Ve*Ve*(t[ge]*pe+s[ge]*Ue+r[ge]*Pe+n[ge]*ct)}let qe=.6-me*me-ht*ht-ut*ut-Pt*Pt;if(qe<0)f=0;else{const ge=Te+Re+e[ke+K+e[Ge+je+e[st+Ne]]];qe*=qe,f=qe*qe*(t[ge]*me+s[ge]*ht+r[ge]*ut+n[ge]*Pt)}let ze=.6-ii*ii-U*U-D*D-le*le;if(ze<0)g=0;else{const ge=Te+1+e[ke+1+e[Ge+1+e[st+1]]];ze*=ze,g=ze*ze*(t[ge]*ii+s[ge]*U+r[ge]*D+n[ge]*le)}return 27*(u+d+p+f+g)}}function jte(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 s=t+~~(i()*(256-t)),r=e[t];e[t]=e[s],e[s]=r}for(let t=256;t<512;t++)e[t]=e[t-256];return e}var Gte=Object.defineProperty,Hte=Object.getOwnPropertyDescriptor,q=(i,e,t,s)=>{for(var r=s>1?void 0:s?Hte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Gte(e,t,r),r};const Vb=oe("debugparticles");var ha=(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))(ha||{});class qc{constructor(){h(this,"alphaKeys"),h(this,"colorKeys")}get duration(){return 1}evaluate(e,t){let s,r=0,n=null,o=0;for(let a=0;a<this.alphaKeys.length;a++){const l=this.alphaKeys[a];(l.time<e||!s)&&(s=l,r=a)}for(let a=0;a<this.colorKeys.length;a++){const l=this.colorKeys[a];(l.time<e||!n)&&(n=l,o=a)}if(n)if(o+1<this.colorKeys.length){const a=this.colorKeys[o+1],l=Je.remap(e,n.time,a.time,0,1);t.r=Je.lerp(n.color.r,a.color.r,l),t.g=Je.lerp(n.color.g,a.color.g,l),t.b=Je.lerp(n.color.b,a.color.b,l)}else t.r=n.color.r,t.g=n.color.g,t.b=n.color.b;if(s)if(r+1<this.alphaKeys.length){const a=this.alphaKeys[r+1],l=Je.remap(e,s.time,a.time,0,1);t.alpha=Je.lerp(s.alpha,a.alpha,l)}else t.alpha=s.alpha;return t}}q([w()],qc.prototype,"alphaKeys",2),q([w()],qc.prototype,"colorKeys",2);var Wb=(i=>(i[i.Local=0]="Local",i[i.World=1]="World",i[i.Custom=2]="Custom",i))(Wb||{}),nU=(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))(nU||{});class tt{constructor(){h(this,"mode"),h(this,"constant"),h(this,"constantMin"),h(this,"constantMax"),h(this,"curve"),h(this,"curveMin"),h(this,"curveMax"),h(this,"curveMultiplier")}evaluate(e,t){const s=t===void 0?Math.random():t;switch(this.mode){case 0:return this.constant;case 1:return e=Je.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:const r=e*this.curveMin.duration,n=e*this.curveMax.duration;return Je.lerp(this.curveMin.evaluate(r),this.curveMax.evaluate(n),s%1)*this.curveMultiplier;case 3:return Je.lerp(this.constantMin,this.constantMax,s%1);default:this.curveMax.evaluate(e)*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(e){if(!e)return 0;let t=Number.MIN_VALUE;for(let s=0;s<e.keys.length;s++){const r=e.keys[s];r.value>t&&(t=r.value)}return t}}q([w()],tt.prototype,"mode",2),q([w()],tt.prototype,"constant",2),q([w()],tt.prototype,"constantMin",2),q([w()],tt.prototype,"constantMax",2),q([w($h)],tt.prototype,"curve",2),q([w($h)],tt.prototype,"curveMin",2),q([w($h)],tt.prototype,"curveMax",2),q([w()],tt.prototype,"curveMultiplier",2);var qb;const Io=(qb=class{constructor(){h(this,"mode"),h(this,"color"),h(this,"colorMin"),h(this,"colorMax"),h(this,"gradient"),h(this,"gradientMin"),h(this,"gradientMax")}evaluate(i,e){const t=e===void 0?Math.random():e;switch(this.mode){case 0:return this.color;case 1:return this.gradient.evaluate(i,Io._temp),Io._temp;case 2:return Io._temp.lerpColors(this.colorMin,this.colorMax,t);case 3:return this.gradientMin.evaluate(i,Io._temp),this.gradientMax.evaluate(i,Io._temp2),Io._temp.lerp(Io._temp2,t)}return Io._temp.set(16711935),Io._temp.alpha=1,Io._temp}},h(qb,"_temp",new vi(0,0,0,1)),h(qb,"_temp2",new vi(0,0,0,1)),qb);let Jr=Io;q([w(vi)],Jr.prototype,"color",2),q([w(vi)],Jr.prototype,"colorMin",2),q([w(vi)],Jr.prototype,"colorMax",2),q([w(qc)],Jr.prototype,"gradient",2),q([w(qc)],Jr.prototype,"gradientMin",2),q([w(qc)],Jr.prototype,"gradientMax",2);class Ws{constructor(){h(this,"cullingMode"),h(this,"duration"),h(this,"emitterVelocityMode"),h(this,"flipRotation"),h(this,"gravityModifier"),h(this,"gravityModifierMultiplier"),h(this,"loop"),h(this,"maxParticles"),h(this,"playOnAwake"),h(this,"prewarm"),h(this,"ringBufferLoopRange"),h(this,"ringBufferMode"),h(this,"scalingMode"),h(this,"simulationSpace"),h(this,"simulationSpeed"),h(this,"startColor"),h(this,"startDelay"),h(this,"startDelayMultiplier"),h(this,"startLifetime"),h(this,"startLifetimeMultiplier"),h(this,"startRotation"),h(this,"startRotationMultiplier"),h(this,"startRotation3D"),h(this,"startRotationX"),h(this,"startRotationXMultiplier"),h(this,"startRotationY"),h(this,"startRotationYMultiplier"),h(this,"startRotationZ"),h(this,"startRotationZMultiplier"),h(this,"startSize"),h(this,"startSize3D"),h(this,"startSizeMultiplier"),h(this,"startSizeX"),h(this,"startSizeXMultiplier"),h(this,"startSizeY"),h(this,"startSizeYMultiplier"),h(this,"startSizeZ"),h(this,"startSizeZMultiplier"),h(this,"startSpeed"),h(this,"startSpeedMultiplier"),h(this,"stopAction"),h(this,"useUnscaledTime")}}q([w(tt)],Ws.prototype,"gravityModifier",2),q([w(Jr)],Ws.prototype,"startColor",2),q([w(tt)],Ws.prototype,"startDelay",2),q([w(tt)],Ws.prototype,"startLifetime",2),q([w(tt)],Ws.prototype,"startRotation",2),q([w(tt)],Ws.prototype,"startRotationX",2),q([w(tt)],Ws.prototype,"startRotationY",2),q([w(tt)],Ws.prototype,"startRotationZ",2),q([w(tt)],Ws.prototype,"startSize",2),q([w(tt)],Ws.prototype,"startSizeX",2),q([w(tt)],Ws.prototype,"startSizeY",2),q([w(tt)],Ws.prototype,"startSizeZ",2),q([w(tt)],Ws.prototype,"startSpeed",2);class Om{constructor(){h(this,"cycleCount"),h(this,"maxCount"),h(this,"minCount"),h(this,"probability"),h(this,"repeatInterval"),h(this,"time"),h(this,"count"),h(this,"_performed",0)}reset(){this._performed=0}run(e){if(e<=this.time)return this.reset(),0;let t=0;if(this.cycleCount===0||this._performed<this.cycleCount){const s=this.time+this.repeatInterval*this._performed;if(e>=s&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=Je.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:const r=Math.random();t=Je.lerp(this.count.curveMin.evaluate(r),this.count.curveMax.evaluate(r),Math.random());break}}return t}}class ua{constructor(){h(this,"enabled"),h(this,"bursts"),h(this,"rateOverTime"),h(this,"rateOverTimeMultiplier"),h(this,"rateOverDistance"),h(this,"rateOverDistanceMultiplier"),h(this,"system")}get burstCount(){var e;return((e=this.bursts)==null?void 0:e.length)??0}reset(){var e;(e=this.bursts)==null||e.forEach(t=>t.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){const s=this.bursts[t];s.time>=this.system.time&&s.reset(),e+=Math.round(s.run(this.system.time))}return e}}q([w()],ua.prototype,"enabled",2),q([w()],ua.prototype,"bursts",2),q([w(tt)],ua.prototype,"rateOverTime",2),q([w()],ua.prototype,"rateOverTimeMultiplier",2),q([w(tt)],ua.prototype,"rateOverDistance",2),q([w()],ua.prototype,"rateOverDistanceMultiplier",2);class Lm{constructor(){h(this,"enabled"),h(this,"color")}}q([w(Jr)],Lm.prototype,"color",2);class Xc{constructor(){h(this,"enabled"),h(this,"separateAxes"),h(this,"size"),h(this,"sizeMultiplier"),h(this,"x"),h(this,"xMultiplier"),h(this,"y"),h(this,"yMultiplier"),h(this,"z"),h(this,"zMultiplier"),h(this,"_time",0),h(this,"_temp",new S)}evaluate(e,t,s){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,s)*this.xMultiplier,t.y=this.y.evaluate(e,s)*this.yMultiplier,t.z=this.z.evaluate(e,s)*this.zMultiplier;else{const r=this.size.evaluate(e,s)*this.sizeMultiplier;t.x=r}return t}}q([w(tt)],Xc.prototype,"size",2),q([w(tt)],Xc.prototype,"x",2),q([w(tt)],Xc.prototype,"y",2),q([w(tt)],Xc.prototype,"z",2);var Xb;const Fm=(Xb=class{constructor(){h(this,"shapeType",5),h(this,"enabled",!0),h(this,"alignToDirection",!1),h(this,"angle",0),h(this,"arc",360),h(this,"arcSpread"),h(this,"arcSpeedMultiplier"),h(this,"arcMode"),h(this,"boxThickness"),h(this,"position"),h(this,"rotation"),h(this,"_rotation",new fs),h(this,"scale"),h(this,"radius"),h(this,"radiusThickness"),h(this,"sphericalDirectionAmount"),h(this,"randomDirectionAmount"),h(this,"randomPositionAmount"),h(this,"system"),h(this,"_space"),h(this,"_worldSpaceMatrix",new Qe),h(this,"_worldSpaceMatrixInverse",new Qe),h(this,"_vector",new S(0,0,0)),h(this,"_temp",new S(0,0,0)),h(this,"_dir",new S),h(this,"_loopTime",0),h(this,"_loopDirection",1),Vb&&console.log(this)}get type(){return nU[this.shapeType]}initialize(i){this.getPosition(),i.position.copy(this._vector)}toJSON(){return this}clone(){return new Fm}update(i,e,t,s){this.system=i,this._space=t,t===1&&(this._worldSpaceMatrix.copy(s.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 e=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return e&&(this._rotation.x=Je.toRadians(this.rotation.x),this._rotation.y=Je.toRadians(this.rotation.y),this._rotation.z=Je.toRadians(this.rotation.z),this._rotation.order="ZYX",i.applyEuler(this._rotation)),e}get vector(){return this._vector}getPosition(){this._vector.set(0,0,0);const i=this._temp.copy(this.position),e=this._space===1;e&&i.applyQuaternion(this.system.worldQuaternion);let t=this.radius;if(e&&(t*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:Vb&&Jo.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,t,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,t,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,t,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),e&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),Vb&&Jo.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(i){var e;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 t=i.x,s=i.y,r=i.z;this._dir.set(t,s,r),(e=this.system)!=null&&e.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),Vb&&(Jo.DrawSphere(i,.01,8925952,.5,!0),Jo.DrawDirection(i,this._dir,8925952,.5,!0)),this._dir}randomizePosition(i,e){if(e<=0)return;const t=Fm._tempVec;t.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),t.x*=e*this.scale.x,t.y*=e*this.scale.y,t.z*=e*this.scale.z,i.add(t)}randomizeDirection(i,e){if(e===0)return;const t=Fm._randomQuat,s=Fm._tempVec;s.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),t.setFromAxisAngle(s,e*Math.random()*Math.PI),i.applyQuaternion(t)}spherizeDirection(i,e){if(e===0)return;const t=Math.random()*Math.PI*2,s=Math.acos(1-Math.random()*2),r=Math.sin(s)*Math.cos(t),n=Math.sin(s)*Math.sin(t),o=Math.cos(s),a=new S(r,n,o);i.lerp(a,e)}randomSpherePoint(i,e,t,s,r){const n=Math.random(),o=Math.random(),a=2*Math.PI*n*(s/360),l=Math.acos(2*o-1),c=Je.lerp(1,1-Math.pow(1-Math.random(),Math.PI),t)*e,u=i.x+this.scale.x*(-c*Math.sin(l)*Math.cos(a)),d=i.y+this.scale.y*(c*Math.sin(l)*Math.sin(a)),p=i.z+this.scale.z*(c*Math.cos(l));r.x=u,r.y=d,r.z=p}randomCirclePoint(i,e,t,s,r){const n=Math.random(),o=2*Math.PI*n*(s/360),a=Je.lerp(1,1-Math.pow(1-Math.random(),Math.PI),t)*e,l=i.x+this.scale.x*a*Math.cos(o),c=i.y+this.scale.y*a*Math.sin(o),u=i.z;r.x=l,r.y=c,r.z=u}randomConePoint(i,e,t,s,r,n,o){let a=0,l=0;switch(n){case 0:a=Math.random(),l=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:a=.5,l=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let c=2*Math.PI*a*(r/360);switch(n){case 2:case 1:c+=Math.PI+.5,c+=this._loopTime*Math.PI*2,c%=Je.toRadians(r);break}const u=Math.acos(2*l-1),d=Je.lerp(1,1-Math.pow(1-Math.random(),Math.PI),s)*t,p=i.x+-d*Math.sin(u)*Math.cos(c),f=i.y+d*Math.sin(u)*Math.sin(c),g=i.z;o.x=p*this.scale.x,o.y=f*this.scale.y,o.z=g*this.scale.z}},h(Xb,"_randomQuat",new xe),h(Xb,"_tempVec",new S),Xb);let $i=Fm;q([w()],$i.prototype,"shapeType",2),q([w()],$i.prototype,"enabled",2),q([w()],$i.prototype,"alignToDirection",2),q([w()],$i.prototype,"angle",2),q([w()],$i.prototype,"arc",2),q([w()],$i.prototype,"arcSpread",2),q([w()],$i.prototype,"arcSpeedMultiplier",2),q([w()],$i.prototype,"arcMode",2),q([w(S)],$i.prototype,"boxThickness",2),q([w(S)],$i.prototype,"position",2),q([w(S)],$i.prototype,"rotation",2),q([w(S)],$i.prototype,"scale",2),q([w()],$i.prototype,"radius",2),q([w()],$i.prototype,"radiusThickness",2),q([w()],$i.prototype,"sphericalDirectionAmount",2),q([w()],$i.prototype,"randomDirectionAmount",2),q([w()],$i.prototype,"randomPositionAmount",2);class hi{constructor(){h(this,"damping"),h(this,"enabled"),h(this,"frequency"),h(this,"octaveCount"),h(this,"octaveMultiplier"),h(this,"octaveScale"),h(this,"positionAmount"),h(this,"quality"),h(this,"remap"),h(this,"remapEnabled"),h(this,"remapMultiplier"),h(this,"remapX"),h(this,"remapXMultiplier"),h(this,"remapY"),h(this,"remapYMultiplier"),h(this,"remapZ"),h(this,"remapZMultiplier"),h(this,"scrollSpeedMultiplier"),h(this,"separateAxes"),h(this,"strengthMultiplier"),h(this,"strengthX"),h(this,"strengthXMultiplier"),h(this,"strengthY"),h(this,"strengthYMultiplier"),h(this,"strengthZ"),h(this,"strengthZMultiplier"),h(this,"_noise"),h(this,"_time",0),h(this,"_temp",new S)}update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}apply(e,t,s,r,n,o){if(!this.enabled)return;this._noise||(this._noise=Qte(()=>0));const a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),l=this._noise(a.x,a.y,a.z,this._time),c=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),u=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(l,c,u).normalize();const d=n/o;let p=this.positionAmount.evaluate(d);this.separateAxes?(this._temp.x*=p*this.strengthXMultiplier,this._temp.y*=p*this.strengthYMultiplier,this._temp.z*=p*this.strengthZMultiplier):(this.strengthX&&(p*=this.strengthX.evaluate(d)*1.5),this._temp.multiplyScalar(p)),s.x+=this._temp.x,s.y+=this._temp.y,s.z+=this._temp.z}}q([w()],hi.prototype,"damping",2),q([w()],hi.prototype,"enabled",2),q([w()],hi.prototype,"frequency",2),q([w()],hi.prototype,"octaveCount",2),q([w()],hi.prototype,"octaveMultiplier",2),q([w()],hi.prototype,"octaveScale",2),q([w(tt)],hi.prototype,"positionAmount",2),q([w()],hi.prototype,"quality",2),q([w(tt)],hi.prototype,"remap",2),q([w()],hi.prototype,"remapEnabled",2),q([w()],hi.prototype,"remapMultiplier",2),q([w(tt)],hi.prototype,"remapX",2),q([w()],hi.prototype,"remapXMultiplier",2),q([w(tt)],hi.prototype,"remapY",2),q([w()],hi.prototype,"remapYMultiplier",2),q([w(tt)],hi.prototype,"remapZ",2),q([w()],hi.prototype,"remapZMultiplier",2),q([w()],hi.prototype,"scrollSpeedMultiplier",2),q([w()],hi.prototype,"separateAxes",2),q([w()],hi.prototype,"strengthMultiplier",2),q([w(tt)],hi.prototype,"strengthX",2),q([w()],hi.prototype,"strengthXMultiplier",2),q([w(tt)],hi.prototype,"strengthY",2),q([w()],hi.prototype,"strengthYMultiplier",2),q([w(tt)],hi.prototype,"strengthZ",2),q([w()],hi.prototype,"strengthZMultiplier",2);class Ti{constructor(){h(this,"enabled"),h(this,"attachRibbonToTransform",!1),h(this,"colorOverLifetime"),h(this,"colorOverTrail"),h(this,"dieWithParticles",!0),h(this,"inheritParticleColor",!0),h(this,"lifetime"),h(this,"lifetimeMultiplier"),h(this,"minVertexDistance",.2),h(this,"mode",0),h(this,"ratio",1),h(this,"ribbonCount",1),h(this,"shadowBias",0),h(this,"sizeAffectsLifetime",!1),h(this,"sizeAffectsWidth",!1),h(this,"splitSubEmitterRibbons",!1),h(this,"textureMode",0),h(this,"widthOverTrail"),h(this,"widthOverTrailMultiplier"),h(this,"worldSpace",!1)}getWidth(e,t,s){let r=this.widthOverTrail.evaluate(s);return s===0&&(r=e),e*=r,e}getColor(e,t,s){const r=this.colorOverTrail.evaluate(s),n=this.colorOverLifetime.evaluate(t);e.x*=r.r*n.r,e.y*=r.g*n.g,e.z*=r.b*n.b,e.w*=r.alpha*n.alpha}}q([w()],Ti.prototype,"enabled",2),q([w()],Ti.prototype,"attachRibbonToTransform",2),q([w(Jr)],Ti.prototype,"colorOverLifetime",2),q([w(Jr)],Ti.prototype,"colorOverTrail",2),q([w()],Ti.prototype,"dieWithParticles",2),q([w()],Ti.prototype,"inheritParticleColor",2),q([w(tt)],Ti.prototype,"lifetime",2),q([w()],Ti.prototype,"lifetimeMultiplier",2),q([w()],Ti.prototype,"minVertexDistance",2),q([w()],Ti.prototype,"mode",2),q([w()],Ti.prototype,"ratio",2),q([w()],Ti.prototype,"ribbonCount",2),q([w()],Ti.prototype,"shadowBias",2),q([w()],Ti.prototype,"sizeAffectsLifetime",2),q([w()],Ti.prototype,"sizeAffectsWidth",2),q([w()],Ti.prototype,"splitSubEmitterRibbons",2),q([w()],Ti.prototype,"textureMode",2),q([w(tt)],Ti.prototype,"widthOverTrail",2),q([w()],Ti.prototype,"widthOverTrailMultiplier",2),q([w()],Ti.prototype,"worldSpace",2);class Fi{constructor(){h(this,"enabled"),h(this,"space",0),h(this,"orbitalX"),h(this,"orbitalY"),h(this,"orbitalZ"),h(this,"orbitalXMultiplier"),h(this,"orbitalYMultiplier"),h(this,"orbitalZMultiplier"),h(this,"orbitalOffsetX"),h(this,"orbitalOffsetY"),h(this,"orbitalOffsetZ"),h(this,"speedModifier"),h(this,"speedModifierMultiplier"),h(this,"x"),h(this,"xMultiplier"),h(this,"y"),h(this,"yMultiplier"),h(this,"z"),h(this,"zMultiplier"),h(this,"_system"),h(this,"_temp",new S),h(this,"_temp2",new S),h(this,"_temp3",new S),h(this,"_hasOrbital",!1),h(this,"_index",0),h(this,"_orbitalMatrix",new Qe)}update(e){this._system=e}init(e){this._index==0&&(e.debug=!0),this._index+=1,e.orbitx=this.orbitalX.evaluate(Math.random()),e.orbity=this.orbitalY.evaluate(Math.random()),e.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=e.orbitx!=0||e.orbity!=0||e.orbitz!=0}apply(e,t,s,r,n,o,a){var l;if(!this.enabled)return;const c=o/a,u=this.speedModifier.evaluate(c)*this.speedModifierMultiplier,d=this.x.evaluate(c),p=this.y.evaluate(c),f=this.z.evaluate(c);if(this._temp.set(-d,p,f),this._system,this._hasOrbital&&((l=this._system)==null?void 0:l.worldPos)){const g=this._temp2.set(s.x,s.y,s.z),m=this.orbitalXMultiplier,v=this.orbitalYMultiplier,A=this.orbitalZMultiplier,b=u*Math.PI*2*10,y=Math.cos(b*m),_=Math.sin(b*m),x=Math.cos(b*v),M=Math.sin(b*v),P=Math.cos(b*A),C=Math.sin(b*A),R=g.x*(x*P)+g.y*(x*C)+g.z*-M,T=g.x*(_*M*P-y*C)+g.y*(_*M*C+y*P)+g.z*(_*x),z=g.x*(y*M*P+_*C)+g.y*(y*M*C-_*P)+g.z*(y*x),G=this._temp3.set(g.x-R,g.y-T,g.z-z);G.normalize(),G.multiplyScalar(.2/n*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),r.x+=G.x,r.y+=G.y,r.z+=G.z}r.x+=this._temp.x,r.y+=this._temp.y,r.z+=this._temp.z,r.x*=u,r.y*=u,r.z*=u}}q([w()],Fi.prototype,"enabled",2),q([w()],Fi.prototype,"space",2),q([w(tt)],Fi.prototype,"orbitalX",2),q([w(tt)],Fi.prototype,"orbitalY",2),q([w(tt)],Fi.prototype,"orbitalZ",2),q([w()],Fi.prototype,"orbitalXMultiplier",2),q([w()],Fi.prototype,"orbitalYMultiplier",2),q([w()],Fi.prototype,"orbitalZMultiplier",2),q([w()],Fi.prototype,"orbitalOffsetX",2),q([w()],Fi.prototype,"orbitalOffsetY",2),q([w()],Fi.prototype,"orbitalOffsetZ",2),q([w(tt)],Fi.prototype,"speedModifier",2),q([w()],Fi.prototype,"speedModifierMultiplier",2),q([w(tt)],Fi.prototype,"x",2),q([w()],Fi.prototype,"xMultiplier",2),q([w(tt)],Fi.prototype,"y",2),q([w()],Fi.prototype,"yMultiplier",2),q([w(tt)],Fi.prototype,"z",2),q([w()],Fi.prototype,"zMultiplier",2);class qs{constructor(){h(this,"animation"),h(this,"enabled"),h(this,"cycleCount"),h(this,"frameOverTime"),h(this,"frameOverTimeMultiplier"),h(this,"numTilesX"),h(this,"numTilesY"),h(this,"startFrame"),h(this,"startFrameMultiplier"),h(this,"rowMode"),h(this,"rowIndex"),h(this,"spriteCount"),h(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(e){if(!this.sampleOnceAtStart())return this.getIndex(e)}getIndex(e){const t=this.numTilesX*this.numTilesY;e=e*this.cycleCount;let s=this.frameOverTime.evaluate(e%1);return s*=this.frameOverTimeMultiplier,s*=t,s=s%t,s=Math.floor(s),s}}q([w()],qs.prototype,"animation",2),q([w()],qs.prototype,"enabled",2),q([w()],qs.prototype,"cycleCount",2),q([w(tt)],qs.prototype,"frameOverTime",2),q([w()],qs.prototype,"frameOverTimeMultiplier",2),q([w()],qs.prototype,"numTilesX",2),q([w()],qs.prototype,"numTilesY",2),q([w(tt)],qs.prototype,"startFrame",2),q([w()],qs.prototype,"startFrameMultiplier",2),q([w()],qs.prototype,"rowMode",2),q([w()],qs.prototype,"rowIndex",2),q([w()],qs.prototype,"spriteCount",2),q([w()],qs.prototype,"timeMode",2);class Xn{constructor(){h(this,"enabled"),h(this,"separateAxes"),h(this,"x"),h(this,"xMultiplier"),h(this,"y"),h(this,"yMultiplier"),h(this,"z"),h(this,"zMultiplier")}evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}q([w()],Xn.prototype,"enabled",2),q([w()],Xn.prototype,"separateAxes",2),q([w(tt)],Xn.prototype,"x",2),q([w()],Xn.prototype,"xMultiplier",2),q([w(tt)],Xn.prototype,"y",2),q([w()],Xn.prototype,"yMultiplier",2),q([w(tt)],Xn.prototype,"z",2),q([w()],Xn.prototype,"zMultiplier",2);class vn{constructor(){h(this,"enabled"),h(this,"range"),h(this,"separateAxes"),h(this,"x"),h(this,"xMultiplier"),h(this,"y"),h(this,"yMultiplier"),h(this,"z"),h(this,"zMultiplier")}evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const s=Je.lerp(this.range.x,this.range.y,t);return this.z.evaluate(s)*-1}return 0}}q([w()],vn.prototype,"enabled",2),q([w()],vn.prototype,"range",2),q([w()],vn.prototype,"separateAxes",2),q([w(tt)],vn.prototype,"x",2),q([w()],vn.prototype,"xMultiplier",2),q([w(tt)],vn.prototype,"y",2),q([w()],vn.prototype,"yMultiplier",2),q([w(tt)],vn.prototype,"z",2),q([w()],vn.prototype,"zMultiplier",2);class us{constructor(){h(this,"enabled"),h(this,"dampen"),h(this,"drag"),h(this,"dragMultiplier"),h(this,"limit"),h(this,"limitMultiplier"),h(this,"separateAxes"),h(this,"limitX"),h(this,"limitXMultiplier"),h(this,"limitY"),h(this,"limitYMultiplier"),h(this,"limitZ"),h(this,"limitZMultiplier"),h(this,"multiplyDragByParticleSize",!1),h(this,"multiplyDragByParticleVelocity",!1),h(this,"space"),h(this,"_temp",new S),h(this,"_temp2",new S)}apply(e,t,s,r,n,o,a){if(this.enabled){const l=this.limit.evaluate(n)*this.limitMultiplier;if(t.length()>l){this._temp.copy(t).normalize().multiplyScalar(l);let c=this.dampen*.5;t.x=Je.lerp(t.x,this._temp.x,c),t.y=Je.lerp(t.y,this._temp.y,c),t.z=Je.lerp(t.z,this._temp.z,c),s.x=Je.lerp(s.x,this._temp.x,c),s.y=Je.lerp(s.y,this._temp.y,c),s.z=Je.lerp(s.z,this._temp.z,c)}}}}q([w()],us.prototype,"enabled",2),q([w()],us.prototype,"dampen",2),q([w(tt)],us.prototype,"drag",2),q([w()],us.prototype,"dragMultiplier",2),q([w(tt)],us.prototype,"limit",2),q([w()],us.prototype,"limitMultiplier",2),q([w()],us.prototype,"separateAxes",2),q([w(tt)],us.prototype,"limitX",2),q([w()],us.prototype,"limitXMultiplier",2),q([w(tt)],us.prototype,"limitY",2),q([w()],us.prototype,"limitYMultiplier",2),q([w(tt)],us.prototype,"limitZ",2),q([w()],us.prototype,"limitZMultiplier",2),q([w()],us.prototype,"multiplyDragByParticleSize",2),q([w()],us.prototype,"multiplyDragByParticleVelocity",2),q([w()],us.prototype,"space",2);class Yc{constructor(){h(this,"enabled"),h(this,"curve"),h(this,"curveMultiplier"),h(this,"mode"),h(this,"system"),h(this,"_lastWorldPosition"),h(this,"_velocity",new S),h(this,"_temp",new S)}update(e){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(e){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const t=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(t),e.add(this._temp)}}applyCurrent(e,t,s){if(this.enabled&&this.system.worldspace!==!1&&this.mode===1){const r=this.curve.evaluate(t,s);this._temp.copy(this._velocity).multiplyScalar(r),e.add(this._temp)}}}q([w()],Yc.prototype,"enabled",2),q([w(tt)],Yc.prototype,"curve",2),q([w()],Yc.prototype,"curveMultiplier",2),q([w()],Yc.prototype,"mode",2);class Dr{constructor(){h(this,"enabled"),h(this,"range"),h(this,"separateAxes"),h(this,"size"),h(this,"sizeMultiplier"),h(this,"x"),h(this,"xMultiplier"),h(this,"y"),h(this,"yMultiplier"),h(this,"z"),h(this,"zMultiplier")}evaluate(e,t,s,r){const n=e.length(),o=Je.remap(n,this.range.x,this.range.y,0,1),a=this.size.evaluate(o,s);return r*a}}q([w()],Dr.prototype,"enabled",2),q([w(W)],Dr.prototype,"range",2),q([w()],Dr.prototype,"separateAxes",2),q([w(tt)],Dr.prototype,"size",2),q([w()],Dr.prototype,"sizeMultiplier",2),q([w(tt)],Dr.prototype,"x",2),q([w()],Dr.prototype,"xMultiplier",2),q([w(tt)],Dr.prototype,"y",2),q([w()],Dr.prototype,"yMultiplier",2),q([w(tt)],Dr.prototype,"z",2),q([w()],Dr.prototype,"zMultiplier",2);class fu{constructor(){h(this,"enabled"),h(this,"range"),h(this,"color")}evaluate(e,t,s){const r=e.length(),n=Je.remap(r,this.range.x,this.range.y,0,1),o=this.color.evaluate(n,t);s.x*=o.r,s.y*=o.g,s.z*=o.b,s.w*=o.alpha}}q([w()],fu.prototype,"enabled",2),q([w(W)],fu.prototype,"range",2),q([w(Jr)],fu.prototype,"color",2);function Vte(i){const e=i.domElement.querySelector("link[rel='ar']");if(e)return e;const t=document.createElement("div");t.classList.add("menu"),t.classList.add("quicklook-menu"),t.style.display="none",t.style.visibility="hidden";const s=document.createElement("button");s.id="open-in-ar",s.innerText="Open in QuickLook",t.appendChild(s);const r=document.createElement("a");r.id="needle-usdz-link",r.style.display="none",r.rel="ar",r.href="",t.appendChild(r);const n=document.createElement("img");return n.id="button",r.appendChild(n),i.domElement.appendChild(t),r}function Wte(){var i=new Date;const e=i.getMonth()+1,t=i.getDate(),s=i.getHours(),r=i.getMinutes(),n=i.getSeconds(),o=(e<10?"0":"")+e,a=(t<10?"0":"")+t,l=(s<10?"0":"")+s,c=(r<10?"0":"")+r,u=(n<10?"0":"")+n;return i.getFullYear()+o+a+"-"+l+c+u}const Yb=oe("debugusdz");function qte(i,e){const t=[],s=$.getComponentsInChildren(i,Gr);let r=!1;Yb&&console.log(s);for(const n of s){if(!n||!n.runtimeAnimatorController)continue;Yb&&console.log(n);const o=[];for(const a of n.runtimeAnimatorController.enumerateActions()){Yb&&console.log(a);const l=a.getClip();if(!r&&l.tracks.length>0){r=!0;const c=l.tracks[0],u=c.name.substring(0,c.name.lastIndexOf(".")),d=new hn(u+".position",[0,.01],[0,0,0,0,0,0]),p=new hn(u+".quaternion",[0,.01],[0,0,0,1,0,0,0,1]);o.push(new Bn("rest",.01,[d,p]))}o.includes(l)||o.push(l)}t.push({root:n.gameObject,clips:o})}Yb&&console.log(t);for(const n of t)for(const o of n.clips)e.registerAnimation(n.root,o)}var Xte=Object.defineProperty,Yte=Object.getOwnPropertyDescriptor,Tl=(i,e,t,s)=>{for(var r=s>1?void 0:s?Yte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Xte(e,t,r),r};const aM=oe("debugtext");var Es=(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))(Es||{});class Or extends hu{constructor(){super(...arguments),h(this,"alignment",0),h(this,"verticalOverflow",0),h(this,"horizontalOverflow",0),h(this,"lineSpacing",1),h(this,"supportRichText",!1),h(this,"font"),h(this,"fontStyle",0),h(this,"_text",""),h(this,"_fontSize",12),h(this,"_textMeshUi",null),h(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 e;const t=(e=this.uiObject)==null?void 0:e._overflow;t&&(t._needsUpdate=!0,this.markDirty())}onCreate(e){aM&&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,aM&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),aM&&(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 s,r,n;if(!this.uiObject)return null;if(this._textMeshUi||(this._textMeshUi=[]),!t||e.length===0)this.uiObject.textContent=e;else{let o=this.getNextTag(e);if(o)o.startIndex>0&&this.uiObject.add(new bb({textContent:e.substring(0,o.startIndex),color:"inherit"}));else return this.uiObject.textContent=e;const a=[];for(;o;){const l=this.getNextTag(e,o.endIndex),c={fontFamily:(s=this.uiObject)==null?void 0:s.get("fontFamily"),color:"inherit",textContent:""};l?(c.textContent=this.getText(e,o,l),this.handleTag(o,c,a),(r=this.uiObject)==null||r.add(new bb(c))):(c.textContent=e.substring(o.endIndex),this.handleTag(o,c,a),(n=this.uiObject)==null||n.add(new bb(c))),o=l}}return null}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,s={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let r=!1;if(this._textMeshUi)for(let n=0;n<this._textMeshUi.length;n++){if(e[n]===!0)continue;r=!0;const o=this._textMeshUi[n];o.textContent&&(Lb(o,s),e[n]=!0)}if(!r)break;yield}}handleTag(e,t,s){if(e.isEndTag){if(s.length>0){const r=s.pop();if(r)for(const n in r.previousValues){const o=r.previousValues[n];t[n]=o}}}else if(e.type.includes("color")){const r=new lM(e,{color:t.color});if(s.push(r),e.type.length>6){const n=parseInt("0x"+e.type.substring(7));t.color=n}else t.color=new _e(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const r=new lM(e,{fontWeight:700});s.push(r)}else if(e.type=="i"){this.setFont(t,2);const r=new lM(e,{fontStyle:"italic"});s.push(r)}}getText(e,t,s){return e.substring(t.endIndex,s.startIndex)}getNextTag(e,t=0){const s=e.indexOf("<",t),r=e.indexOf(">",s);if(s>=0&&r>=0){const n=e.substring(s+1,r);return{type:n,startIndex:s,endIndex:r+1,isEndTag:n.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;let s=this.font,r=IE.getFontFamily(s);r||(r=IE.addFontFamily(s)),e.fontFamily=r;const n=s.toLowerCase();switch(t){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal",n.includes("-bold")||(s+="-bold");break;case 2:e.fontWeight=400,e.fontStyle="italic",n.includes("-italic")||(s+="-italic");break;case 3:e.fontStyle="italic",e.fontWeight=400,n.includes("-bold")||(s+="-bold"),n.includes("-italic")||(s+="-italic")}let o=r.getVariant(e.fontWeight,e.fontStyle);if(!o){let a=s;a!=null&&a.endsWith("-msdf.json")||(a+="-msdf.json");let l=s;l!=null&&l.endsWith(".png")||(l+=".png"),o=r.addVariant(e.fontWeight,e.fontStyle,a,l),o?.addEventListener("ready",()=>{this.markDirty()})}}}Tl([w()],Or.prototype,"alignment",2),Tl([w()],Or.prototype,"verticalOverflow",2),Tl([w()],Or.prototype,"horizontalOverflow",2),Tl([w()],Or.prototype,"lineSpacing",2),Tl([w()],Or.prototype,"supportRichText",2),Tl([w(URL)],Or.prototype,"font",2),Tl([w()],Or.prototype,"fontStyle",2),Tl([w()],Or.prototype,"text",1),Tl([w()],Or.prototype,"fontSize",1);class lM{constructor(e,t){h(this,"tag"),h(this,"previousValues"),this.tag=e,this.previousValues=t}}class Jc{constructor(e){h(this,"id"),h(this,"content",""),h(this,"font",[]),h(this,"pointSize",144),h(this,"width"),h(this,"height"),h(this,"depth"),h(this,"wrapMode"),h(this,"horizontalAlignment"),h(this,"verticalAlignment"),h(this,"material"),this.id=e}static getId(){return this.global_id++}setDepth(e){return this.depth=e,this}setPointSize(e){return this.pointSize=e,this}setHorizontalAlignment(e){return this.horizontalAlignment=e,this}setVerticalAlignment(e){return this.verticalAlignment=e,this}writeTo(e,t){var s;t.beginBlock(`def Preliminary_Text "${this.id}"`),this.content&&t.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(s=this.font)==null||s.push("sans-serif"));const r=this.font.map(n=>`"${n}"`).join(", ");t.appendLine(`string[] font = [ ${r} ]`),t.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&t.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&t.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&t.appendLine(`double depth = ${this.depth}`),this.wrapMode&&t.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&t.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&t.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&t.appendLine(`rel material:binding = </Materials/Material_${this.material.id}>`),t.closeBlock()}}h(Jc,"global_id",0);class Jb{static singleLine(e,t,s){const r=new Jc("text_"+Jc.getId());return r.content=e,t&&(r.pointSize=t),s&&(r.depth=s),r}static multiLine(e,t,s,r,n,o){const a=new Jc("text_"+Jc.getId());return a.content=e,a.width=t,a.height=s,a.horizontalAlignment=r,a.verticalAlignment=n,o!==void 0&&(a.wrapMode=o),a}}const Jte=new Qe().makeRotationY(Math.PI);class Kb{get extensionName(){return"text"}onExportObject(e,t,s){const r=$.getComponent(e,Or);if(r){const n=$.getComponent(e,ur);let o=100,a=100;n&&(o=n.width,a=n.height);const l=t.clone();l.matrix=Jte.clone();const c=new _e().copySRGBToLinear(r.color);l.material=new Mh({color:c,emissive:c}),t.add(l),l.addEventListener("serialize",(u,d)=>{const p=Jb.multiLine(r.text,o,a,"center","bottom","flowing");this.setTextAlignment(p,r.alignment),this.setOverflow(p,r),l.material&&(p.material=l.material),p.pointSize=this.convertToTextSize(r.fontSize),p.depth=.001,p.writeTo(void 0,u)})}}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case Es.LowerLeft:case Es.MiddleLeft:case Es.UpperLeft:e.horizontalAlignment="left";break;case Es.LowerCenter:case Es.MiddleCenter:case Es.UpperCenter:e.horizontalAlignment="center";break;case Es.LowerRight:case Es.MiddleRight:case Es.UpperRight:e.horizontalAlignment="right";break}switch(t){case Es.LowerLeft:case Es.LowerCenter:case Es.LowerRight:e.verticalAlignment="bottom";break;case Es.MiddleLeft:case Es.MiddleCenter:case Es.MiddleRight:e.verticalAlignment="middle";break;case Es.UpperLeft:case Es.UpperCenter:case Es.UpperRight:e.verticalAlignment="top";break}}}var Kte=Object.defineProperty,Zte=Object.getOwnPropertyDescriptor,Yn=(i,e,t,s)=>{for(var r=s>1?void 0:s?Zte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Kte(e,t,r),r};const da=oe("debugusdz");class Kc{constructor(){h(this,"callToAction"),h(this,"checkoutTitle"),h(this,"checkoutSubtitle"),h(this,"callToActionURL")}}Yn([w()],Kc.prototype,"callToAction",2),Yn([w()],Kc.prototype,"checkoutTitle",2),Yn([w()],Kc.prototype,"checkoutSubtitle",2),Yn([w()],Kc.prototype,"callToActionURL",2);class Jn extends Ee{constructor(){super(...arguments),h(this,"objectToExport"),h(this,"autoExportAnimations",!1),h(this,"exportFileName"),h(this,"customUsdzFile"),h(this,"customBranding"),h(this,"anchoringType","plane"),h(this,"planeAnchoringAlignment","horizontal"),h(this,"interactive",!0),h(this,"extensions",[]),h(this,"link"),h(this,"webxr"),h(this,"webARSessionRoot"),h(this,"lastCallback"),h(this,"_quicklookButton"),h(this,"_quicklookButtonContainer",null)}start(){var e,t,s,r;da&&(console.log(this),console.log("Debug USDZ, press 't' to export"),window.addEventListener("keydown",n=>{switch(n.key){case"t":this.exportAsync();break}}),lh()&&setTimeout(()=>{this.exportAsync()},2e3)),(e=document.getElementById("open-in-ar"))==null||e.addEventListener("click",n=>{n.preventDefault(),this.exportAsync()}),this.objectToExport||(this.objectToExport=this.gameObject),!((s=(t=this.objectToExport)==null?void 0:t.children)!=null&&s.length)&&!((r=this.objectToExport)!=null&&r.isMesh)&&(this.objectToExport=this.context.scene),this.interactive&&(this.extensions.push(new Ob),this.extensions.push(new kb),this.extensions.push(new Kb))}onEnable(){const e=ff(),t=Pa();(da||e&&t)&&(this.addQuicklookButton(),this.webARSessionRoot=$.findObjectOfType(Dc)??void 0,this.lastCallback=this.quicklookCallback.bind(this),this.link=Vte(this.context),this.link.addEventListener("message",this.lastCallback)),da&&Rs("USDZ Exporter enabled: "+this.name)}onDisable(){var e;(e=this.link)==null||e.removeEventListener("message",this.lastCallback);const t=ff(),s=Pa();(da||t&&s)&&this.removeQuicklookButton(),da&&Rs("USDZ Exporter disabled: "+this.name)}async exportAsync(){var e;let t=this.exportFileName??((e=this.objectToExport)==null?void 0:e.name)??this.name;if(Ac()||(t+="-MadeWithNeedle"),t+="-"+Wte(),this.customUsdzFile){const f=this.buildQuicklookOverlay();da&&console.log(f);const g=f.callToAction?encodeURIComponent(f.callToAction):"",m=f.checkoutTitle?encodeURIComponent(f.checkoutTitle):"",v=f.checkoutSubtitle?encodeURIComponent(f.checkoutSubtitle):"";this.link.href=this.customUsdzFile+`#callToAction=${g}&checkoutTitle=${m}&checkoutSubtitle=${v}&callToActionURL=${f.callToActionURL}`,console.log(this.link.href),this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=t+".usdz",this.link.click();return}if(!this.objectToExport)return;if(this.webARSessionRoot){const f=this.webARSessionRoot.gameObject,g=1/this.webARSessionRoot.arScale;f.matrix.makeScale(g,g,g),this.webARSessionRoot.invertForward&&f.matrix.multiply(new Qe().makeRotationY(Math.PI))}const s=new hY,r=[...this.extensions],n=new Xy;r.push(n),this.autoExportAnimations&&qte(this.objectToExport,n);const o={self:this,exporter:s,extensions:r,object:this.objectToExport};this.dispatchEvent(new CustomEvent("before-export",{detail:o})),s.debug=da,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 a=await s.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:r,quickLookCompatible:!0}),l=new Blob([a],{type:"application/octet-stream"});this.dispatchEvent(new CustomEvent("after-export",{detail:o}));const c=this.buildQuicklookOverlay();da&&console.log(c);const u=c.callToAction?encodeURIComponent(c.callToAction):"",d=c.checkoutTitle?encodeURIComponent(c.checkoutTitle):"",p=c.checkoutSubtitle?encodeURIComponent(c.checkoutSubtitle):"";this.link.href=URL.createObjectURL(l)+`#callToAction=${u}&checkoutTitle=${d}&checkoutSubtitle=${p}&callToActionURL=${c.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=t+".usdz",this.link.click()}quicklookCallback(e){if(e?.data=="_apple_ar_quicklook_button_tapped"){da&&uo("Quicklook closed via call to action button");var t=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(t),!t.defaultPrevented){const s=new URLSearchParams(this.link.href);if(s){const r=s.get("callToActionURL");da&&Rs("Quicklook url: "+r),r&&(Ac()?globalThis.open(r,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",r))}}}}buildQuicklookOverlay(){var e,t,s;const r={};return this.customBranding&&Object.assign(r,this.customBranding),Ac()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),r.callToAction="Close",r.checkoutTitle="\u{1F335} Made with Needle",r.checkoutSubtitle="_"),(e=r.callToAction)!=null&&e.length||(r.callToAction="Close"),(t=r.checkoutTitle)!=null&&t.length||(r.checkoutTitle="\u{1F335} Made with Needle"),(s=r.checkoutSubtitle)!=null&&s.length||(r.checkoutSubtitle="_"),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:r})),r}async createQuicklookButton(){var e,t;if(!this.webxr)if(await pf(1),this.webxr=$.findObjectOfType(xt)??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 s=(t=this.webxr.ARButton.parentElement)==null?void 0:t.querySelector("a");s&&(s.href=""),this.webxr.ARButton.innerText="Open in Quicklook",this.webxr.ARButton.disabled=!1,this.webxr.ARButton.addEventListener("click",r=>{r.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 s=window.document.querySelector(".webxr-buttons");s||(s=document.createElement("div"),s.classList.add("webxr-buttons"));const r=document.createElement("button");r.innerText="Open in Quicklook",r.addEventListener("click",()=>{this.exportAsync()}),r.classList.add("webxr-ar-button"),r.classList.add("webxr-button"),r.classList.add("quicklook-ar-button"),s.appendChild(r),this._quicklookButtonContainer=s,this.dispatchEvent(new CustomEvent("created-button",{detail:r}))}else console.warn("Could not find WebXR component: will not create Quicklook button",_t.Current)}async addQuicklookButton(){await this.createQuicklookButton(),this._quicklookButton&&this._quicklookButtonContainer&&this._quicklookButtonContainer.appendChild(this._quicklookButton)}removeQuicklookButton(){var e;(e=this._quicklookButton)==null||e.remove()}}Yn([w(Me)],Jn.prototype,"objectToExport",2),Yn([w()],Jn.prototype,"autoExportAnimations",2),Yn([w()],Jn.prototype,"exportFileName",2),Yn([w(URL)],Jn.prototype,"customUsdzFile",2),Yn([w(Kc)],Jn.prototype,"customBranding",2),Yn([w()],Jn.prototype,"anchoringType",2),Yn([w()],Jn.prototype,"planeAnchoringAlignment",2),Yn([w()],Jn.prototype,"interactive",2);const oU=oe("debugdeletable");class Zb extends Ko{}class cM extends Ee{constructor(){super(...arguments),h(this,"deleteBoxes",[])}awake(){this.deleteBoxes=$.findObjectsOfType(Zb,this.context)}update(){for(const e of this.deleteBoxes){const t=this.gameObject;if(e.isInBox(t)===!0){const s=$.getComponentInParent(this.gameObject,rp);s?oU&&console.warn("Can not delete object with usage marker",this.guid,s):(oU&&console.log("DESTROY",this.gameObject),Y0(this.gameObject,this.context.connection))}}}}var $te=Object.defineProperty,eie=Object.getOwnPropertyDescriptor,gu=(i,e,t,s)=>{for(var r=s>1?void 0:s?eie(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&$te(e,t,r),r};class To extends kr{constructor(){super(...arguments),h(this,"mode"),h(this,"focusDistance"),h(this,"focalLength"),h(this,"aperture"),h(this,"gaussianMaxRadius"),h(this,"resolutionScale"),h(this,"bokehScale")}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=t=>{const s=t/300,r=2;return Je.lerp(r,.01,s)};const e=20;this.aperture.valueProcessor=t=>{const s=1-t/32;return Je.lerp(1,e,s)}}onCreateEffect(){if(this.mode===0)return;const e=1/window.devicePixelRatio;if(this.resolutionScale===void 0){let s=1;lh()&&(s=.6),this.resolutionScale=new Dt(s*e)}const t=new nD(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=s=>{t.circleOfConfusionMaterial.worldFocusDistance=s},this.focalLength.onValueChanged=s=>t.circleOfConfusionMaterial.worldFocusRange=s,this.aperture.onValueChanged=s=>t.bokehScale=s,this.resolutionScale&&(this.resolutionScale.onValueChanged=s=>t.resolution.scale=s),[t]}unapply(){}}gu([w()],To.prototype,"mode",2),gu([w(Dt)],To.prototype,"focusDistance",2),gu([w(Dt)],To.prototype,"focalLength",2),gu([w(Dt)],To.prototype,"aperture",2),gu([w(Dt)],To.prototype,"gaussianMaxRadius",2),gu([w(Dt)],To.prototype,"resolutionScale",2),gu([w(Dt)],To.prototype,"bokehScale",2),oa("DepthOfField",To);var tie=Object.defineProperty,iie=Object.getOwnPropertyDescriptor,sie=(i,e,t,s)=>{for(var r=s>1?void 0:s?iie(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&tie(e,t,r),r};class $b extends Ee{constructor(){super(...arguments),h(this,"visibleOn")}onEnable(){this.apply()}apply(){this.test()||$.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:rie()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}sie([w()],$b.prototype,"visibleOn",2);let e_;function rie(){if(e_===!0||e_===!1)return e_;let i=!1;return function(e){(/(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(e)||/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(e.substr(0,4)))&&(i=!0)}(navigator.userAgent||navigator.vendor||window.opera),e_=i,i}class hM{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}var aU=(i=>(i.SelectStart="selectstart",i.SelectEnd="selectend",i))(aU||{});const Zc=class extends sp{constructor(){super(),h(this,"transformSelf",!0),h(this,"orbit",null),h(this,"selectStartEventListener",[]),h(this,"selectEndEventListener",[]),h(this,"_dragHelper",null),h(this,"_draggingRigidbodies",[]),h(this,"_waitingForDragStart",null),h(this,"_isDragging",!1),h(this,"_marker",null),h(this,"_dragDelta"),h(this,"_didDrag",!1),h(this,"_activePointerId"),this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new W}static get HasAnySelected(){return this._active>0}addDragEventListener(i,e){switch(i){case"selectstart":this.selectStartEventListener.push(e);break;case"selectend":this.selectEndEventListener.push(e);break}}start(){this.orbit=$.findObjectOfType(Cl,this.context)}allowEdit(i=null){return this.context.connection.allowEditing}onPointerEnter(i){if(!this.allowEdit(this.gameObject)||xt.IsInWebXR)return;const e=$.getComponentInParent(i.object,Zc);!e||e!==this||(Zc.lastHovered=i.object,this.context.domElement.style.cursor="pointer")}onPointerExit(i){this.allowEdit(this.gameObject)&&(xt.IsInWebXR||Zc.lastHovered===i.object&&(this.context.domElement.style.cursor="auto"))}onPointerDown(i){this.allowEdit(this.gameObject)&&(xt.IsInWebXR||(Zc._active+=1,this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=i,i.StopPropagation(),this.orbit&&(this.orbit.enabled=!1)))}onPointerUp(i){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&(Zc._active>0&&(Zc._active-=1),!xt.IsInWebXR&&(this.onDragEnd(i),i.StopPropagation(),this.orbit&&(this.orbit.enabled=!0)))}update(){var i;if(!xt.IsInWebXR){if(this._waitingForDragStart){if(!this._didDrag){const t=this.context.input.getPointerPositionDelta(0);if(t&&this._dragDelta.add(t),this._dragDelta.length()>2)this._didDrag=!0;else return}const e=this._waitingForDragStart;this._waitingForDragStart=null,this.onDragStart(e)}this._dragHelper&&this._dragHelper.hasSelected&&this.onUpdateDrag(),(((i=this._dragHelper)==null?void 0:i.hasSelected)===!1||this._activePointerId!==void 0&&this.context.input.getPointerPressed(this._activePointerId)===!1)&&this.onDragEnd(null)}}onDragStart(i){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new cU(this.context.mainCamera);else return;if(!i||!i.object)return;const e=$.getComponentInParent(i.object,Zc);if(!e||e!==this)return;let t=i.object;this.transformSelf&&(t=this.gameObject);const s={selected:t,attached:t};for(const a of this.selectStartEventListener)a(this,s);if(this._activePointerId=i.pointerId,!s.attached)return;s.attached,t=s.attached,this._isDragging=!0,this._dragHelper.setSelected(t,this.context),this.orbit&&(this.orbit.enabled=!1);const r=$.getComponentInChildren(t,Uc);r&&(r.fastMode=!0,r?.requestOwnership()),this._marker=$.addNewComponent(t,rp),this._draggingRigidbodies.length=0;const n=$.getComponentsInChildren(t,Li);n&&this._draggingRigidbodies.push(...n);const o=zv();$.invokeOnChildren(this._dragHelper.selected,o("onDragStart"))}onUpdateDrag(){if(this._dragHelper){this._dragHelper.onUpdate(this.context);for(const i of this._draggingRigidbodies)i.wakeUp(),i.resetVelocities()}}onDragEnd(i){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;for(const s of this._draggingRigidbodies)s.setVelocity(s.smoothedVelocity);this._draggingRigidbodies.length=0;const e=this._dragHelper.selected;if(this._dragHelper.setSelected(null,this.context),this.orbit&&(this.orbit.enabled=!0),i!=null&&i.object){const s=$.getComponentInChildren(i.object,Uc);s&&(s.fastMode=!1)}this._marker&&this._marker.destroy();for(const s of this.selectEndEventListener)s(this);const t=zv();$.invokeOnChildren(e,t("onDragEnd"))}};let kp=Zc;h(kp,"_active",0),h(kp,"lastHovered");const lU=class{constructor(i){h(this,"_selected",null),h(this,"_context",null),h(this,"_camera"),h(this,"_cameraPlane",new Tn),h(this,"_hasGroundPlane",!1),h(this,"_groundPlane",new Tn),h(this,"_groundOffset",new S),h(this,"_groundOffsetFactor",0),h(this,"_groundDistance",0),h(this,"_groundPlanePoint",new S),h(this,"_raycaster",new vd),h(this,"_cameraPlaneOffset",new S),h(this,"_intersection",new S),h(this,"_worldPosition",new S),h(this,"_inverseMatrix",new Qe),h(this,"_rbs",[]),h(this,"_groundLine"),h(this,"_groundMarker"),h(this,"_groundOffsetVector",new S(0,1,0)),h(this,"_requireUpdateGroundPlane",!0),h(this,"_didDragOnGroundPlaneLastFrame",!1),this._camera=i;const e=new qi(lU.geometry),t=e.material;t.color=new _e(.4,.4,.4),e.layers.set(2),e.name="line",e.scale.y=1,this._groundLine=e;const s=new to(.5,22,22),r=new di({color:t.color}),n=new ye(s,r);n.visible=!1,n.layers.set(2),this._groundMarker=n}get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}setSelected(i,e){if(this._selected&&e)for(const t of this._rbs)t.wakeUp(),t.setVelocity(0,0,0);if(this._selected&&Pr.Remove(e,this._selected),this._selected=i,this._context=e,this._rbs.length=0,i?(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}Pr.Add(e,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this.onUpdateScreenSpacePlane()}}onUpdate(i){var e,t,s,r,n;if(!this._context)return;const o="Space",a="KeyD",l=((e=this._context)==null?void 0:e.input.isKeyPressed(o))||((t=this._context)==null?void 0:t.input.isKeyPressed(a)),c=this._context.input.getTouchesPressedCount()>=2||l;if(c){const d=this._context.input.getPointerPositionDelta(0);d&&(this._groundOffsetVector.set(0,1,0),(s=this._selected)==null||s.rotateOnWorldAxis(this._groundOffsetVector,d.x*this._context.time.deltaTime))}const u=this._context.input.getPointerPositionRC(0);if(u&&(this._raycaster.setFromCamera(u,this._camera),this._selected)){this._groundOffsetVector.set(0,1,0);const d=wt(this._camera).clone().sub(wt(this._selected)).normalize(),p=Math.abs(d.dot(this._groundOffsetVector)),f=((r=this._context)==null?void 0:r.input.isKeyPressed(o))||((n=this._context)==null?void 0:n.input.isKeyPressed(a)),g=!c&&p>.2&&!f&&this._context.input.getPointerPressedCount()<=1,m=this._didDragOnGroundPlaneLastFrame!==g;if(this._didDragOnGroundPlaneLastFrame=g,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!g||m)&&this.onUpdateGroundPlane(),this._requireUpdateGroundPlane=!1,this._hasGroundPlane)if(this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection)){const v=this._intersection.y;if(this._groundPlanePoint.copy(this._intersection).sub(this._groundOffset),this._groundPlanePoint.y=v,g){this._groundOffsetVector.set(0,1,0);const A=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(A,this._groundPlanePoint,!1),this.onDidUpdate();return}}else this._groundPlanePoint.set(0,99999,0);m&&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(i,e,t){if(this._selected){if(t){const s=wt(this._selected);s.y=i.y,i=s}if(Yi(this._selected,i),Yi(this._groundLine,i),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=e!==null,e){const s=wt(this._camera).distanceTo(e)*.01;this._groundMarker.scale.set(s,s,s),Yi(this._groundMarker,e)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;const i=this._context.input.getPointerPositionRC(0);i&&(this._raycaster.setFromCamera(i,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 i=wt(this._selected),e=new za(new S(0,.1,0).add(i),new S(0,-1,0)),t=new fo;t.ignore=[this._selected];const s=this._context.physics.raycastFromRay(e,t);for(let r=0;r<s.length;r++){const n=s[r];if(!n.face||this.contains(this._selected,n.object))continue;const o=new S(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(o,n.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(i),this._groundOffset.copy(this._intersection).sub(i)}onDidUpdate(){en.markDirty(this._selected);for(const i of this._rbs)i.wakeUp(),i.resetForcesAndTorques(),i.setAngularVelocity(0,0,0)}contains(i,e){if(i===e)return!0;if(i.children){for(const t of i.children)if(this.contains(t,e))return!0}return!1}};let cU=lU;h(cU,"geometry",new At().setFromPoints([new S(0,0,0),new S(0,-1,0)]));function uM(i,e,t){console.warn("Adding components on object has been temporarily disabled")}var hU=(i=>(i.File_Spawned="file-spawned",i))(hU||{});class uU{constructor(e,t,s,r,n,o,a,l){h(this,"guid"),h(this,"file_name"),h(this,"file_hash"),h(this,"file_size"),h(this,"position"),h(this,"seed"),h(this,"sender"),h(this,"serverUrl"),h(this,"parentGuid"),h(this,"boundsSize"),this.seed=t,this.guid=s,this.file_name=r,this.file_hash=n,this.file_size=o,this.position=a,this.sender=e,this.serverUrl=l}}async function dM(i,e,t){const s=i.name;return s.endsWith(".gltf")||s.endsWith(".glb")?new Promise((r,n)=>{const o=new FileReader;o.readAsArrayBuffer(i),o.onloadend=async a=>{const l=o.result,c=J0(),u=new Ur(c),d=await Ao().parseSync(e,l,i.name,u);if(d&&d.scene){const p=d.scene;if(!p.guid){const f=new Ur(c);p.guid=f.generateUUID()}t&&nie(e.connection,i,c,p,t),uM(),r(d)}}}):(console.warn("Unsupported file type: "+s),console.log(i),null)}async function dU(i,e){return new Promise(async(t,s)=>{const r=J0(),n=new Ur(r),o=i.toString(),a=await Ao().loadSync(e,o,o,n);a&&a.scene?(a.scene,uM(),t(a)):console.warn("Unsupported file type: "+i.toString())})}Gi.registerCallback(Cn.ContextCreated,i=>{pU(i.context)});function pU(i){i.connection.beginListen("file-spawned",async e=>{if(e.sender!==i.connection.connectionId){console.log("received file event",e),oie(e,i);let t=null;try{t=await AC(e.file_name,e.file_hash,e.file_size,e.serverUrl)}finally{aie(e)}if(t){const s=new Ur(e.seed),r=await Ao().parseSync(i,t,null,s);if(r&&r.scene){const n=r.scene;if(uM(),e.parentGuid){const o=yg(e.parentGuid,i.scene);"add"in o&&o.add(n)}n.parent||i.scene.add(n),e.position!==null&&n.position.copy(e.position)}}else console.error("download didnt return file")}})}async function nie(i,e,t,s,r){if(!i.connectionId){console.error("Can not upload file - no connection id");return}if(!s.guid){console.error("Can not upload file - no guid",s,s.guid);return}const n=await xD(e,r);if(!n)return;if(!n.filename){console.error("Can not send upload event - no filename",e.name);return}if(!n.hash){console.error("Can not send upload event - no hash",e.name);return}const o=new uU(i.connectionId,t,s.guid,n.filename,n.hash,e.size,s.position,n.url??r);s.parent&&(o.parentGuid=s.parent.guid),i.send("file-spawned",o)}const pM={};function oie(i,e){const t=new fi,s=new ye(t,new di({color:65280})),r=new g0(s,5592405);if(pM[i.guid]=r,e.scene.add(r),i.parentGuid){const n=yg(i.parentGuid,e.scene);n&&n.add(r)}i.position&&r.position.copy(i.position)}function aie(i,e){const t=i.guid,s=pM[t];s&&(delete pM[t],s.removeFromParent())}var lie=Object.defineProperty,cie=Object.getOwnPropertyDescriptor,fM=(i,e,t,s)=>{for(var r=s>1?void 0:s?cie(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&lie(e,t,r),r};const hie=oe("debugnet"),gM=class extends Ee{constructor(){super(...arguments),h(this,"url",null),h(this,"urlParameterName",null),h(this,"localhost",null)}awake(){hie&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let i=this.url?gM.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const t=oe(this.urlParameterName);t&&typeof t=="string"&&(i=t)}if(!i)return null;const e=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(i);return e!=null&&e.groups?e?.groups.socket_prefix?i:"wss://"+e?.groups.url:null}static GetUrl(i,e){let t=i;const s=gM.IsLocalNetwork()&&e;return s&&(t=e),i!=null&&i.startsWith("/")&&(t=(s?t:window.location.origin)+i),t}static IsLocalNetwork(i=window.location.hostname){return gr(i)}};let mu=gM;fM([w()],mu.prototype,"url",2),fM([w()],mu.prototype,"urlParameterName",2),fM([w()],mu.prototype,"localhost",2);var uie=Object.defineProperty,die=Object.getOwnPropertyDescriptor,fU=(i,e,t,s)=>{for(var r=s>1?void 0:s?die(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&uie(e,t,r),r};class Um extends Ee{constructor(){super(...arguments),h(this,"filesBackendUrl"),h(this,"localhost"),h(this,"_dragOver"),h(this,"_drop")}onEnable(){this.filesBackendUrl=this.filesBackendUrl?mu.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 s=await dM(t,this.context,this.filesBackendUrl);this.dispatchEvent(new CustomEvent("file-dropped",{detail:t})),s&&this.addObject(void 0,s)}}async onDrop(e){if(console.log(e),!e.dataTransfer)return;e.preventDefault();const t=e.dataTransfer.items;if(t)for(const s in t){const r=t[s];if(r.kind==="file"){const n=r.getAsFile();if(!n)continue;console.log("Register file "+n.name+" to",this.filesBackendUrl,n);const o=await dM(n,this.context,this.filesBackendUrl);this.dispatchEvent(new CustomEvent("file-dropped",{detail:n})),o&&this.addObject(e,o)}else r.kind==="string"&&r.type=="text/plain"&&r.getAsString(async n=>{console.log("dropped url",n);try{const o=new URL(n);if(!o)return;const a=await dU(o,this.context);a&&this.addObject(e,a)}catch{console.log("dropped string is not a valid URL!",n)}})}}async addObject(e,t){console.log("Dropped",t);const s=t.scene;if(e!==void 0){const r=new fo;r.setMask(16777215),r.screenPointFromOffset(e.offsetX,e.offsetY);const n=this.context.physics.raycast(r);if(n&&n.length>0)for(const o of n){s.position.copy(o.point);break}}this.gameObject.add(s),this.dispatchEvent(new CustomEvent("object-added",{detail:t}))}}fU([w()],Um.prototype,"filesBackendUrl",2),fU([w()],Um.prototype,"localhost",2);var pie=Object.defineProperty,fie=Object.getOwnPropertyDescriptor,t_=(i,e,t,s)=>{for(var r=s>1?void 0:s?fie(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&pie(e,t,r),r};class vu extends sp{constructor(){super(...arguments),h(this,"parent",null),h(this,"object",null),h(this,"limitCount",10),h(this,"limitInterval",60),h(this,"_currentCount",0),h(this,"_startPosition",null),h(this,"_startQuaternion",null)}awake(){var e,t;if(this.object){if(this.object===this.gameObject){console.error("Can not duplicate self");return}this.object.visible=!1,this._startPosition=((e=this.object.position)==null?void 0:e.clone())??new S(0,0,0),this._startQuaternion=((t=this.object.quaternion)==null?void 0:t.clone())??new xe(0,0,0,1)}const s=$.getComponentInParent(this.gameObject,kp);s?s.addDragEventListener(aU.SelectStart,(r,n)=>{if(this._currentCount>=this.limitCount){n.attached=null;return}const o=this.handleDuplication(n.selected);o&&(console.assert(o!==n.selected,"Duplicated object is original"),n.attached=o)}):console.warn("Could no find drag controls in parent",this.name),cs.addEventListener(bl.SelectStart,(r,n)=>{if(this._currentCount>=this.limitCount){n.grab=null;return}const o=this.handleDuplication(n.selected);o&&(n.grab=o)}),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 s=new Go;this.parent||(this.parent=this.gameObject.parent),this.parent&&(s.parent=this.parent.guid??((t=this.parent.userData)==null?void 0:t.guid),s.keepWorldPosition=!0),s.position=this.worldPosition,s.rotation=this.worldQuaternion,s.context=this.context,this._currentCount+=1;const r=$.instantiateSynced(this.object,s);return console.assert(r!==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),r}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 s of e.children)if(this.isInChildren(s,t))return!0}return!1}}t_([w(Me)],vu.prototype,"parent",2),t_([w(Me)],vu.prototype,"object",2),t_([w()],vu.prototype,"limitCount",2),t_([w()],vu.prototype,"limitInterval",2);var Dp=(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))(Dp||{}),gie=Object.defineProperty,mie=Object.getOwnPropertyDescriptor,mM=(i,e,t,s)=>{for(var r=s>1?void 0:s?mie(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&gie(e,t,r),r};class vM{constructor(){h(this,"eventID"),h(this,"callback")}}mM([w()],vM.prototype,"eventID",2),mM([w(Vr)],vM.prototype,"callback",2);class i_ extends Ee{constructor(){super(...arguments),h(this,"triggers")}invoke(e){if(this.triggers)for(const t of this.triggers)t.eventID===e&&t.callback.invoke()}onPointerClick(e){this.invoke(Dp.PointerClick)}onPointerEnter(e){this.invoke(Dp.PointerEnter)}onPointerExit(e){this.invoke(Dp.PointerExit)}onPointerDown(e){this.invoke(Dp.PointerDown)}onPointerUp(e){this.invoke(Dp.PointerUp)}}mM([w(vM)],i_.prototype,"triggers",2);var vie=Object.defineProperty,Aie=Object.getOwnPropertyDescriptor,AM=(i,e,t,s)=>{for(var r=s>1?void 0:s?Aie(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&vie(e,t,r),r};class yM extends Ee{constructor(){super(...arguments),h(this,"connectedBody"),h(this,"_rigidBody",null)}get rigidBody(){return this._rigidBody}onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(Li)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.createJoint(this.rigidBody,this.connectedBody)}}AM([w(Li)],yM.prototype,"connectedBody",2);class bM extends yM{createJoint(e,t){var s;(s=this.context.physics.engine)==null||s.addFixedJoint(e,t)}}class Nm extends yM{constructor(){super(...arguments),h(this,"anchor"),h(this,"axis")}createJoint(e,t){var s;this.axis&&this.anchor&&((s=this.context.physics.engine)==null||s.addHingeJoint(e,t,this.anchor,this.axis))}}AM([w(S)],Nm.prototype,"anchor",2),AM([w(S)],Nm.prototype,"axis",2);const yie={type:"change"};let bie=class extends vs{constructor(i,e){super(),this.object=i,this.domElement=e,this.movementSpeed=1,this.rollSpeed=.005,this.dragToLook=!1,this.autoForward=!1;const t=this,s=1e-6,r=new xe,n=new S;this.tmpQuaternion=new xe,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 S(0,0,0),this.rotationVector=new S(0,0,0),this.keydown=function(d){if(!d.altKey){switch(d.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(d){switch(d.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(d){if(this.dragToLook)this.status++;else{switch(d.button){case 0:this.moveState.forward=1;break;case 2:this.moveState.back=1;break}this.updateMovementVector()}},this.pointermove=function(d){if(!this.dragToLook||this.status>0){const p=this.getContainerDimensions(),f=p.size[0]/2,g=p.size[1]/2;this.moveState.yawLeft=-(d.pageX-p.offset[0]-f)/f,this.moveState.pitchDown=(d.pageY-p.offset[1]-g)/g,this.updateRotationVector()}},this.pointerup=function(d){if(this.dragToLook)this.status--,this.moveState.yawLeft=this.moveState.pitchDown=0;else{switch(d.button){case 0:this.moveState.forward=0;break;case 2:this.moveState.back=0;break}this.updateMovementVector()}this.updateRotationVector()},this.update=function(d){const p=d*t.movementSpeed,f=d*t.rollSpeed;t.object.translateX(t.moveVector.x*p),t.object.translateY(t.moveVector.y*p),t.object.translateZ(t.moveVector.z*p),t.tmpQuaternion.set(t.rotationVector.x*f,t.rotationVector.y*f,t.rotationVector.z*f,1).normalize(),t.object.quaternion.multiply(t.tmpQuaternion),(n.distanceToSquared(t.object.position)>s||8*(1-r.dot(t.object.quaternion))>s)&&(t.dispatchEvent(yie),r.copy(t.object.quaternion),n.copy(t.object.position))},this.updateMovementVector=function(){const d=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=-d+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",gU),this.domElement.removeEventListener("pointerdown",a),this.domElement.removeEventListener("pointermove",o),this.domElement.removeEventListener("pointerup",l),window.removeEventListener("keydown",c),window.removeEventListener("keyup",u)};const o=this.pointermove.bind(this),a=this.pointerdown.bind(this),l=this.pointerup.bind(this),c=this.keydown.bind(this),u=this.keyup.bind(this);this.domElement.addEventListener("contextmenu",gU),this.domElement.addEventListener("pointerdown",a),this.domElement.addEventListener("pointermove",o),this.domElement.addEventListener("pointerup",l),window.addEventListener("keydown",c),window.addEventListener("keyup",u),this.updateMovementVector(),this.updateRotationVector()}};function gU(i){i.preventDefault()}class _M extends Ee{constructor(){super(...arguments),h(this,"_controls",null)}onEnable(){var e;const t=(e=$.getComponent(this.gameObject,Mi))==null?void 0:e.cam;this._controls=new bie(t,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 _ie=Object.defineProperty,wie=Object.getOwnPropertyDescriptor,wM=(i,e,t,s)=>{for(var r=s>1?void 0:s?wie(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&_ie(e,t,r),r};class Op extends Ee{constructor(){super(...arguments),h(this,"_fog")}get fog(){return this._fog||(this._fog=new Mx(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)}}wM([w()],Op.prototype,"near",1),wM([w()],Op.prototype,"far",1),wM([w(_e)],Op.prototype,"color",1);let xM,CM,Lp,s_;function SM(i,e,t){CM||(CM=new Ls(2,2,1,1)),Lp||(Lp=new Vt({uniforms:{blitTexture:new Ce(i)},vertexShader:`
|
|
4561
|
+
`&&i.length>1&&IF([t],i[i.length-2]),e.offsetX}function O$(i){if(!i[0])return 0;let e=[],t;for(let s=0;s<i.length;s++){const r=i[s];if(r.char&&EF[r.char]&&i.length>s){e.push(r),t=i[s+1];continue}break}TF(e,t),e=[],t=null;for(let s=i.length-1;s>0;s--){const r=i[s];if(r.char&&EF[r.char]&&s>0){e.push(r),t=i[s-1];continue}break}return IF(e,t),i[0].offsetX}function L$(i){return i[0]?i[0].offsetX:0}function IF(i,e){if(e)for(let t=0;t<i.length;t++){const s=i[t];s.fontFactor=0,s.offsetX=e.offsetX+e.cumulativeWidth,s.cumulativeWidth=0}}function TF(i,e){if(e)for(let t=0;t<i.length;t++){const s=i[t];s.fontFactor=0,s.offsetX=e.offsetX,s.cumulativeWidth=0}}function RF(i,e,t,s){if(s=s||0,!i[e])return s;const r=i[e];return r.lineBreak?s+r.xadvance:RF(i,e+1,t,s+r.xadvance+r.xoffset+r.kerning+t.LETTERSPACING)}function F$(i,e,t,s){return!i||!i.char||e+t<s.INNER_WIDTH?!1:s.BREAKON.indexOf(i.char)>-1}class PF extends I3{constructor(){super(),this._input="inherit",this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}_computeFromInherited(e){super._computeFromInherited(e),e._fontSize._needsProcess=!0,e._layouter._needsProcess=!0}}class BF extends Si{constructor(){super("fontSize","inherit",!0),this._allowsInherit=!1}computeOutputValue(e){this._value=this._inheritedInput,e._font._fontVariant&&(e._bounds._needsProcess=!0,e._layouter._needsProcess=!0)}process(e){if(!e._font._fontVariant||!e._font._fontVariant.isReady)return;const t=this._value/e._font._fontVariant.typographic.size,s=e._inlines._value;for(let r=0;r<s.length;r++){const n=s[r];n.resetOffsets(),n.fontSize=this._value,n.fontFactor=t}}get value(){return this._value}}class kF extends T3{constructor(){super("segments",1,!1),this._notInheritedValue=void 0}update(e,t){this._notInheritedValue=this._value,this._notInheritedValue==="inherit"&&(this._notInheritedValue=this.getInheritedInput(e)),e._layouter._needsUpdate=!0}set value(e){this._value!==e&&(this._value=e,this._needsUpdate=!0)}get value(){return this._value==="inherit"?this._notInheritedValue:this._value}}class U$ extends kF{constructor(){super(),this._value="inherit"}}class N$ extends cb{constructor(){super(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}_computeFromInherited(e){super._computeFromInherited(e),e._parent._value._layouter._needsProcess=!1}process(e){if(this._value!=="none"){const t=e._whiteSpace._whiteSpacedContent,s=e._inlines._value;for(let r=1;r<s.length;r++){const n=t[r-1]+t[r];s[r].kerning=e._font._fontVariant.getKerningAmount(n)}}}}class DF extends ci{constructor(){super("children",null,!1),this._uis=[]}update(e,t){}process(e){}_compute(e){}dispose(){}}function z$(i,e=!1){const t=i[0].index!==null,s=new Set(Object.keys(i[0].attributes)),r=new Set(Object.keys(i[0].morphAttributes)),n={},o={},a=i[0].morphTargetsRelative,l=new Ke.BufferGeometry;let c=0;for(let u=0;u<i.length;++u){const d=i[u];let p=0;if(t!==(d.index!==null))return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+u+". All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them."),null;for(const f in d.attributes){if(!s.has(f))return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+u+'. All geometries must have compatible attributes; make sure "'+f+'" attribute exists among all geometries, or in none of them.'),null;n[f]===void 0&&(n[f]=[]),n[f].push(d.attributes[f]),p++}if(p!==s.size)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+u+". Make sure all geometries have the same number of attributes."),null;if(a!==d.morphTargetsRelative)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+u+". .morphTargetsRelative must be consistent throughout all geometries."),null;for(const f in d.morphAttributes){if(!r.has(f))return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+u+". .morphAttributes must be consistent throughout all geometries."),null;o[f]===void 0&&(o[f]=[]),o[f].push(d.morphAttributes[f])}if(l.userData.mergedUserData=l.userData.mergedUserData||[],l.userData.mergedUserData.push(d.userData),e){let f;if(t)f=d.index.count;else if(d.attributes.position!==void 0)f=d.attributes.position.count;else return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+u+". The geometry must have either an index or a position attribute"),null;l.addGroup(c,f,u),c+=f}}if(t){let u=0;const d=[];for(let p=0;p<i.length;++p){const f=i[p].index;for(let g=0;g<f.count;++g)d.push(f.getX(g)+u);u+=i[p].attributes.position.count}l.setIndex(d)}for(const u in n){const d=OF(n[u]);if(!d)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the "+u+" attribute."),null;l.setAttribute(u,d)}for(const u in o){const d=o[u][0].length;if(d===0)break;l.morphAttributes=l.morphAttributes||{},l.morphAttributes[u]=[];for(let p=0;p<d;++p){const f=[];for(let m=0;m<o[u].length;++m)f.push(o[u][m][p]);const g=OF(f);if(!g)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the "+u+" morphAttribute."),null;l.morphAttributes[u].push(g)}}return l}function OF(i){let e,t,s,r=0;for(let a=0;a<i.length;++a){const l=i[a];if(l.isInterleavedBufferAttribute)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. InterleavedBufferAttributes are not supported."),null;if(e===void 0&&(e=l.array.constructor),e!==l.array.constructor)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes."),null;if(t===void 0&&(t=l.itemSize),t!==l.itemSize)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes."),null;if(s===void 0&&(s=l.normalized),s!==l.normalized)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes."),null;r+=l.array.length}const n=new e(r);let o=0;for(let a=0;a<i.length;++a)n.set(i[a].array,o),o+=i[a].array.length;return new Ke.BufferAttribute(n,t,s)}class Q$ extends ci{constructor(){super("renderer")}render(e){if(!e._inlines._value||!e._inlines._value.length)return;const t=e._inlines._value.map(r=>e._font._fontVariant.getGeometricGlyph(r,e).translate(r.offsetX,r.offsetY,0)),s=z$(t);e.setFontMesh(new Ke.Mesh(s,e.fontMaterial)),e._fontMesh.renderOrder=1/0}}class j$ extends qS{constructor(){super(),this._allowsInherit=!1,this._needsUpdate=!1}computeOutputValue(e){this._value=this._inheritedInput,e._layouter._needsProcess=!0}}class cf extends om{constructor(e={}){const t={};cf.definePropertiesValues(t,e),super(t,e),h(this,"_rebuildParentUI",()=>{super._rebuildParentUI(),this._layouter._needsUpdate=!0}),cf.init(this)}add(e){const t=[];for(let s=0;s<arguments.length;s++){const r=arguments[s];!r.isUI||r.isInline?(t.push(r),r.position.z=.005):console.warn("Block element can only contain Box elements.",r)}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=DF),e.textContent||(e.textContent=w$),e.glyphs||(e.glyphs=C$),e.inlines||(e.inlines=x$),e.layouter||(e.layouter=wF),e.renderer||(e.renderer=Q$),e.fontFamily||(e.fontFamily=SF),e.fontWeight||(e.fontWeight=CF),e.fontStyle||(e.fontStyle=xF),e.fontSize||(e.fontSize=BF),e.color||(e.color=S$),e.backgroundColor||(e.backgroundColor=E$),e.lineBreak||(e.lineBreak=_F),e.letterSpacing||(e.letterSpacing=PF),e.whiteSpace||(e.whiteSpace=EE),e.segments||(e.segments=U$),e.textAlign||(e.textAlign=j$),e.fontKerning||(e.fontKerning=N$)}static init(e){Object.defineProperties(e,{isInline:{configurable:!1,enumerable:!0,value:!0}})}}class G$ extends m3{constructor(){super("textContent",null,!1),this._needsUpdate=!1}set value(e){this._value!==e&&(this._value=e,this._needsUpdate=!0)}update(e,t){this._needsUpdate=!1;for(let s=e.children.length-1;s>=0;s--){const r=e.children[s];r.isUI&&(e.remove(r),r.clear())}e._children._uis=[],this._value&&e.add(new cf({name:"anonymousInline",textContent:this._value}))}}class H$ extends Array{constructor(...e){super(...e),this.width=0,this.height=0}}class V$ extends ci{constructor(){super("layouter",null,!1),this._value=null}update(e,t){}process(e){let t=e._width._value;e._width._auto?t=1/0:t=e._bounds._innerWidth;const s=e._lineHeight._value,r=new H$(new bF);let n=0;e._children._inlines.forEach(d=>{if(!d._inlines.value)return;this._resetInlines(d);const p=d._fontSize._value,f=d._letterSpacing._value*p,g=d._whiteSpace._value,m=d._lineBreak._value,v={WHITESPACE:g,LETTERSPACING:f,BREAKON:m,INNER_WIDTH:t},A=d._whiteSpace._inlineWrapper;n+=d._margin._value.w+d._padding._value.w,d._inlines.value.forEach((b,y,_)=>{const x=r[r.length-1];if(A(_,y,n,v)){if(r.push(new bF(b)),b.offsetX=b.xoffset,b.width===0){n=0;return}b.cumulativeWidth=b.xadvance+f,n=b.cumulativeWidth;return}r[r.length-1].push(b),b.offsetX=n+b.xoffset+b.kerning,b.cumulativeWidth=b.xadvance+b.kerning+f,n+=b.cumulativeWidth,x.length-1===1&&x[x.length-2].width===0&&(b.offsetX-=b.xoffset,n-=b.xoffset)}),n+=d._margin._value.y+d._padding._value.y});const o=e._whiteSpace._inlineCollapser;let a=0,l=0,c=0;r.forEach((d,p)=>{const f=o(d);let g=0,m=0;if(d.forEach(v=>{g=Math.max(g,v.lineHeight),m=Math.max(m,v.lineBase),v.offsetX-=f}),d.lineHeight=g,d.lineBase=m,p===0?c=-(g*s-g)*.5:c-=r[p-1].lineHeight*s,d.y=c,d.x=0,d.forEach(v=>{v.offsetY=c-v.anchor,v.lineHeight<d.lineHeight&&(v.offsetY-=d.lineBase-v.lineBase)}),l+=d.lineHeight*s,d.width=0,d[0]){const v=d[d.length-1];d.width=v.offsetX+v.cumulativeWidth+v.paddingRight+v.marginRight+d[0].offsetX,a=Math.max(a,d.width)}}),r.height=l,r.width=a,this._value=r,t===1/0&&e._bounds.setChildrenWidth(e,r.width),e._height._auto&&e._bounds.setChildrenHeight(e,r.height);const u=e._parent._value;u&&(u._autoSize._needsProcess=!0,u._flexDirection._needsProcess=!0),e._inlineJustificator._needsProcess=!0,e._textAlign._needsProcess=!0,e._overflow._needsUpdate=!0}_resetInlines(e){e._fontSize.process(e)}}class W$ extends qS{constructor(){super(),this._allowsInherit=!1,this._needsUpdate=!0}computeOutputValue(e){this._value=this._inheritedInput,this._needsProcess=!0}process(e){q$(e),e._renderer._needsRender=!0}}function q$(i){const e=i._layouter._value,t=i._textAlign._value,s=i._bounds._innerWidth;for(let r=0;r<e.length;r++){const n=e[r],o=X$(i,n,r===e.length-1),a=i._padding._value,l=i._borderWidth._value,c=(-a.w+a.y)/2+(-l.w+l.y)/2;n.x+=o;for(let u=0;u<n.length;u++)n[u].offsetX+=o-c}if(t.indexOf("justify")===0)for(let r=0;r<e.length;r++){const n=e[r];if(t.indexOf("-")!==-1&&r===e.length-1)return;const o=s-n.width;if(o<=0)return;let a=0;for(let d=1;d<n.length-1;d++)a+=n[d].char===" "?1:0;const l=o/a;let c=1;t==="justify-right"&&(n.reverse(),c=-1);let u=0;for(let d=1;d<=n.length-1;d++){const p=n[d];p.offsetX+=u*c,u+=p.char===" "?l:0}t==="justify-right"&&n.reverse()}}function X$(i,e,t){switch(i._textAlign._value){case"justify-left":case"justify":case"left":return-i._bounds._innerWidth/2;case"justify-right":case"right":return-e.width+i._bounds._innerWidth/2;case"center":return-e.width/2;case"justify-center":return t?-e.width/2:-i._bounds._innerWidth/2;default:console.warn(`textAlign: '${i._textAlign._value}' is not valid`)}}class Y$ extends XS{constructor(){super(),this._value=this._input="column",this._allowsInherit=!1,this._needsUpdate=!0}computeOutputValue(e){this._value=this._inheritedInput}}class J$ extends E3{constructor(){super(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}}class K$ extends cb{constructor(){super(),this._value=this._input=this.getDefaultValue(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}_computeFromInherited(e){super._computeFromInherited(e)}}class Z$ extends mF{constructor(){super(),this._innerWidth=1/0,this._innerHeight=0}}class $$ extends ci{constructor(){super("children",null,!1),h(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 eee extends ci{constructor(){super("autosize")}process(e){if(e._layouter._value&&e._layouter._value.length){const t=e._layouter._value,s=e._padding._value,r=e._borderWidth._value;e._width._auto&&e._bounds.setOffsetWidth(e,t.width+s.w+s.y+r.w+r.y),e._height._auto&&e._bounds.setOffsetHeight(e,t.height+s.x+s.z+r.x+r.z)}}}class tee extends yF{constructor(){super("renderer"),this._needsUpdate=!1}render(e){super.render(e);for(const t of e._children._inlines)t._renderer.render(t);e.performAfterUpdate()}}class Uv extends Lv{constructor(e={},t={}){Uv.definePropertiesValues(t,e),super(t,e),Uv.init(this)}add(e){const t=[];let s=!1;for(let r=0;r<arguments.length;r++){const n=arguments[r];!n.isUI||n.isInline?(n.isInline&&(s=!0),t.push(n)):console.warn("Block element can only contain Box elements.",n)}return t.length>0&&super.add(...t),s&&(this._children._needsUpdate=!0,this._layouter._needsProcess=!0),this}set textContent(e){this._textContent.value=e}get textContent(){return super.textContent}set invertAlpha(e){this._invertAlpha.value=e}get invertAlpha(){return this._invertAlpha._value}get lines(){return this._layouter._value}static definePropertiesValues(e,t){e.flexDirection=Y$,e.justifyContent=YS,e.alignItems=WS,e.bounds=Z$,e.autoSize=eee,e.renderer=tee,e.children||(e.children=$$),e.textContent||(e.textContent=G$),e.layouter||(e.layouter=V$),e.lineHeight||(e.lineHeight=J$),e.textAlign||(e.textAlign=W$),e.whiteSpace||(e.whiteSpace=EE),e.fontKerning||(e.fontKerning=K$),e.segments||(e.segments=kF),t.width||(t.width="100%"),t.fontSide||(t.fontSide=0)}static init(e){Object.defineProperties(e,{isText:{configurable:!1,enumerable:!0,value:!0}})}}class iee extends ci{constructor(){super("inlines",null,!1),this._value=[]}process(e){this._value[0].paddingLeft=e._padding._value.w,this._value[0].marginLeft=e._margin._value.w;const t=this._value.length-1;this._value[t].paddingRight=e._padding._value.y,this._value[t].marginRight=e._margin._value.y}}class see extends ci{constructor(){super("renderer")}render(e){e._backgroundMesh||e.setBackgroundMesh(new AF(e)),e._backgroundMesh.position.x=e._inlines._value[0].offsetX+e._inlines._value[0].width/2,e._backgroundMesh.position.y=e._inlines._value[0].offsetY+e._inlines._value[0].lineBase/2,e._bounds.render(e)}}class ree extends ci{constructor(){super("bounds",null,!1),this._size=new Ke.Vector3(1,1,1),this._offsetWidth=0,this._offsetHeight=0,this._innerWidth=0,this._innerHeight=0}update(e,t){this.output(t),this._needsProcess=!0}process(e){this._offsetWidth=this._innerWidth=e._inlines._value[0].width,this._offsetHeight=this._innerHeight=e._inlines._value[0].height,this._needsRender=!0,e._borderWidth._needsRender=!0,e._borderRadius._needsRender=!0}render(e){this._size.x=this._offsetWidth,this._size.y=this._offsetHeight}output(e){e.size=this._size}}class Nv extends om{constructor(e={}){const t={};Nv.definePropertiesValues(t,e),super(t,e),Nv.init(this)}clear(){for(const e of this._inlines._value)e.clear();return super.clear()}bindBackgroundMeshProperties(){this._backgroundMesh.raycast=()=>{},this._bounds._size=this._backgroundMesh.scale,this._bounds._needsUpdate=!0}unbindBackgroundMeshProperties(){this._bounds._size=new Ke.Vector3(1,1,1),this._bounds._needsUpdate=!0}add(e){const t=[];for(let s=0;s<arguments.length;s++){const r=arguments[s];r.isUI?console.warn("ThreeMeshUI::InlineBlockElement cannot contains UI Elements.",r):(t.push(r),r.position.z=.005)}return super.add(...t)}static definePropertiesValues(e,t){e.children||(e.children=DF),e.bounds||(e.bounds=ree),e.inlines||(e.inlines=iee),e.layouter||(e.layouter=wF),e.renderer||(e.renderer=see),e.fontFamily||(e.fontFamily=SF),e.fontWeight||(e.fontWeight=CF),e.fontStyle||(e.fontStyle=xF),e.fontSize||(e.fontSize=BF),e.backgroundColor||(e.backgroundColor=p3),e.lineBreak||(e.lineBreak=_F),e.letterSpacing||(e.letterSpacing=PF),e.whiteSpace||(e.whiteSpace=EE),e.fontKerning||(e.fontKerning=cb),t.backgroundSize||(t.backgroundSize="cover"),t.width||(t.width="100%"),t.height||(t.height="100%"),t.boxSizing||(t.boxSizing="border-box")}static init(e){Object.defineProperties(e,{isInline:{configurable:!1,enumerable:!0,value:!0},isInlineBlock:{configurable:!1,enumerable:!0,value:!0}}),e._inlines._value=[new nee(e)],e.backgroundMaterial=new gF,e._renderer.render(e)}}class nee extends _3{constructor(e){super(),this._uiElement=e}get xadvance(){const e=this._uiElement._padding._value,t=this._uiElement._width;return t._relative?t._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):e.w+e.y+t.value}get width(){const e=this._uiElement._width;return e._relative?e._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):e.value}get height(){const e=this._uiElement._height;return e._relative?e._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):e.value}get anchor(){return this.height}get lineHeight(){const e=this._uiElement._height;return e._relative?e._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):e.value}get lineBase(){const e=this._uiElement._height;return e._relative?e._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):e.value}clear(){this._uiElement=null}}class LF{constructor(e){this._subject=e}attach(){console.error(`Behavior::attach() - Is abstract and therefore should be overridden in ${this.constructor.name}`)}act(){throw new Error(`Behavior::act() - Is abstract and therefore should be overridden in ${this.constructor.name}`)}detach(){console.error(`Behavior::detach() - Is abstract and therefore should be overridden in ${this.constructor.name}`)}clear(){}}const FF=()=>Ab.update(),UF={BaseProperty:ci,Block:Fv,Text:Uv,Inline:cf,InlineBlock:Nv,MeshUIBaseElement:om,FontLibrary:tu,update:FF,MSDFFontMaterialUtils:io,ShaderChunkUI:fF,Behavior:LF,FontVariant:Zg};typeof global<"u"&&(global.ThreeMeshUI=UF);const oee=UF;var aee=ls.w8,NF=ls.cg,ME=ls.gO,lee=ls.wb,IE=ls.zV,cee=ls.HS,hee=ls.Ec,bb=ls.gF,uee=ls.ol,dee=ls.pz,pee=ls.tx,fee=ls.hj,gee=ls.FV,mee=ls.sV,zF=ls.xv,vee=ls.mx,Aee=ls.gE,yee=ls.ZP,QF=ls.Vx;const jF=Object.freeze(Object.defineProperty({__proto__:null,BaseProperty:aee,Behavior:NF,Block:ME,DefaultValues:lee,FontLibrary:IE,FontVariant:cee,InheritableProperty:hee,Inline:bb,InlineBlock:uee,InlineGlyph:dee,MSDFFontMaterialUtils:pee,MaterialTransformers:fee,MeshUIBaseElement:gee,ShaderChunkUI:mee,Text:zF,TypographicFont:vee,TypographicGlyph:Aee,default:yee,update:QF},Symbol.toStringTag,{value:"Module"}));ME.prototype.interactable={get(){return this.interactive},set(i){this.interactable=i}};const yl=Symbol("shadowDomOwner");class Bo extends Ee{constructor(){super(...arguments),h(this,"shadowComponent",null),h(this,"_controlsChildLayout",!0),h(this,"_root"),h(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(){Wn.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=$.getComponentInParent(this.gameObject,am)),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 s;this.removeShadowComponent();const r=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=$.getComponentInParent(r,Bo),!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[yl]=this,this.setShadowComponentOwner(e);let n=!1;if(((s=this.Root)==null?void 0:s.gameObject)===this.gameObject)this.gameObject.add(e);else{let o=this._parentComponent.shadowComponent;o&&(o?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),Zf&&e.add(new Ad(.5)),this.onAfterAddedToScene(),n&&QF()}set(e){}setShadowComponentOwner(e){if(e&&(e[yl]===void 0||e[yl]===this)&&(e[yl]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,s){if(e&&e[yl]===t){s(e);for(const r of e.children)this.traverseOwnedShadowComponents(r,t,s)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class am extends Bo{awake(){super.awake()}}class up{static getObject(e){const t=e[yl];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const s=this.tryFindCanvasGroup(e);if(s?.isCanvasGroup===!0&&(t&&(t.canvasGroup=s),s.blocksRaycasts===!1||s.interactable===!1))return!1;const r=Hh(e,n=>{if(n.isGraphic===!0)return n},!1);return t&&r?.isGraphic===!0&&(t.graphic=r),!(r?.raycastTarget===!1||r?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=Hh(e,s=>{const r=s;if(r.blocksRaycasts!==void 0&&r.interactable!==void 0)return r},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}const lm=oe("debugwebxrcontroller");var dp=(i=>(i[i.PhysicalDevice=0]="PhysicalDevice",i[i.Touch=1]="Touch",i))(dp||{}),bl=(i=>(i.SelectStart="select-start",i.SelectEnd="select-end",i.Update="update",i))(bl||{});class _b extends Ee{}const Hs=class extends Ee{constructor(){super(...arguments),h(this,"webXR"),h(this,"index",-1),h(this,"controllerModel"),h(this,"controller"),h(this,"controllerGrip"),h(this,"hand"),h(this,"handPointerModel"),h(this,"grabbed",null),h(this,"input",null),h(this,"type",0),h(this,"showRaycastLine",!0),h(this,"_wristQuaternion",null),h(this,"movementVector",new S),h(this,"worldRot",new xe),h(this,"joystick",new W),h(this,"didRotate",!1),h(this,"didTeleport",!1),h(this,"didChangeScale",!1),h(this,"lastHit",null),h(this,"raycastLine",null),h(this,"_raycastHitPoint",null),h(this,"_connnectedCallback",null),h(this,"_disconnectedCallback",null),h(this,"_selectStartEvt",null),h(this,"_selectEndEvt",null),h(this,"_selectionPressed",!1),h(this,"_selectionPressedLastFrame",!1),h(this,"_selectionStartTime",0),h(this,"_selectionEndTime",0),h(this,"_useSmoothing",!0),h(this,"_isConnected",!1),h(this,"rayRotation",new xe),h(this,"_pinchStartTime"),h(this,"selectStartCallback",null),h(this,"lastSelectStartObject",null),h(this,"_didNotEndSelection",!1),h(this,"closeGrabBoundingBoxHelper")}static CreateRaycastLine(){const i=new qi(this.geometry),e=i.material;return e.color=this.raycastColor,i.layers.set(2),i.name="line",i.scale.z=1,i}static CreateRaycastHitPoint(){const i=new to(.5,22,22),e=new di({color:this.raycastColor}),t=new ye(i,e);return t.visible=!1,t.layers.set(2),t}static Create(i,e,t,s){const r=t?$.addNewComponent(t,Hs,!1):new Hs;r.webXR=i,r.index=e,r.type=s;const n=i.context;r.controller=n.renderer.xr.getController(e),r.controllerGrip=n.renderer.xr.getControllerGrip(e),r.controllerModel=this.Factory.createControllerModel(r.controller),r.controllerGrip.add(r.controllerModel),r.hand=n.renderer.xr.getHand(e);const o=new Bd;Rg(o,n),r.webXR.handModelPath&&r.webXR.handModelPath!==""?o.setPath(zl(i.sourceId,r.webXR.handModelPath)):o.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/");const a=new WY(r.hand,o);return r.hand.add(a),r.hand.traverse(l=>l.layers.set(2)),r.handPointerModel=new $Y(r.hand,r.controller),r.controller.addEventListener("connected",l=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),r.setControllerLayers(r.hand,2),setTimeout(()=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),r.setControllerLayers(r.hand,2)},1e3)}),r.hand.addEventListener("connected",l=>{var c;if(l.data.hand){i.Rig&&i.Rig.add(r.hand),r.type=0,r.handPointerModel.traverse(d=>d.layers.set(2)),(c=r.handPointerModel.pointerObject)==null||c.traverse(d=>d.layers.set(2));const u=r.hand.joints;if(u)for(const d of Object.keys(u)){const p=u[d];p.parent||r.hand.add(p)}}}),r}static addEventListener(i,e){const t=this.eventSubs[i]??[];t.push(e),this.eventSubs[i]=t}static removeEventListener(i,e){if(!e)return;const t=this.eventSubs[i]??[],s=t.indexOf(e);s>=0&&t.splice(s,1),this.eventSubs[i]=t}get isUsingHands(){var i;return((i=this.input)==null?void 0:i.hand)!=null}get wrist(){if(!this.hand)return null;const i=this.hand.joints;return i?i.wrist:null}getWristQuaternion(){const i=this.wrist;return i?(this._wristQuaternion||(this._wristQuaternion=new xe),ws(i).multiply(this._wristQuaternion.setFromEuler(new fs(-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 i,e,t;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)),(i=this.hand)==null||i.clear(),(e=this.controllerGrip)==null||e.clear(),(t=this.controller)==null||t.clear()}onEnable(){var i,e,t,s,r;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=Hs.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=Hs.CreateRaycastHitPoint()),(i=this.webXR.Rig)==null||i.add(this.hand),(e=this.webXR.Rig)==null||e.add(this.controllerGrip),(t=this.webXR.Rig)==null||t.add(this.controller),(s=this.webXR.Rig)==null||s.add(this.raycastLine),(r=this.raycastLine)==null||r.add(this._raycastHitPoint),this._raycastHitPoint.visible=!1,this.hand.add(this.handPointerModel),lm&&console.log("ADDED TO RIG",this.webXR.Rig)}onDisable(){var i,e,t,s,r;(i=this.hand)==null||i.removeFromParent(),(e=this.controllerGrip)==null||e.removeFromParent(),(t=this.controller)==null||t.removeFromParent(),(s=this.raycastLine)==null||s.removeFromParent(),(r=this._raycastHitPoint)==null||r.removeFromParent();const n=this.webXR.Controllers.indexOf(this);n>=0&&this.webXR.Controllers.splice(n,1)}onSourceConnected(i){if(this._isConnected){console.warn("Received connected event for controller that is already connected",this.index,i);return}this._isConnected=!0,this.input=i.data,this.type===1&&(this.onSelectStart(),this.createPointerEvent("down"))}onSourceDisconnected(i){if(!this._isConnected){console.warn("Received discnnected event for controller that is not connected",i);return}this._isConnected=!1,this.type===1&&(this.onSelectEnd(),this.createPointerEvent("up")),this.input=null}createPointerEvent(i){switch(i){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 i=Hs.eventSubs.update;if(i&&i.length>0)for(const s of i)s(this);let e=1;this.type===0?e=this.context.time.deltaTime/.1:this.isUsingHands&&this.handPointerModel.pinched&&(e=this.context.time.deltaTime/.3),this.rayRotation.slerp(ws(this.controller),this.useSmoothing?e:1);const t=wt(this.controller);if(this.isUsingHands&&this.handPointerModel.cursorObject&&(this.handPointerModel.cursorObject.visible=!1),this.raycastLine){const s=this.showRaycastLine&&this.type!==1;if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed&&s,Yi(this.raycastLine,t);const r=this.hand.joints;if(r&&r.wrist&&this.grabbed&&this.grabbed.isCloseGrab){const n=this.getWristQuaternion();n&&this.rayRotation.copy(n)}Nr(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=s,Nr(this.raycastLine,this.rayRotation),Yi(this.raycastLine,t)}this.lastHit=this.updateLastHit(),this.grabbed&&this.grabbed.update(),this._selectionPressedLastFrame=this._selectionPressed,this.selectStartCallback&&this.selectStartCallback()}onUpdate(i){var e,t;if(this.lastHit=null,!i||i.inputSources.length<=this.index){this.input=null;return}if(this.type===0&&(this.input=i.inputSources[this.index]),!this.input)return;const s=this.webXR.Rig;if(!s)return;this._didNotEndSelection&&!this.handPointerModel.pinched&&(this._didNotEndSelection=!1,this.onSelectEnd()),this.updateStick(this.input);const r=(t=(e=this.input)==null?void 0:e.gamepad)==null?void 0:t.buttons;switch(this.input.handedness){case"left":const n=3*Hs.MovementSpeedFactor,o=2,a=Je.clamp01(this.joystick.length()*2),l=this.joystick.x>0?1:-1;let c=Math.pow(this.joystick.x,o);c*=l,c*=a;const u=this.joystick.y>0?1:-1;let d=Math.pow(this.joystick.y,o);d*=u,c*=a,s.getWorldQuaternion(this.worldRot),this.movementVector.set(c,0,d),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),this.movementVector.multiplyScalar(n*this.context.time.deltaTime),s.position.add(this.movementVector),this.isUsingHands&&this.runTeleport(s,r);break;case"right":const p=this.joystick.x,f=Math.abs(p);if(f<.4)this.didRotate=!1;else if(f>.5&&!this.didRotate){const g=p>0?-1:1;s.rotateY(Je.toRadians(30*g)),this.didRotate=!0}this.runTeleport(s,r);break}}runTeleport(i,e){var t,s,r;let n=-this.joystick.y;if((t=this.hand)!=null&&t.visible&&!this.grabbed){const c=this.handPointerModel.isPinched();c&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),c&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(n=this.handPointerModel.isPinched()?1:0),c||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;let o=n>.5&&this.webXR.IsInVR,a=this.webXR.Rig?((r=(s=this.webXR.Rig)==null?void 0:s.scale)==null?void 0:r.x)<.999:!1,l=null;if(e&&this.input&&!this.input.hand)for(let c=0;c<e.length;c++){const u=e[c];if(c===4)if(u.pressed&&!this.didChangeScale&&this.webXR.IsInVR){this.didChangeScale=!0;const d=this.webXR.Rig;if(d)if(a){a=!1,d.scale.set(1,1,1),l=1,Hs.MovementSpeedFactor=1;const p=this.context.mainCamera;Hs.PreviousCameraFarDistance&&(p.far=Hs.PreviousCameraFarDistance)}else{a=!0,o=!0,l=.1,Hs.MovementSpeedFactor=l*2;const p=this.context.mainCamera;Hs.PreviousCameraFarDistance=p.far,p.far/=l}}else u.pressed||(this.didChangeScale=!1)}if(o){if(!this.didTeleport){const c=this.raycast();if(this.didTeleport=!0,c&&c.length>0){const u=c[0];if(a||this.isValidTeleportTarget(u.object)){const d=u.point;Yi(i,d)}}}}else n<.1&&(this.didTeleport=!1);l!==null&&(i.scale.set(l,l,l),i.updateMatrixWorld())}isValidTeleportTarget(i){return $.getComponentInParent(i,_b)!=null}updateStick(i){var e;!i||!i.gamepad||((e=i.gamepad.axes)==null?void 0:e.length)<4||(this.joystick.x=i.gamepad.axes[2],this.joystick.y=i.gamepad.axes[3])}updateLastHit(){var i;const e=this.raycast(),t=e?e[0]:null;this.lastHit=t;let s=1;if(this.webXR.Rig&&(s/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=s*(((i=this.lastHit)==null?void 0:i.distance)??9999);const r=this.raycastLine.material;t!=null?r.color=Hs.raycastColor:r.color=Hs.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;const r=Je.clamp(this.lastHit.distance*.01*s,.015,.1);this._raycastHitPoint.scale.set(r,r,r)}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 i=null,e=!1;if(this.isUsingHands?(i=this.overlap(),i.length<=0?(i=this.raycast(),e=!1):e=!0):i=this.raycast(),lm&&console.log("onHandleSelectStart","close grab? "+e,"intersections",i),i&&i.length>0)for(const t of i){const s=t.object;this.lastSelectStartObject=s;const r={selected:s,grab:s},n=Hs.eventSubs["select-start"];if(n&&n.length>0)for(const o of n)o(this,r);r.grab!==s&&lm&&console.log("Grabbed object changed","original",s,"new",r.grab),r.grab&&(this.grabbed=na.TryTake(this,r.grab,t,e));break}else{const t=Hs.eventSubs["select-start"],s={selected:null,grab:null};if(t&&t.length>0)for(const r of t)r(this,s)}}onSelectEnd(){var i;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:((i=this.grabbed)==null?void 0:i.selected)??this.lastSelectStartObject},t=Hs.eventSubs["select-end"];if(t&&t.length>0)for(const s of t)s(this,e);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(i){return!(!i||$.isActiveInHierarchy(i)===!1||up.isInteractable(i)===!1)}setControllerLayers(i,e){var t,s;if(i&&(i.layers.set(e),i.children))for(const r of i.children)((t=this.grabbed)==null?void 0:t.selected)===r||((s=this.grabbed)==null?void 0:s.selectedMesh)===r||this.setControllerLayers(r,e)}getRay(){const i=new za;return i.origin.copy(wt(this.controller)),i.direction.set(0,0,-1).applyQuaternion(this.rayRotation),i}overlap(){const i=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(lm&&(!this.closeGrabBoundingBoxHelper&&i&&(this.closeGrabBoundingBoxHelper=new g0(i,16776960),this.scene.add(this.closeGrabBoundingBoxHelper)),this.closeGrabBoundingBoxHelper&&i&&this.closeGrabBoundingBoxHelper.setFromObject(i)),!i)return new Array;const e=wt(i).clone();return this.context.physics.sphereOverlap(e,.02)}raycast(){const i=new fo;i.layerMask=new Mn,i.layerMask.enableAll(),i.layerMask.disable(2),i.ray=this.getRay();const e=this.context.physics.raycast(i);for(let t=0;t<e.length;t++){const s=e[t],r=s.object;if(!this.testIsVisible(r)){e.splice(t,1),t--;continue}s.object=up.getObject(r);break}return e}};let cs=Hs;h(cs,"Factory",new uJ),h(cs,"raycastColor",new _e(.9,.3,.3)),h(cs,"raycastNoHitColor",new _e(.6,.6,.6)),h(cs,"geometry",new At().setFromPoints([new S(0,0,0),new S(0,0,-1)])),h(cs,"handModels",{}),h(cs,"eventSubs",{}),h(cs,"PreviousCameraFarDistance"),h(cs,"MovementSpeedFactor",1);var wb=(i=>(i.WillTake="WillTake",i.DidTake="DidTake",i.WillFree="WillFree",i.DidFree="DidFree",i))(wb||{});const Yr=class{constructor(){h(this,"sync",null),h(this,"selected",null),h(this,"selectedParent",null),h(this,"selectedMesh",null),h(this,"controller",null),h(this,"grabTime",0),h(this,"grabUUID",""),h(this,"isCloseGrab",!1),h(this,"originalMaterial",null),h(this,"usageMarker",null),h(this,"rigidbodies",null),h(this,"didReparent",!1),h(this,"grabDistance",0),h(this,"interactable",null),h(this,"positionSource",null),h(this,"grabPoint",new S),h(this,"localPositionOffsetToGrab",null),h(this,"localPositionOffsetToGrab_worldSpace",new S),h(this,"localQuaternionToGrab",new xe(0,0,0,1)),h(this,"targetDir",null),h(this,"quaternionLerp",null),h(this,"controllerDir",new S),h(this,"controllerWorldPos",new S),h(this,"lastControllerWorldPos",new S),h(this,"controllerPosDelta",new S),h(this,"totalChangeAlongDirection",0),h(this,"rigPositionLastFrame",new S)}static AddEventListener(i,e){return Yr.Events[i]||(Yr.Events[i]=[]),Yr.Events[i].push(e),e}static RemoveEventListener(i,e){if(!e||!Yr.Events[i])return;const t=Yr.Events[i].indexOf(e);t>=0&&Yr.Events[i].splice(t,1)}static Register(i){this.Current.find(e=>e===i)||this.Current.push(i)}static Remove(i){const e=this.Current.indexOf(i);e>=0&&this.Current.splice(e,1)}static TryTake(i,e,t,s){const r=$.getComponentInParent(e,sp);if(r)e=r.gameObject;else return lm&&console.warn("Prevented taking object that is not interactable",e),null;let n=e;const o=$.getComponentInParent(e,Uc);o&&(o.requestOwnership(),n=o.gameObject);for(const l of this.Current)if(l.selected===n)return l.controller===i||(l.free(),l.Take(i,n,e,o,r,t,s)),l;const a=new Yr;return a.Take(i,n,e,o,r,t,s),a}Take(i,e,t,s,r,n,o){var a,l;if(console.assert(e!==null,"Expected object to be taken but was",e),i.isUsingHands?this.positionSource=o?i.wrist:i.controller:this.positionSource=i.controller,!this.positionSource)return console.warn("No position source"),this;const c={controller:i,take:e,hit:t,sync:s,interactable:r};(a=Yr.Events.WillTake)==null||a.forEach(g=>g(this,c));const u=t;u!=null&&u.material&&(this.originalMaterial=u.material,Array.isArray(u.material)||(u.material=u.material.clone(),u.material&&u.material.emissive&&(u.material.emissive.b=.2))),this.selected=e,this.selectedParent||(this.selectedParent=e.parent),this.selectedMesh=u,this.controller=i,this.interactable=r,this.isCloseGrab=o,this.didReparent=!1,this.sync=s,this.grabTime=i.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=$.addNewComponent(this.selected,rp),this.rigidbodies=$.getComponentsInChildren(this.selected,Li),wt(this.positionSource,this.lastControllerWorldPos);const d=()=>o?this.lastControllerWorldPos.clone():n.point.clone();this.grabDistance=d().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(d());const p=i.isUsingHands&&o?this.controller.getWristQuaternion().clone():i.rayRotation.clone();ws(this.selected,this.localQuaternionToGrab).premultiply(p.invert());const f=this.controller.webXR.Rig;return f&&this.rigPositionLastFrame.copy(wt(f)),Pr.Add(i.context,this.selected),Yr.Register(this),this.sync&&(this.sync.fastMode=!0),(l=Yr.Events.DidTake)==null||l.forEach(g=>g(this,c)),this}free(){var i,e,t,s;if(!this.selected)return;const r={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};(i=Yr.Events.WillFree)==null||i.forEach(a=>a(this,r)),Pr.Remove(this.controller.context,this.selected),Yr.Remove(this),this.sync&&(this.sync.fastMode=!1);const n=this.selectedMesh;n&&this.originalMaterial&&n.material&&(n.material=this.originalMaterial);const o=this.selected;if(this.didReparent&&o.parent){const a=this.selectedParent;a?a.attach(o):(e=this.controller)==null||e.context.scene.attach(o)}if((t=this.usageMarker)==null||t.destroy(),this.controller&&(this.controller.grabbed=null),this.selected=null,this.selectedParent=null,this.selectedMesh=null,this.sync=null,this.rigidbodies)for(const a of this.rigidbodies)a.wakeUp(),a.setVelocity(a.smoothedVelocity);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,(s=Yr.Events.DidFree)==null||s.forEach(a=>a(this,r))}controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),wt(this.positionSource,this.controllerWorldPos),this.controllerPosDelta.copy(this.controllerWorldPos),this.controllerPosDelta.sub(this.lastControllerWorldPos),this.lastControllerWorldPos.copy(this.controllerWorldPos);const i=this.controller.webXR.Rig;if(i){const e=wt(i),t=this.rigPositionLastFrame.sub(e);this.controllerPosDelta.add(t),this.rigPositionLastFrame.copy(e)}return this.controllerDir.dot(this.controllerPosDelta)}update(){var i;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=((i=this.controller.webXR.Rig)==null?void 0:i.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 S),this.targetDir.set(0,0,-this.grabDistance*t);const s=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),r=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=r.clone()),this.quaternionLerp.slerp(r,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),Nr(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(s),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(wt(this.selected)),s.sub(this.localPositionOffsetToGrab_worldSpace)),Yi(this.selected,s)}if(this.rigidbodies!=null)for(const e of this.rigidbodies)e.wakeUp();en.markDirty(this.selected,!0)}}};let na=Yr;h(na,"Events",{}),h(na,"Current",[]);var bee=Object.defineProperty,_ee=Object.getOwnPropertyDescriptor,TE=(i,e,t,s)=>{for(var r=s>1?void 0:s?_ee(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&bee(e,t,r),r};class su extends Ee{constructor(){super(...arguments),h(this,"objectBounds",!1),h(this,"color"),h(this,"isGizmo",!0),h(this,"_gizmoObject",null),h(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!Zf||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new g0(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=_L(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),dn.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(var e;this._boxHelper;)(e=this._boxHelper)==null||e.update(),yield}}TE([w()],su.prototype,"objectBounds",2),TE([w(_e)],su.prototype,"color",2),TE([w()],su.prototype,"isGizmo",2);const wee=oe("debugrig");class xb extends Ee{awake(){if(wee){const e=new Me;e.position.y+=.5,this.gameObject.add(e);const t=e.addNewComponent(su);t&&(t.isGizmo=!1)}}}class pp{constructor(){h(this,"bb",null),h(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}w(){return this.bb.readFloat32(this.bb_pos+12)}static sizeOf(){return 16}static createVec4(e,t,s,r,n){return e.prep(4,16),e.writeFloat32(n),e.writeFloat32(r),e.writeFloat32(s),e.writeFloat32(t),e.offset()}}class pr{constructor(){h(this,"bb",null),h(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsVrUserStateBuffer(e,t){return(t||new pr).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+D0),(t||new pr).__init(e.readInt32(e.position())+e.position(),e)}guid(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}time(){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}avatarId(e){const t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__string(this.bb_pos+t,e):null}position(e){const t=this.bb.__offset(this.bb_pos,10);return t?(e||new pn).__init(this.bb_pos+t,this.bb):null}rotation(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new pp).__init(this.bb_pos+t,this.bb):null}scale(){const e=this.bb.__offset(this.bb_pos,14);return e?this.bb.readFloat32(this.bb_pos+e):0}posLeftHand(e){const t=this.bb.__offset(this.bb_pos,16);return t?(e||new pn).__init(this.bb_pos+t,this.bb):null}posRightHand(e){const t=this.bb.__offset(this.bb_pos,18);return t?(e||new pn).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){const t=this.bb.__offset(this.bb_pos,20);return t?(e||new pp).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){const t=this.bb.__offset(this.bb_pos,22);return t?(e||new pp).__init(this.bb_pos+t,this.bb):null}static startVrUserStateBuffer(e){e.startObject(10)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addTime(e,t){e.addFieldInt64(1,t,e.createLong(0,0))}static addAvatarId(e,t){e.addFieldOffset(2,t,0)}static addPosition(e,t){e.addFieldStruct(3,t,0)}static addRotation(e,t){e.addFieldStruct(4,t,0)}static addScale(e,t){e.addFieldFloat32(5,t,0)}static addPosLeftHand(e,t){e.addFieldStruct(6,t,0)}static addPosRightHand(e,t){e.addFieldStruct(7,t,0)}static addRotLeftHand(e,t){e.addFieldStruct(8,t,0)}static addRotRightHand(e,t){e.addFieldStruct(9,t,0)}static endVrUserStateBuffer(e){return e.endObject()}static finishVrUserStateBufferBuffer(e,t){e.finish(t)}static finishSizePrefixedVrUserStateBufferBuffer(e,t){e.finish(t,void 0,!0)}}const GF=oe("debugxr"),cm=oe("debugavatar"),RE="VRUS";k1(RE,pr.getRootAsVrUserStateBuffer);function PE(){return new Date().getTime()}function xee(i){let e=i&4294967295,t=i/Math.pow(2,32)&1048575;return Ma.create(e,t)}const Cb=class{constructor(i){h(this,"guid"),h(this,"time"),h(this,"avatarId"),h(this,"position",new S),h(this,"rotation",new it),h(this,"scale",1),h(this,"posLeftHand",new S),h(this,"posRightHand",new S),h(this,"rotLeftHand",new xe),h(this,"rotRightHand",new xe),this.guid=i}update(i,e,t,s,r){var n,o,a,l,c,u;this.time=PE(),this.avatarId=r,this.position.set(e.x,e.y,e.z),i&&this.position.applyMatrix4(i.matrixWorld);let d=Cb.quat0;const p=Cb.quat1;d.set(t.x,t.y,t.z,t.w),d=d.multiplyQuaternions(d,Cb.invertRotation),i&&(i.getWorldQuaternion(p),d.multiplyQuaternions(p,d)),this.rotation.set(d.x,d.y,d.z,d.w),this.scale=i.scale.x;const f=(n=s.LeftController)==null?void 0:n.controllerGrip;f&&(f.getWorldPosition(this.posLeftHand),f.getWorldQuaternion(this.rotLeftHand));const g=(o=s.RightController)==null?void 0:o.controllerGrip;if(g&&(g.getWorldPosition(this.posRightHand),g.getWorldQuaternion(this.rotRightHand)),(l=(a=s.LeftController)==null?void 0:a.hand)!=null&&l.visible){const m=s.LeftController.wrist;m&&(m.getWorldPosition(this.posLeftHand),m.getWorldQuaternion(this.rotLeftHand))}if((u=(c=s.RightController)==null?void 0:c.hand)!=null&&u.visible){const m=s.RightController.wrist;m&&(m.getWorldPosition(this.posRightHand),m.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(i,e){i.clear();const t=i.createString(this.guid),s=i.createString(this.avatarId);pr.startVrUserStateBuffer(i),pr.addGuid(i,t),pr.addTime(i,xee(this.time)),pr.addAvatarId(i,s),pr.addPosition(i,pn.createVec3(i,this.position.x,this.position.y,this.position.z)),pr.addRotation(i,pp.createVec4(i,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),pr.addScale(i,this.scale),pr.addPosLeftHand(i,pn.createVec3(i,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),pr.addPosRightHand(i,pn.createVec3(i,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),pr.addRotLeftHand(i,pp.createVec4(i,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),pr.addRotRightHand(i,pp.createVec4(i,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));const r=pr.endVrUserStateBuffer(i);i.finish(r,RE);const n=i.asUint8Array();e.sendBinary(n)}setFromBuffer(i,e){if(!i)return;this.guid=i,this.time=e.time().toFloat64();const t=e.avatarId();t&&(this.avatarId=t);const s=e.position();s&&this.position.set(s.x(),s.y(),s.z());const r=e.rotation();r&&this.rotation.set(r.x(),r.y(),r.z(),r.w());const n=e.posLeftHand();n&&this.posLeftHand.set(n.x(),n.y(),n.z());const o=e.posRightHand();o&&this.posRightHand.set(o.x(),o.y(),o.z());const a=e.rotLeftHand();a&&this.rotLeftHand.set(a.x(),a.y(),a.z(),a.w());const l=e.rotRightHand();l&&this.rotRightHand.set(l.x(),l.y(),l.z(),l.w()),this.scale=e.scale()}};let _l=Cb;h(_l,"invertRotation",new xe().setFromAxisAngle(new S(0,1,0),Math.PI)),h(_l,"quat0",new xe),h(_l,"quat1",new xe);class hm extends Ee{constructor(){super(...arguments),h(this,"webXR",null),h(this,"debugAvatarUser",null),h(this,"voip",null),h(this,"tempState",new _l("")),h(this,"_removeAvatarsList",[]),h(this,"eventSub_ConnectionEvent",null),h(this,"eventSub_WebXRStartEvent",null),h(this,"eventSub_WebXREndEvent",null),h(this,"eventSub_WebXRUpdateEvent",null),h(this,"avatars",{}),h(this,"localAvatar",null),h(this,"k_LocalAvatarNoNetworkingGuid","local"),h(this,"ownership",null),h(this,"xrState",null),h(this,"builder",new af(1024))}async awake(){if(this.webXR||(this.webXR=$.getComponent(this.gameObject,xt)),this.webXR||(this.webXR=$.findObjectOfType(xt,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=$.findObjectOfType(xt,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=$.findObjectOfType(Fl,this.context)),cm){const e="debug-avatar-"+cm,t=new Lc(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof cm=="string"&&cm.length>0)if(await t.setAvatarOverride(cm)){const s=new _l(e);s.position.y+=1;const r=.5;s.posLeftHand.y+=r,s.posLeftHand.x+=r,s.posRightHand.y+=r,s.posRightHand.x-=r,t.tryUpdate(s,0)}else t.destroy()}}onEnable(){if(!this.webXR&&(this.webXR=$.getComponent(this.gameObject,xt),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),xt.addEventListener(_i.XRStarted,this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),xt.addEventListener(_i.XRUpdate,this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),xt.addEventListener(_i.XRStopped,this.eventSub_WebXREndEvent),this.eventSub_ConnectionEvent=this.onConnected.bind(this),this.context.connection.beginListen(Ni.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 s=this.avatars[e.id];s?.destroy(),this.avatars[e.id]=void 0}}),this.context.connection.beginListenBinary(RE,e=>{const t=e.guid();if(!t)return;const s=e.time().toFloat64(),r=this.tempState;r.setFromBuffer(t,e);const n=this.onTryGetAvatar(t,s);n?.tryUpdate(r,s)}),this.context.connection.beginListen("vr-session-update",e=>{const t=e.guid,s=e.time,r=this.onTryGetAvatar(t,s);r?.tryUpdate(e,s)})}onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;const s=new Date().getTime()-t;if(s>5e3)return GF&&console.log("old data",s,e),null;let r=this.avatars[e];if(r===void 0)try{console.log("create new avatar");const n=new Lc(this.context,e,this.webXR);r=n,this.avatars[e]=n}catch(n){this.avatars[e]=null,console.error(n)}return r}onDisable(){this.eventSub_ConnectionEvent&&this.context.connection.stopListen(Ni.JoinedRoom,this.eventSub_ConnectionEvent),xt.removeEventListener(_i.XRStarted,this.eventSub_WebXRStartEvent),xt.removeEventListener(_i.XRUpdate,this.eventSub_WebXRUpdateEvent),xt.removeEventListener(_i.XRStopped,this.eventSub_WebXREndEvent)}update(){const e=PE();this.debugAvatarUser&&(this.debugAvatarUser.lastUpdate=e),this.detectPotentiallyDisconnectedAvatarsAndRemove();for(const t in this.avatars){const s=this.avatars[t];s&&s.update()}}detectPotentiallyDisconnectedAvatarsAndRemove(){const e=PE();for(const t in this.avatars){const s=this.avatars[t];if(!s){this._removeAvatarsList.push(t);continue}e-s.lastUpdate>1e4&&(console.log("avatar timed out (didnt receive any updates in a while) - destroying it now"),s.destroy(),this.avatars[t]=void 0)}for(const t of this._removeAvatarsList)delete this.avatars[t];this._removeAvatarsList.length=0}buildLocalAvatar(){var e;if(this.localAvatar)return;const t=((e=this.context.connection)==null?void 0:e.connectionId)??this.k_LocalAvatarNoNetworkingGuid;this.localAvatar=new Lc(this.context,t,this.webXR),this.localAvatar.isLocalAvatar=!0,this.localAvatar.setAvatarOverride(this.getAvatarId()),this.avatars[this.localAvatar.guid]=this.localAvatar}onConnected(){var e,t,s;GF&&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,(s=this.ownership)==null||s.freeOwnership(),this.ownership=null)}onXRSessionStart(e){var t,s,r;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,(s=this.ownership)==null||s.freeOwnership(),this.ownership=null,this.avatars)for(const n in this.avatars)(r=this.avatars[n])==null||r.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 _l(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid)),this.ownership??(this.ownership=new q0(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:s,rig:r}=e,n=t.getViewerPose(s.getReferenceSpace());if(!n)return;const o=n?.transform,a=o.position,l=o.orientation;this.xrState.update(r,a,l,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 oe("avatar")??null}}var Cee=Object.defineProperty,See=Object.getOwnPropertyDescriptor,fp=(i,e,t,s)=>{for(var r=s>1?void 0:s?See(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Cee(e,t,r),r};async function HF(){return nw()?!0:"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function VF(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}let Sb=!1,Eb=!1;HF().then(i=>Sb=i),VF().then(i=>Eb=i);var _i=(i=>(i.XRStarted="xrStarted",i.XRStopped="xrStopped",i.XRUpdate="xrUpdate",i.RequestVRSession="requestVRSession",i.ModifyAROptions="modify-ar-options",i))(_i||{}),gp;const Ss=(gp=class extends Ee{constructor(){super(...arguments),h(this,"enableVR",!0),h(this,"enableAR",!0),h(this,"defaultAvatar"),h(this,"handModelPath",""),h(this,"createVRButton",!0),h(this,"createARButton",!0),h(this,"controllers",[]),h(this,"rig"),h(this,"isInit",!1),h(this,"_requestedAR",!1),h(this,"_requestedVR",!1),h(this,"_isInAR",!1),h(this,"_isInVR",!1),h(this,"_arButton"),h(this,"_vrButton"),h(this,"webAR",null),h(this,"_transformOrientation",new xe),h(this,"_currentHeadPose",null),h(this,"_originalCameraParent",null),h(this,"_originalCameraPosition",new S),h(this,"_originalCameraRotation",new xe),h(this,"_originalXRRigParent",null),h(this,"_originalXRRigPosition",new S),h(this,"_originalXRRigRotation",new xe),h(this,"xrMirrorWindow",null)}static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(Sb||Eb)}static get IsARSupported(){return Sb}static get IsVRSupported(){return Eb}static get OptionalFeatures_VR(){return this._optionalFeatures_VR}static get OptionalFeatures_AR(){return this._optionalFeatures_AR}static addEventListener(i,e){return this.events.addEventListener(i,e),e}static removeEventListener(i,e){return this.events.removeEventListener(i,e),e}static dispatchEvent(i,e){this.events.dispatchEvent({type:i,detail:e})}static createVRButton(i,e){Ss.XRSupported?i.__internalAwake():console.warn("WebXR is not supported on this device");const t={optionalFeatures:Ss.OptionalFeatures_VR},s=FS.createButton(i.context.renderer,t);return s.classList.add("webxr-ar-button"),s.classList.add("webxr-button"),this.resetButtonStyles(s),(e?.registerClick??!0)&&s.addEventListener("click",i.onClickedVRButton.bind(i)),s}static createARButton(i,e){var t;i.__internalAwake();const s=(t=i.webAR)==null?void 0:t.getAROverlayContainer(),r={optionalFeatures:[...this.OptionalFeatures_AR]};s?(r.domOverlay={root:s},r.optionalFeatures.push("dom-overlay"),r.optionalFeatures.push("hit-test")):console.warn("No dom overlay root found, HTML overlays on top of screen-based AR will not work.");const n=OY.createButton(i.context.renderer,r,this.onModifyAROptions.bind(this));return n.classList.add("webxr-ar-button"),n.classList.add("webxr-button"),Ss.resetButtonStyles(n),(e?.registerClick??!0)&&n.addEventListener("click",i.onClickedARButton.bind(i)),n}static onModifyAROptions(i){Ss.dispatchEvent("modify-ar-options",i)}static resetButtonStyles(i){i&&(i.style.position="",i.style.bottom="",i.style.left="")}endSession(){const i=this.context.renderer.xr.getSession();i&&i.end()}get Rig(){return this.rig||this.ensureRig(),this.rig}get Controllers(){return this.controllers}get LeftController(){var i,e;return this.controllers.length>0&&((i=this.controllers[0].input)==null?void 0:i.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 i,e;return this.controllers.length>0&&((i=this.controllers[0].input)==null?void 0:i.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=lr.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!$.findObjectOfType(hm,this.context)){const i=$.addNewComponent(this.gameObject,hm,!1);i.webXR=this}this.webAR=new dm(this)}start(){location.protocol=="http:"&&location.host.indexOf("localhost")<0&&(uo("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,Ss.XRSupported;let i,e;const t=document.createElement("div");t.classList.add("webxr-buttons"),this.context.domElement.append(t),this.enableAR&&this.createARButton&&Sb&&(i=Ss.createARButton(this),this._arButton=i,t.appendChild(i)),this.createVRButton&&this.enableVR&&Eb&&(e=Ss.createVRButton(this),this._vrButton=e,t.appendChild(e)),setTimeout(()=>{Ss.resetButtonStyles(e),Ss.resetButtonStyles(i)},1e3)}get TransformOrientation(){return this._transformOrientation}get HeadPose(){return this._currentHeadPose}onBeforeRender(i){var e;if(!i)return;const t=this.context.renderer.xr.getSession();if(t){const s=i.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(!s)return;this._currentHeadPose=s;const r=s?.transform;r&&this._transformOrientation.set(r.orientation.x,r.orientation.y,r.orientation.z,r.orientation.w),Ss._isInXr===!1&&t&&this.onEnterXR(t,i);for(const n of this.controllers)n.onUpdate(t);this._isInAR&&((e=this.webAR)==null||e.onUpdate(t,i))}Ss.events.dispatchEvent({type:"xrUpdate",frame:i,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 i=0;i<2;i++)cs.Create(this,i,this.gameObject,dp.PhysicalDevice);Ss.events.dispatchEvent({type:"requestVRSession"})}}captureStateBeforeXR(){this.context.mainCamera&&(this._originalCameraPosition.copy(wt(this.context.mainCamera)),this._originalCameraRotation.copy(ws(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 i=$.findObjectOfType(xb,this.context);i?this.rig=i.gameObject:(this.rig=new Rn,this.rig.rotateY(Math.PI),this.rig.name="XRRig",this.context.scene.add(this.rig))}}onEnterXR(i,e){var t,s;console.log("[XR] session begin",i),Ss._isInXr=!0,this.ensureRig();const r=this.context.renderer.xr.getReferenceSpace();if(r&&this.rig){const a=e.getViewerPose(r),l=a?.transform.orientation;if(l){const c=new xe(l.x,l.y,l.z,l.w),u=new fs().setFromQuaternion(c);this.rig.rotateY(u.y)}}const n=this.context.renderer.xr;if(this.context.mainCamera){const a=n.getCamera(this.context.mainCamera),l=(t=this.context.mainCameraComponent)==null?void 0:t.cullingMask;if(l!==void 0){for(const c of a.cameras)c.layers.mask=l;a.layers.mask=l}else{for(const c of a.cameras)c.layers.enableAll();a.layers.enableAll()}this.rig.add(this.context.mainCamera),this._requestedAR&&this.context.scene.add(this.rig)}const o=this._requestedAR?as.AR:as.VR;switch($o.Global.Set(o),o){case as.AR:this.context.xrSessionMode=Eg.ImmersiveAR,this._isInAR=!0,(s=this.webAR)==null||s.onBegin(i);break;case as.VR:this.context.xrSessionMode=Eg.ImmersiveVR,this._isInVR=!0,this.onEnterVR(i);break}i.addEventListener("end",()=>{console.log("[XR] session end"),Ss._isInXr=!1,this.onExitXR(i)}),this.onEnterXR_HandleMirrorWindow(i),Ss.events.dispatchEvent({type:"xrStarted",session:i})}onExitXR(i){var e,t,s;const r=this._isInAR;this._isInAR&&i&&((e=this.webAR)==null||e.onEnd(i)),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&&((t=this._originalCameraParent)==null||t.add(this.context.mainCamera),Yi(this.context.mainCamera,this._originalCameraPosition),Nr(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),r&&((s=this._originalXRRigParent)==null||s.add(this.rig),this.rig.position.copy(this._originalXRRigPosition),this.rig.quaternion.copy(this._originalXRRigRotation)),$o.Global.Set(as.Browser|as.ThirdPerson),Ss.events.dispatchEvent({type:"xrStopped",session:i})}onEnterVR(i){}destroyControllers(){var i;for(let e=this.controllers.length-1;e>=0;e-=1)(i=this.controllers[e])==null||i.destroy();this.controllers.length=0}onEnterXR_HandleMirrorWindow(i){oe("mirror")&&setTimeout(()=>{if(!Ss.IsInWebXR)return;const e=new URL(window.location.href);df(e.searchParams,Yy,1),df(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=()=>{Ss.IsInWebXR&&i.end()})})},1e3)}},h(gp,"_isInXr",!1),h(gp,"events",new vs),h(gp,"_optionalFeatures_VR",["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]),h(gp,"_optionalFeatures_AR",["anchors","local-floor","hand-tracking","layers"]),gp);let xt=Ss;fp([w()],xt.prototype,"enableVR",2),fp([w()],xt.prototype,"enableAR",2),fp([w(lr)],xt.prototype,"defaultAvatar",2),fp([w()],xt.prototype,"handModelPath",2),fp([w()],xt.prototype,"createVRButton",2),fp([w()],xt.prototype,"createARButton",2);const um=class{constructor(i){h(this,"_webxr"),h(this,"reticle",null),h(this,"reticleParent",null),h(this,"hitTestSource",null),h(this,"reticleActive",!0),h(this,"previousBackground",null),h(this,"previousEnvironment",null),h(this,"sessionRoot",null),h(this,"_previousParent",null),h(this,"arDomOverlay",null),h(this,"arOverlayElement",null),h(this,"noHitTestAvailable",!1),h(this,"didPlaceARSessionRoot",!1),this._webxr=i}get webxr(){return this._webxr}get context(){return this.webxr.context}getAROverlayContainer(){this.arDomOverlay=this.webxr.context.domElement;const i=this.arDomOverlay;return i.getAROverlayContainer?this.arOverlayElement=i.getAROverlayContainer():this.arOverlayElement=this.arDomOverlay,this.arOverlayElement}setReticleActive(i){this.reticleActive=i}async onBegin(i){var e,t,s,r;const n=this.webxr.context;this.reticleActive=!0,this.didPlaceARSessionRoot=!1,this.getAROverlayContainer();const o=(e=navigator.userAgent)!=null&&e.includes("OculusBrowser")?dp.PhysicalDevice:dp.Touch,a=o===dp.Touch?4:2;for(let c=0;c<a;c++)cs.Create(this.webxr,c,this.webxr.gameObject,o);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=$.findObjectOfType(Dc,n)),this.previousBackground=n.scene.background,this.previousEnvironment=n.scene.environment,n.scene.background=null,i.requestReferenceSpace("viewer").then(c=>{var u,d;(d=(u=i.requestHitTestSource)==null?void 0:u.call(i,{space:c}))==null||d.then(p=>{this.hitTestSource=p}).catch(p=>{this.noHitTestAvailable=!0,console.warn("WebXR: Hit test not supported",p)})}),!this.reticle&&this.sessionRoot&&(this.reticle=new ye(new of(.07,.09,32).rotateX(-Math.PI/2),new di),this.reticle.name="AR Placement reticle",this.reticle.matrixAutoUpdate=!1,this.reticle.visible=!1,this.reticleParent=new Me,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,um.tempWebXRObject||(um.tempWebXRObject=new Me),this.context.scene.add(um.tempWebXRObject),$.addComponent(um.tempWebXRObject,this.webxr),this.sessionRoot?(this.sessionRoot.webAR=this,(t=this.sessionRoot)==null||t.onBegin(i)):console.warn("No WebARSessionRoot found in scene");const l=this.context.domElement;(s=l?.onEnterAR)==null||s.call(l,i,this.arOverlayElement),(r=this.context.mainCameraComponent)==null||r.applyClearFlagsIfIsActiveCamera()}onEnd(i){var e,t;this._previousParent&&($.addComponent(this._previousParent,this.webxr),this._previousParent=null),this.hitTestSource=null;const s=this.webxr.context;s.scene.background=this.previousBackground,s.scene.environment=this.previousEnvironment,this.sessionRoot&&this.sessionRoot.onEnd(this.webxr.Rig,i);const r=this.context.domElement;(e=r.onExitAR)==null||e.call(r,i),(t=this.context.mainCameraComponent)==null||t.applyClearFlagsIfIsActiveCamera()}onUpdate(i,e){var t,s;if(this.noHitTestAvailable===!0){if(this.reticle&&(this.reticle.visible=!1),!this.didPlaceARSessionRoot){this.didPlaceARSessionRoot=!0;const n=this.webxr.Rig,o=Eee.clone();(t=this.sessionRoot)==null||t.placeAt(n,o)}return}if(!this.hitTestSource)return;const r=e.getHitTestResults(this.hitTestSource);if(r.length){const n=r[0],o=this.webxr.context.renderer.xr.getReferenceSpace();if(o){const a=n.getPose(o);if(this.sessionRoot){const l=this.sessionRoot.onUpdate(this.webxr.Rig,i,a);this.didPlaceARSessionRoot=l}if(this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&a)){const l=a.transform.matrix;this.reticle.matrix.fromArray(l),this.webxr.Rig&&this.reticle.matrix.premultiply(this.webxr.Rig.matrix)}}}else(s=this.sessionRoot)==null||s.onUpdate(this.webxr.Rig,i,null),this.reticle&&(this.reticle.visible=!1)}};let dm=um;h(dm,"tempWebXRObject");const Eee=new Qe().identity().makeTranslation(0,0,0);class ru{constructor(e,t){h(this,"used",!1),h(this,"inputSource"),h(this,"object"),h(this,"pointerId"),h(this,"isDown"),h(this,"isUp"),h(this,"isPressed"),h(this,"isClicked"),h(this,"input"),h(this,"event"),this.event=t,this.input=e}use(){this.used=!0,this.pointerId!==void 0&&this.input.setPointerUsed(this.pointerId)}stopPropagation(){var e;(e=this.event)==null||e.stopImmediatePropagation()}Use(){this.use()}StopPropagation(){var e;(e=this.event)==null||e.stopImmediatePropagation()}}class mp extends Ee{awake(){Wn.createIfNoneExists(this.context)}onEnable(){var e;(e=Wn.get(this.context))==null||e.register(this)}onDisable(){var e;(e=Wn.get(this.context))==null||e.unregister(this)}performRaycast(e=null){return null}}class nu extends mp{constructor(){super(...arguments),h(this,"targets",null),h(this,"raycastHits",[])}start(){this.targets=[this.gameObject]}performRaycast(e=null){return this.targets?(e??(e=new fo),e.targets=this.targets,e.results=this.raycastHits,this.context.physics.raycast(e)):null}}class BE extends nu{}const pm=oe("debugeventsystem");var kE=(i=>(i.BeforeHandleInput="BeforeHandleInput",i.AfterHandleInput="AfterHandleInput",i))(kE||{});const wl=class extends Ee{constructor(){super(),h(this,"raycaster",[]),h(this,"_selectStartFn"),h(this,"_selectEndFn"),h(this,"_selectUpdateFn"),h(this,"_handleEventFn"),h(this,"lastPointerEvent",null),h(this,"objectsHoveredThisFrame",[]),h(this,"objectsHoveredLastFrame",[]),h(this,"raisedPointerDownEvents",[]),h(this,"raisedPointerDownObjects",[]),h(this,"_didMove",!1),h(this,"_tempComponentsArray",[]),h(this,"_sortedHits",[]),h(this,"_sortingBuffer",[]),h(this,"_noDepthTestingResults",[]),h(this,"handleEventsArray",[]),h(this,"out",{}),h(this,"currentActiveMeshUIComponents",[]),wl.systems.push(this)}static createIfNoneExists(i){this.didSearchEventSystem||(this.didSearchEventSystem=!0,wl.systems.length<=0&&wl.systems.push(...$.findObjectsOfType(wl,i)));for(const t of wl.systems)if(t.context===i)return;const e=new Me;$.addNewComponent(e,wl),i.scene.add(e)}static get systems(){const i=_t.Current;return this._eventSystemMap.has(i)||this._eventSystemMap.set(i,[]),this._eventSystemMap.get(i)}static get(i){const e=this._eventSystemMap.get(i);return e&&e.length>0?e[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(i,e){xl.update(i,e)}static markUIDirty(i){xl.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.objectsHoveredThisFrame.length>0}onDestroy(){wl.systems.splice(wl.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!$.findObjectOfType(mp,this.context)){const i=$.addNewComponent(this.context.scene,nu);this.raycaster.push(i),_r()&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found",this)}}register(i){var e;i&&this.raycaster&&!this.raycaster.includes(i)&&((e=this.raycaster)==null||e.push(i))}unregister(i){var e,t;const s=(e=this.raycaster)==null?void 0:e.indexOf(i);s!==void 0&&s!==-1&&((t=this.raycaster)==null||t.splice(s,1))}onEnable(){const i=new Map;this._selectStartFn??(this._selectStartFn=(t,s)=>{if(!s.grab)return;xl.resetLastSelected();const r=new ru(this.context.input);r.inputSource=t,r.isDown=t.selectionDown,r.isUp=t.selectionUp,r.isPressed=t.selectionPressed,r.isClicked=!1,i.set(t,s.grab),s.grab&&!this.handleEvents(s.grab,r)&&(s.grab=null)}),this._selectEndFn??(this._selectEndFn=(t,s)=>{var r;if(!s.grab)return;const n=new ru(this.context.input);n.inputSource=t,n.isDown=t.selectionDown,n.isUp=t.selectionUp,n.isPressed=t.selectionPressed,n.isClicked=t.selectionClick,this.handleEvents(s.grab,n);const o=i.get(t);if(i.set(t,null),o)for(let a=0;a<this.raisedPointerDownEvents.length;a++){const l=this.raisedPointerDownEvents[a];this.raisedPointerDownObjects[a]===o&&l&&((r=l.onPointerUp)==null||r.call(l,n),this.raisedPointerDownEvents.splice(a,1),this.raisedPointerDownObjects.splice(a,1),a--)}});const e=new fo;this._selectUpdateFn??(this._selectUpdateFn=t=>{e.ray=t.getRay();const s=this.performRaycast(e);if(!s)return;const r=new ru(this.context.input);r.inputSource=t,this.handleIntersections(s,r)}),cs.addEventListener(bl.SelectStart,this._selectStartFn),cs.addEventListener(bl.SelectEnd,this._selectEndFn),cs.addEventListener(bl.Update,this._selectUpdateFn),this._handleEventFn??(this._handleEventFn=this.onHandleEvents.bind(this)),this.context.pre_update_callbacks.push(this._handleEventFn)}onDisable(){cs.removeEventListener(bl.SelectStart,this._selectStartFn),cs.removeEventListener(bl.SelectEnd,this._selectEndFn),cs.removeEventListener(bl.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(),xt.IsInWebXR||this.context.input.isKeyPressed("AltLeft")||this.context.input.isKeyPressed("AltRight"))return;if(!this._didMove){const n=this.context.input.getPointerPositionRC(0);if(n&&n.x===0&&n.y===0)return;this._didMove=!0}let i=0;for(const n of this.context.input.foreachPointerId()){const o=this.context.input.getPointerDown(n),a=this.context.input.getPointerUp(n);if(o||a){i=n;break}}const e=this.context.input.getPointerEvent(i),t=new ru(this.context.input,e);t.inputSource=this.context.input,t.pointerId=i,t.isClicked=this.context.input.getPointerClicked(i),t.isDown=this.context.input.getPointerDown(i),t.isUp=this.context.input.getPointerUp(i),t.isPressed=this.context.input.getPointerPressed(i),pm&&t.isClicked&&console.log("CLICK",i);const s=this.performRaycast(null);if(!s)return;this.lastPointerEvent=t;const r={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};pm&&t.isClicked&&Rs("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown),this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:r})),this.handleIntersections(s,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:r}))}onBeforeRender(){if(this.lastPointerEvent)this.lastPointerEvent.used=!1;else return;if(this.lastPointerEvent.isUp){for(const e of this.raisedPointerDownEvents)e.onPointerUp&&e.onPointerUp(this.lastPointerEvent);this.raisedPointerDownEvents.length=0,this.raisedPointerDownObjects.length=0}for(const e of this.objectsHoveredLastFrame)if(this.objectsHoveredThisFrame.indexOf(e)<0){this._tempComponentsArray.length=0;const t=$.getComponentsInParent(e,Ee,this._tempComponentsArray);this.lastPointerEvent.object=e;for(let s=0;s<t.length;s++){const r=t[s];if(!r.gameObject||r.destroyed)continue;const n=r;n.onPointerExit&&n.onPointerExit(this.lastPointerEvent)}}const i=this.objectsHoveredLastFrame;this.objectsHoveredLastFrame=this.objectsHoveredThisFrame,this.objectsHoveredThisFrame=i}performRaycast(i){if(!this.raycaster)return null;this._sortedHits.length=0;for(const e of this.raycaster){if(!e.activeAndEnabled)continue;const t=e.performRaycast(i);t&&t.length>0&&this._sortedHits.push(...t)}return this._sortedHits.sort((e,t)=>e.distance-t.distance),this._sortedHits}handleIntersections(i,e){if(!i||i.length<=0)return!1;i=this.sortCandidates(i);for(const t of i){const{object:s}=t;if(this.handleEvents(s,e))return!0}return!1}sortCandidates(i){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let e=0;e<i.length;e++){const t=i[e],s=t.object;if(s.material&&s.material.depthTest===!1){this._noDepthTestingResults.push(t);continue}this._sortingBuffer.push(t)}for(const e of this._sortingBuffer)this._noDepthTestingResults.push(e);return this._noDepthTestingResults}handleEvents(i,e){if(!this.testIsVisible(i))return e.isClicked&&pm&&console.log("not allowed",i),!1;const t=i;e.object=i,this.lastPointerEvent=e;const s=i.parent;let r=!1;const n=e.isClicked??!1;let o=null;if(s&&s.isUI){const a=(e.isPressed||e.isClicked)??!1;if(s[yl]){const l=s[yl].gameObject;if(l){if(!up.isInteractable(l,this.out))return!1;o=this.out.canvasGroup??null,this.handleMeshUIIntersection(i,a),i=l,r=!0}}if(!r&&this.handleMeshUiObjectWithoutShadowDom(s,a))return!0}if(n&&pm&&console.log(this.context.time.frame,i),this.objectsHoveredThisFrame.push(i),o===null||o.interactable){const a=this.objectsHoveredLastFrame.indexOf(i)>=0;this.handleEventsArray.length=0;const l=$.getComponentsInParent(i,Ee,this.handleEventsArray);for(let c=0;c<l.length;c++){if(e.used)return!0;if(l[c].destroyed)continue;const u=l[c];if(u.interactable!==!1){if(u.onPointerEnter&&(a||u.onPointerEnter(e)),u.onPointerMove&&u.onPointerMove(e),e.isDown&&u.onPointerDown&&!this.raisedPointerDownEvents.includes(u)&&(u.onPointerDown(e),this.raisedPointerDownEvents.push(u),this.raisedPointerDownObjects.push(t)),e.isUp&&u.onPointerUp){const d=this.raisedPointerDownEvents.indexOf(u);d!==-1&&this.raisedPointerDownEvents.splice(d,1),u.onPointerUp(e)}e.isClicked&&u.onPointerClick&&u.onPointerClick(e)}}}return!0}handleMeshUiObjectWithoutShadowDom(i,e){return!i||!i.isUI?!0:this.handleMeshUIIntersection(i,e)}handleMeshUIIntersection(i,e){const t=xl.updateState(i,e);return t&&this.currentActiveMeshUIComponents.push(t),t!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&xl.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let i=0;i<this.currentActiveMeshUIComponents.length;i++){const e=this.currentActiveMeshUIComponents[i];xl.resetState(e)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(i){return i?$.isActiveSelf(i)?this.testIsVisible(i.parent):!1:!0}};let Wn=wl;h(Wn,"_eventSystemMap",new Map),h(Wn,"didSearchEventSystem",!1);class xl{static markDirty(){this.needsUpdate=!0}static update(e,t){const s=t.time.frameCount;for(const r of this.lastUpdateFrame)if(r.context===t){if(s===r.frame)return;r.frame=s;let n=this.needsUpdate||s<1;r.nextUpdate===t.time.frameCount&&(n=!0),n&&(pm&&console.log("Update threemeshui"),this.needsUpdate=!1,e.update());return}this.lastUpdateFrame=[{context:t,frame:s,nextUpdate:s}],e.update()}static updateState(e,t){let s=null;if(e&&(s=this.findBlockInParent(e),s&&s!==this.lastSelected)){if(s.interactable===!1)return null;this.needsUpdate=!0}return s}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockInParent(e){return e?e.isBlock?e:this.findBlockInParent(e.parent):null}}h(xl,"lastSelected",null),h(xl,"lastUpdateFrame",[]),h(xl,"needsUpdate",!1);const Mb=Symbol("cameraController");function Mee(i){return i[Mb]}function WF(i,e,t){t?i[Mb]=e:i[Mb]===e&&(i[Mb]=null)}var Iee=Object.defineProperty,Tee=Object.getOwnPropertyDescriptor,Ree=(i,e,t,s)=>{for(var r=s>1?void 0:s?Tee(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Iee(e,t,r),r};const Ib=oe("freecam"),qF=oe("debugcamerafit"),Pee={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let DE;class Cl extends Ee{constructor(){super(...arguments),h(this,"autoRotate",!1),h(this,"autoRotateSpeed",1),h(this,"enableKeys",!0),h(this,"enableDamping",!0),h(this,"dampingFactor",.1),h(this,"enableZoom",!0),h(this,"minZoom",0),h(this,"maxZoom",1/0),h(this,"enablePan",!0),h(this,"lookAtConstraint",null),h(this,"lookAtConstraint01",1),h(this,"middleClickToFocus",!0),h(this,"doubleClickToFocus",!0),h(this,"useSlerp",!0),h(this,"debugLog",!1),h(this,"targetLerpSpeed",5),h(this,"_lookTargetPosition"),h(this,"_controls",null),h(this,"_cameraObject",null),h(this,"_lerpToTargetPosition",!1),h(this,"_lerpCameraToTarget",!1),h(this,"_cameraTargetPosition",null),h(this,"_inputs",0),h(this,"_enableTime",0),h(this,"_startedListeningToKeyEvents",!1),h(this,"_eventSystem"),h(this,"_afterHandleInputFn"),h(this,"_camera",null),h(this,"_syncedTransform"),h(this,"targetElement",null),h(this,"onControlsChangeStarted",()=>{this._syncedTransform&&this._syncedTransform.requestOwnership()}),h(this,"_shouldDisable",!1),h(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 S,this._startedListeningToKeyEvents=!1}start(){if(this._controls){const e=$.getComponent(this.gameObject,Mi);if(e&&!this.setFromTargetPosition()){this.debugLog&&console.log("NO TARGET");const t=wt(e.cam).length(),s=new S(0,0,-t).applyMatrix4(e.cam.matrixWorld);this.setTarget(s,!0)}}this.startCoroutine(this.startRaycastDelayed()),this._eventSystem=Wn.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(kE.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var e,t;(e=this._controls)==null||e.dispose(),(t=this._eventSystem)==null||t.removeEventListener(kE.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._enableTime=this.context.time.time;const e=$.getComponent(this.gameObject,Mi);this._camera=e;const t=e?.cam;if(t&&WF(t,this,!0),!this._controls){console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t);const s=this.targetElement??this.context.domElement,r=t?.quaternion.clone();this._controls=new DY(t,s),t?.quaternion.copy(r),DE===void 0&&(DE={...this._controls.keys})}this._controls&&(Ib&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,lh()&&(this.doubleClickToFocus=!0)),this._controls.enableDamping=this.enableDamping,this._controls.keys=this.enableKeys?DE:Pee,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.addEventListener("start",this.onControlsChangeStarted),t?.type==="PerspectiveCamera"?Ib||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):Ib||(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=$.getComponent(this.gameObject,Uc)??void 0}onDisable(){var e;(e=this._camera)!=null&&e.cam&&WF(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 fo;e.screenPoint=new W(0,0),e.lineThreshold=.1;const t=this.context.physics.raycast(e);t.length>0&&this.setTarget(t[0].point,!0)}}onBeforeRender(){var e,t,s;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 r=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(r||(r=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3),r?this.setTargetFromRaycast():(this.context.input.getPointerDown(0)||this.context.input.mouseWheelChanged)&&(this._lerpToTargetPosition=!1,this._lerpCameraToTarget=!1),this._lerpToTargetPosition||this._lerpCameraToTarget){const n=this.context.time.deltaTime*this.targetLerpSpeed;if(this._lerpCameraToTarget&&this._cameraTargetPosition&&this._cameraObject){if(this.useSlerp){const o=(e=this._cameraObject)==null?void 0:e.position;wB(o,this._cameraTargetPosition,n)}else(t=this._cameraObject)==null||t.position.lerp(this._cameraTargetPosition,n);this._cameraObject.position.distanceTo(this._cameraTargetPosition)<1e-4&&(this._lerpCameraToTarget=!1)}this._lerpToTargetPosition&&(this.lerpTarget(this._lookTargetPosition,n),this._lookTargetPosition.distanceTo(this._controls.target)<1e-5&&(this._lerpToTargetPosition=!1))}!Ib&&(s=this.lookAtConstraint)!=null&&s.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 s;e?(this._lerpCameraToTarget=!0,this._cameraTargetPosition=e.clone(),t&&this._cameraTargetPosition&&((s=this.controllerObject)==null||s.position.copy(this._cameraTargetPosition))):this._lerpCameraToTarget=!1}setFromTargetPosition(e=0,t=1){var s;if(!this._controls)return!1;const r=(s=this.lookAtConstraint)==null?void 0:s.sources;if(r&&r.length>0){const n=r[e];if(n)return n.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 e,t;if(!this.controls)return;const s=this.context.physics.raycast();for(const r of s)if(r.distance>0&&$.isActiveInHierarchy(r.object)){if(this._lookTargetPosition.copy(r.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;const n=wt(this.context.mainCamera);this._cameraTargetPosition=n.clone().sub(this.controls.target).add(this._lookTargetPosition),(t=(e=this._cameraObject)==null?void 0:e.parent)==null||t.worldToLocal(this._cameraTargetPosition)}break}}fitCamera(e,t=1.1){const s=this._cameraObject,r=this._controls;if(e!=null&&e.length||(e=this.context.scene.children),!s||!r)return;const n=new S,o=new S,a=new ir;a.makeEmpty();for(const m of e)m instanceof f1||a.expandByObject(m,!0);s.updateMatrixWorld(),s.updateProjectionMatrix(),a.getCenter(o),a.applyMatrix4(s.matrixWorldInverse),a.getSize(n),a.setFromCenterAndSize(o,n);const l=s.fov,c=2*Math.atan(Math.tan(l*Math.PI/360/2)*s.aspect)/Math.PI*360,u=n.y/(2*Math.atan(Math.PI*l/360)),d=n.x/(2*Math.atan(Math.PI*c/360)),p=t*Math.max(u,d)+n.z/2;qF&&console.log("Fit camera to objects",u,d,"distance",p);const f=wt(s),g=r.target.clone().sub(f).normalize().multiplyScalar(p);if(r.maxDistance=p*10,r.minDistance=p*.01,r.target.copy(o),s.near=p/100,s.far=p*100,s.updateMatrixWorld(),s.updateProjectionMatrix(),Yi(s,r.target.clone().sub(g)),qF){const m=new f1(a);this.context.scene.add(m),RB(m,x0(s)),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",v=>{v.code==="KeyF"&&this.fitCamera(e)}))}r.update()}}Ree([w(qg)],Cl.prototype,"lookAtConstraint",2);var Bee=Object.defineProperty,kee=Object.getOwnPropertyDescriptor,qn=(i,e,t,s)=>{for(var r=s>1?void 0:s?kee(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Bee(e,t,r),r},XF=(i=>(i[i.Skybox=1]="Skybox",i[i.SolidColor=2]="SolidColor",i[i.Uninitialized=4]="Uninitialized",i))(XF||{});const fm=oe("debugcam"),YF=oe("debugscreenpointtoray");var Tb;const gm=(Tb=class extends Ee{constructor(){super(...arguments),h(this,"_nearClipPlane",.1),h(this,"_farClipPlane",1e3),h(this,"orthographic",!1),h(this,"orthographicSize",5),h(this,"ARBackgroundAlpha",0),h(this,"_cullingMask",4294967295),h(this,"_backgroundBlurriness"),h(this,"_backgroundIntensity"),h(this,"_targetTexture",null),h(this,"_backgroundColor"),h(this,"_fov"),h(this,"_cam",null),h(this,"_clearFlags",2),h(this,"_skybox")}get isCamera(){return!0}get aspect(){return this._cam instanceof Xt?this._cam.aspect:this.context.domWidth/this.context.domHeight}get fieldOfView(){return this._cam instanceof Xt?this._cam.fov:this._fov}set fieldOfView(i){const e=this._fov!=i;if(this._fov=i,e&&this._cam&&this._cam instanceof Xt){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(i){const e=this._nearClipPlane!=i;this._nearClipPlane=i,this._cam&&e&&(this._cam.near=i,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(i){const e=this._farClipPlane!=i;this._farClipPlane=i,this._cam&&e&&(this._cam.far=i,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(i){i!==this._clearFlags&&(this._clearFlags=i,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(i){this._cullingMask=i,this._cam&&(this._cam.layers.mask=i)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set backgroundBlurriness(i){i!==this._backgroundBlurriness&&(i===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(i,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(i){i!==this._backgroundIntensity&&(i===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(i,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(i){if(i){if(this._backgroundColor)this._backgroundColor.copy(i);else{if(!i.clone)return;this._backgroundColor=i.clone()}i.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(i){this._targetTexture=i}get targetTexture(){return this._targetTexture}get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(i,e,t){let s=this.cam;const r=gm._origin;r.set(i,e,-1),this.context.input.convertScreenspaceToRaycastSpace(r),YF&&console.log("screenPointToRay",i.toFixed(2),e.toFixed(2),"now:",r.x.toFixed(2),r.y.toFixed(2),"isInXR:"+this.context.isInXR),r.z=-1,r.unproject(s);const n=gm._direction.set(r.x,r.y,r.z),o=wt(s);return n.sub(o),n.normalize(),t?(t.set(o,n),t):new za(o.clone(),n.clone())}awake(){YF&&window.addEventListener("pointerdown",i=>{const e=i.clientX,t=i.clientY;console.log("touch",e.toFixed(2),t.toFixed(2));const s=this.screenPointToRay(e,t),r="#"+Math.floor(Math.random()*16777215).toString(16);Jo.DrawRay(s.origin,s.direction,r,10)})}onEnable(){fm&&console.log(this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),Oee(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 i=this.context.renderer;i&&this._targetTexture.render(this.context.scene,this._cam,i)}}buildCamera(){if(this._cam)return;const i=this.gameObject.isCamera;let e=null;if(i?(e=this.gameObject,e?.layers.enableAll(),e instanceof Xt&&(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 Xt(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 sd(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){fm&&console.log("Camera does not exist (apply clear flags)");return}switch(fm&&Rs("apply Camera clear flags: "+this._clearFlags),this._clearFlags){case 1:if(gm.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 i=this._backgroundColor.alpha;gm.backgroundShouldBeTransparent(this.context)&&(i=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,i)}break;case 4:this.context.scene.background=null,this.context.renderer.setClearColor(0,0);break}}enableSkybox(){this._skybox||(this._skybox=new Dee(this)),this._skybox.enable()}static backgroundShouldBeTransparent(i){var e,t,s,r;const n=(e=i.renderer.xr)==null?void 0:e.getSession();if(!n)return!1;const o=n.environmentBlendMode;fm&&Rs("Environment blend mode: "+o+" on "+navigator.userAgent);const a=o==="additive"||o==="alpha-blend";return i.xrSessionMode===Eg.ImmersiveAR&&o==="opaque"&&((t=navigator.userAgent)!=null&&t.includes("OculusBrowser")||(s=navigator.userAgent)!=null&&s.includes("Mozilla")&&(r=navigator.userAgent)!=null&&r.includes("Mobile WebXRViewer/v2"))?!0:a}},h(Tb,"_origin",new S),h(Tb,"_direction",new S),Tb);let Mi=gm;qn([w()],Mi.prototype,"fieldOfView",1),qn([w()],Mi.prototype,"nearClipPlane",1),qn([w()],Mi.prototype,"farClipPlane",1),qn([w()],Mi.prototype,"clearFlags",1),qn([w()],Mi.prototype,"orthographic",2),qn([w()],Mi.prototype,"orthographicSize",2),qn([w()],Mi.prototype,"ARBackgroundAlpha",2),qn([w()],Mi.prototype,"cullingMask",1),qn([w()],Mi.prototype,"backgroundBlurriness",1),qn([w()],Mi.prototype,"backgroundIntensity",1),qn([w(vi)],Mi.prototype,"backgroundColor",1),qn([w(Yd)],Mi.prototype,"targetTexture",1);class Dee{constructor(e){h(this,"_camera"),h(this,"_skybox"),this._camera=e}get context(){var e;return(e=this._camera)==null?void 0:e.context}enable(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?this.context.scene.background!==this._skybox&&(fm&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=yt,this._skybox.mapping=Sn,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this._camera.sourceId,this.context.lightmaps)}}function Oee(i){oe("freecam")&&i.context.mainCameraComponent===i&&$.getOrAddComponent(i.gameObject,Cl)}class vp extends Ee{constructor(){super(...arguments),h(this,"_listener",null)}get listener(){return this._listener==null&&(this._listener=new l1),this._listener}awake(){os.registerWaitForAllowAudio(()=>{if(this.destroyed)return;const e=this.listener;if(e==null||e.parent)return;const t=$.getComponentInParent(this.gameObject,Mi);t?t.cam.add(e):this.gameObject.add(e)})}}var Lee=Object.defineProperty,Fee=Object.getOwnPropertyDescriptor,Rb=(i,e,t,s)=>{for(var r=s>1?void 0:s?Fee(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Lee(e,t,r),r};class mm{constructor(){h(this,"guid")}}Rb([w()],mm.prototype,"guid",2);class Ap{constructor(){h(this,"signal"),h(this,"reaction")}}Rb([w(mm)],Ap.prototype,"signal",2),Rb([w(Vr)],Ap.prototype,"reaction",2);var OE;const Sl=(OE=class extends Ee{constructor(){super(...arguments),h(this,"events")}static invoke(i){if(Sl.receivers[i]){const e=Sl.receivers[i];if(!e)return;for(const t of e)t.invoke(i)}}onEnable(){if(this.events)for(const i of this.events)Sl.receivers[i.signal.guid]||(Sl.receivers[i.signal.guid]=[]),Sl.receivers[i.signal.guid].push(this)}onDisable(){if(this.events){for(const i of this.events)if(Sl.receivers[i.signal.guid]){const e=Sl.receivers[i.signal.guid].indexOf(this);e>=0&&Sl.receivers[i.signal.guid].splice(e,1)}}}invoke(i){if(!this.events||!Array.isArray(this.events))return;let e=typeof i=="object"?i.guid:i;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(s){console.error(s)}}},h(OE,"receivers",{}),OE);let yp=Sl;Rb([w(Ap)],yp.prototype,"events",2);var fn=(i=>(i.Activation="ActivationTrack",i.Animation="AnimationTrack",i.Audio="AudioTrack",i.Control="ControlTrack",i.Marker="MarkerTrack",i.Signal="SignalTrack",i))(fn||{}),Qc=(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))(Qc||{}),LE=(i=>(i.Signal="SignalEmitter",i))(LE||{});const vm=oe("debugtimeline"),FE=class extends Ee{constructor(){super(...arguments),h(this,"playableAsset"),h(this,"playOnAwake"),h(this,"extrapolationMode",1),h(this,"waitForAudio",!0),h(this,"_visibilityChangeEvt"),h(this,"_clonedPlayableAsset",!1),h(this,"_speed",1),h(this,"_guidsMap"),h(this,"_isPlaying",!1),h(this,"_internalUpdateRoutine"),h(this,"_isPaused",!1),h(this,"_time",0),h(this,"_duration",0),h(this,"_weight",1),h(this,"_animationTracks",[]),h(this,"_audioTracks",[]),h(this,"_signalTracks",[]),h(this,"_controlTracks",[]),h(this,"_customTracks",[]),h(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks])}static registerCreateTrack(i,e){this.createTrackFunctions[i]=e}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(i){typeof i=="number"&&!Number.isNaN(i)?this._time=i:(vm||gr())&&console.error("INVALID TIMELINE.TIME VALUE",i,this.name)}get duration(){return this._duration}set duration(i){this._duration=i}get weight(){return this._weight}set weight(i){this._weight=i}get speed(){return this._speed}set speed(i){this._speed=i}awake(){var i,e,t;vm&&console.log(this,(i=this.playableAsset)==null?void 0:i.tracks),this.rebuildGraph(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,(e=this.playableAsset)==null?void 0:e.tracks,Array.isArray((t=this.playableAsset)==null?void 0:t.tracks),this)}onEnable(){var i,e;for(const t of this._audioTracks)(i=t.onEnable)==null||i.call(t);for(const t of this._customTracks)(e=t.onEnable)==null||e.call(t);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 i,e;this.stop();for(const t of this._audioTracks)(i=t.onDisable)==null||i.call(t);for(const t of this._customTracks)(e=t.onDisable)==null||e.call(t);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var i;for(const e of this._allTracks)for(const t of e)(i=t.onDestroy)==null||i.call(t)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const i=this._isPaused==!0;if(this._isPaused=!1,i&&this.invokePauseChangedMethodsOnTracks(),!this._isPlaying){if(this._isPlaying=!0,this.waitForAudio){const e=[];for(const t of this._audioTracks){const s=t.loadAudio(this._time,1,0);s&&e.push(s)}if(e.length>0&&(await Promise.all(e),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!os.userInteractionRegistered&&this.waitForAudio;)await pf(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 t of this._audioTracks)t.stop();const i=this._isPaused==!0,e=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.evaluate(),i&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,i&&!e&&this.invokePauseChangedMethodsOnTracks(),this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null}evaluate(){if(!this.isValid())return;let i=this._time;switch(this.extrapolationMode){case 0:this._speed>0?i=Math.min(i,this._duration):this._speed<0&&(i=Math.max(i,0)),this._time=i;break;case 1:i%=this._duration,this._time=i;break;case 2:if(i>this._duration){this.stop();return}break}this.internalEvaluate(i)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(const i of this._allTracks)for(const e of i)yield e}get audioTracks(){return this._audioTracks}resolveGuids(i){this._guidsMap=i}invokePauseChangedMethodsOnTracks(){var i;for(const e of this.forEachTrack())(i=e.onPauseChanged)==null||i.call(e)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.evaluate()),yield}internalEvaluate(i){for(const e of this.playableAsset.tracks)if(!e.muted)switch(e.type){case fn.Activation:for(let t=0;t<e.outputs.length;t++){const s=e.outputs[t];if(typeof s=="object"){let r=!1;for(const o of e.clips)o.start<=i&&i<=o.end&&(r=!0);const n=s;n.visible!==void 0&&(n.visible=r)}}break}for(const e of this._animationTracks)e.evaluate(i);for(const e of this._audioTracks)e.evaluate(i);for(const e of this._signalTracks)e.evaluate(i);for(const e of this._controlTracks)e.evaluate(i);for(const e of this._customTracks)e.evaluate(i)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Qv(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const i=this.findRoot(this.gameObject);for(const e of this.playableAsset.tracks){for(let t=e.outputs.length-1;t>=0;t--){let s=e.outputs[t];if(typeof s=="string"){this._guidsMap&&this._guidsMap[s]&&(s=this._guidsMap[s]);const r=$.findByGuid(s,i);r===null||typeof r!="object"?(e.outputs.splice(t,1),console.warn("Failed to resolve binding",s,e.name,e.type)):(vm&&console.log("Resolved binding",s,"to",r),e.outputs[t]=r)}else if(s===null){if(e.outputs.splice(t,1),FE.createTrackFunctions[e.type])continue;e.type!==fn.Audio&&e.type!==fn.Control&&e.type!==fn.Marker&&e.type!==fn.Signal&&console.warn("Missing binding",s,e.name,e.type,this.name,this.playableAsset.name)}}if(e.type===fn.Control)for(let t=0;t<e.clips.length;t++){const s=e.clips[t];let r=s.asset.sourceObject;if(typeof r=="string"){this._guidsMap&&this._guidsMap[r]&&(r=this._guidsMap[r]);const n=$.findByGuid(r,i);n===null||typeof n!="object"?console.warn("Failed to resolve sourceObject binding",r,e.name,s):(vm&&console.log("Resolved binding",r,"to",n),s.asset.sourceObject=n)}}}}findRoot(i){return i.parent?this.findRoot(i.parent):i}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const i of this.playableAsset.tracks)if(i.muted!==!0){for(const e of i.clips)e.end>this._duration&&(this._duration=e.end);for(const e of i.markers)e.time>this._duration&&(this._duration=e.time+.001)}}}setupAndCreateTrackHandlers(){var i,e;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;const t=$.findObjectOfType(vp,this.context);for(const s of this.playableAsset.tracks){const r=s.type,n=FE.createTrackFunctions[r];if(n!=null){const o=n(this,s);if(typeof o.evaluate=="function"){o.director=this,o.track=s,this._customTracks.push(o);continue}}if(s.type===fn.Animation){if(s.clips.length<=0){vm&&console.warn("Animation track has no clips",s);continue}for(let o=s.outputs.length-1;o>=0;o--){let a=s.outputs[o];if(a instanceof Me){const c=$.getOrAddComponent(a,Gr);c&&(a=c)}const l=(i=a?.gameObject)==null?void 0:i.animations;if(l){const c=new Pb;c.trackOffset=s.trackOffset,c.director=this,c.track=s;for(let u=0;u<s.clips.length;u++){const d=s.clips[u],p=d.asset;if(!p){console.error("MISSING anim model?","clip#"+u,d,s,this.playableAsset,this.name);continue}const f=p.clip;let g=f;if((typeof g=="string"||typeof g=="number")&&(g=l.find(v=>v.name===f)),!g){console.warn("Could not find animationClip for model",d,s.name,this.name,(e=this.playableAsset)==null?void 0:e.name);continue}c.mixer||(c.mixer=new c0(a.gameObject)),c.clips.push(g),c.mixer.uncacheAction(g),c.createHooks(d.asset,g);const m=c.mixer.clipAction(g);c.actions.push(m),c.models.push(d)}this._animationTracks.push(c)}}}else if(s.type===fn.Audio){if(s.clips.length<=0)continue;const o=new _m;if(o.director=this,o.track=s,this._audioTracks.push(o),!t)continue;o.listener=t.listener;for(let a=0;a<s.clips.length;a++){const l=s.clips[a];o.addModel(l)}}else if(s.type===fn.Marker){const o=new wm;o.director=this,o.track=s;for(const a of s.markers)switch(a.type){case LE.Signal:o.models.push(a),o.didTrigger.push(!1);break}if(o!==null&&o.models.length>0){const a=$.getComponent(this.gameObject,yp);a&&(o.receivers.push(a),this._signalTracks.push(o))}}else if(s.type===fn.Signal){const o=new wm;o.director=this,o.track=s;for(const a of s.markers)o.models.push(a),o.didTrigger.push(!1);for(const a of s.outputs)o.receivers.push(a);this._signalTracks.push(o)}else if(s.type===fn.Control){const o=new Bb;o.director=this,o.track=s;for(const a of s.clips)o.models.push(a);o.resolveSourceObjects(this.context),this._controlTracks.push(o)}}}setAudioTracksAllowPlaying(i){for(const e of this._audioTracks)e.onAllowAudioChanged(i)}};let Am=FE;h(Am,"createTrackFunctions",{});const ou=oe("debugtimeline");class ym{constructor(){h(this,"director"),h(this,"track")}get muted(){return this.track.muted}set muted(e){var t;e!==this.track.muted&&(this.track.muted=e,(t=this.onMuteChanged)==null||t.call(this))}*forEachClip(e=!1){var t;if((t=this.track)!=null&&t.clips)if(e)for(let s=this.track.clips.length-1;s>=0;s--)yield this.track.clips[s];else for(const s of this.track.clips)yield s}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,s,r=!0){if(t<0||t>=s.length)return 0;const n=s[t];if(r||e>=n.start&&e<=n.end){let o=1,a=!1;if(n.easeInDuration>0){const l=Math.min((e-n.start)/n.easeInDuration,1);o*=l}if(n.easeOutDuration>0&&!a){const l=Math.min((n.end-e)/n.easeOutDuration,1);o*=l}return o}return 0}}class Uee{constructor(e){h(this,"clip"),h(this,"rootPositionOffset"),h(this,"rootQuaternionOffset"),h(this,"rootStartPosition"),h(this,"rootEndPosition"),h(this,"rootStartQuaternion"),h(this,"rootEndQuaternion");const t=e.getClip();this.clip=t;const s=e.getRoot(),r=s.name+".position",n=s.name+".quaternion";ou&&console.log(t.name,t.tracks,r);for(const o of t.tracks)if(!(o.times.length<=0)){if(o.name.endsWith(r))this.rootStartPosition=new S().fromArray(o.values,0),this.rootEndPosition=new S().fromArray(o.values,o.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),ou&&console.log(this.rootPositionOffset);else if(o.name.endsWith(n)&&(this.rootStartQuaternion=new xe().fromArray(o.values,0),this.rootEndQuaternion=new xe().fromArray(o.values,o.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),ou)){const a=new fs().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",a)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class Pb extends ym{constructor(){super(...arguments),h(this,"models",[]),h(this,"trackOffset"),h(this,"target"),h(this,"mixer"),h(this,"clips",[]),h(this,"actions",[]),h(this,"_actionOffsets",[]),h(this,"_didBind",!1),h(this,"_animator",null),h(this,"_animatorWasEnabled",!1),h(this,"_useclipOffsets",!0),h(this,"_totalOffsetPosition",new S),h(this,"_totalOffsetRotation",new xe),h(this,"_totalOffsetPosition2",new S),h(this,"_totalOffsetRotation2",new xe),h(this,"_summedPos",new S),h(this,"_tempPos",new S),h(this,"_summedRot",new xe),h(this,"_tempRot",new xe),h(this,"_clipRotQuat",new xe)}onPauseChanged(){this._animator&&this._animatorWasEnabled!==void 0&&(this._animator.enabled=this.director.isPlaying===!1?this._animatorWasEnabled:!1)}createHooks(e,t){var s,r;if(((s=t.tracks)==null?void 0:s.length)<=0){console.warn("No tracks in AnimationClip",t);return}const n=t.tracks[0].name.split("."),o=n[n.length-2],a=o+".position",l=o+".quaternion";let c=!1,u=!1;for(const d of t.tracks)d.name.endsWith(a)?(c=!0,this.createPositionInterpolant(t,e,d)):d.name.endsWith(l)&&(u=!0,this.createRotationInterpolant(t,e,d));if(!c||!u){const d=(r=this.mixer)==null?void 0:r.getRoot(),p=t.tracks[0],f=p.name.lastIndexOf("."),g=p.name.substring(0,f),m=g.substring(g.lastIndexOf(".")+1),v=d.getObjectByName(m);if(v)if(c){if(!u){const A=t.tracks[0].name.substring(0,f)+".quaternion";ou&&console.warn("Create quaternion track",m,v);const b=v.quaternion,y=new Fo(A,[0,t.duration],[b.x,b.y,b.z,b.w,b.x,b.y,b.z,b.w]);t.tracks.push(y),this.createRotationInterpolant(t,e,y)}}else{const A=g+".position";ou&&console.warn("Create position track",m,v);const b=v.position,y=new nc(A,[0,t.duration],[b.x,b.y,b.z,b.x,b.y,b.z]);t.tracks.push(y),this.createPositionInterpolant(t,e,y)}}}bind(){if(!this._didBind){this._didBind=!0,ou&&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 Uee(e);this._actionOffsets.push(t)}this.target&&(this._animator=$.getComponent(this.target,Gr)??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,s=t.position,r=t.rotation;s&&s.x!==void 0&&(s.isVector3||(t.position=new S(s.x,s.y,s.z)),r.isQuaternion||(t.rotation=new xe(r.x,r.y,r.z,r.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new S(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new xe(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,s=0,r=!1,n=!1;for(let o=0;o<this.clips.length;o++){const a=this.models[o],l=this.actions[o],c=a.asset;l.weight=0;const u=e>=a.start&&e<=a.end,d=a.preExtrapolationMode,p=a.postExtrapolationMode,f=o<this.clips.length-1?this.models[o+1]:null;let g=u,m=!1;if(!g&&!r&&a.end<e&&p!==Qc.None?(!f||f.start>e)&&(g=!0,r=!0):o==0&&!g&&!n&&a.start>e&&d!==Qc.None&&(!f||f.start<e)&&(g=!0,m=!0,n=!0),g){let v=1;v*=this.evaluateWeight(e,o,this.models,g),v*=this.director.weight;let A=u;m&&d!==Qc.Hold&&(e+=a.start,A=!0);let b=this.getClipTime(e,a),y=0;const _=c.duration;if(m&&d===Qc.Hold&&(b=0),A){if(c.loop)for(y+=Math.floor(b/(_+1e-6));b>_;)b-=_}else if(!u)switch(p){case Qc.Loop:b%=_;break;case Qc.PingPong:const M=Math.floor(b/_)%2!==0;b%=_,M&&(b=_-b);break}a.reversed===!0?l.time=l.getClip().duration-b:l.time=b,l.timeScale=0;const x=v;if(l.weight=x,l.clampWhenFinished=!0,l.isRunning()||l.play(),this._useclipOffsets){const M=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,P=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(s=1-v),t+=1;const C=this._summedPos.set(0,0,0),R=this._tempPos.set(0,0,0),T=this._summedRot.identity(),z=this._tempRot.identity(),G=c.rotation;G&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(G,v));const N=this._actionOffsets[o];if(N.hasOffsets)for(let F=0;F<y;F++)N.rootPositionOffset?R.copy(N.rootPositionOffset):R.set(0,0,0),R.applyQuaternion(T),this._clipRotQuat&&R.applyQuaternion(this._clipRotQuat),N.rootQuaternionOffset&&(z.copy(N.rootQuaternionOffset),T.multiply(z)),C.add(R);this._clipRotQuat&&P.multiply(this._clipRotQuat),P.multiply(T),c.position&&C.add(c.position),M.add(C)}}}this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,s),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,s)),this.mixer.update(e)}createRotationInterpolant(e,t,s){var r;const n=s.createInterpolant.bind(s),o=new xe;this.ensureTrackOffsets();const a=(r=this.trackOffset)==null?void 0:r.rotation;s.createInterpolant=()=>{const l=n(),c=l.evaluate.bind(l);return l.evaluate=u=>{const d=c(u);return o.set(d[0],d[1],d[2],d[3]),o.premultiply(this._totalOffsetRotation),a&&o.premultiply(a),d[0]=o.x,d[1]=o.y,d[2]=o.z,d[3]=o.w,d},l}}createPositionInterpolant(e,t,s){var r,n;const o=s.createInterpolant.bind(s),a=new S;this.ensureTrackOffsets();const l=(r=this.trackOffset)==null?void 0:r.rotation,c=(n=this.trackOffset)==null?void 0:n.position;let u;s.createInterpolant=()=>{const d=o(),p=d.evaluate.bind(d);return d.evaluate=f=>{var g,m;const v=p(f);return a.set(v[0],v[1],v[2]),t.removeStartOffset&&(u===void 0?(u=null,u=(m=(g=this._actionOffsets.find(A=>A.clip===e))==null?void 0:g.rootStartPosition)==null?void 0:m.clone()):u!=null&&u.isVector3&&a.sub(u)),a.applyQuaternion(this._totalOffsetRotation),a.add(this._totalOffsetPosition),l&&a.applyQuaternion(l),c&&(a.x-=c.x,a.y+=c.y,a.z+=c.z),v[0]=a.x,v[1]=a.y,v[2]=a.z,v},d}}}const Nee=oe("mutetimeline"),bm=class extends ym{constructor(){super(...arguments),h(this,"models",[]),h(this,"listener"),h(this,"audio",[]),h(this,"audioContextTimeOffset",[]),h(this,"lastTime",0),h(this,"_audioLoader",null)}getAudioFilePath(i){const e=this.director.sourceId;return zl(e,i)}onAllowAudioChanged(i){for(let e=0;e<this.models.length;e++){const t=this.models[e];this.audio[e].setVolume(i?t.asset.volume:0)}}addModel(i){const e=new l0(this.listener);this.audio.push(e),this.models.push(i)}onDisable(){for(const i of this.audio)i.isPlaying&&i.stop()}onMuteChanged(){if(this.muted)for(let i=0;i<this.audio.length;i++){const e=this.audio[i];e!=null&&e.isPlaying&&e.stop()}}stop(){for(let i=0;i<this.audio.length;i++){const e=this.audio[i];e!=null&&e.isPlaying&&e.stop()}}evaluate(i){if(Nee||this.track.muted||this.director.speed<0)return;const e=this.director.context.application.muted,t=e?.1:0;for(let s=0;s<this.models.length;s++){const r=this.models[s],n=this.audio[s];if((!n||!n.buffer)&&this.isInTimeRange(r,i-1,i+1)&&this.handleAudioLoading(r,n),os.userInteractionRegistered!==!1&&!(n===null||!n.buffer))if(n.playbackRate=this.director.context.time.timeScale,n.loop=r.asset.loop,i>=r.start&&i<=r.end&&i<this.director.duration){if(this.director.isPlaying==!1){if(n.isPlaying&&n.stop(),this.lastTime===i)continue}else if(!n.isPlaying)n.offset=r.clipIn+(i-r.start)*r.timeScale,n.play(t);else{const a=r.clipIn+(i-r.start)*r.timeScale,l=n.context.currentTime-n._startedAt+n.offset;Math.abs(a-l)>.3&&(n.offset=a,n.stop(),n.play(t))}let o=r.asset.volume;if(e&&(o=0),r.easeInDuration>0){const a=Math.min((i-r.start)/r.easeInDuration,1);o*=a}if(r.easeOutDuration>0){const a=Math.min((r.end-i)/r.easeOutDuration,1);o*=a}n.setVolume(o*this.director.weight)}else n.isPlaying&&n.stop()}this.lastTime=i}loadAudio(i,e=0,t=0){let s=null;const r=i-t,n=i+e;for(const o of this.models)if(this.isInTimeRange(o,r,n)){const a=this.audio[this.models.indexOf(o)],l=this.handleAudioLoading(o,a);l!==null&&(s===null&&(s=[]),s.push(l))}return s!==null?Promise.all(s):null}isInTimeRange(i,e,t){return e<=i.start&&t>=i.end||e>=i.start&&e<=i.end||t>=i.start&&t<=i.end}static dispose(){bm._currentlyLoading.clear()}handleAudioLoading(i,e){this._audioLoader||(this._audioLoader=new o0);const t=this.getAudioFilePath(i.asset.clip);if(bm._currentlyLoading.get(t)){const r=bm._currentlyLoading.get(t);return r.then(n=>{n&&e.setBuffer(n)}),r}ou&&console.warn("LOAD audio track",t,this.director.sourceId);const s=new Promise((r,n)=>{this._audioLoader.load(t,o=>{e.setBuffer(o),r(o)},void 0,o=>{console.error("Error loading audio",o),r(null)})});return bm._currentlyLoading.set(t,s),s}};let _m=bm;h(_m,"_currentlyLoading",new Map);class wm extends ym{constructor(){super(...arguments),h(this,"models",[]),h(this,"didTrigger",[]),h(this,"receivers",[])}evaluate(e){var t;if(!this.track.muted)for(let s=0;s<this.models.length;s++){const r=this.models[s],n=this.didTrigger[s],o=r.time-e;let a=!1;if(r.retroActive)a=o<=1e-6;else{const l=Math.abs(o);l>=1e-5&&l<.1&&(a=!0)}if(a){if(!n)if(this.didTrigger[s]=!0,((t=this.receivers)==null?void 0:t.length)<=0)yp.invoke(r.asset);else for(const l of this.receivers)l&&l.invoke(r.asset)}else r.emitOnce||(this.didTrigger[s]=!1)}}}class Bb extends ym{constructor(){super(...arguments),h(this,"models",[]),h(this,"timelines",[]),h(this,"_previousActiveModel",null)}resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const s=this.models[t].asset;if(!s.sourceObject||typeof s.sourceObject!="object"){console.log("no source object, removing model",t,s),this.models.splice(t,1);continue}else{const r=$.getComponent(s.sourceObject,Am);this.timelines.push(r),r&&s.updateDirector&&(r.playOnAwake=!1)}}}evaluate(e){var t;this._previousActiveModel=null;for(let s=0;s<this.models.length;s++){const r=this.models[s],n=r.asset;if(e>=r.start&&e<=r.end){this._previousActiveModel=r;const o=this.getClipTime(e,r);if(n.controlActivation){const a=n.sourceObject;a.visible=!0}if(n.updateDirector){const a=this.timelines[s];a&&(a.isPlaying&&a.pause(),a.time=o,a.evaluate())}}else{const o=(t=this._previousActiveModel)==null?void 0:t.asset;if(n.controlActivation){const a=n.sourceObject;o?.sourceObject!==a&&(a.visible=!1)}}}}}var zee=Object.defineProperty,Qee=Object.getOwnPropertyDescriptor,JF=(i,e,t,s)=>{for(var r=s>1?void 0:s?Qee(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&zee(e,t,r),r};class Dt{constructor(e){h(this,"_active",!0),h(this,"_value"),h(this,"_valueRaw"),h(this,"_defaultValue"),h(this,"valueProcessor"),h(this,"onValueChanged"),this._value=e,this._defaultValue=e}get overrideState(){return this._active}set overrideState(e){if(this._active===e)return;this._active=e;const t=e?this._valueRaw:this._defaultValue;this.processValue(t,!0)}get value(){return this._valueRaw}set value(e){this.processValue(e,!1)}set defaultValue(e){this._defaultValue=e}__init(){this.processValue(this._valueRaw,!0)}processValue(e,t){if(e==null||!t&&this.testIfValueChanged(e)===!1)return;const s=this._value;!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,e=this._defaultValue,this._valueRaw=e):(this._valueRaw=e,this._active&&this.valueProcessor&&(e=this.valueProcessor(e)),this._value=e),this.onValueChanged&&this.onValueChanged(e,s,this)}testIfValueChanged(e){return this._valueRaw!==e}}JF([w()],Dt.prototype,"overrideState",1),JF([w()],Dt.prototype,"value",1);var jee=Object.defineProperty,Gee=Object.getOwnPropertyDescriptor,Hee=(i,e,t,s)=>{for(var r=s>1?void 0:s?Gee(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&jee(e,t,r),r};const Vee=oe("debugpost");class kr extends vc{constructor(){super(...arguments),h(this,"active",!0),h(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(){Vee&&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 s=this[t];s instanceof Dt&&s.__init()}}onAfterDeserialize(e,t){if(typeof e=="object"){const s=this.$serializedTypes;if(s){for(const r of Object.keys(s))if(s[r]===Dt){const n=e[r];if(n!==void 0){const o=this[r];o.value=n}}}}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof Dt){const s=e.value;return this[t].value=s,!0}}}Hee([w()],kr.prototype,"active",2);var Wee=Object.defineProperty,qee=Object.getOwnPropertyDescriptor,Xee=(i,e,t,s)=>{for(var r=s>1?void 0:s?qee(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Wee(e,t,r),r};const Yee=oe("debugpost"),UE={};function oa(i,e){UE[i]=e}function Jee(i){return i.__type in UE?UE[i.__type]:(Yee&&i.__type&&console.warn("Unknown postprocessing type",i.__type,i),kr)}class xm{constructor(){h(this,"components")}init(){var e;(e=this.components)==null||e.forEach(t=>t.init())}}Xee([Pd([i=>Jee(i),kr])],xm.prototype,"components",2);var Kee=Object.defineProperty,Zee=Object.getOwnPropertyDescriptor,$ee=(i,e,t,s)=>{for(var r=s>1?void 0:s?Zee(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Kee(e,t,r),r};class Cm extends kr{constructor(){super(...arguments),h(this,"preset")}get typeName(){return"Antialiasing"}onCreateEffect(){const e=new b7({preset:Id.HIGH,edgeDetectionMode:aC.DEPTH});return this.preset.onValueChanged=t=>{e.applyPreset(t)},e}}$ee([w(Dt)],Cm.prototype,"preset",2),oa("Antialiasing",Cm);class kb{constructor(){h(this,"files",[])}get extensionName(){return"Audio"}onExportObject(e,t,s){const r=$.getComponents(e,os);if(r.length)for(const n of r){if(!n.playOnAwake)continue;const o=n.clip.split("/").pop();this.files.includes(n.clip)||this.files.push(n.clip),t.addEventListener("serialize",(a,l)=>{a.appendLine(),a.beginBlock(`def SpatialAudio "${t.name}"`),a.appendLine(`uniform asset filePath = @audio/${o}@`),a.appendLine(`uniform token auralMode = "${n.spatialBlend>0?"spatial":"nonSpatial"}"`),a.appendLine(`uniform token playbackMode = "${n.loop?"loopFromStage":"onceFromStart"}"`),a.appendLine(`uniform float gain = ${n.volume}`),a.closeBlock()})}}async onAfterSerialize(e){console.warn("onAfterSerialize",this);for(const t of this.files){const s=t.split("/").pop(),r=await(await(await fetch(t)).blob()).arrayBuffer(),n=new Uint8Array(r);e.files["audio/"+s]=n}}}var ete=Object.defineProperty,tte=Object.getOwnPropertyDescriptor,KF=(i,e,t,s)=>{for(var r=s>1?void 0:s?tte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&ete(e,t,r),r};const ite=oe("debugmouth");class Sm extends Ee{constructor(){super(...arguments),h(this,"idle",[]),h(this,"talking",[]),h(this,"marker",null),h(this,"voip",null),h(this,"lastMouthChangeTime",0),h(this,"mouthChangeLength",0)}awake(){setTimeout(()=>{this.voip=$.findObjectOfType(Fl,this.context),this.marker||(this.marker=$.getComponentInParent(this.gameObject,hr))},3e3)}update(){var e;if(!this.voip||this.context.time.frameCount%10!==0)return;let t=((e=this.marker)==null?void 0:e.connectionId)??null;if(!t){ite&&(t=null);return}const s=this.voip.getFrequency(t)??0;this.updateLips(s)}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(s=>s.visible=!1):this.talking.map(s=>s.visible=!1);for(let s=0;s<e.length;s++){const r=e[s];r&&(r.visible=s===t)}}}}KF([w(Me)],Sm.prototype,"idle",2),KF([w(Me)],Sm.prototype,"talking",2);class NE extends Ee{constructor(){super(...arguments),h(this,"voip",null),h(this,"marker",null),h(this,"_startPosition",null)}awake(){this.voip=$.findObjectOfType(Fl,this.context),this.marker=$.getComponentInParent(this.gameObject,hr)}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 s=t/100;this.gameObject.position.y=this._startPosition.y+s*.07}}var ste=Object.defineProperty,rte=Object.getOwnPropertyDescriptor,Db=(i,e,t,s)=>{for(var r=s>1?void 0:s?rte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&ste(e,t,r),r};class au extends Ee{constructor(){super(...arguments),h(this,"eyes",[]),h(this,"lastBlinkTime",0),h(this,"blinkLength",0),h(this,"eyesOpen",!0),h(this,"state",null)}awake(){this.state=$.getComponentInParent(this.gameObject,Rr)}update(){if(!(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)&&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 e of this.eyes)e&&(e.visible=this.eyesOpen)}}}Db([w(Me)],au.prototype,"eyes",2),Db([w()],au.prototype,"lastBlinkTime",2),Db([w()],au.prototype,"blinkLength",2),Db([w()],au.prototype,"eyesOpen",2);var nte=Object.defineProperty,ote=Object.getOwnPropertyDescriptor,zE=(i,e,t,s)=>{for(var r=s>1?void 0:s?ote(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&nte(e,t,r),r},QE;const ZF=(QE=class extends Ee{constructor(){super(...arguments),h(this,"head",null),h(this,"eyes",null),h(this,"target",null),h(this,"brain",null),h(this,"vec",new S),h(this,"currentTargetPoint",new S)}awake(){this.brain||(this.brain=$.getComponentInParent(this.gameObject,Jg)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=$.addNewComponent(this.gameObject,Jg)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}update(){const i=this.target;if(i&&this.head){const e=this.eyes;if(e){const t=wt(i);this.currentTargetPoint.lerp(t,this.context.time.deltaTime/.1);const s=wt(this.head),r=this.vec.copy(this.currentTargetPoint).sub(s).normalize();if(r.length()<.1)return;const n=ZF.forward;if(n.set(0,0,1),n.applyQuaternion(ws(this.head)),n.dot(r)>.45)for(let o=0;o<e.length;o++)e[o].lookAt(this.currentTargetPoint)}}}},h(QE,"forward",new S(0,0,1)),QE);let bp=ZF;zE([w(Me)],bp.prototype,"head",2),zE([w(Me)],bp.prototype,"eyes",2),zE([w(Me)],bp.prototype,"target",2);var ate=Object.defineProperty,lte=Object.getOwnPropertyDescriptor,jE=(i,e,t,s)=>{for(var r=s>1?void 0:s?lte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&ate(e,t,r),r};class _p extends Ee{constructor(){super(...arguments),h(this,"length",1),h(this,"depthTest",!0),h(this,"isGizmo",!0),h(this,"_axes",null)}onEnable(){if(this.isGizmo&&!Zf)return;this._axes||(this._axes=new Ad(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)}}jE([w()],_p.prototype,"length",2),jE([w()],_p.prototype,"depthTest",2),jE([w()],_p.prototype,"isGizmo",2);class GE extends Ee{constructor(){super(...arguments),h(this,"from"),h(this,"to"),h(this,"hint"),h(this,"desiredDistance",1)}onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=wt(this.to).clone(),t=wt(this.from).clone(),s=e.distanceTo(t),r=e.clone();r.sub(t);let n=t.clone();n.add(e),n.multiplyScalar(.5);let o=wt(this.hint).clone();o.sub(n);let a=new S;a.crossVectors(o,r),a.crossVectors(r,a),a.normalize();let l=s*.5,c=Math.max(this.desiredDistance,l),u=Math.sqrt(c*c-l*l),d=a.clone();d.multiplyScalar(u),d.add(n),Yi(this.gameObject,d);let p=n.clone();p.sub(a),this.gameObject.lookAt(p)}}class Ob{constructor(){h(this,"behaviours",[]),h(this,"behaviourComponents",[]),h(this,"behaviourComponentsCopy",[])}get extensionName(){return"Behaviour"}addBehavior(e){this.behaviours.push(e)}onBeforeBuildDocument(e){e.root.traverse(t=>{$.foreachComponent(t,s=>{var r;const n=s;(typeof n.createBehaviours=="function"||typeof n.beforeCreateDocument=="function"||typeof n.afterCreateDocument=="function")&&(this.behaviourComponents.push(n),(r=n.beforeCreateDocument)==null||r.call(n,this,e))},!1)})}onExportObject(e,t,s){var r;for(const n of this.behaviourComponents)(r=n.createBehaviours)==null||r.call(n,this,t,s)}onAfterBuildDocument(e){for(const t of this.behaviourComponents)typeof t.afterCreateDocument=="function"&&t.afterCreateDocument(this,e);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0}onAfterHierarchy(e,t){var s;if((s=this.behaviours)!=null&&s.length){t.beginBlock('def Scope "Behaviors"');for(const r of this.behaviours)r.writeTo(this,e.document,t);t.closeBlock()}}async onAfterSerialize(e){console.log("onAfterSerialize",this.behaviourComponentsCopy);for(const t of this.behaviourComponentsCopy)console.log("behaviour",t),typeof t.afterSerialize=="function"&&(console.log("beh has afterSerialize",t),t.afterSerialize.constructor.name==="AsyncFunction"?await t.afterSerialize(this,e):t.afterSerialize(this,e))}}var cte=Object.defineProperty,hte=Object.getOwnPropertyDescriptor,HE=(i,e,t,s)=>{for(var r=s>1?void 0:s?hte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&cte(e,t,r),r};class lu extends kr{constructor(){super(...arguments),h(this,"threshold"),h(this,"intensity"),h(this,"scatter"),h(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 lD(this.context.scene,this.context.mainCamera,{blendFunction:kt.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,intensity:this.intensity.value});t.inverted=!0}else e=new pC;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}}HE([w(Dt)],lu.prototype,"threshold",2),HE([w(Dt)],lu.prototype,"intensity",2),HE([w(Dt)],lu.prototype,"scatter",2),oa("Bloom",lu);var ute=Object.defineProperty,dte=Object.getOwnPropertyDescriptor,Mo=(i,e,t,s)=>{for(var r=s>1?void 0:s?dte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&ute(e,t,r),r};class aa extends Ee{constructor(){super(...arguments),h(this,"attachedRigidbody",null),h(this,"isTrigger",!1),h(this,"sharedMaterial")}get isCollider(){return!0}awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Li))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Li))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Li))}onDisable(){var e;(e=this.context.physics.engine)==null||e.removeBody(this)}}Mo([w(Li)],aa.prototype,"attachedRigidbody",2),Mo([w()],aa.prototype,"isTrigger",2),Mo([w()],aa.prototype,"sharedMaterial",2);class Em extends aa{constructor(){super(...arguments),h(this,"radius",.5),h(this,"center",new S(0,0,0))}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addSphereCollider(this,this.center,this.radius)}}Mo([w()],Em.prototype,"radius",2),Mo([w(S)],Em.prototype,"center",2);class Mm extends aa{constructor(){super(...arguments),h(this,"size",new S(1,1,1)),h(this,"center",new S(0,0,0))}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addBoxCollider(this,this.center,this.size)}}Mo([w(S)],Mm.prototype,"size",2),Mo([w(S)],Mm.prototype,"center",2);class Im extends aa{constructor(){super(...arguments),h(this,"sharedMesh"),h(this,"convex",!1)}onEnable(){var e,t,s,r,n;if(super.onEnable(),(e=this.sharedMesh)!=null&&e.isMesh||this.gameObject instanceof ye&&(this.sharedMesh=this.gameObject),(t=this.sharedMesh)!=null&&t.isMesh)(s=this.context.physics.engine)==null||s.addMeshCollider(this,this.sharedMesh,this.convex,Ns(this.gameObject));else{const o=this.sharedMesh;if(o!=null&&o.isGroup){console.warn(`MeshCollider mesh is a group "${(r=this.sharedMesh)==null?void 0:r.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);for(const a in o.children){const l=o.children[a];l.isMesh&&((n=this.context.physics.engine)==null||n.addMeshCollider(this,l,this.convex,Ns(this.gameObject)))}}}}}Mo([w()],Im.prototype,"convex",2);class jc extends aa{constructor(){super(...arguments),h(this,"center",new S(0,0,0)),h(this,"radius",.5),h(this,"height",2)}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addCapsuleCollider(this,this.center,this.height,this.radius)}}Mo([w(S)],jc.prototype,"center",2),Mo([w()],jc.prototype,"radius",2),Mo([w()],jc.prototype,"height",2);function VE(i){return i[yl]||(i.parent?VE(i.parent):null)}function Lb(i,e){if(!i)return;const t=i.material;if(t?.isMaterial===!0){const s=i.parent;s&&s.isText,t.side=e.doubleSided??!0?bi:mr,t.shadowSide=e.doubleSided?bi:mr,i.castShadow=e.castShadows?e.castShadows:!1,i.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const s of i.children)Lb(s,e)}function wp(i,e,t){i[e]===void 0&&console.warn("Field",e,"is undefined on",i);const s=Proxy.revocable(i[e],{set(o,a,l,c){const u=o[a],d=Reflect.set(o,a,l,c);return t(l,u),d}}),r=s.revoke,n=i[e];return s.revoke=()=>{i[e]=n,r()},i[e]=s.proxy,s}const $F=Symbol("Scheduled action");function pte(i,e,t=dn.OnBeforeRender){let s=i[$F];s||(s=i[$F]={});const r=e.name;s[t]||(s[t]={});const n=s[t];if(n[r])return;function*o(){e?.call(i),n[r]=null}const a=i.startCoroutine(o(),t);n[r]=a}var fte=Object.defineProperty,gte=Object.getOwnPropertyDescriptor,cu=(i,e,t,s)=>{for(var r=s>1?void 0:s?gte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&fte(e,t,r),r};const WE=oe("debugui"),qE=oe("debuguilayout");class XE{constructor(){h(this,"width"),h(this,"height")}}class YE{constructor(){h(this,"x"),h(this,"y"),h(this,"width"),h(this,"height")}}const la=new S,Tm=new Qe,Fb=new xe,eU=class extends Bo{constructor(){super(...arguments),h(this,"offset",.01),h(this,"_anchoredPosition"),h(this,"sizeDelta",new W(100,100)),h(this,"pivot",new W(.5,.5)),h(this,"anchorMin",new W(0,0)),h(this,"anchorMax",new W(1,1)),h(this,"offsetMin",new W(0,0)),h(this,"offsetMax",new W(0,0)),h(this,"lastMatrix"),h(this,"rectBlock"),h(this,"_transformNeedsUpdate",!1),h(this,"_initialPosition"),h(this,"_parentRectTransform"),h(this,"_lastUpdateFrame",-1),h(this,"_lastAnchoring"),h(this,"_createdBlocks",[]),h(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 W),this._anchoredPosition}set anchoredPosition(i){this._anchoredPosition=i}get width(){if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const i=this._parentRectTransform.width,e=this.anchorMax.x-this.anchorMin.x;let t=i*e;return t+=this.sizeDelta.x,t}return this.sizeDelta.x}get height(){if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const i=this._parentRectTransform.height,e=this.anchorMax.y-this.anchorMin.y;let t=i*e;return t+=this.sizeDelta.y,t}return this.sizeDelta.y}awake(){super.awake(),this._anchoredPosition||(this._anchoredPosition=new W),this.lastMatrix=new Qe,this.rectBlock=new Me,this.rectBlock.position.z=.1,this.rectBlock.name=this.name,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this.onApplyTransform("RectTransform awake"),wp(this,"_anchoredPosition",()=>{this.markDirty()}),wp(this,"sizeDelta",()=>{this.markDirty()}),wp(this,"pivot",()=>{this.markDirty()}),wp(this,"anchorMin",()=>{this.markDirty()}),wp(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var i;super.onEnable(),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(i=this.Canvas)==null||i.registerTransform(this)}onDisable(){var i;super.onDisable(),this.removeShadowComponent(),(i=this.Canvas)==null||i.unregisterTransform(this)}onParentRectTransformChanged(i){this._transformNeedsUpdate||this.onApplyTransform(qE?`${i.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(qE&&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(i){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=$.getComponentInParent(this.gameObject.parent,eU):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,qE&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+i),this.isRoot()?this.Root.screenspace||(e.rotation.y=Math.PI):(e.matrix.identity(),e.matrixAutoUpdate=!1,la.set(0,0,0),this.applyPivot(la),e.matrix.setPosition(la.x,la.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(Fb.copy(this.gameObject.quaternion),Fb.x*=-1,Fb.z*=-1,Tm.makeRotationFromQuaternion(Fb),e.matrix.premultiply(Tm)),la.set(0,0,0),this.applyAnchoring(la),la.z+=this.offset,Tm.identity(),Tm.setPosition(la.x,la.y,la.z),e.matrix.premultiply(Tm),e.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const t=!0;for(const s of tC(this.gameObject,Bo,t,1)){if(s===this||!s.activeAndEnabled)continue;const r=s;r.onParentRectTransformChanged&&r.onParentRectTransformChanged(this)}}applyAnchoring(i){this._lastAnchoring||(this._lastAnchoring=new W);const e=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=e.x,this.gameObject.position.y+=e.y,this._lastAnchoring.copy(this._anchoredPosition),i.x+=this._initialPosition.x-this.gameObject.position.x,i.y+=this._initialPosition.y-this.gameObject.position.y,i.z+=this._initialPosition.z-this.gameObject.position.z;const t=this._parentRectTransform;if(t){let s=0;const r=1-this.anchorMax.y-this.anchorMin.y;s-=t.height*.5*r,i.y+=s;let n=0;const o=1-this.anchorMax.x-this.anchorMin.x;n-=t.width*.5*o,i.x+=n}}applyPivot(i){if(this.pivot&&!this.isRoot()){const e=this.pivot.x-.5;i.x-=e*this.sizeDelta.x*this.gameObject.scale.x;const t=this.pivot.y-.5;i.y-=t*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const i={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:this.offset,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(i),i}ensureValidSize(i,e=1e-4){return i.width<=0&&(i.width=e),i.height<=0&&(i.height=1e-4),i}createNewBlock(i){i={...this.getBasicOptions(),...i},WE&&console.log(this.name,i);const e=new ME(i);return this._createdBlocks.push(e),e}createNewText(i){WE&&console.log(i),i={...this.getBasicOptions(),...i},WE&&console.log(this.name,i);const e=new zF(i);return this._createdTextBlocks.push(e),e}};let ur=eU;cu([w(W)],ur.prototype,"anchoredPosition",1),cu([w(W)],ur.prototype,"sizeDelta",2),cu([w(W)],ur.prototype,"pivot",2),cu([w(W)],ur.prototype,"anchorMin",2),cu([w(W)],ur.prototype,"anchorMax",2),cu([w(W)],ur.prototype,"offsetMin",2),cu([w(W)],ur.prototype,"offsetMax",2);class mte extends NF{constructor(e,t={}){super(e),e._simpleState__activeStates=[],e._simpleState__normalStyles={},e._simpleState__states=t,e._simpleState__statesProperties={};for(const s in t)for(const r in t[s])e._simpleState__statesProperties[r]||(e._simpleState__statesProperties[r]=[]),e._simpleState__statesProperties[r].push(s);for(const s of e._components)e._simpleState__statesProperties[s.id]&&(e._simpleState__normalStyles[s.id]=s.inline?s.inline:s._value);e.__overridedSet=e.set,e.set=this.storeSet.bind(e),e.renderStates=this.renderStates.bind(e),e.setupState=this.setupState.bind(e),e.setState=this.setState.bind(e),e.activatePseudoState=this.activatePseudoState.bind(e),e.deactivatePseudoState=this.deactivatePseudoState.bind(e),e.togglePseudoState=this.togglePseudoState.bind(e)}act(){}attach(){}detach(){}setupState(e,t){this._simpleState__states[e]=t;const s=[];for(const r in t)this._simpleState__statesProperties[r]||(this._simpleState__statesProperties[r]=[],s.push(r)),this._simpleState__statesProperties[r].push(e);for(const r of this._components)s.indexOf(r.id)>-1&&(this._simpleState__normalStyles[r.id]=r.inline?r.inline:r._value)}renderStates(){let e={...this._simpleState__normalStyles};for(const t in this._simpleState__states)this._simpleState__activeStates.indexOf(t)>-1&&(e={...e,...this._simpleState__states[t]});this.set(e,!1)}storeSet(e,t=!0){if(t)for(const s in e)this._simpleState__statesProperties[s]&&(this._simpleState__normalStyles[s]=e[s]);this.__overridedSet(e)}activatePseudoState(e){this._simpleState__activeStates.indexOf(e)===-1&&(this._simpleState__activeStates.push(e),this.renderStates())}deactivatePseudoState(e){const t=this._simpleState__activeStates.indexOf(e);t>-1&&(this._simpleState__activeStates.splice(t,1),this.renderStates())}togglePseudoState(e){const t=this._simpleState__activeStates.indexOf(e);t>-1?this._simpleState__activeStates.splice(t,1):this._simpleState__activeStates.push(e),this.renderStates()}setState(e){Array.isArray(e)?this._simpleState__activeStates=e:this._simpleState__activeStates=[e],this.renderStates()}}var vte=Object.defineProperty,Ate=Object.getOwnPropertyDescriptor,tU=(i,e,t,s)=>{for(var r=s>1?void 0:s?Ate(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&vte(e,t,r),r};class xp extends Ee{constructor(){super(...arguments),h(this,"effectColor"),h(this,"effectDistance")}}tU([w(vi)],xp.prototype,"effectColor",2),tU([w(W)],xp.prototype,"effectDistance",2);var yte=Object.defineProperty,bte=Object.getOwnPropertyDescriptor,iU=(i,e,t,s)=>{for(var r=s>1?void 0:s?bte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&yte(e,t,r),r};const Ub={backgroundColor:new _e(1,1,1),backgroundOpacity:1,borderColor:new _e(1,1,1),borderOpacity:1};var JE;const Nb=(JE=class extends Bo{constructor(){super(...arguments),h(this,"_alphaFactor",1),h(this,"raycastTarget",!0),h(this,"uiObject",null),h(this,"_color",null),h(this,"_rect",null),h(this,"_stateManager",null),h(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new vi(1,1,1,1)),this._color}set color(i){(!this._color||this._color.r!==i.r||this._color.g!==i.g||this._color.b!==i.b||this._color.alpha!==i.alpha)&&(this._color||(this._color=new vi(1,1,1,1)),this._color.copy(i))}setAlphaFactor(i){this._alphaFactor=i,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(Ub.backgroundColor=this._color,Ub.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(Ub,this._alphaFactor),this.uiObject.set(Ub),this.markDirty())}get m_Color(){return this._color}get rectTransform(){return this._rect||(this._rect=$.getComponent(this.gameObject,ur)),this._rect}onParentRectTransformChanged(){var i;(i=this.uiObject)==null||i.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(i){this.makePanel(),this.uiObject&&(this.uiObject.setState(i),this==null||this.markDirty())}setupState(i){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new mte(this.uiObject)),this.uiObject.setupState(i.state,i.attributes))}setOptions(i){this.makePanel(),this.uiObject&&this.uiObject.set(i)}awake(){super.awake(),this.makePanel(),wp(this,"_color",()=>pte(this,this.onColorChanged))}onEnable(){var i;super.onEnable(),this.uiObject&&((i=this.rectTransform.shadowComponent)==null||i.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 i={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:1};this.onBeforeCreate(i),this.applyEffects(i),this.onCreate(i),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated()}onBeforeCreate(i){}onCreate(i){this.uiObject=this.rectTransform.createNewBlock(i),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(i,e=1){var t;const s=(t=this.gameObject)==null?void 0:t.getComponent(xp);s&&(s.effectDistance&&(i.borderWidth=Math.max(Math.abs(s.effectDistance.x),Math.abs(s.effectDistance.y))),s.effectColor&&(i.borderColor=s.effectColor,i.borderOpacity=s.effectColor.alpha*e))}async setTexture(i){if(this.setOptions({backgroundOpacity:0}),i){if(i.encoding===yt)if(Nb.textureCache.has(i))i=Nb.textureCache.get(i);else{const e=i.clone();e.encoding=Hi,Nb.textureCache.set(i,e),i=e}this.setOptions({backgroundImage:i,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)}},h(JE,"textureCache",new Map),JE);let hu=Nb;iU([w(vi)],hu.prototype,"color",1),iU([w()],hu.prototype,"raycastTarget",2);class Rm extends hu{constructor(){super(...arguments),h(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var _te=Object.defineProperty,wte=Object.getOwnPropertyDescriptor,zb=(i,e,t,s)=>{for(var r=s>1?void 0:s?wte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&_te(e,t,r),r};let KE=class{constructor(){h(this,"texture",null),h(this,"rect")}};zb([w(Nt)],KE.prototype,"texture",2);let Cp=class extends Rm{constructor(){super(...arguments),h(this,"_sprite"),h(this,"pixelsPerUnitMultiplier",1)}set image(i){this.sprite?this.sprite.texture=i:(this.sprite=new KE,this.sprite.texture=i),this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(i){this._sprite!==i&&(this._sprite=i,this.onAfterCreated())}isBuiltinSprite(){var i,e,t,s,r,n,o,a;switch((e=(i=this.sprite)==null?void 0:i.texture)==null?void 0:e.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return((r=(s=(t=this.sprite)==null?void 0:t.texture)==null?void 0:s.image)==null?void 0:r.width)===32&&((a=(o=(n=this.sprite)==null?void 0:n.texture)==null?void 0:o.image)==null?void 0:a.height)===32}onBeforeCreate(i){var e,t;super.onBeforeCreate(i),this.isBuiltinSprite()&&(i.borderRadius=5/this.pixelsPerUnitMultiplier,((t=(e=this.sprite)==null?void 0:e.texture)==null?void 0:t.name)==="Knob"&&(i.borderRadius=999))}onAfterCreated(){var i;this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture((i=this.sprite)==null?void 0:i.texture))}};zb([w(KE)],Cp.prototype,"sprite",1),zb([w()],Cp.prototype,"pixelsPerUnitMultiplier",2);class Qb extends Rm{constructor(){super(...arguments),h(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))}}zb([w(Nt)],Qb.prototype,"mainTexture",1);var xte=Object.defineProperty,Cte=Object.getOwnPropertyDescriptor,gn=(i,e,t,s)=>{for(var r=s>1?void 0:s?Cte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&xte(e,t,r),r};const Sp=oe("debugbutton");class uu{constructor(){h(this,"colorMultiplier"),h(this,"disabledColor"),h(this,"fadeDuration"),h(this,"highlightedColor"),h(this,"normalColor"),h(this,"pressedColor"),h(this,"selectedColor")}}gn([w()],uu.prototype,"colorMultiplier",2),gn([w(vi)],uu.prototype,"disabledColor",2),gn([w()],uu.prototype,"fadeDuration",2),gn([w(vi)],uu.prototype,"highlightedColor",2),gn([w(vi)],uu.prototype,"normalColor",2),gn([w(vi)],uu.prototype,"pressedColor",2),gn([w(vi)],uu.prototype,"selectedColor",2);class El extends Ee{constructor(){super(...arguments),h(this,"onClick"),h(this,"_isHovered",!1),h(this,"colors"),h(this,"transition"),h(this,"animationTriggers"),h(this,"animator"),h(this,"_interactable",!0),h(this,"_requestedAnimatorTrigger"),h(this,"_isInit",!1),h(this,"_image")}onPointerEnter(e){var t,s;Sp&&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&&((s=this._image)==null||s.setState("hovered")),this.context.input.setCursorPointer())}onPointerExit(){var e,t;Sp&&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,s;Sp&&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&&((s=this._image)==null||s.setState("pressed")))}onPointerUp(e){var t,s;Sp&&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&&((s=this._image)==null||s.setState(this._isHovered?"hovered":"normal")))}onPointerClick(e){var t;this.interactable&&(Sp&&(console.warn("Button Click",this.onClick),Rs("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(),Sp&&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=$.getComponent(this.gameObject,Cp),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){var t,s,r,n,o;e.setInteractable(this.interactable);const a=this.getFinalColor(e.color,(t=this.colors)==null?void 0:t.normalColor),l={state:"normal",attributes:{backgroundColor:a,backgroundOpacity:a.alpha}};e.setupState(l);const c=this.getFinalColor(e.color,(s=this.colors)==null?void 0:s.highlightedColor),u={state:"hovered",attributes:{backgroundColor:c,backgroundOpacity:c.alpha}};e.setupState(u);const d=this.getFinalColor(e.color,(r=this.colors)==null?void 0:r.pressedColor),p={state:"pressed",attributes:{backgroundColor:d,backgroundOpacity:d.alpha}};e.setupState(p);const f=this.getFinalColor(e.color,(n=this.colors)==null?void 0:n.selectedColor),g={state:"selected",attributes:{backgroundColor:f,backgroundOpacity:f.alpha}};e.setupState(g);const m=this.getFinalColor(e.color,(o=this.colors)==null?void 0:o.disabledColor),v={state:"disabled",attributes:{backgroundColor:m,backgroundOpacity:m.alpha}};e.setupState(v)}getFinalColor(e,t){return t?e.clone().multiply(t):e.clone()}}gn([w(Vr)],El.prototype,"onClick",2),gn([w()],El.prototype,"colors",2),gn([w()],El.prototype,"transition",2),gn([w()],El.prototype,"animationTriggers",2),gn([w(Gr)],El.prototype,"animator",2),gn([w()],El.prototype,"interactable",1);var Ste=Object.defineProperty,Ete=Object.getOwnPropertyDescriptor,hs=(i,e,t,s)=>{for(var r=s>1?void 0:s?Ete(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Ste(e,t,r),r};const sU=oe("debuguilayout");class Gc{constructor(){h(this,"left",0),h(this,"right",0),h(this,"top",0),h(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}hs([w()],Gc.prototype,"left",2),hs([w()],Gc.prototype,"right",2),hs([w()],Gc.prototype,"top",2),hs([w()],Gc.prototype,"bottom",2);class mn extends Ee{constructor(){super(...arguments),h(this,"_rectTransform",null),h(this,"_needsUpdate",!1),h(this,"childAlignment",0),h(this,"reverseArrangement",!1),h(this,"spacing",0),h(this,"padding"),h(this,"minWidth",0),h(this,"minHeight",0),h(this,"flexibleHeight",0),h(this,"flexibleWidth",0),h(this,"preferredHeight",0),h(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&&(sU&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){sU&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(ur);const e=this.gameObject.getComponentInParent(dr);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(dr);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}hs([w()],mn.prototype,"childAlignment",2),hs([w()],mn.prototype,"reverseArrangement",2),hs([w()],mn.prototype,"spacing",2),hs([w(Gc)],mn.prototype,"padding",2),hs([w()],mn.prototype,"minWidth",2),hs([w()],mn.prototype,"minHeight",2),hs([w()],mn.prototype,"flexibleHeight",2),hs([w()],mn.prototype,"flexibleWidth",2),hs([w()],mn.prototype,"preferredHeight",2),hs([w()],mn.prototype,"preferredWidth",2);class Hc extends mn{constructor(){super(...arguments),h(this,"childControlHeight",!0),h(this,"childControlWidth",!0),h(this,"childForceExpandHeight",!1),h(this,"childForceExpandWidth",!1),h(this,"childScaleHeight",!1),h(this,"childScaleWidth",!1)}onCalculateLayout(e){var t;const s=this.primaryAxis,r=e.width;let n=r;const o=e.height;let a=o;n-=this.padding.horizontal,a-=this.padding.vertical,s==="x"?this.padding.horizontal:this.padding.vertical;const l=s==="x",c=l?"y":"x",u=l?this.childControlWidth:this.childControlHeight,d=l?this.childControlHeight:this.childControlWidth,p=l?this.childForceExpandWidth:this.childForceExpandHeight,f=l?this.childForceExpandHeight:this.childForceExpandWidth,g=l?a:n,m=l?r:o,v=.5*(l?this.childAlignment%3:Math.floor(this.childAlignment/3));let A=0;l?A+=this.padding.left:A+=this.padding.top;let b=0,y=0;for(let C=0;C<this.gameObject.children.length;C++){const R=this.gameObject.children[C],T=$.getComponent(R,ur);T!=null&&T.activeAndEnabled&&(y+=1,l?b+=T.width:b+=T.height)}let _=0;const x=this.spacing*(y-1);if(p||u){let C=0;l?C=n-=x:C=a-=x,y>0&&(_=C/y)}let M=0;M+=this.padding.left,M-=this.padding.right,v!==0&&(A=m-b,A*=v,A-=x*v,l?(A-=this.padding.right*v,A+=this.padding.left*(1-v),A<this.padding.left&&(A=this.padding.left)):(A-=this.padding.bottom*v,A+=this.padding.top*(1-v),A<this.padding.top&&(A=this.padding.top)));let P=1;for(let C=0;C<this.gameObject.children.length;C++){const R=this.gameObject.children[C],T=$.getComponent(R,ur);if(T!=null&&T.activeAndEnabled){(t=T.pivot)==null||t.set(.5,.5),T.anchorMin.set(0,1),T.anchorMax.set(0,1);const z=r*.5+M*.5;T.anchoredPosition.x!==z&&(T.anchoredPosition.x=z);const G=o*-.5;T.anchoredPosition.y!==G&&(T.anchoredPosition.y=G),f&&d&&T.sizeDelta[c]!==g&&(T.sizeDelta[c]=g),p&&u&&T.sizeDelta[s]!==_&&(T.sizeDelta[s]=_);const N=l?T.width:T.height;let F=N*.5;if(A+=F,p){let te=_*P-_*.5;te>A&&(A=te-_*.5+N+this.padding.left,A-=F)}let X=A;s==="y"&&(X=-X),T.anchoredPosition[s]!==X&&(T.anchoredPosition[s]=X),A+=F,A+=this.spacing,P+=1}}}}hs([w()],Hc.prototype,"childControlHeight",2),hs([w()],Hc.prototype,"childControlWidth",2),hs([w()],Hc.prototype,"childForceExpandHeight",2),hs([w()],Hc.prototype,"childForceExpandWidth",2),hs([w()],Hc.prototype,"childScaleHeight",2),hs([w()],Hc.prototype,"childScaleWidth",2);class ZE extends Hc{get primaryAxis(){return"y"}}class $E extends Hc{get primaryAxis(){return"x"}}class eM extends mn{onCalculateLayout(){}}var Mte=Object.defineProperty,Ite=Object.getOwnPropertyDescriptor,ca=(i,e,t,s)=>{for(var r=s>1?void 0:s?Ite(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Mte(e,t,r),r};const tM=oe("debuguilayout"),rU=class extends am{constructor(){super(...arguments),h(this,"_renderOnTop"),h(this,"_depthWrite",!1),h(this,"_doubleSided",!0),h(this,"_castShadows",!1),h(this,"_receiveShadows",!1),h(this,"_renderMode",-1),h(this,"_rootCanvas"),h(this,"_scaleFactor",1),h(this,"worldCamera"),h(this,"planeDistance",-1),h(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this)),h(this,"previousParent",null),h(this,"_lastMatrixWorld",null),h(this,"_rectTransforms",[]),h(this,"_layoutGroups",new Map),h(this,"onBeforeRenderRoutine",()=>{var i,e;this.previousParent=this.gameObject.parent,this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(i=this.shadowComponent)==null||i.updateMatrixWorld(!0),(e=this.shadowComponent)==null||e.updateWorldMatrix(!0,!0),Wn.ensureUpdateMeshUI(jF,this.context))}),h(this,"onAfterRenderRoutine",()=>{var i,e;if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const t=this.context.mainCamera;t?.add(this.gameObject)}else this.previousParent.add(this.gameObject);this.context.renderer.autoClear=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(i=this.shadowComponent)==null||i.updateMatrixWorld(!0),Wn.ensureUpdateMeshUI(jF,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)}),h(this,"_updateRenderSettingsRoutine"),h(this,"_activeRenderMode",-1),h(this,"_lastWidth",-1),h(this,"_lastHeight",-1)}get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(i){i!==this._renderOnTop&&(this._renderOnTop=i,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(i){this._depthWrite!==i&&(this._depthWrite=i,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(i){this._doubleSided!==i&&(this._doubleSided=i,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(i){this._castShadows!==i&&(this._castShadows=i,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(i){this._receiveShadows!==i&&(this._receiveShadows=i,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(i){this._renderMode!==i&&(this._renderMode=i,this.onRenderSettingsChanged())}set rootCanvas(i){this._rootCanvas instanceof rU||(this._rootCanvas=i)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(i){this._scaleFactor=i}awake(){var i;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,tM&&console.log("Canvas.Awake()",((i=this.previousParent)==null?void 0:i.name)+"/"+this.gameObject.name),super.awake()}start(){this.onUpdateRenderMode()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new Qe,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 i=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);i!==-1&&this.context.pre_render_callbacks.splice(i,1);const e=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);e!==-1&&this.context.post_render_callbacks.splice(e,1)}registerTransform(i){this._rectTransforms.push(i)}unregisterTransform(i){const e=this._rectTransforms.indexOf(i);e!==-1&&this._rectTransforms.splice(e,1)}registerLayoutGroup(i){const e=i.gameObject;this._layoutGroups.set(e,i)}unregisterLayoutGroup(i){const e=i.gameObject;this._layoutGroups.delete(e)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new Qe);const i=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);tM&&i&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);let e=!1;for(const t of this._rectTransforms){i&&t.markDirty();let s=this._layoutGroups.get(t.gameObject);t.isDirty&&!s&&(s=t.gameObject.getComponentInParent(mn)),(t.isDirty||s!=null&&s.isDirty)&&(tM&&!e&&console.log("CANVAS UPDATE ### "+t.name+" ##################################### "+this.context.time.frame),s?.updateLayout(),t.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),dn.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),Lb(this.shadowComponent,this);for(const i of $.getComponentsInChildren(this.gameObject,Bo))Lb(i.shadowComponent,this)}}onUpdateRenderMode(i=!1){if(!i&&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=Je.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 s=t+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-s,this.gameObject.quaternion.identity();const r=this.gameObject.getComponent(ur);let n=!1;r.sizeDelta.x!==this.context.domWidth&&(n=!0),r.sizeDelta.y!==this.context.domHeight&&(n=!0);const o=e.fieldOfView*Math.PI/180,a=2*Math.tan(o/2)*Math.abs(s);this.gameObject.scale.x=a/this.context.domHeight,this.gameObject.scale.y=a/this.context.domHeight,this.gameObject.scale.z=.01,n&&(r.sizeDelta.x=this.context.domWidth,r.sizeDelta.y=this.context.domHeight,r?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};let dr=rU;ca([w()],dr.prototype,"renderOnTop",1),ca([w()],dr.prototype,"depthWrite",1),ca([w()],dr.prototype,"doubleSided",1),ca([w()],dr.prototype,"castShadows",1),ca([w()],dr.prototype,"receiveShadows",1),ca([w()],dr.prototype,"renderMode",1),ca([w(dr)],dr.prototype,"rootCanvas",1),ca([w()],dr.prototype,"scaleFactor",1),ca([w(Mi)],dr.prototype,"worldCamera",2),ca([w()],dr.prototype,"planeDistance",2);var Tte=Object.defineProperty,Rte=Object.getOwnPropertyDescriptor,iM=(i,e,t,s)=>{for(var r=s>1?void 0:s?Rte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Tte(e,t,r),r};class Ep extends Ee{constructor(){super(...arguments),h(this,"_alpha",1),h(this,"interactable",!0),h(this,"blocksRaycasts",!0),h(this,"_isDirty",!1),h(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(),dn.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){for(const e of $.getComponentsInChildren(this.gameObject,Bo,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}iM([w()],Ep.prototype,"alpha",1),iM([w()],Ep.prototype,"interactable",2),iM([w()],Ep.prototype,"blocksRaycasts",2);var Pte=Object.defineProperty,Bte=Object.getOwnPropertyDescriptor,Ii=(i,e,t,s)=>{for(var r=s>1?void 0:s?Bte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Pte(e,t,r),r};class du extends Ee{constructor(){super(...arguments),h(this,"object"),h(this,"target"),h(this,"duration",1),h(this,"relativeMotion",!1),h(this,"coroutine",null),h(this,"targetPos",new S),h(this,"targetRot",new xe),h(this,"targetScale",new S)}*moveToTarget(){if(!this.target||!this.object)return;const e=wt(this.object).clone(),t=wt(this.target).clone(),s=ws(this.object).clone(),r=ws(this.target).clone(),n=Ns(this.object).clone(),o=Ns(this.target).clone(),a=e.distanceTo(t),l=s.angleTo(r),c=n.distanceTo(o);if(a<.01&&l<.01&&c<.01){Yi(this.object,t),Nr(this.object,r),I1(this.object,o),this.coroutine=null;return}let u=0,d=0;for(;u<1;)u+=this.context.time.deltaTime/this.duration,u>1&&(u=1),d=u<.5?4*u*u*u:1-Math.pow(-2*u+2,3)/2,this.targetPos.lerpVectors(e,t,d),this.targetRot.slerpQuaternions(s,r,d),this.targetScale.lerpVectors(n,o,d),Yi(this.object,this.targetPos),Nr(this.object,this.targetRot),I1(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(),s=this.object.scale.clone(),r=this.target.position.clone(),n=this.target.quaternion.clone(),o=this.target.scale.clone();r.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(r),this.targetRot.copy(this.object.quaternion).multiply(n),this.targetScale.copy(this.object.scale).multiply(o);let a=0,l=0;for(;a<1;)a+=this.context.time.deltaTime/this.duration,a>1&&(a=1),l=a<.5?4*a*a*a:1-Math.pow(-2*a+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,l),this.object.quaternion.slerpQuaternions(t,this.targetRot,l),this.object.scale.lerpVectors(s,this.targetScale,l),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 s=new Tr("Move to "+((t=this.target)==null?void 0:t.name),Wr.tapTrigger(this.gameObject),ni.transformAction(this.object,this.target,this.duration,this.relativeMotion?RS.Relative:RS.Absolute));e.addBehavior(s)}}}Ii([w(Me)],du.prototype,"object",2),Ii([w(Me)],du.prototype,"target",2),Ii([w()],du.prototype,"duration",2),Ii([w()],du.prototype,"relativeMotion",2);var sM;const Mp=(sM=class extends Ee{constructor(){super(...arguments),h(this,"materialToSwitch"),h(this,"variantMaterial"),h(this,"_objectsWithThisMaterial",[]),h(this,"selfModel"),h(this,"targetModels",[])}awake(){if(this.variantMaterial&&this.materialToSwitch){const i=$.findObjectsOfType(zi);for(const e of i)e.sharedMaterial===this.materialToSwitch&&this._objectsWithThisMaterial.push(e)}}onPointerClick(){if(this.variantMaterial)for(const i of this._objectsWithThisMaterial)i.sharedMaterial=this.variantMaterial}createBehaviours(i,e,t){this._objectsWithThisMaterial.find(s=>s.gameObject.uuid===e.uuid)&&this.targetModels.push(e),this.gameObject.uuid===e.uuid&&(this.selfModel=e,this.materialToSwitch&&(Mp._materialTriggersPerId[this.materialToSwitch.uuid]||(Mp._materialTriggersPerId[this.materialToSwitch.uuid]=[]),Mp._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(i,e){if(!this.materialToSwitch)return;const t=Mp._materialTriggersPerId[this.materialToSwitch.uuid];if(t){const s={};for(const n of t){const o=n.createVariants();o&&o.length>0&&(s[n.selfModel.uuid]=o)}const r=[];for(const n of t){for(const o in s)o!==n.selfModel.uuid&&r.push(s[o]);n.createAndAttachBehaviors(i,s[n.selfModel.uuid],r)}}delete Mp._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(i,e,t){const s=[],r=[];for(const n of this.targetModels){const o=ni.fadeAction(n,0,!1);r.push(o)}for(const n of t)r.push(ni.fadeAction(n,0,!1));for(const n of e)s.push(ni.fadeAction(n,0,!1)),r.push(ni.fadeAction(n,0,!0));i.addBehavior(new Tr("Select "+this.selfModel.name,Wr.tapTrigger(this.selfModel),ni.parallel(...r))),i.addBehavior(new Tr("Start hidden "+this.selfModel.name,Wr.sceneStartTrigger(),ni.parallel(...s)))}createVariants(){if(!this.variantMaterial)return null;const i=[];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())&&Zo.createEmptyParent(e),e.parent&&e.parent.add(t),i.push(t)}return i}},h(sM,"_materialTriggersPerId",{}),sM);let Pm=Mp;Ii([w(Tt)],Pm.prototype,"materialToSwitch",2),Ii([w(Tt)],Pm.prototype,"variantMaterial",2);class Ip extends Ee{constructor(){super(...arguments),h(this,"target"),h(this,"toggleOnClick",!1),h(this,"targetState",!0),h(this,"hideSelf",!0),h(this,"selfModel"),h(this,"otherModel"),h(this,"toggleModel"),h(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,s){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 s=this.hideSelf;this.targetState,this.toggleOnClick&&(s=!0,this.target.visible,(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&DL.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.clone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel));const r=[];if(s&&r.push(ni.fadeAction(this.selfModel,0,!1)),this.toggleModel&&r.push(ni.fadeAction(this.toggleModel,0,!0)),r.push(ni.fadeAction(this.otherModel,0,this.targetState)),e.addBehavior(new Tr("Toggle_"+this.selfModel.name+"_hideSelf",Wr.tapTrigger(this.selfModel),ni.sequence(...r))),this.toggleOnClick&&this.toggleModel){const n=[];n.push(ni.fadeAction(this.toggleModel,0,!1)),n.push(ni.fadeAction(this.selfModel,0,!0)),n.push(ni.fadeAction(this.otherModel,0,!this.targetState)),e.addBehavior(new Tr("Toggle_"+this.selfModel.name+"_toggleSelf",Wr.tapTrigger(this.toggleModel),ni.sequence(...n))),e.addBehavior(new Tr("HideOnStart_"+this.gameObject.name,Wr.sceneStartTrigger(),ni.fadeAction(this.toggleModel,0,!1)))}}this.gameObject.visible=this.stateBeforeCreatingDocument}}}Ii([w(Me)],Ip.prototype,"target",2),Ii([w()],Ip.prototype,"targetState",2),Ii([w()],Ip.prototype,"hideSelf",2);class rM extends Ee{start(){this.gameObject.visible=!1}createBehaviours(e,t,s){t.uuid===this.gameObject.uuid&&e.addBehavior(new Tr("HideOnStart_"+this.gameObject.name,Wr.sceneStartTrigger(),ni.fadeAction(t,0,!1)))}beforeCreateDocument(){this.gameObject.visible=!0}afterCreateDocument(){this.gameObject.visible=!1}}class Tp extends Ee{constructor(){super(...arguments),h(this,"target"),h(this,"duration",.5),h(this,"motionType",TS.bounce)}beforeCreateDocument(){}createBehaviours(e,t,s){if(this.target&&t.uuid===this.gameObject.uuid){const r=new Tr("emphasize "+this.name,Wr.tapTrigger(this.gameObject),ni.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(r)}}afterCreateDocument(e,t){}}Ii([w()],Tp.prototype,"target",2),Ii([w()],Tp.prototype,"duration",2),Ii([w()],Tp.prototype,"motionType",2);class Rp extends Ee{constructor(){super(...arguments),h(this,"target"),h(this,"clip",""),h(this,"toggleOnClick",!1)}onPointerClick(){if(!(!this.target&&!this.clip)){if(!this.target){const e=this.gameObject.addNewComponent(os);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,s){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const r=this.clip?this.clip:this.target?this.target.clip:void 0;if(!r)return;const n=this.target?this.target.gameObject:this.gameObject,o=r.split("/").pop(),a=this.target?this.target.volume:1,l=this.target&&this.target.spatialBlend==0?BS.NonSpatial:BS.Spatial,c=new Tr("playAudio "+this.name,Wr.tapTrigger(this.gameObject),ni.playAudioAction(n,"audio/"+o,qL.Play,a,l));e.addBehavior(c)}}async afterSerialize(e,t){if(!this.target&&!this.clip)return;const s=this.clip?this.clip:this.target?this.target.clip:void 0;if(!s)return;const r=s.split("/").pop(),n=await(await(await fetch(this.clip)).blob()).arrayBuffer(),o=new Uint8Array(n);t.files["audio/"+r]=o}}Ii([w(os)],Rp.prototype,"target",2),Ii([w(URL)],Rp.prototype,"clip",2),Ii([w()],Rp.prototype,"toggleOnClick",2);var nM;const Pp=(nM=class extends Ee{constructor(){super(...arguments),h(this,"target"),h(this,"animator"),h(this,"stateName"),h(this,"stateNameAfterPlaying"),h(this,"loopAfterPlaying",!1),h(this,"selfModel"),h(this,"stateAnimationModel"),h(this,"stateAnimation"),h(this,"stateAfterPlayingAnimationModel"),h(this,"stateAfterPlayingAnimation")}onPointerClick(){var i;this.target&&this.stateName&&((i=this.animator)==null||i.play(this.stateName,0,0,.1))}createBehaviours(i,e,t){e.uuid===this.gameObject.uuid&&(this.selfModel=e)}onAfterHierarchy(){Pp.animationActions=[]}afterCreateDocument(i,e){!this.stateAnimation||!this.stateAnimationModel||e.document.traverse(t=>{var s,r;if(t.uuid===((s=this.target)==null?void 0:s.uuid)&&this.stateAnimation){const n=[];let o=Pp.animationActions.find(l=>l.affectedObjects==t&&l.start==this.stateAnimation.start&&l.duration==this.stateAnimation.duration);if(o||(o=ni.startAnimationAction(t,this.stateAnimation.start,this.stateAnimation.duration),Pp.animationActions.push(o)),n.push(o),this.stateAfterPlayingAnimation&&this.stateAfterPlayingAnimationModel){let l=Pp.animationActions.find(u=>u.affectedObjects==t&&u.start==this.stateAfterPlayingAnimation.start&&u.duration==this.stateAfterPlayingAnimation.duration);l||(l=ni.startAnimationAction(t,this.stateAfterPlayingAnimation.start,this.stateAfterPlayingAnimation.duration),Pp.animationActions.push(l));const c=ni.sequence(l);this.loopAfterPlaying&&c.makeLooping(),n.push(c)}const a=new Tr("tap "+this.name+" for "+this.stateName+" on "+((r=this.target)==null?void 0:r.name),Wr.tapTrigger(this.selfModel),ni.sequence(...n));i.addBehavior(a)}})}createAnimation(i,e,t){var s,r,n,o;if(this.target&&this.animator){const a=(r=(s=this.animator)==null?void 0:s.runtimeAnimatorController)==null?void 0:r.findState(this.stateName);this.stateAnimationModel=e,this.stateAnimation=i.registerAnimation(this.target,a?.motion.clip);const l=(o=(n=this.animator)==null?void 0:n.runtimeAnimatorController)==null?void 0:o.findState(this.stateNameAfterPlaying);this.stateAfterPlayingAnimationModel=e,this.stateAfterPlayingAnimation=i.registerAnimation(this.target,l?.motion.clip)}}},h(nM,"animationActions",[]),nM);let Vc=Pp;Ii([w(Me)],Vc.prototype,"target",2),Ii([w(Gr)],Vc.prototype,"animator",2),Ii([w()],Vc.prototype,"stateName",2),Ii([w()],Vc.prototype,"stateNameAfterPlaying",2),Ii([w()],Vc.prototype,"loopAfterPlaying",2);class Bp extends Ee{constructor(){super(...arguments),h(this,"target")}getType(){}getDuration(){}}Ii([w(Me)],Bp.prototype,"target",2);class Bm extends Ee{constructor(){super(...arguments),h(this,"target")}}Ii([w(Bp)],Bm.prototype,"target",2);class km extends Bp{constructor(){super(...arguments),h(this,"type",1),h(this,"duration",1)}getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Ii([w()],km.prototype,"type",2),Ii([w()],km.prototype,"duration",2);class oM extends Bm{}var kte=Object.defineProperty,Dte=Object.getOwnPropertyDescriptor,Ml=(i,e,t,s)=>{for(var r=s>1?void 0:s?Dte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&kte(e,t,r),r};class pu extends Ee{constructor(){super(...arguments),h(this,"center",new S(0,0,0)),h(this,"radius",.5),h(this,"height",2),h(this,"_rigidbody",null),h(this,"_activeGroundCollisions",new Set)}get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(Li),this._rigidbody||(this._rigidbody=this.gameObject.addNewComponent(Li)),this.rigidbody)}onEnable(){let e=this.rigidbody,t=this.gameObject.getComponent(jc);t||(t=this.gameObject.addNewComponent(jc)),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}}Ml([w(S)],pu.prototype,"center",2),Ml([w()],pu.prototype,"radius",2),Ml([w()],pu.prototype,"height",2);class Il extends Ee{constructor(){super(...arguments),h(this,"controller"),h(this,"movementSpeed",2),h(this,"rotationSpeed",2),h(this,"jumpForce",1),h(this,"doubleJumpForce",2),h(this,"animator"),h(this,"lookForward",!0),h(this,"_currentSpeed",new S(0,0,0)),h(this,"_currentAngularSpeed",new S(0,0,0)),h(this,"_temp",new S(0,0,0)),h(this,"_jumpCount",0),h(this,"_currentRotation"),h(this,"_raycastOptions",new fo)}awake(){this._currentRotation=new xe}update(){var e,t,s,r,n,o,a,l,c,u,d;(e=this.controller)!=null&&e.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&((t=this.animator)==null||t.setBool("doubleJump",!1)));const p=this.context.input.isKeyPressed("w"),f=this.context.input.isKeyPressed("s"),g=this.context.input.isKeyPressed("a"),m=this.context.input.isKeyPressed("d"),v=this.context.input.isKeyDown(" "),A=(p?1:0)+(f?-1:0);this._currentSpeed.z+=A*this.movementSpeed*this.context.time.deltaTime,(s=this.animator)==null||s.setBool("running",A!=0),(n=this.animator)==null||n.setBool("jumping",((r=this.controller)==null?void 0:r.isGrounded)===!0&&v),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 b=(g?1:0)+(m?-1:0);if(this._currentAngularSpeed.y+=Je.toRadians(b*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const y=this.context.mainCameraComponent.forward;y.y=0,y.normalize(),this._currentRotation.setFromUnitVectors(new S(0,0,1),y),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&&v&&this.jumpForce>0){let y=(o=this.controller)==null?void 0:o.isGrounded;if(this.doubleJumpForce>0&&!((a=this.controller)!=null&&a.isGrounded)&&this._jumpCount===1&&(y=!0,(l=this.animator)==null||l.setBool("doubleJump",!0)),y){this._jumpCount+=1;const _=this.controller.rigidbody,x=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;_.applyImpulse(new S(0,1,0).multiplyScalar(x))}}if(this.controller){const y=(c=this.controller)==null?void 0:c.rigidbody.getVelocity().y;if(y<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new za),this._raycastOptions.ray.origin.copy(wt(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const _=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const x=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(_),(x.length&&x[0].distance>2||y<-10)&&((u=this.animator)==null||u.setBool("falling",!0))}else(d=this.animator)==null||d.setBool("falling",!1)}}}Ml([w(pu)],Il.prototype,"controller",2),Ml([w()],Il.prototype,"movementSpeed",2),Ml([w()],Il.prototype,"rotationSpeed",2),Ml([w()],Il.prototype,"jumpForce",2),Ml([w()],Il.prototype,"doubleJumpForce",2),Ml([w(Gr)],Il.prototype,"animator",2);var Ote=Object.defineProperty,Lte=Object.getOwnPropertyDescriptor,Fte=(i,e,t,s)=>{for(var r=s>1?void 0:s?Lte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Ote(e,t,r),r};class Dm extends kr{constructor(){super(...arguments),h(this,"intensity")}get typeName(){return"ChromaticAberration"}init(){this.intensity.defaultValue=0}onCreateEffect(){const e=new rD;return e.offset=new W(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}}Fte([w(Dt)],Dm.prototype,"intensity",2),oa("ChromaticAberration",Dm);var Ute=Object.defineProperty,Nte=Object.getOwnPropertyDescriptor,jb=(i,e,t,s)=>{for(var r=s>1?void 0:s?Nte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Ute(e,t,r),r};class Wc extends kr{constructor(){super(...arguments),h(this,"postExposure"),h(this,"contrast"),h(this,"hueShift"),h(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===vr&&this.postExposure.overrideState&&(this.context.renderer.toneMapping=Af);const e=new sD;this.postExposure.onValueChanged=s=>{this.context.renderer.toneMapping===vr&&(this.context.renderer.toneMapping=Af),this.context.renderer.toneMappingExposure=s},this.contrast.onValueChanged=s=>{e.contrast=s};const t=new oD;return this.hueShift.onValueChanged=s=>t.hue=s,this.saturation.onValueChanged=s=>t.saturation=s,[t,e]}}jb([w(Dt)],Wc.prototype,"postExposure",2),jb([w(Dt)],Wc.prototype,"contrast",2),jb([w(Dt)],Wc.prototype,"hueShift",2),jb([w(Dt)],Wc.prototype,"saturation",2),oa("ColorAdjustments",Wc);const zte=(Math.sqrt(5)-1)/4,Vs=(5-Math.sqrt(5))/20,Gb=i=>Math.floor(i)|0,Hb=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 Qte(i=Math.random){const e=jte(i),t=new Float64Array(e).map(o=>Hb[o%32*4]),s=new Float64Array(e).map(o=>Hb[o%32*4+1]),r=new Float64Array(e).map(o=>Hb[o%32*4+2]),n=new Float64Array(e).map(o=>Hb[o%32*4+3]);return function(o,a,l,c){let u,d,p,f,g;const m=(o+a+l+c)*zte,v=Gb(o+m),A=Gb(a+m),b=Gb(l+m),y=Gb(c+m),_=(v+A+b+y)*Vs,x=v-_,M=A-_,P=b-_,C=y-_,R=o-x,T=a-M,z=l-P,G=c-C;let N=0,F=0,X=0,te=0;R>T?N++:F++,R>z?N++:X++,R>G?N++:te++,T>z?F++:X++,T>G?F++:te++,z>G?X++:te++;const re=N>=3?1:0,Z=F>=3?1:0,fe=X>=3?1:0,ae=te>=3?1:0,Oe=N>=2?1:0,Se=F>=2?1:0,ie=X>=2?1:0,ce=te>=2?1:0,Re=N>=1?1:0,K=F>=1?1:0,je=X>=1?1:0,Ne=te>=1?1:0,Be=R-re+Vs,ve=T-Z+Vs,de=z-fe+Vs,Ae=G-ae+Vs,pe=R-Oe+2*Vs,Ue=T-Se+2*Vs,Pe=z-ie+2*Vs,ct=G-ce+2*Vs,me=R-Re+3*Vs,ht=T-K+3*Vs,ut=z-je+3*Vs,Pt=G-Ne+3*Vs,ii=R-1+4*Vs,U=T-1+4*Vs,D=z-1+4*Vs,le=G-1+4*Vs,Te=v&255,ke=A&255,Ge=b&255,st=y&255;let Q=.6-R*R-T*T-z*z-G*G;if(Q<0)u=0;else{const ge=Te+e[ke+e[Ge+e[st]]];Q*=Q,u=Q*Q*(t[ge]*R+s[ge]*T+r[ge]*z+n[ge]*G)}let J=.6-Be*Be-ve*ve-de*de-Ae*Ae;if(J<0)d=0;else{const ge=Te+re+e[ke+Z+e[Ge+fe+e[st+ae]]];J*=J,d=J*J*(t[ge]*Be+s[ge]*ve+r[ge]*de+n[ge]*Ae)}let Ve=.6-pe*pe-Ue*Ue-Pe*Pe-ct*ct;if(Ve<0)p=0;else{const ge=Te+Oe+e[ke+Se+e[Ge+ie+e[st+ce]]];Ve*=Ve,p=Ve*Ve*(t[ge]*pe+s[ge]*Ue+r[ge]*Pe+n[ge]*ct)}let qe=.6-me*me-ht*ht-ut*ut-Pt*Pt;if(qe<0)f=0;else{const ge=Te+Re+e[ke+K+e[Ge+je+e[st+Ne]]];qe*=qe,f=qe*qe*(t[ge]*me+s[ge]*ht+r[ge]*ut+n[ge]*Pt)}let ze=.6-ii*ii-U*U-D*D-le*le;if(ze<0)g=0;else{const ge=Te+1+e[ke+1+e[Ge+1+e[st+1]]];ze*=ze,g=ze*ze*(t[ge]*ii+s[ge]*U+r[ge]*D+n[ge]*le)}return 27*(u+d+p+f+g)}}function jte(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 s=t+~~(i()*(256-t)),r=e[t];e[t]=e[s],e[s]=r}for(let t=256;t<512;t++)e[t]=e[t-256];return e}var Gte=Object.defineProperty,Hte=Object.getOwnPropertyDescriptor,q=(i,e,t,s)=>{for(var r=s>1?void 0:s?Hte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Gte(e,t,r),r};const Vb=oe("debugparticles");var ha=(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))(ha||{});class qc{constructor(){h(this,"alphaKeys"),h(this,"colorKeys")}get duration(){return 1}evaluate(e,t){let s,r=0,n=null,o=0;for(let a=0;a<this.alphaKeys.length;a++){const l=this.alphaKeys[a];(l.time<e||!s)&&(s=l,r=a)}for(let a=0;a<this.colorKeys.length;a++){const l=this.colorKeys[a];(l.time<e||!n)&&(n=l,o=a)}if(n)if(o+1<this.colorKeys.length){const a=this.colorKeys[o+1],l=Je.remap(e,n.time,a.time,0,1);t.r=Je.lerp(n.color.r,a.color.r,l),t.g=Je.lerp(n.color.g,a.color.g,l),t.b=Je.lerp(n.color.b,a.color.b,l)}else t.r=n.color.r,t.g=n.color.g,t.b=n.color.b;if(s)if(r+1<this.alphaKeys.length){const a=this.alphaKeys[r+1],l=Je.remap(e,s.time,a.time,0,1);t.alpha=Je.lerp(s.alpha,a.alpha,l)}else t.alpha=s.alpha;return t}}q([w()],qc.prototype,"alphaKeys",2),q([w()],qc.prototype,"colorKeys",2);var Wb=(i=>(i[i.Local=0]="Local",i[i.World=1]="World",i[i.Custom=2]="Custom",i))(Wb||{}),nU=(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))(nU||{});class tt{constructor(){h(this,"mode"),h(this,"constant"),h(this,"constantMin"),h(this,"constantMax"),h(this,"curve"),h(this,"curveMin"),h(this,"curveMax"),h(this,"curveMultiplier")}evaluate(e,t){const s=t===void 0?Math.random():t;switch(this.mode){case 0:return this.constant;case 1:return e=Je.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:const r=e*this.curveMin.duration,n=e*this.curveMax.duration;return Je.lerp(this.curveMin.evaluate(r),this.curveMax.evaluate(n),s%1)*this.curveMultiplier;case 3:return Je.lerp(this.constantMin,this.constantMax,s%1);default:this.curveMax.evaluate(e)*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(e){if(!e)return 0;let t=Number.MIN_VALUE;for(let s=0;s<e.keys.length;s++){const r=e.keys[s];r.value>t&&(t=r.value)}return t}}q([w()],tt.prototype,"mode",2),q([w()],tt.prototype,"constant",2),q([w()],tt.prototype,"constantMin",2),q([w()],tt.prototype,"constantMax",2),q([w($h)],tt.prototype,"curve",2),q([w($h)],tt.prototype,"curveMin",2),q([w($h)],tt.prototype,"curveMax",2),q([w()],tt.prototype,"curveMultiplier",2);var qb;const Io=(qb=class{constructor(){h(this,"mode"),h(this,"color"),h(this,"colorMin"),h(this,"colorMax"),h(this,"gradient"),h(this,"gradientMin"),h(this,"gradientMax")}evaluate(i,e){const t=e===void 0?Math.random():e;switch(this.mode){case 0:return this.color;case 1:return this.gradient.evaluate(i,Io._temp),Io._temp;case 2:return Io._temp.lerpColors(this.colorMin,this.colorMax,t);case 3:return this.gradientMin.evaluate(i,Io._temp),this.gradientMax.evaluate(i,Io._temp2),Io._temp.lerp(Io._temp2,t)}return Io._temp.set(16711935),Io._temp.alpha=1,Io._temp}},h(qb,"_temp",new vi(0,0,0,1)),h(qb,"_temp2",new vi(0,0,0,1)),qb);let Jr=Io;q([w(vi)],Jr.prototype,"color",2),q([w(vi)],Jr.prototype,"colorMin",2),q([w(vi)],Jr.prototype,"colorMax",2),q([w(qc)],Jr.prototype,"gradient",2),q([w(qc)],Jr.prototype,"gradientMin",2),q([w(qc)],Jr.prototype,"gradientMax",2);class Ws{constructor(){h(this,"cullingMode"),h(this,"duration"),h(this,"emitterVelocityMode"),h(this,"flipRotation"),h(this,"gravityModifier"),h(this,"gravityModifierMultiplier"),h(this,"loop"),h(this,"maxParticles"),h(this,"playOnAwake"),h(this,"prewarm"),h(this,"ringBufferLoopRange"),h(this,"ringBufferMode"),h(this,"scalingMode"),h(this,"simulationSpace"),h(this,"simulationSpeed"),h(this,"startColor"),h(this,"startDelay"),h(this,"startDelayMultiplier"),h(this,"startLifetime"),h(this,"startLifetimeMultiplier"),h(this,"startRotation"),h(this,"startRotationMultiplier"),h(this,"startRotation3D"),h(this,"startRotationX"),h(this,"startRotationXMultiplier"),h(this,"startRotationY"),h(this,"startRotationYMultiplier"),h(this,"startRotationZ"),h(this,"startRotationZMultiplier"),h(this,"startSize"),h(this,"startSize3D"),h(this,"startSizeMultiplier"),h(this,"startSizeX"),h(this,"startSizeXMultiplier"),h(this,"startSizeY"),h(this,"startSizeYMultiplier"),h(this,"startSizeZ"),h(this,"startSizeZMultiplier"),h(this,"startSpeed"),h(this,"startSpeedMultiplier"),h(this,"stopAction"),h(this,"useUnscaledTime")}}q([w(tt)],Ws.prototype,"gravityModifier",2),q([w(Jr)],Ws.prototype,"startColor",2),q([w(tt)],Ws.prototype,"startDelay",2),q([w(tt)],Ws.prototype,"startLifetime",2),q([w(tt)],Ws.prototype,"startRotation",2),q([w(tt)],Ws.prototype,"startRotationX",2),q([w(tt)],Ws.prototype,"startRotationY",2),q([w(tt)],Ws.prototype,"startRotationZ",2),q([w(tt)],Ws.prototype,"startSize",2),q([w(tt)],Ws.prototype,"startSizeX",2),q([w(tt)],Ws.prototype,"startSizeY",2),q([w(tt)],Ws.prototype,"startSizeZ",2),q([w(tt)],Ws.prototype,"startSpeed",2);class Om{constructor(){h(this,"cycleCount"),h(this,"maxCount"),h(this,"minCount"),h(this,"probability"),h(this,"repeatInterval"),h(this,"time"),h(this,"count"),h(this,"_performed",0)}reset(){this._performed=0}run(e){if(e<=this.time)return this.reset(),0;let t=0;if(this.cycleCount===0||this._performed<this.cycleCount){const s=this.time+this.repeatInterval*this._performed;if(e>=s&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=Je.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:const r=Math.random();t=Je.lerp(this.count.curveMin.evaluate(r),this.count.curveMax.evaluate(r),Math.random());break}}return t}}class ua{constructor(){h(this,"enabled"),h(this,"bursts"),h(this,"rateOverTime"),h(this,"rateOverTimeMultiplier"),h(this,"rateOverDistance"),h(this,"rateOverDistanceMultiplier"),h(this,"system")}get burstCount(){var e;return((e=this.bursts)==null?void 0:e.length)??0}reset(){var e;(e=this.bursts)==null||e.forEach(t=>t.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){const s=this.bursts[t];s.time>=this.system.time&&s.reset(),e+=Math.round(s.run(this.system.time))}return e}}q([w()],ua.prototype,"enabled",2),q([w()],ua.prototype,"bursts",2),q([w(tt)],ua.prototype,"rateOverTime",2),q([w()],ua.prototype,"rateOverTimeMultiplier",2),q([w(tt)],ua.prototype,"rateOverDistance",2),q([w()],ua.prototype,"rateOverDistanceMultiplier",2);class Lm{constructor(){h(this,"enabled"),h(this,"color")}}q([w(Jr)],Lm.prototype,"color",2);class Xc{constructor(){h(this,"enabled"),h(this,"separateAxes"),h(this,"size"),h(this,"sizeMultiplier"),h(this,"x"),h(this,"xMultiplier"),h(this,"y"),h(this,"yMultiplier"),h(this,"z"),h(this,"zMultiplier"),h(this,"_time",0),h(this,"_temp",new S)}evaluate(e,t,s){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,s)*this.xMultiplier,t.y=this.y.evaluate(e,s)*this.yMultiplier,t.z=this.z.evaluate(e,s)*this.zMultiplier;else{const r=this.size.evaluate(e,s)*this.sizeMultiplier;t.x=r}return t}}q([w(tt)],Xc.prototype,"size",2),q([w(tt)],Xc.prototype,"x",2),q([w(tt)],Xc.prototype,"y",2),q([w(tt)],Xc.prototype,"z",2);var Xb;const Fm=(Xb=class{constructor(){h(this,"shapeType",5),h(this,"enabled",!0),h(this,"alignToDirection",!1),h(this,"angle",0),h(this,"arc",360),h(this,"arcSpread"),h(this,"arcSpeedMultiplier"),h(this,"arcMode"),h(this,"boxThickness"),h(this,"position"),h(this,"rotation"),h(this,"_rotation",new fs),h(this,"scale"),h(this,"radius"),h(this,"radiusThickness"),h(this,"sphericalDirectionAmount"),h(this,"randomDirectionAmount"),h(this,"randomPositionAmount"),h(this,"system"),h(this,"_space"),h(this,"_worldSpaceMatrix",new Qe),h(this,"_worldSpaceMatrixInverse",new Qe),h(this,"_vector",new S(0,0,0)),h(this,"_temp",new S(0,0,0)),h(this,"_dir",new S),h(this,"_loopTime",0),h(this,"_loopDirection",1),Vb&&console.log(this)}get type(){return nU[this.shapeType]}initialize(i){this.getPosition(),i.position.copy(this._vector)}toJSON(){return this}clone(){return new Fm}update(i,e,t,s){this.system=i,this._space=t,t===1&&(this._worldSpaceMatrix.copy(s.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 e=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return e&&(this._rotation.x=Je.toRadians(this.rotation.x),this._rotation.y=Je.toRadians(this.rotation.y),this._rotation.z=Je.toRadians(this.rotation.z),this._rotation.order="ZYX",i.applyEuler(this._rotation)),e}get vector(){return this._vector}getPosition(){this._vector.set(0,0,0);const i=this._temp.copy(this.position),e=this._space===1;e&&i.applyQuaternion(this.system.worldQuaternion);let t=this.radius;if(e&&(t*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:Vb&&Jo.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,t,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,t,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,t,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),e&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),Vb&&Jo.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(i){var e;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 t=i.x,s=i.y,r=i.z;this._dir.set(t,s,r),(e=this.system)!=null&&e.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),Vb&&(Jo.DrawSphere(i,.01,8925952,.5,!0),Jo.DrawDirection(i,this._dir,8925952,.5,!0)),this._dir}randomizePosition(i,e){if(e<=0)return;const t=Fm._tempVec;t.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),t.x*=e*this.scale.x,t.y*=e*this.scale.y,t.z*=e*this.scale.z,i.add(t)}randomizeDirection(i,e){if(e===0)return;const t=Fm._randomQuat,s=Fm._tempVec;s.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),t.setFromAxisAngle(s,e*Math.random()*Math.PI),i.applyQuaternion(t)}spherizeDirection(i,e){if(e===0)return;const t=Math.random()*Math.PI*2,s=Math.acos(1-Math.random()*2),r=Math.sin(s)*Math.cos(t),n=Math.sin(s)*Math.sin(t),o=Math.cos(s),a=new S(r,n,o);i.lerp(a,e)}randomSpherePoint(i,e,t,s,r){const n=Math.random(),o=Math.random(),a=2*Math.PI*n*(s/360),l=Math.acos(2*o-1),c=Je.lerp(1,1-Math.pow(1-Math.random(),Math.PI),t)*e,u=i.x+this.scale.x*(-c*Math.sin(l)*Math.cos(a)),d=i.y+this.scale.y*(c*Math.sin(l)*Math.sin(a)),p=i.z+this.scale.z*(c*Math.cos(l));r.x=u,r.y=d,r.z=p}randomCirclePoint(i,e,t,s,r){const n=Math.random(),o=2*Math.PI*n*(s/360),a=Je.lerp(1,1-Math.pow(1-Math.random(),Math.PI),t)*e,l=i.x+this.scale.x*a*Math.cos(o),c=i.y+this.scale.y*a*Math.sin(o),u=i.z;r.x=l,r.y=c,r.z=u}randomConePoint(i,e,t,s,r,n,o){let a=0,l=0;switch(n){case 0:a=Math.random(),l=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:a=.5,l=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let c=2*Math.PI*a*(r/360);switch(n){case 2:case 1:c+=Math.PI+.5,c+=this._loopTime*Math.PI*2,c%=Je.toRadians(r);break}const u=Math.acos(2*l-1),d=Je.lerp(1,1-Math.pow(1-Math.random(),Math.PI),s)*t,p=i.x+-d*Math.sin(u)*Math.cos(c),f=i.y+d*Math.sin(u)*Math.sin(c),g=i.z;o.x=p*this.scale.x,o.y=f*this.scale.y,o.z=g*this.scale.z}},h(Xb,"_randomQuat",new xe),h(Xb,"_tempVec",new S),Xb);let $i=Fm;q([w()],$i.prototype,"shapeType",2),q([w()],$i.prototype,"enabled",2),q([w()],$i.prototype,"alignToDirection",2),q([w()],$i.prototype,"angle",2),q([w()],$i.prototype,"arc",2),q([w()],$i.prototype,"arcSpread",2),q([w()],$i.prototype,"arcSpeedMultiplier",2),q([w()],$i.prototype,"arcMode",2),q([w(S)],$i.prototype,"boxThickness",2),q([w(S)],$i.prototype,"position",2),q([w(S)],$i.prototype,"rotation",2),q([w(S)],$i.prototype,"scale",2),q([w()],$i.prototype,"radius",2),q([w()],$i.prototype,"radiusThickness",2),q([w()],$i.prototype,"sphericalDirectionAmount",2),q([w()],$i.prototype,"randomDirectionAmount",2),q([w()],$i.prototype,"randomPositionAmount",2);class hi{constructor(){h(this,"damping"),h(this,"enabled"),h(this,"frequency"),h(this,"octaveCount"),h(this,"octaveMultiplier"),h(this,"octaveScale"),h(this,"positionAmount"),h(this,"quality"),h(this,"remap"),h(this,"remapEnabled"),h(this,"remapMultiplier"),h(this,"remapX"),h(this,"remapXMultiplier"),h(this,"remapY"),h(this,"remapYMultiplier"),h(this,"remapZ"),h(this,"remapZMultiplier"),h(this,"scrollSpeedMultiplier"),h(this,"separateAxes"),h(this,"strengthMultiplier"),h(this,"strengthX"),h(this,"strengthXMultiplier"),h(this,"strengthY"),h(this,"strengthYMultiplier"),h(this,"strengthZ"),h(this,"strengthZMultiplier"),h(this,"_noise"),h(this,"_time",0),h(this,"_temp",new S)}update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}apply(e,t,s,r,n,o){if(!this.enabled)return;this._noise||(this._noise=Qte(()=>0));const a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),l=this._noise(a.x,a.y,a.z,this._time),c=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),u=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(l,c,u).normalize();const d=n/o;let p=this.positionAmount.evaluate(d);this.separateAxes?(this._temp.x*=p*this.strengthXMultiplier,this._temp.y*=p*this.strengthYMultiplier,this._temp.z*=p*this.strengthZMultiplier):(this.strengthX&&(p*=this.strengthX.evaluate(d)*1.5),this._temp.multiplyScalar(p)),s.x+=this._temp.x,s.y+=this._temp.y,s.z+=this._temp.z}}q([w()],hi.prototype,"damping",2),q([w()],hi.prototype,"enabled",2),q([w()],hi.prototype,"frequency",2),q([w()],hi.prototype,"octaveCount",2),q([w()],hi.prototype,"octaveMultiplier",2),q([w()],hi.prototype,"octaveScale",2),q([w(tt)],hi.prototype,"positionAmount",2),q([w()],hi.prototype,"quality",2),q([w(tt)],hi.prototype,"remap",2),q([w()],hi.prototype,"remapEnabled",2),q([w()],hi.prototype,"remapMultiplier",2),q([w(tt)],hi.prototype,"remapX",2),q([w()],hi.prototype,"remapXMultiplier",2),q([w(tt)],hi.prototype,"remapY",2),q([w()],hi.prototype,"remapYMultiplier",2),q([w(tt)],hi.prototype,"remapZ",2),q([w()],hi.prototype,"remapZMultiplier",2),q([w()],hi.prototype,"scrollSpeedMultiplier",2),q([w()],hi.prototype,"separateAxes",2),q([w()],hi.prototype,"strengthMultiplier",2),q([w(tt)],hi.prototype,"strengthX",2),q([w()],hi.prototype,"strengthXMultiplier",2),q([w(tt)],hi.prototype,"strengthY",2),q([w()],hi.prototype,"strengthYMultiplier",2),q([w(tt)],hi.prototype,"strengthZ",2),q([w()],hi.prototype,"strengthZMultiplier",2);class Ti{constructor(){h(this,"enabled"),h(this,"attachRibbonToTransform",!1),h(this,"colorOverLifetime"),h(this,"colorOverTrail"),h(this,"dieWithParticles",!0),h(this,"inheritParticleColor",!0),h(this,"lifetime"),h(this,"lifetimeMultiplier"),h(this,"minVertexDistance",.2),h(this,"mode",0),h(this,"ratio",1),h(this,"ribbonCount",1),h(this,"shadowBias",0),h(this,"sizeAffectsLifetime",!1),h(this,"sizeAffectsWidth",!1),h(this,"splitSubEmitterRibbons",!1),h(this,"textureMode",0),h(this,"widthOverTrail"),h(this,"widthOverTrailMultiplier"),h(this,"worldSpace",!1)}getWidth(e,t,s){let r=this.widthOverTrail.evaluate(s);return s===0&&(r=e),e*=r,e}getColor(e,t,s){const r=this.colorOverTrail.evaluate(s),n=this.colorOverLifetime.evaluate(t);e.x*=r.r*n.r,e.y*=r.g*n.g,e.z*=r.b*n.b,e.w*=r.alpha*n.alpha}}q([w()],Ti.prototype,"enabled",2),q([w()],Ti.prototype,"attachRibbonToTransform",2),q([w(Jr)],Ti.prototype,"colorOverLifetime",2),q([w(Jr)],Ti.prototype,"colorOverTrail",2),q([w()],Ti.prototype,"dieWithParticles",2),q([w()],Ti.prototype,"inheritParticleColor",2),q([w(tt)],Ti.prototype,"lifetime",2),q([w()],Ti.prototype,"lifetimeMultiplier",2),q([w()],Ti.prototype,"minVertexDistance",2),q([w()],Ti.prototype,"mode",2),q([w()],Ti.prototype,"ratio",2),q([w()],Ti.prototype,"ribbonCount",2),q([w()],Ti.prototype,"shadowBias",2),q([w()],Ti.prototype,"sizeAffectsLifetime",2),q([w()],Ti.prototype,"sizeAffectsWidth",2),q([w()],Ti.prototype,"splitSubEmitterRibbons",2),q([w()],Ti.prototype,"textureMode",2),q([w(tt)],Ti.prototype,"widthOverTrail",2),q([w()],Ti.prototype,"widthOverTrailMultiplier",2),q([w()],Ti.prototype,"worldSpace",2);class Fi{constructor(){h(this,"enabled"),h(this,"space",0),h(this,"orbitalX"),h(this,"orbitalY"),h(this,"orbitalZ"),h(this,"orbitalXMultiplier"),h(this,"orbitalYMultiplier"),h(this,"orbitalZMultiplier"),h(this,"orbitalOffsetX"),h(this,"orbitalOffsetY"),h(this,"orbitalOffsetZ"),h(this,"speedModifier"),h(this,"speedModifierMultiplier"),h(this,"x"),h(this,"xMultiplier"),h(this,"y"),h(this,"yMultiplier"),h(this,"z"),h(this,"zMultiplier"),h(this,"_system"),h(this,"_temp",new S),h(this,"_temp2",new S),h(this,"_temp3",new S),h(this,"_hasOrbital",!1),h(this,"_index",0),h(this,"_orbitalMatrix",new Qe)}update(e){this._system=e}init(e){this._index==0&&(e.debug=!0),this._index+=1,e.orbitx=this.orbitalX.evaluate(Math.random()),e.orbity=this.orbitalY.evaluate(Math.random()),e.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=e.orbitx!=0||e.orbity!=0||e.orbitz!=0}apply(e,t,s,r,n,o,a){var l;if(!this.enabled)return;const c=o/a,u=this.speedModifier.evaluate(c)*this.speedModifierMultiplier,d=this.x.evaluate(c),p=this.y.evaluate(c),f=this.z.evaluate(c);if(this._temp.set(-d,p,f),this._system,this._hasOrbital&&((l=this._system)==null?void 0:l.worldPos)){const g=this._temp2.set(s.x,s.y,s.z),m=this.orbitalXMultiplier,v=this.orbitalYMultiplier,A=this.orbitalZMultiplier,b=u*Math.PI*2*10,y=Math.cos(b*m),_=Math.sin(b*m),x=Math.cos(b*v),M=Math.sin(b*v),P=Math.cos(b*A),C=Math.sin(b*A),R=g.x*(x*P)+g.y*(x*C)+g.z*-M,T=g.x*(_*M*P-y*C)+g.y*(_*M*C+y*P)+g.z*(_*x),z=g.x*(y*M*P+_*C)+g.y*(y*M*C-_*P)+g.z*(y*x),G=this._temp3.set(g.x-R,g.y-T,g.z-z);G.normalize(),G.multiplyScalar(.2/n*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),r.x+=G.x,r.y+=G.y,r.z+=G.z}r.x+=this._temp.x,r.y+=this._temp.y,r.z+=this._temp.z,r.x*=u,r.y*=u,r.z*=u}}q([w()],Fi.prototype,"enabled",2),q([w()],Fi.prototype,"space",2),q([w(tt)],Fi.prototype,"orbitalX",2),q([w(tt)],Fi.prototype,"orbitalY",2),q([w(tt)],Fi.prototype,"orbitalZ",2),q([w()],Fi.prototype,"orbitalXMultiplier",2),q([w()],Fi.prototype,"orbitalYMultiplier",2),q([w()],Fi.prototype,"orbitalZMultiplier",2),q([w()],Fi.prototype,"orbitalOffsetX",2),q([w()],Fi.prototype,"orbitalOffsetY",2),q([w()],Fi.prototype,"orbitalOffsetZ",2),q([w(tt)],Fi.prototype,"speedModifier",2),q([w()],Fi.prototype,"speedModifierMultiplier",2),q([w(tt)],Fi.prototype,"x",2),q([w()],Fi.prototype,"xMultiplier",2),q([w(tt)],Fi.prototype,"y",2),q([w()],Fi.prototype,"yMultiplier",2),q([w(tt)],Fi.prototype,"z",2),q([w()],Fi.prototype,"zMultiplier",2);class qs{constructor(){h(this,"animation"),h(this,"enabled"),h(this,"cycleCount"),h(this,"frameOverTime"),h(this,"frameOverTimeMultiplier"),h(this,"numTilesX"),h(this,"numTilesY"),h(this,"startFrame"),h(this,"startFrameMultiplier"),h(this,"rowMode"),h(this,"rowIndex"),h(this,"spriteCount"),h(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(e){if(!this.sampleOnceAtStart())return this.getIndex(e)}getIndex(e){const t=this.numTilesX*this.numTilesY;e=e*this.cycleCount;let s=this.frameOverTime.evaluate(e%1);return s*=this.frameOverTimeMultiplier,s*=t,s=s%t,s=Math.floor(s),s}}q([w()],qs.prototype,"animation",2),q([w()],qs.prototype,"enabled",2),q([w()],qs.prototype,"cycleCount",2),q([w(tt)],qs.prototype,"frameOverTime",2),q([w()],qs.prototype,"frameOverTimeMultiplier",2),q([w()],qs.prototype,"numTilesX",2),q([w()],qs.prototype,"numTilesY",2),q([w(tt)],qs.prototype,"startFrame",2),q([w()],qs.prototype,"startFrameMultiplier",2),q([w()],qs.prototype,"rowMode",2),q([w()],qs.prototype,"rowIndex",2),q([w()],qs.prototype,"spriteCount",2),q([w()],qs.prototype,"timeMode",2);class Xn{constructor(){h(this,"enabled"),h(this,"separateAxes"),h(this,"x"),h(this,"xMultiplier"),h(this,"y"),h(this,"yMultiplier"),h(this,"z"),h(this,"zMultiplier")}evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}q([w()],Xn.prototype,"enabled",2),q([w()],Xn.prototype,"separateAxes",2),q([w(tt)],Xn.prototype,"x",2),q([w()],Xn.prototype,"xMultiplier",2),q([w(tt)],Xn.prototype,"y",2),q([w()],Xn.prototype,"yMultiplier",2),q([w(tt)],Xn.prototype,"z",2),q([w()],Xn.prototype,"zMultiplier",2);class vn{constructor(){h(this,"enabled"),h(this,"range"),h(this,"separateAxes"),h(this,"x"),h(this,"xMultiplier"),h(this,"y"),h(this,"yMultiplier"),h(this,"z"),h(this,"zMultiplier")}evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const s=Je.lerp(this.range.x,this.range.y,t);return this.z.evaluate(s)*-1}return 0}}q([w()],vn.prototype,"enabled",2),q([w()],vn.prototype,"range",2),q([w()],vn.prototype,"separateAxes",2),q([w(tt)],vn.prototype,"x",2),q([w()],vn.prototype,"xMultiplier",2),q([w(tt)],vn.prototype,"y",2),q([w()],vn.prototype,"yMultiplier",2),q([w(tt)],vn.prototype,"z",2),q([w()],vn.prototype,"zMultiplier",2);class us{constructor(){h(this,"enabled"),h(this,"dampen"),h(this,"drag"),h(this,"dragMultiplier"),h(this,"limit"),h(this,"limitMultiplier"),h(this,"separateAxes"),h(this,"limitX"),h(this,"limitXMultiplier"),h(this,"limitY"),h(this,"limitYMultiplier"),h(this,"limitZ"),h(this,"limitZMultiplier"),h(this,"multiplyDragByParticleSize",!1),h(this,"multiplyDragByParticleVelocity",!1),h(this,"space"),h(this,"_temp",new S),h(this,"_temp2",new S)}apply(e,t,s,r,n,o,a){if(this.enabled){const l=this.limit.evaluate(n)*this.limitMultiplier;if(t.length()>l){this._temp.copy(t).normalize().multiplyScalar(l);let c=this.dampen*.5;t.x=Je.lerp(t.x,this._temp.x,c),t.y=Je.lerp(t.y,this._temp.y,c),t.z=Je.lerp(t.z,this._temp.z,c),s.x=Je.lerp(s.x,this._temp.x,c),s.y=Je.lerp(s.y,this._temp.y,c),s.z=Je.lerp(s.z,this._temp.z,c)}}}}q([w()],us.prototype,"enabled",2),q([w()],us.prototype,"dampen",2),q([w(tt)],us.prototype,"drag",2),q([w()],us.prototype,"dragMultiplier",2),q([w(tt)],us.prototype,"limit",2),q([w()],us.prototype,"limitMultiplier",2),q([w()],us.prototype,"separateAxes",2),q([w(tt)],us.prototype,"limitX",2),q([w()],us.prototype,"limitXMultiplier",2),q([w(tt)],us.prototype,"limitY",2),q([w()],us.prototype,"limitYMultiplier",2),q([w(tt)],us.prototype,"limitZ",2),q([w()],us.prototype,"limitZMultiplier",2),q([w()],us.prototype,"multiplyDragByParticleSize",2),q([w()],us.prototype,"multiplyDragByParticleVelocity",2),q([w()],us.prototype,"space",2);class Yc{constructor(){h(this,"enabled"),h(this,"curve"),h(this,"curveMultiplier"),h(this,"mode"),h(this,"system"),h(this,"_lastWorldPosition"),h(this,"_velocity",new S),h(this,"_temp",new S)}update(e){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(e){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const t=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(t),e.add(this._temp)}}applyCurrent(e,t,s){if(this.enabled&&this.system.worldspace!==!1&&this.mode===1){const r=this.curve.evaluate(t,s);this._temp.copy(this._velocity).multiplyScalar(r),e.add(this._temp)}}}q([w()],Yc.prototype,"enabled",2),q([w(tt)],Yc.prototype,"curve",2),q([w()],Yc.prototype,"curveMultiplier",2),q([w()],Yc.prototype,"mode",2);class Dr{constructor(){h(this,"enabled"),h(this,"range"),h(this,"separateAxes"),h(this,"size"),h(this,"sizeMultiplier"),h(this,"x"),h(this,"xMultiplier"),h(this,"y"),h(this,"yMultiplier"),h(this,"z"),h(this,"zMultiplier")}evaluate(e,t,s,r){const n=e.length(),o=Je.remap(n,this.range.x,this.range.y,0,1),a=this.size.evaluate(o,s);return r*a}}q([w()],Dr.prototype,"enabled",2),q([w(W)],Dr.prototype,"range",2),q([w()],Dr.prototype,"separateAxes",2),q([w(tt)],Dr.prototype,"size",2),q([w()],Dr.prototype,"sizeMultiplier",2),q([w(tt)],Dr.prototype,"x",2),q([w()],Dr.prototype,"xMultiplier",2),q([w(tt)],Dr.prototype,"y",2),q([w()],Dr.prototype,"yMultiplier",2),q([w(tt)],Dr.prototype,"z",2),q([w()],Dr.prototype,"zMultiplier",2);class fu{constructor(){h(this,"enabled"),h(this,"range"),h(this,"color")}evaluate(e,t,s){const r=e.length(),n=Je.remap(r,this.range.x,this.range.y,0,1),o=this.color.evaluate(n,t);s.x*=o.r,s.y*=o.g,s.z*=o.b,s.w*=o.alpha}}q([w()],fu.prototype,"enabled",2),q([w(W)],fu.prototype,"range",2),q([w(Jr)],fu.prototype,"color",2);function Vte(i){const e=i.domElement.querySelector("link[rel='ar']");if(e)return e;const t=document.createElement("div");t.classList.add("menu"),t.classList.add("quicklook-menu"),t.style.display="none",t.style.visibility="hidden";const s=document.createElement("button");s.id="open-in-ar",s.innerText="Open in QuickLook",t.appendChild(s);const r=document.createElement("a");r.id="needle-usdz-link",r.style.display="none",r.rel="ar",r.href="",t.appendChild(r);const n=document.createElement("img");return n.id="button",r.appendChild(n),i.domElement.appendChild(t),r}function Wte(){var i=new Date;const e=i.getMonth()+1,t=i.getDate(),s=i.getHours(),r=i.getMinutes(),n=i.getSeconds(),o=(e<10?"0":"")+e,a=(t<10?"0":"")+t,l=(s<10?"0":"")+s,c=(r<10?"0":"")+r,u=(n<10?"0":"")+n;return i.getFullYear()+o+a+"-"+l+c+u}const Yb=oe("debugusdz");function qte(i,e){const t=[],s=$.getComponentsInChildren(i,Gr);let r=!1;Yb&&console.log(s);for(const n of s){if(!n||!n.runtimeAnimatorController)continue;Yb&&console.log(n);const o=[];for(const a of n.runtimeAnimatorController.enumerateActions()){Yb&&console.log(a);const l=a.getClip();if(!r&&l.tracks.length>0){r=!0;const c=l.tracks[0],u=c.name.substring(0,c.name.lastIndexOf(".")),d=new hn(u+".position",[0,.01],[0,0,0,0,0,0]),p=new hn(u+".quaternion",[0,.01],[0,0,0,1,0,0,0,1]);o.push(new Bn("rest",.01,[d,p]))}o.includes(l)||o.push(l)}t.push({root:n.gameObject,clips:o})}Yb&&console.log(t);for(const n of t)for(const o of n.clips)e.registerAnimation(n.root,o)}var Xte=Object.defineProperty,Yte=Object.getOwnPropertyDescriptor,Tl=(i,e,t,s)=>{for(var r=s>1?void 0:s?Yte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Xte(e,t,r),r};const aM=oe("debugtext");var Es=(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))(Es||{});class Or extends hu{constructor(){super(...arguments),h(this,"alignment",0),h(this,"verticalOverflow",0),h(this,"horizontalOverflow",0),h(this,"lineSpacing",1),h(this,"supportRichText",!1),h(this,"font"),h(this,"fontStyle",0),h(this,"_text",""),h(this,"_fontSize",12),h(this,"_textMeshUi",null),h(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 e;const t=(e=this.uiObject)==null?void 0:e._overflow;t&&(t._needsUpdate=!0,this.markDirty())}onCreate(e){aM&&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,aM&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),aM&&(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 s,r,n;if(!this.uiObject)return null;if(this._textMeshUi||(this._textMeshUi=[]),!t||e.length===0)this.uiObject.textContent=e;else{let o=this.getNextTag(e);if(o)o.startIndex>0&&this.uiObject.add(new bb({textContent:e.substring(0,o.startIndex),color:"inherit"}));else return this.uiObject.textContent=e;const a=[];for(;o;){const l=this.getNextTag(e,o.endIndex),c={fontFamily:(s=this.uiObject)==null?void 0:s.get("fontFamily"),color:"inherit",textContent:""};l?(c.textContent=this.getText(e,o,l),this.handleTag(o,c,a),(r=this.uiObject)==null||r.add(new bb(c))):(c.textContent=e.substring(o.endIndex),this.handleTag(o,c,a),(n=this.uiObject)==null||n.add(new bb(c))),o=l}}return null}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,s={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let r=!1;if(this._textMeshUi)for(let n=0;n<this._textMeshUi.length;n++){if(e[n]===!0)continue;r=!0;const o=this._textMeshUi[n];o.textContent&&(Lb(o,s),e[n]=!0)}if(!r)break;yield}}handleTag(e,t,s){if(e.isEndTag){if(s.length>0){const r=s.pop();if(r)for(const n in r.previousValues){const o=r.previousValues[n];t[n]=o}}}else if(e.type.includes("color")){const r=new lM(e,{color:t.color});if(s.push(r),e.type.length>6){const n=parseInt("0x"+e.type.substring(7));t.color=n}else t.color=new _e(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const r=new lM(e,{fontWeight:700});s.push(r)}else if(e.type=="i"){this.setFont(t,2);const r=new lM(e,{fontStyle:"italic"});s.push(r)}}getText(e,t,s){return e.substring(t.endIndex,s.startIndex)}getNextTag(e,t=0){const s=e.indexOf("<",t),r=e.indexOf(">",s);if(s>=0&&r>=0){const n=e.substring(s+1,r);return{type:n,startIndex:s,endIndex:r+1,isEndTag:n.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;let s=this.font,r=IE.getFontFamily(s);r||(r=IE.addFontFamily(s)),e.fontFamily=r;const n=s.toLowerCase();switch(t){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal",n.includes("-bold")||(s+="-bold");break;case 2:e.fontWeight=400,e.fontStyle="italic",n.includes("-italic")||(s+="-italic");break;case 3:e.fontStyle="italic",e.fontWeight=400,n.includes("-bold")||(s+="-bold"),n.includes("-italic")||(s+="-italic")}let o=r.getVariant(e.fontWeight,e.fontStyle);if(!o){let a=s;a!=null&&a.endsWith("-msdf.json")||(a+="-msdf.json");let l=s;l!=null&&l.endsWith(".png")||(l+=".png"),o=r.addVariant(e.fontWeight,e.fontStyle,a,l),o?.addEventListener("ready",()=>{this.markDirty()})}}}Tl([w()],Or.prototype,"alignment",2),Tl([w()],Or.prototype,"verticalOverflow",2),Tl([w()],Or.prototype,"horizontalOverflow",2),Tl([w()],Or.prototype,"lineSpacing",2),Tl([w()],Or.prototype,"supportRichText",2),Tl([w(URL)],Or.prototype,"font",2),Tl([w()],Or.prototype,"fontStyle",2),Tl([w()],Or.prototype,"text",1),Tl([w()],Or.prototype,"fontSize",1);class lM{constructor(e,t){h(this,"tag"),h(this,"previousValues"),this.tag=e,this.previousValues=t}}class Jc{constructor(e){h(this,"id"),h(this,"content",""),h(this,"font",[]),h(this,"pointSize",144),h(this,"width"),h(this,"height"),h(this,"depth"),h(this,"wrapMode"),h(this,"horizontalAlignment"),h(this,"verticalAlignment"),h(this,"material"),this.id=e}static getId(){return this.global_id++}setDepth(e){return this.depth=e,this}setPointSize(e){return this.pointSize=e,this}setHorizontalAlignment(e){return this.horizontalAlignment=e,this}setVerticalAlignment(e){return this.verticalAlignment=e,this}writeTo(e,t){var s;t.beginBlock(`def Preliminary_Text "${this.id}"`),this.content&&t.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(s=this.font)==null||s.push("sans-serif"));const r=this.font.map(n=>`"${n}"`).join(", ");t.appendLine(`string[] font = [ ${r} ]`),t.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&t.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&t.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&t.appendLine(`double depth = ${this.depth}`),this.wrapMode&&t.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&t.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&t.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&t.appendLine(`rel material:binding = </Materials/Material_${this.material.id}>`),t.closeBlock()}}h(Jc,"global_id",0);class Jb{static singleLine(e,t,s){const r=new Jc("text_"+Jc.getId());return r.content=e,t&&(r.pointSize=t),s&&(r.depth=s),r}static multiLine(e,t,s,r,n,o){const a=new Jc("text_"+Jc.getId());return a.content=e,a.width=t,a.height=s,a.horizontalAlignment=r,a.verticalAlignment=n,o!==void 0&&(a.wrapMode=o),a}}const Jte=new Qe().makeRotationY(Math.PI);class Kb{get extensionName(){return"text"}onExportObject(e,t,s){const r=$.getComponent(e,Or);if(r){const n=$.getComponent(e,ur);let o=100,a=100;n&&(o=n.width,a=n.height);const l=t.clone();l.matrix=Jte.clone();const c=new _e().copySRGBToLinear(r.color);l.material=new Mh({color:c,emissive:c}),t.add(l),l.addEventListener("serialize",(u,d)=>{const p=Jb.multiLine(r.text,o,a,"center","bottom","flowing");this.setTextAlignment(p,r.alignment),this.setOverflow(p,r),l.material&&(p.material=l.material),p.pointSize=this.convertToTextSize(r.fontSize),p.depth=.001,p.writeTo(void 0,u)})}}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case Es.LowerLeft:case Es.MiddleLeft:case Es.UpperLeft:e.horizontalAlignment="left";break;case Es.LowerCenter:case Es.MiddleCenter:case Es.UpperCenter:e.horizontalAlignment="center";break;case Es.LowerRight:case Es.MiddleRight:case Es.UpperRight:e.horizontalAlignment="right";break}switch(t){case Es.LowerLeft:case Es.LowerCenter:case Es.LowerRight:e.verticalAlignment="bottom";break;case Es.MiddleLeft:case Es.MiddleCenter:case Es.MiddleRight:e.verticalAlignment="middle";break;case Es.UpperLeft:case Es.UpperCenter:case Es.UpperRight:e.verticalAlignment="top";break}}}var Kte=Object.defineProperty,Zte=Object.getOwnPropertyDescriptor,Yn=(i,e,t,s)=>{for(var r=s>1?void 0:s?Zte(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&Kte(e,t,r),r};const da=oe("debugusdz");class Kc{constructor(){h(this,"callToAction"),h(this,"checkoutTitle"),h(this,"checkoutSubtitle"),h(this,"callToActionURL")}}Yn([w()],Kc.prototype,"callToAction",2),Yn([w()],Kc.prototype,"checkoutTitle",2),Yn([w()],Kc.prototype,"checkoutSubtitle",2),Yn([w()],Kc.prototype,"callToActionURL",2);class Jn extends Ee{constructor(){super(...arguments),h(this,"objectToExport"),h(this,"autoExportAnimations",!1),h(this,"exportFileName"),h(this,"customUsdzFile"),h(this,"customBranding"),h(this,"anchoringType","plane"),h(this,"planeAnchoringAlignment","horizontal"),h(this,"interactive",!0),h(this,"extensions",[]),h(this,"link"),h(this,"webxr"),h(this,"webARSessionRoot"),h(this,"lastCallback"),h(this,"_quicklookButton"),h(this,"_quicklookButtonContainer",null)}start(){var e,t,s,r;da&&(console.log(this),console.log("Debug USDZ, press 't' to export"),window.addEventListener("keydown",n=>{switch(n.key){case"t":this.exportAsync();break}}),lh()&&setTimeout(()=>{this.exportAsync()},2e3)),(e=document.getElementById("open-in-ar"))==null||e.addEventListener("click",n=>{n.preventDefault(),this.exportAsync()}),this.objectToExport||(this.objectToExport=this.gameObject),!((s=(t=this.objectToExport)==null?void 0:t.children)!=null&&s.length)&&!((r=this.objectToExport)!=null&&r.isMesh)&&(this.objectToExport=this.context.scene),this.interactive&&(this.extensions.push(new Ob),this.extensions.push(new kb),this.extensions.push(new Kb))}onEnable(){const e=ff(),t=Pa();(da||e&&t)&&(this.addQuicklookButton(),this.webARSessionRoot=$.findObjectOfType(Dc)??void 0,this.lastCallback=this.quicklookCallback.bind(this),this.link=Vte(this.context),this.link.addEventListener("message",this.lastCallback)),da&&Rs("USDZ Exporter enabled: "+this.name)}onDisable(){var e;(e=this.link)==null||e.removeEventListener("message",this.lastCallback);const t=ff(),s=Pa();(da||t&&s)&&this.removeQuicklookButton(),da&&Rs("USDZ Exporter disabled: "+this.name)}async exportAsync(){var e;let t=this.exportFileName??((e=this.objectToExport)==null?void 0:e.name)??this.name;if(Ac()||(t+="-MadeWithNeedle"),t+="-"+Wte(),this.customUsdzFile){const f=this.buildQuicklookOverlay();da&&console.log(f);const g=f.callToAction?encodeURIComponent(f.callToAction):"",m=f.checkoutTitle?encodeURIComponent(f.checkoutTitle):"",v=f.checkoutSubtitle?encodeURIComponent(f.checkoutSubtitle):"";this.link.href=this.customUsdzFile+`#callToAction=${g}&checkoutTitle=${m}&checkoutSubtitle=${v}&callToActionURL=${f.callToActionURL}`,console.log(this.link.href),this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=t+".usdz",this.link.click();return}if(!this.objectToExport)return;if(this.webARSessionRoot){const f=this.webARSessionRoot.gameObject,g=1/this.webARSessionRoot.arScale;f.matrix.makeScale(g,g,g),this.webARSessionRoot.invertForward&&f.matrix.multiply(new Qe().makeRotationY(Math.PI))}const s=new hY,r=[...this.extensions],n=new Xy;r.push(n),this.autoExportAnimations&&qte(this.objectToExport,n);const o={self:this,exporter:s,extensions:r,object:this.objectToExport};this.dispatchEvent(new CustomEvent("before-export",{detail:o})),s.debug=da,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 a=await s.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:r,quickLookCompatible:!0}),l=new Blob([a],{type:"application/octet-stream"});this.dispatchEvent(new CustomEvent("after-export",{detail:o}));const c=this.buildQuicklookOverlay();da&&console.log(c);const u=c.callToAction?encodeURIComponent(c.callToAction):"",d=c.checkoutTitle?encodeURIComponent(c.checkoutTitle):"",p=c.checkoutSubtitle?encodeURIComponent(c.checkoutSubtitle):"";this.link.href=URL.createObjectURL(l)+`#callToAction=${u}&checkoutTitle=${d}&checkoutSubtitle=${p}&callToActionURL=${c.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=t+".usdz",this.link.click()}quicklookCallback(e){if(e?.data=="_apple_ar_quicklook_button_tapped"){da&&uo("Quicklook closed via call to action button");var t=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(t),!t.defaultPrevented){const s=new URLSearchParams(this.link.href);if(s){const r=s.get("callToActionURL");da&&Rs("Quicklook url: "+r),r&&(Ac()?globalThis.open(r,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",r))}}}}buildQuicklookOverlay(){var e,t,s;const r={};return this.customBranding&&Object.assign(r,this.customBranding),Ac()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),r.callToAction="Close",r.checkoutTitle="\u{1F335} Made with Needle",r.checkoutSubtitle="_"),(e=r.callToAction)!=null&&e.length||(r.callToAction="Close"),(t=r.checkoutTitle)!=null&&t.length||(r.checkoutTitle="\u{1F335} Made with Needle"),(s=r.checkoutSubtitle)!=null&&s.length||(r.checkoutSubtitle="_"),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:r})),r}async createQuicklookButton(){var e,t;if(!this.webxr)if(await pf(1),this.webxr=$.findObjectOfType(xt)??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 s=(t=this.webxr.ARButton.parentElement)==null?void 0:t.querySelector("a");s&&(s.href=""),this.webxr.ARButton.innerText="Open in Quicklook",this.webxr.ARButton.disabled=!1,this.webxr.ARButton.addEventListener("click",r=>{r.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 s=window.document.querySelector(".webxr-buttons");s||(s=document.createElement("div"),s.classList.add("webxr-buttons"));const r=document.createElement("button");r.innerText="Open in Quicklook",r.addEventListener("click",()=>{this.exportAsync()}),r.classList.add("webxr-ar-button"),r.classList.add("webxr-button"),r.classList.add("quicklook-ar-button"),s.appendChild(r),this._quicklookButtonContainer=s,this.dispatchEvent(new CustomEvent("created-button",{detail:r}))}else console.warn("Could not find WebXR component: will not create Quicklook button",_t.Current)}async addQuicklookButton(){await this.createQuicklookButton(),this._quicklookButton&&this._quicklookButtonContainer&&this._quicklookButtonContainer.appendChild(this._quicklookButton)}removeQuicklookButton(){var e;(e=this._quicklookButton)==null||e.remove()}}Yn([w(Me)],Jn.prototype,"objectToExport",2),Yn([w()],Jn.prototype,"autoExportAnimations",2),Yn([w()],Jn.prototype,"exportFileName",2),Yn([w(URL)],Jn.prototype,"customUsdzFile",2),Yn([w(Kc)],Jn.prototype,"customBranding",2),Yn([w()],Jn.prototype,"anchoringType",2),Yn([w()],Jn.prototype,"planeAnchoringAlignment",2),Yn([w()],Jn.prototype,"interactive",2);const oU=oe("debugdeletable");class Zb extends Ko{}class cM extends Ee{constructor(){super(...arguments),h(this,"deleteBoxes",[])}awake(){this.deleteBoxes=$.findObjectsOfType(Zb,this.context)}update(){for(const e of this.deleteBoxes){const t=this.gameObject;if(e.isInBox(t)===!0){const s=$.getComponentInParent(this.gameObject,rp);s?oU&&console.warn("Can not delete object with usage marker",this.guid,s):(oU&&console.log("DESTROY",this.gameObject),Y0(this.gameObject,this.context.connection))}}}}var $te=Object.defineProperty,eie=Object.getOwnPropertyDescriptor,gu=(i,e,t,s)=>{for(var r=s>1?void 0:s?eie(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&$te(e,t,r),r};class To extends kr{constructor(){super(...arguments),h(this,"mode"),h(this,"focusDistance"),h(this,"focalLength"),h(this,"aperture"),h(this,"gaussianMaxRadius"),h(this,"resolutionScale"),h(this,"bokehScale")}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=t=>{const s=t/300,r=2;return Je.lerp(r,.01,s)};const e=20;this.aperture.valueProcessor=t=>{const s=1-t/32;return Je.lerp(1,e,s)}}onCreateEffect(){if(this.mode===0)return;const e=1/window.devicePixelRatio;if(this.resolutionScale===void 0){let s=1;lh()&&(s=.6),this.resolutionScale=new Dt(s*e)}const t=new nD(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=s=>{t.circleOfConfusionMaterial.worldFocusDistance=s},this.focalLength.onValueChanged=s=>t.circleOfConfusionMaterial.worldFocusRange=s,this.aperture.onValueChanged=s=>t.bokehScale=s,this.resolutionScale&&(this.resolutionScale.onValueChanged=s=>t.resolution.scale=s),[t]}unapply(){}}gu([w()],To.prototype,"mode",2),gu([w(Dt)],To.prototype,"focusDistance",2),gu([w(Dt)],To.prototype,"focalLength",2),gu([w(Dt)],To.prototype,"aperture",2),gu([w(Dt)],To.prototype,"gaussianMaxRadius",2),gu([w(Dt)],To.prototype,"resolutionScale",2),gu([w(Dt)],To.prototype,"bokehScale",2),oa("DepthOfField",To);var tie=Object.defineProperty,iie=Object.getOwnPropertyDescriptor,sie=(i,e,t,s)=>{for(var r=s>1?void 0:s?iie(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&tie(e,t,r),r};class $b extends Ee{constructor(){super(...arguments),h(this,"visibleOn")}onEnable(){this.apply()}apply(){this.test()||$.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:rie()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}sie([w()],$b.prototype,"visibleOn",2);let e_;function rie(){if(e_===!0||e_===!1)return e_;let i=!1;return function(e){(/(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(e)||/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(e.substr(0,4)))&&(i=!0)}(navigator.userAgent||navigator.vendor||window.opera),e_=i,i}class hM{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}var aU=(i=>(i.SelectStart="selectstart",i.SelectEnd="selectend",i))(aU||{});const Zc=class extends sp{constructor(){super(),h(this,"transformSelf",!0),h(this,"orbit",null),h(this,"selectStartEventListener",[]),h(this,"selectEndEventListener",[]),h(this,"_dragHelper",null),h(this,"_draggingRigidbodies",[]),h(this,"_waitingForDragStart",null),h(this,"_isDragging",!1),h(this,"_marker",null),h(this,"_dragDelta"),h(this,"_didDrag",!1),h(this,"_activePointerId"),this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new W}static get HasAnySelected(){return this._active>0}addDragEventListener(i,e){switch(i){case"selectstart":this.selectStartEventListener.push(e);break;case"selectend":this.selectEndEventListener.push(e);break}}start(){this.orbit=$.findObjectOfType(Cl,this.context)}allowEdit(i=null){return this.context.connection.allowEditing}onPointerEnter(i){if(!this.allowEdit(this.gameObject)||xt.IsInWebXR)return;const e=$.getComponentInParent(i.object,Zc);!e||e!==this||(Zc.lastHovered=i.object,this.context.domElement.style.cursor="pointer")}onPointerExit(i){this.allowEdit(this.gameObject)&&(xt.IsInWebXR||Zc.lastHovered===i.object&&(this.context.domElement.style.cursor="auto"))}onPointerDown(i){this.allowEdit(this.gameObject)&&(xt.IsInWebXR||(Zc._active+=1,this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=i,i.StopPropagation(),this.orbit&&(this.orbit.enabled=!1)))}onPointerUp(i){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&(Zc._active>0&&(Zc._active-=1),!xt.IsInWebXR&&(this.onDragEnd(i),i.StopPropagation(),this.orbit&&(this.orbit.enabled=!0)))}update(){var i;if(!xt.IsInWebXR){if(this._waitingForDragStart){if(!this._didDrag){const t=this.context.input.getPointerPositionDelta(0);if(t&&this._dragDelta.add(t),this._dragDelta.length()>2)this._didDrag=!0;else return}const e=this._waitingForDragStart;this._waitingForDragStart=null,this.onDragStart(e)}this._dragHelper&&this._dragHelper.hasSelected&&this.onUpdateDrag(),(((i=this._dragHelper)==null?void 0:i.hasSelected)===!1||this._activePointerId!==void 0&&this.context.input.getPointerPressed(this._activePointerId)===!1)&&this.onDragEnd(null)}}onDragStart(i){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new cU(this.context.mainCamera);else return;if(!i||!i.object)return;const e=$.getComponentInParent(i.object,Zc);if(!e||e!==this)return;let t=i.object;this.transformSelf&&(t=this.gameObject);const s={selected:t,attached:t};for(const a of this.selectStartEventListener)a(this,s);if(this._activePointerId=i.pointerId,!s.attached)return;s.attached,t=s.attached,this._isDragging=!0,this._dragHelper.setSelected(t,this.context),this.orbit&&(this.orbit.enabled=!1);const r=$.getComponentInChildren(t,Uc);r&&(r.fastMode=!0,r?.requestOwnership()),this._marker=$.addNewComponent(t,rp),this._draggingRigidbodies.length=0;const n=$.getComponentsInChildren(t,Li);n&&this._draggingRigidbodies.push(...n);const o=zv();$.invokeOnChildren(this._dragHelper.selected,o("onDragStart"))}onUpdateDrag(){if(this._dragHelper){this._dragHelper.onUpdate(this.context);for(const i of this._draggingRigidbodies)i.wakeUp(),i.resetVelocities()}}onDragEnd(i){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;for(const s of this._draggingRigidbodies)s.setVelocity(s.smoothedVelocity);this._draggingRigidbodies.length=0;const e=this._dragHelper.selected;if(this._dragHelper.setSelected(null,this.context),this.orbit&&(this.orbit.enabled=!0),i!=null&&i.object){const s=$.getComponentInChildren(i.object,Uc);s&&(s.fastMode=!1)}this._marker&&this._marker.destroy();for(const s of this.selectEndEventListener)s(this);const t=zv();$.invokeOnChildren(e,t("onDragEnd"))}};let kp=Zc;h(kp,"_active",0),h(kp,"lastHovered");const lU=class{constructor(i){h(this,"_selected",null),h(this,"_context",null),h(this,"_camera"),h(this,"_cameraPlane",new Tn),h(this,"_hasGroundPlane",!1),h(this,"_groundPlane",new Tn),h(this,"_groundOffset",new S),h(this,"_groundOffsetFactor",0),h(this,"_groundDistance",0),h(this,"_groundPlanePoint",new S),h(this,"_raycaster",new vd),h(this,"_cameraPlaneOffset",new S),h(this,"_intersection",new S),h(this,"_worldPosition",new S),h(this,"_inverseMatrix",new Qe),h(this,"_rbs",[]),h(this,"_groundLine"),h(this,"_groundMarker"),h(this,"_groundOffsetVector",new S(0,1,0)),h(this,"_requireUpdateGroundPlane",!0),h(this,"_didDragOnGroundPlaneLastFrame",!1),this._camera=i;const e=new qi(lU.geometry),t=e.material;t.color=new _e(.4,.4,.4),e.layers.set(2),e.name="line",e.scale.y=1,this._groundLine=e;const s=new to(.5,22,22),r=new di({color:t.color}),n=new ye(s,r);n.visible=!1,n.layers.set(2),this._groundMarker=n}get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}setSelected(i,e){if(this._selected&&e)for(const t of this._rbs)t.wakeUp(),t.setVelocity(0,0,0);if(this._selected&&Pr.Remove(e,this._selected),this._selected=i,this._context=e,this._rbs.length=0,i?(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}Pr.Add(e,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this.onUpdateScreenSpacePlane()}}onUpdate(i){var e,t,s,r,n;if(!this._context)return;const o="Space",a="KeyD",l=((e=this._context)==null?void 0:e.input.isKeyPressed(o))||((t=this._context)==null?void 0:t.input.isKeyPressed(a)),c=this._context.input.getTouchesPressedCount()>=2||l;if(c){const d=this._context.input.getPointerPositionDelta(0);d&&(this._groundOffsetVector.set(0,1,0),(s=this._selected)==null||s.rotateOnWorldAxis(this._groundOffsetVector,d.x*this._context.time.deltaTime))}const u=this._context.input.getPointerPositionRC(0);if(u&&(this._raycaster.setFromCamera(u,this._camera),this._selected)){this._groundOffsetVector.set(0,1,0);const d=wt(this._camera).clone().sub(wt(this._selected)).normalize(),p=Math.abs(d.dot(this._groundOffsetVector)),f=((r=this._context)==null?void 0:r.input.isKeyPressed(o))||((n=this._context)==null?void 0:n.input.isKeyPressed(a)),g=!c&&p>.2&&!f&&this._context.input.getPointerPressedCount()<=1,m=this._didDragOnGroundPlaneLastFrame!==g;if(this._didDragOnGroundPlaneLastFrame=g,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!g||m)&&this.onUpdateGroundPlane(),this._requireUpdateGroundPlane=!1,this._hasGroundPlane)if(this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection)){const v=this._intersection.y;if(this._groundPlanePoint.copy(this._intersection).sub(this._groundOffset),this._groundPlanePoint.y=v,g){this._groundOffsetVector.set(0,1,0);const A=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(A,this._groundPlanePoint,!1),this.onDidUpdate();return}}else this._groundPlanePoint.set(0,99999,0);m&&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(i,e,t){if(this._selected){if(t){const s=wt(this._selected);s.y=i.y,i=s}if(Yi(this._selected,i),Yi(this._groundLine,i),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=e!==null,e){const s=wt(this._camera).distanceTo(e)*.01;this._groundMarker.scale.set(s,s,s),Yi(this._groundMarker,e)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;const i=this._context.input.getPointerPositionRC(0);i&&(this._raycaster.setFromCamera(i,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 i=wt(this._selected),e=new za(new S(0,.1,0).add(i),new S(0,-1,0)),t=new fo;t.ignore=[this._selected];const s=this._context.physics.raycastFromRay(e,t);for(let r=0;r<s.length;r++){const n=s[r];if(!n.face||this.contains(this._selected,n.object))continue;const o=new S(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(o,n.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(i),this._groundOffset.copy(this._intersection).sub(i)}onDidUpdate(){en.markDirty(this._selected);for(const i of this._rbs)i.wakeUp(),i.resetForcesAndTorques(),i.setAngularVelocity(0,0,0)}contains(i,e){if(i===e)return!0;if(i.children){for(const t of i.children)if(this.contains(t,e))return!0}return!1}};let cU=lU;h(cU,"geometry",new At().setFromPoints([new S(0,0,0),new S(0,-1,0)]));function uM(i,e,t){console.warn("Adding components on object has been temporarily disabled")}var hU=(i=>(i.File_Spawned="file-spawned",i))(hU||{});class uU{constructor(e,t,s,r,n,o,a,l){h(this,"guid"),h(this,"file_name"),h(this,"file_hash"),h(this,"file_size"),h(this,"position"),h(this,"seed"),h(this,"sender"),h(this,"serverUrl"),h(this,"parentGuid"),h(this,"boundsSize"),this.seed=t,this.guid=s,this.file_name=r,this.file_hash=n,this.file_size=o,this.position=a,this.sender=e,this.serverUrl=l}}async function dM(i,e,t){const s=i.name;return s.endsWith(".gltf")||s.endsWith(".glb")?new Promise((r,n)=>{const o=new FileReader;o.readAsArrayBuffer(i),o.onloadend=async a=>{const l=o.result,c=J0(),u=new Ur(c),d=await Ao().parseSync(e,l,i.name,u);if(d&&d.scene){const p=d.scene;if(!p.guid){const f=new Ur(c);p.guid=f.generateUUID()}t&&nie(e.connection,i,c,p,t),uM(),r(d)}}}):(console.warn("Unsupported file type: "+s),console.log(i),null)}async function dU(i,e){return new Promise(async(t,s)=>{const r=J0(),n=new Ur(r),o=i.toString(),a=await Ao().loadSync(e,o,o,n);a&&a.scene?(a.scene,uM(),t(a)):console.warn("Unsupported file type: "+i.toString())})}Gi.registerCallback(Cn.ContextCreated,i=>{pU(i.context)});function pU(i){i.connection.beginListen("file-spawned",async e=>{if(e.sender!==i.connection.connectionId){console.log("received file event",e),oie(e,i);let t=null;try{t=await AC(e.file_name,e.file_hash,e.file_size,e.serverUrl)}finally{aie(e)}if(t){const s=new Ur(e.seed),r=await Ao().parseSync(i,t,null,s);if(r&&r.scene){const n=r.scene;if(uM(),e.parentGuid){const o=yg(e.parentGuid,i.scene);"add"in o&&o.add(n)}n.parent||i.scene.add(n),e.position!==null&&n.position.copy(e.position)}}else console.error("download didnt return file")}})}async function nie(i,e,t,s,r){if(!i.connectionId){console.error("Can not upload file - no connection id");return}if(!s.guid){console.error("Can not upload file - no guid",s,s.guid);return}const n=await xD(e,r);if(!n)return;if(!n.filename){console.error("Can not send upload event - no filename",e.name);return}if(!n.hash){console.error("Can not send upload event - no hash",e.name);return}const o=new uU(i.connectionId,t,s.guid,n.filename,n.hash,e.size,s.position,n.url??r);s.parent&&(o.parentGuid=s.parent.guid),i.send("file-spawned",o)}const pM={};function oie(i,e){const t=new fi,s=new ye(t,new di({color:65280})),r=new g0(s,5592405);if(pM[i.guid]=r,e.scene.add(r),i.parentGuid){const n=yg(i.parentGuid,e.scene);n&&n.add(r)}i.position&&r.position.copy(i.position)}function aie(i,e){const t=i.guid,s=pM[t];s&&(delete pM[t],s.removeFromParent())}var lie=Object.defineProperty,cie=Object.getOwnPropertyDescriptor,fM=(i,e,t,s)=>{for(var r=s>1?void 0:s?cie(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&lie(e,t,r),r};const hie=oe("debugnet"),gM=class extends Ee{constructor(){super(...arguments),h(this,"url",null),h(this,"urlParameterName",null),h(this,"localhost",null)}awake(){hie&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let i=this.url?gM.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const t=oe(this.urlParameterName);t&&typeof t=="string"&&(i=t)}if(!i)return null;const e=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(i);return e!=null&&e.groups?e?.groups.socket_prefix?i:"wss://"+e?.groups.url:null}static GetUrl(i,e){let t=i;const s=gM.IsLocalNetwork()&&e;return s&&(t=e),i!=null&&i.startsWith("/")&&(t=(s?t:window.location.origin)+i),t}static IsLocalNetwork(i=window.location.hostname){return gr(i)}};let mu=gM;fM([w()],mu.prototype,"url",2),fM([w()],mu.prototype,"urlParameterName",2),fM([w()],mu.prototype,"localhost",2);var uie=Object.defineProperty,die=Object.getOwnPropertyDescriptor,fU=(i,e,t,s)=>{for(var r=s>1?void 0:s?die(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&uie(e,t,r),r};class Um extends Ee{constructor(){super(...arguments),h(this,"filesBackendUrl"),h(this,"localhost"),h(this,"_dragOver"),h(this,"_drop")}onEnable(){this.filesBackendUrl=this.filesBackendUrl?mu.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 s=await dM(t,this.context,this.filesBackendUrl);this.dispatchEvent(new CustomEvent("file-dropped",{detail:t})),s&&this.addObject(void 0,s)}}async onDrop(e){if(console.log(e),!e.dataTransfer)return;e.preventDefault();const t=e.dataTransfer.items;if(t)for(const s in t){const r=t[s];if(r.kind==="file"){const n=r.getAsFile();if(!n)continue;console.log("Register file "+n.name+" to",this.filesBackendUrl,n);const o=await dM(n,this.context,this.filesBackendUrl);this.dispatchEvent(new CustomEvent("file-dropped",{detail:n})),o&&this.addObject(e,o)}else r.kind==="string"&&r.type=="text/plain"&&r.getAsString(async n=>{console.log("dropped url",n);try{const o=new URL(n);if(!o)return;const a=await dU(o,this.context);a&&this.addObject(e,a)}catch{console.log("dropped string is not a valid URL!",n)}})}}async addObject(e,t){console.log("Dropped",t);const s=t.scene;if(e!==void 0){const r=new fo;r.setMask(16777215),r.screenPointFromOffset(e.offsetX,e.offsetY);const n=this.context.physics.raycast(r);if(n&&n.length>0)for(const o of n){s.position.copy(o.point);break}}this.gameObject.add(s),this.dispatchEvent(new CustomEvent("object-added",{detail:t}))}}fU([w()],Um.prototype,"filesBackendUrl",2),fU([w()],Um.prototype,"localhost",2);var pie=Object.defineProperty,fie=Object.getOwnPropertyDescriptor,t_=(i,e,t,s)=>{for(var r=s>1?void 0:s?fie(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&pie(e,t,r),r};class vu extends sp{constructor(){super(...arguments),h(this,"parent",null),h(this,"object",null),h(this,"limitCount",10),h(this,"limitInterval",60),h(this,"_currentCount",0),h(this,"_startPosition",null),h(this,"_startQuaternion",null)}awake(){var e,t;if(this.object){if(this.object===this.gameObject){console.error("Can not duplicate self");return}this.object.visible=!1,this._startPosition=((e=this.object.position)==null?void 0:e.clone())??new S(0,0,0),this._startQuaternion=((t=this.object.quaternion)==null?void 0:t.clone())??new xe(0,0,0,1)}const s=$.getComponentInParent(this.gameObject,kp);s?s.addDragEventListener(aU.SelectStart,(r,n)=>{if(this._currentCount>=this.limitCount){n.attached=null;return}const o=this.handleDuplication(n.selected);o&&(console.assert(o!==n.selected,"Duplicated object is original"),n.attached=o)}):console.warn("Could no find drag controls in parent",this.name),cs.addEventListener(bl.SelectStart,(r,n)=>{if(this._currentCount>=this.limitCount){n.grab=null;return}const o=this.handleDuplication(n.selected);o&&(n.grab=o)}),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 s=new Go;this.parent||(this.parent=this.gameObject.parent),this.parent&&(s.parent=this.parent.guid??((t=this.parent.userData)==null?void 0:t.guid),s.keepWorldPosition=!0),s.position=this.worldPosition,s.rotation=this.worldQuaternion,s.context=this.context,this._currentCount+=1;const r=$.instantiateSynced(this.object,s);return console.assert(r!==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),r}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 s of e.children)if(this.isInChildren(s,t))return!0}return!1}}t_([w(Me)],vu.prototype,"parent",2),t_([w(Me)],vu.prototype,"object",2),t_([w()],vu.prototype,"limitCount",2),t_([w()],vu.prototype,"limitInterval",2);var Dp=(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))(Dp||{}),gie=Object.defineProperty,mie=Object.getOwnPropertyDescriptor,mM=(i,e,t,s)=>{for(var r=s>1?void 0:s?mie(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&gie(e,t,r),r};class vM{constructor(){h(this,"eventID"),h(this,"callback")}}mM([w()],vM.prototype,"eventID",2),mM([w(Vr)],vM.prototype,"callback",2);class i_ extends Ee{constructor(){super(...arguments),h(this,"triggers")}invoke(e){if(this.triggers)for(const t of this.triggers)t.eventID===e&&t.callback.invoke()}onPointerClick(e){this.invoke(Dp.PointerClick)}onPointerEnter(e){this.invoke(Dp.PointerEnter)}onPointerExit(e){this.invoke(Dp.PointerExit)}onPointerDown(e){this.invoke(Dp.PointerDown)}onPointerUp(e){this.invoke(Dp.PointerUp)}}mM([w(vM)],i_.prototype,"triggers",2);var vie=Object.defineProperty,Aie=Object.getOwnPropertyDescriptor,AM=(i,e,t,s)=>{for(var r=s>1?void 0:s?Aie(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&vie(e,t,r),r};class yM extends Ee{constructor(){super(...arguments),h(this,"connectedBody"),h(this,"_rigidBody",null)}get rigidBody(){return this._rigidBody}onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(Li)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.createJoint(this.rigidBody,this.connectedBody)}}AM([w(Li)],yM.prototype,"connectedBody",2);class bM extends yM{createJoint(e,t){var s;(s=this.context.physics.engine)==null||s.addFixedJoint(e,t)}}class Nm extends yM{constructor(){super(...arguments),h(this,"anchor"),h(this,"axis")}createJoint(e,t){var s;this.axis&&this.anchor&&((s=this.context.physics.engine)==null||s.addHingeJoint(e,t,this.anchor,this.axis))}}AM([w(S)],Nm.prototype,"anchor",2),AM([w(S)],Nm.prototype,"axis",2);const yie={type:"change"};let bie=class extends vs{constructor(i,e){super(),this.object=i,this.domElement=e,this.movementSpeed=1,this.rollSpeed=.005,this.dragToLook=!1,this.autoForward=!1;const t=this,s=1e-6,r=new xe,n=new S;this.tmpQuaternion=new xe,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 S(0,0,0),this.rotationVector=new S(0,0,0),this.keydown=function(d){if(!d.altKey){switch(d.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(d){switch(d.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(d){if(this.dragToLook)this.status++;else{switch(d.button){case 0:this.moveState.forward=1;break;case 2:this.moveState.back=1;break}this.updateMovementVector()}},this.pointermove=function(d){if(!this.dragToLook||this.status>0){const p=this.getContainerDimensions(),f=p.size[0]/2,g=p.size[1]/2;this.moveState.yawLeft=-(d.pageX-p.offset[0]-f)/f,this.moveState.pitchDown=(d.pageY-p.offset[1]-g)/g,this.updateRotationVector()}},this.pointerup=function(d){if(this.dragToLook)this.status--,this.moveState.yawLeft=this.moveState.pitchDown=0;else{switch(d.button){case 0:this.moveState.forward=0;break;case 2:this.moveState.back=0;break}this.updateMovementVector()}this.updateRotationVector()},this.update=function(d){const p=d*t.movementSpeed,f=d*t.rollSpeed;t.object.translateX(t.moveVector.x*p),t.object.translateY(t.moveVector.y*p),t.object.translateZ(t.moveVector.z*p),t.tmpQuaternion.set(t.rotationVector.x*f,t.rotationVector.y*f,t.rotationVector.z*f,1).normalize(),t.object.quaternion.multiply(t.tmpQuaternion),(n.distanceToSquared(t.object.position)>s||8*(1-r.dot(t.object.quaternion))>s)&&(t.dispatchEvent(yie),r.copy(t.object.quaternion),n.copy(t.object.position))},this.updateMovementVector=function(){const d=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=-d+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",gU),this.domElement.removeEventListener("pointerdown",a),this.domElement.removeEventListener("pointermove",o),this.domElement.removeEventListener("pointerup",l),window.removeEventListener("keydown",c),window.removeEventListener("keyup",u)};const o=this.pointermove.bind(this),a=this.pointerdown.bind(this),l=this.pointerup.bind(this),c=this.keydown.bind(this),u=this.keyup.bind(this);this.domElement.addEventListener("contextmenu",gU),this.domElement.addEventListener("pointerdown",a),this.domElement.addEventListener("pointermove",o),this.domElement.addEventListener("pointerup",l),window.addEventListener("keydown",c),window.addEventListener("keyup",u),this.updateMovementVector(),this.updateRotationVector()}};function gU(i){i.preventDefault()}class _M extends Ee{constructor(){super(...arguments),h(this,"_controls",null)}onEnable(){var e;const t=(e=$.getComponent(this.gameObject,Mi))==null?void 0:e.cam;this._controls=new bie(t,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 _ie=Object.defineProperty,wie=Object.getOwnPropertyDescriptor,wM=(i,e,t,s)=>{for(var r=s>1?void 0:s?wie(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&_ie(e,t,r),r};class Op extends Ee{constructor(){super(...arguments),h(this,"_fog")}get fog(){return this._fog||(this._fog=new Mx(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)}}wM([w()],Op.prototype,"near",1),wM([w()],Op.prototype,"far",1),wM([w(_e)],Op.prototype,"color",1);let xM,CM,Lp,s_;function SM(i,e,t){CM||(CM=new Ls(2,2,1,1)),Lp||(Lp=new Vt({uniforms:{blitTexture:new Ce(i)},vertexShader:`
|
|
4562
4562
|
varying vec2 vUv;
|
|
4563
4563
|
void main(){
|
|
4564
4564
|
vUv = uv;
|