@needle-tools/engine 2.24.0-pre → 2.25.0-pre

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.
@@ -1,60 +1,60 @@
1
- var xf=Object.create;var zs=Object.defineProperty;var $d=Object.getOwnPropertyDescriptor;var Tf=Object.getOwnPropertyNames;var Rf=Object.getPrototypeOf,Cf=Object.prototype.hasOwnProperty;var Sf=(l,e,t)=>e in l?zs(l,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):l[e]=t;var bl=(l=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(l,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):l)(function(l){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+l+'" is not supported')});var Gs=(l,e)=>()=>(e||l((e={exports:{}}).exports,e),e.exports),Kd=(l,e)=>{for(var t in e)zs(l,t,{get:e[t],enumerable:!0})},Pf=(l,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Tf(e))!Cf.call(l,n)&&n!==t&&zs(l,n,{get:()=>e[n],enumerable:!(i=$d(e,n))||i.enumerable});return l};var vl=(l,e,t)=>(t=l!=null?xf(Rf(l)):{},Pf(e||!l||!l.__esModule?zs(t,"default",{value:l,enumerable:!0}):t,l));var k=(l,e,t,i)=>{for(var n=i>1?void 0:i?$d(e,t):e,r=l.length-1,s;r>=0;r--)(s=l[r])&&(n=(i?s(e,t,n):s(n))||n);return i&&n&&zs(e,t,n),n};var z=(l,e,t)=>(Sf(l,typeof e!="symbol"?e+"":e,t),t);var gc=Gs((Nu,mc)=>{parcelRequire=function(l,e,t,i){var n,r=typeof parcelRequire=="function"&&parcelRequire,s=typeof bl=="function"&&bl;function o(a,h){if(!e[a]){if(!l[a]){var u=typeof parcelRequire=="function"&&parcelRequire;if(!h&&u)return u(a,!0);if(r)return r(a,!0);if(s&&typeof a=="string")return s(a);var g=new Error("Cannot find module '"+a+"'");throw g.code="MODULE_NOT_FOUND",g}b.resolve=function(y){return l[a][1][y]||y},b.cache={};var E=e[a]=new o.Module(a);l[a][0].call(E.exports,b,E,E.exports,this)}return e[a].exports;function b(y){return o(b.resolve(y))}}o.isParcelRequire=!0,o.Module=function(a){this.id=a,this.bundle=o,this.exports={}},o.modules=l,o.cache=e,o.parent=r,o.register=function(a,h){l[a]=[function(u,g){g.exports=h},{}]};for(var c=0;c<t.length;c++)try{o(t[c])}catch(a){n||(n=a)}if(t.length){var d=o(t[t.length-1]);typeof Nu=="object"&&typeof mc<"u"?mc.exports=d:typeof define=="function"&&define.amd?define(function(){return d}):i&&(this[i]=d)}if(parcelRequire=o,n)throw n;return o}({EgBh:[function(l,e,t){var i={};i.useBlobBuilder=function(){try{return new Blob([]),!1}catch{return!0}}(),i.useArrayBufferView=!i.useBlobBuilder&&function(){try{return new Blob([new Uint8Array([])]).size===0}catch{return!0}}(),e.exports.binaryFeatures=i;var n=e.exports.BlobBuilder;function r(){this._pieces=[],this._parts=[]}typeof window<"u"&&(n=e.exports.BlobBuilder=window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder||window.BlobBuilder),r.prototype.append=function(s){typeof s=="number"?this._pieces.push(s):(this.flush(),this._parts.push(s))},r.prototype.flush=function(){if(this._pieces.length>0){var s=new Uint8Array(this._pieces);i.useArrayBufferView||(s=s.buffer),this._parts.push(s),this._pieces=[]}},r.prototype.getBuffer=function(){if(this.flush(),i.useBlobBuilder){for(var s=new n,o=0,c=this._parts.length;o<c;o++)s.append(this._parts[o]);return s.getBlob()}return new Blob(this._parts)},e.exports.BufferBuilder=r},{}],kdPp:[function(l,e,t){var i=l("./bufferbuilder").BufferBuilder,n=l("./bufferbuilder").binaryFeatures,r={unpack:function(a){return new s(a).unpack()},pack:function(a){var h=new o;return h.pack(a),h.getBuffer()}};function s(a){this.index=0,this.dataBuffer=a,this.dataView=new Uint8Array(this.dataBuffer),this.length=this.dataBuffer.byteLength}function o(){this.bufferBuilder=new i}function c(a){var h=a.charCodeAt(0);return h<=2047?"00":h<=65535?"000":h<=2097151?"0000":h<=67108863?"00000":"000000"}function d(a){return a.length>600?new Blob([a]).size:a.replace(/[^\u0000-\u007F]/g,c).length}e.exports=r,s.prototype.unpack=function(){var a,h=this.unpack_uint8();if(h<128)return h;if((224^h)<32)return(224^h)-32;if((a=160^h)<=15)return this.unpack_raw(a);if((a=176^h)<=15)return this.unpack_string(a);if((a=144^h)<=15)return this.unpack_array(a);if((a=128^h)<=15)return this.unpack_map(a);switch(h){case 192:return null;case 193:return;case 194:return!1;case 195:return!0;case 202:return this.unpack_float();case 203:return this.unpack_double();case 204:return this.unpack_uint8();case 205:return this.unpack_uint16();case 206:return this.unpack_uint32();case 207:return this.unpack_uint64();case 208:return this.unpack_int8();case 209:return this.unpack_int16();case 210:return this.unpack_int32();case 211:return this.unpack_int64();case 212:case 213:case 214:case 215:return;case 216:return a=this.unpack_uint16(),this.unpack_string(a);case 217:return a=this.unpack_uint32(),this.unpack_string(a);case 218:return a=this.unpack_uint16(),this.unpack_raw(a);case 219:return a=this.unpack_uint32(),this.unpack_raw(a);case 220:return a=this.unpack_uint16(),this.unpack_array(a);case 221:return a=this.unpack_uint32(),this.unpack_array(a);case 222:return a=this.unpack_uint16(),this.unpack_map(a);case 223:return a=this.unpack_uint32(),this.unpack_map(a)}},s.prototype.unpack_uint8=function(){var a=255&this.dataView[this.index];return this.index++,a},s.prototype.unpack_uint16=function(){var a=this.read(2),h=256*(255&a[0])+(255&a[1]);return this.index+=2,h},s.prototype.unpack_uint32=function(){var a=this.read(4),h=256*(256*(256*a[0]+a[1])+a[2])+a[3];return this.index+=4,h},s.prototype.unpack_uint64=function(){var a=this.read(8),h=256*(256*(256*(256*(256*(256*(256*a[0]+a[1])+a[2])+a[3])+a[4])+a[5])+a[6])+a[7];return this.index+=8,h},s.prototype.unpack_int8=function(){var a=this.unpack_uint8();return a<128?a:a-256},s.prototype.unpack_int16=function(){var a=this.unpack_uint16();return a<32768?a:a-65536},s.prototype.unpack_int32=function(){var a=this.unpack_uint32();return a<Math.pow(2,31)?a:a-Math.pow(2,32)},s.prototype.unpack_int64=function(){var a=this.unpack_uint64();return a<Math.pow(2,63)?a:a-Math.pow(2,64)},s.prototype.unpack_raw=function(a){if(this.length<this.index+a)throw new Error("BinaryPackFailure: index is out of range "+this.index+" "+a+" "+this.length);var h=this.dataBuffer.slice(this.index,this.index+a);return this.index+=a,h},s.prototype.unpack_string=function(a){for(var h,u,g=this.read(a),E=0,b="";E<a;)(h=g[E])<128?(b+=String.fromCharCode(h),E++):(192^h)<32?(u=(192^h)<<6|63&g[E+1],b+=String.fromCharCode(u),E+=2):(u=(15&h)<<12|(63&g[E+1])<<6|63&g[E+2],b+=String.fromCharCode(u),E+=3);return this.index+=a,b},s.prototype.unpack_array=function(a){for(var h=new Array(a),u=0;u<a;u++)h[u]=this.unpack();return h},s.prototype.unpack_map=function(a){for(var h={},u=0;u<a;u++){var g=this.unpack(),E=this.unpack();h[g]=E}return h},s.prototype.unpack_float=function(){var a=this.unpack_uint32(),h=(a>>23&255)-127;return(a>>31===0?1:-1)*(8388607&a|8388608)*Math.pow(2,h-23)},s.prototype.unpack_double=function(){var a=this.unpack_uint32(),h=this.unpack_uint32(),u=(a>>20&2047)-1023;return(a>>31===0?1:-1)*((1048575&a|1048576)*Math.pow(2,u-20)+h*Math.pow(2,u-52))},s.prototype.read=function(a){var h=this.index;if(h+a<=this.length)return this.dataView.subarray(h,h+a);throw new Error("BinaryPackFailure: read index out of range")},o.prototype.getBuffer=function(){return this.bufferBuilder.getBuffer()},o.prototype.pack=function(a){var h=typeof a;if(h==="string")this.pack_string(a);else if(h==="number")Math.floor(a)===a?this.pack_integer(a):this.pack_double(a);else if(h==="boolean")a===!0?this.bufferBuilder.append(195):a===!1&&this.bufferBuilder.append(194);else if(h==="undefined")this.bufferBuilder.append(192);else{if(h!=="object")throw new Error('Type "'+h+'" not yet supported');if(a===null)this.bufferBuilder.append(192);else{var u=a.constructor;if(u==Array)this.pack_array(a);else if(u==Blob||u==File||a instanceof Blob||a instanceof File)this.pack_bin(a);else if(u==ArrayBuffer)n.useArrayBufferView?this.pack_bin(new Uint8Array(a)):this.pack_bin(a);else if("BYTES_PER_ELEMENT"in a)n.useArrayBufferView?this.pack_bin(new Uint8Array(a.buffer)):this.pack_bin(a.buffer);else if(u==Object||u.toString().startsWith("class"))this.pack_object(a);else if(u==Date)this.pack_string(a.toString());else{if(typeof a.toBinaryPack!="function")throw new Error('Type "'+u.toString()+'" not yet supported');this.bufferBuilder.append(a.toBinaryPack())}}}this.bufferBuilder.flush()},o.prototype.pack_bin=function(a){var h=a.length||a.byteLength||a.size;if(h<=15)this.pack_uint8(160+h);else if(h<=65535)this.bufferBuilder.append(218),this.pack_uint16(h);else{if(!(h<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(219),this.pack_uint32(h)}this.bufferBuilder.append(a)},o.prototype.pack_string=function(a){var h=d(a);if(h<=15)this.pack_uint8(176+h);else if(h<=65535)this.bufferBuilder.append(216),this.pack_uint16(h);else{if(!(h<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(217),this.pack_uint32(h)}this.bufferBuilder.append(a)},o.prototype.pack_array=function(a){var h=a.length;if(h<=15)this.pack_uint8(144+h);else if(h<=65535)this.bufferBuilder.append(220),this.pack_uint16(h);else{if(!(h<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(221),this.pack_uint32(h)}for(var u=0;u<h;u++)this.pack(a[u])},o.prototype.pack_integer=function(a){if(a>=-32&&a<=127)this.bufferBuilder.append(255&a);else if(a>=0&&a<=255)this.bufferBuilder.append(204),this.pack_uint8(a);else if(a>=-128&&a<=127)this.bufferBuilder.append(208),this.pack_int8(a);else if(a>=0&&a<=65535)this.bufferBuilder.append(205),this.pack_uint16(a);else if(a>=-32768&&a<=32767)this.bufferBuilder.append(209),this.pack_int16(a);else if(a>=0&&a<=4294967295)this.bufferBuilder.append(206),this.pack_uint32(a);else if(a>=-2147483648&&a<=2147483647)this.bufferBuilder.append(210),this.pack_int32(a);else if(a>=-9223372036854776e3&&a<=9223372036854776e3)this.bufferBuilder.append(211),this.pack_int64(a);else{if(!(a>=0&&a<=18446744073709552e3))throw new Error("Invalid integer");this.bufferBuilder.append(207),this.pack_uint64(a)}},o.prototype.pack_double=function(a){var h=0;a<0&&(h=1,a=-a);var u=Math.floor(Math.log(a)/Math.LN2),g=a/Math.pow(2,u)-1,E=Math.floor(g*Math.pow(2,52)),b=Math.pow(2,32),y=h<<31|u+1023<<20|E/b&1048575,m=E%b;this.bufferBuilder.append(203),this.pack_int32(y),this.pack_int32(m)},o.prototype.pack_object=function(a){var h=Object.keys(a).length;if(h<=15)this.pack_uint8(128+h);else if(h<=65535)this.bufferBuilder.append(222),this.pack_uint16(h);else{if(!(h<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(223),this.pack_uint32(h)}for(var u in a)a.hasOwnProperty(u)&&(this.pack(u),this.pack(a[u]))},o.prototype.pack_uint8=function(a){this.bufferBuilder.append(a)},o.prototype.pack_uint16=function(a){this.bufferBuilder.append(a>>8),this.bufferBuilder.append(255&a)},o.prototype.pack_uint32=function(a){var h=4294967295&a;this.bufferBuilder.append((4278190080&h)>>>24),this.bufferBuilder.append((16711680&h)>>>16),this.bufferBuilder.append((65280&h)>>>8),this.bufferBuilder.append(255&h)},o.prototype.pack_uint64=function(a){var h=a/Math.pow(2,32),u=a%Math.pow(2,32);this.bufferBuilder.append((4278190080&h)>>>24),this.bufferBuilder.append((16711680&h)>>>16),this.bufferBuilder.append((65280&h)>>>8),this.bufferBuilder.append(255&h),this.bufferBuilder.append((4278190080&u)>>>24),this.bufferBuilder.append((16711680&u)>>>16),this.bufferBuilder.append((65280&u)>>>8),this.bufferBuilder.append(255&u)},o.prototype.pack_int8=function(a){this.bufferBuilder.append(255&a)},o.prototype.pack_int16=function(a){this.bufferBuilder.append((65280&a)>>8),this.bufferBuilder.append(255&a)},o.prototype.pack_int32=function(a){this.bufferBuilder.append(a>>>24&255),this.bufferBuilder.append((16711680&a)>>>16),this.bufferBuilder.append((65280&a)>>>8),this.bufferBuilder.append(255&a)},o.prototype.pack_int64=function(a){var h=Math.floor(a/Math.pow(2,32)),u=a%Math.pow(2,32);this.bufferBuilder.append((4278190080&h)>>>24),this.bufferBuilder.append((16711680&h)>>>16),this.bufferBuilder.append((65280&h)>>>8),this.bufferBuilder.append(255&h),this.bufferBuilder.append((4278190080&u)>>>24),this.bufferBuilder.append((16711680&u)>>>16),this.bufferBuilder.append((65280&u)>>>8),this.bufferBuilder.append(255&u)}},{"./bufferbuilder":"EgBh"}],iSxC:[function(l,e,t){"use strict";function i(p,f,v){return f in p?Object.defineProperty(p,f,{value:v,enumerable:!0,configurable:!0,writable:!0}):p[f]=v,p}function n(p){return(n=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(f){return typeof f}:function(f){return f&&typeof Symbol=="function"&&f.constructor===Symbol&&f!==Symbol.prototype?"symbol":typeof f})(p)}Object.defineProperty(t,"__esModule",{value:!0}),t.extractVersion=o,t.wrapPeerConnectionEvent=c,t.disableLog=d,t.disableWarnings=a,t.log=h,t.deprecated=u,t.detectBrowser=g,t.compactObject=b,t.walkStats=y,t.filterStats=m;var r=!0,s=!0;function o(p,f,v){var w=p.match(f);return w&&w.length>=v&&parseInt(w[v],10)}function c(p,f,v){if(p.RTCPeerConnection){var w=p.RTCPeerConnection.prototype,x=w.addEventListener;w.addEventListener=function(R,C){if(R!==f)return x.apply(this,arguments);var P=function(S){var L=v(S);L&&(C.handleEvent?C.handleEvent(L):C(L))};return this._eventMap=this._eventMap||{},this._eventMap[f]||(this._eventMap[f]=new Map),this._eventMap[f].set(C,P),x.apply(this,[R,P])};var T=w.removeEventListener;w.removeEventListener=function(R,C){if(R!==f||!this._eventMap||!this._eventMap[f])return T.apply(this,arguments);if(!this._eventMap[f].has(C))return T.apply(this,arguments);var P=this._eventMap[f].get(C);return this._eventMap[f].delete(C),this._eventMap[f].size===0&&delete this._eventMap[f],Object.keys(this._eventMap).length===0&&delete this._eventMap,T.apply(this,[R,P])},Object.defineProperty(w,"on"+f,{get:function(){return this["_on"+f]},set:function(R){this["_on"+f]&&(this.removeEventListener(f,this["_on"+f]),delete this["_on"+f]),R&&this.addEventListener(f,this["_on"+f]=R)},enumerable:!0,configurable:!0})}}function d(p){return typeof p!="boolean"?new Error("Argument type: "+n(p)+". Please use a boolean."):(r=p,p?"adapter.js logging disabled":"adapter.js logging enabled")}function a(p){return typeof p!="boolean"?new Error("Argument type: "+n(p)+". Please use a boolean."):(s=!p,"adapter.js deprecation warnings "+(p?"disabled":"enabled"))}function h(){if((typeof window>"u"?"undefined":n(window))==="object"){if(r)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function u(p,f){s&&console.warn(p+" is deprecated, please use "+f+" instead.")}function g(p){var f={browser:null,version:null};if(p===void 0||!p.navigator)return f.browser="Not a browser.",f;var{navigator:v}=p;if(v.mozGetUserMedia)f.browser="firefox",f.version=o(v.userAgent,/Firefox\/(\d+)\./,1);else if(v.webkitGetUserMedia||p.isSecureContext===!1&&p.webkitRTCPeerConnection&&!p.RTCIceGatherer)f.browser="chrome",f.version=o(v.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(v.mediaDevices&&v.userAgent.match(/Edge\/(\d+).(\d+)$/))f.browser="edge",f.version=o(v.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!p.RTCPeerConnection||!v.userAgent.match(/AppleWebKit\/(\d+)\./))return f.browser="Not a supported browser.",f;f.browser="safari",f.version=o(v.userAgent,/AppleWebKit\/(\d+)\./,1),f.supportsUnifiedPlan=p.RTCRtpTransceiver&&"currentDirection"in p.RTCRtpTransceiver.prototype}return f}function E(p){return Object.prototype.toString.call(p)==="[object Object]"}function b(p){return E(p)?Object.keys(p).reduce(function(f,v){var w=E(p[v]),x=w?b(p[v]):p[v],T=w&&!Object.keys(x).length;return x===void 0||T?f:Object.assign(f,i({},v,x))},{}):p}function y(p,f,v){f&&!v.has(f.id)&&(v.set(f.id,f),Object.keys(f).forEach(function(w){w.endsWith("Id")?y(p,p.get(f[w]),v):w.endsWith("Ids")&&f[w].forEach(function(x){y(p,p.get(x),v)})}))}function m(p,f,v){var w=v?"outbound-rtp":"inbound-rtp",x=new Map;if(f===null)return x;var T=[];return p.forEach(function(R){R.type==="track"&&R.trackIdentifier===f.id&&T.push(R)}),T.forEach(function(R){p.forEach(function(C){C.type===w&&C.trackId===R.id&&y(p,C,x)})}),x}},{}],s6SN:[function(l,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetUserMedia=c;var i=r(l("../utils.js"));function n(){if(typeof WeakMap!="function")return null;var d=new WeakMap;return n=function(){return d},d}function r(d){if(d&&d.__esModule)return d;if(d===null||typeof d!="object"&&typeof d!="function")return{default:d};var a=n();if(a&&a.has(d))return a.get(d);var h={},u=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var g in d)if(Object.prototype.hasOwnProperty.call(d,g)){var E=u?Object.getOwnPropertyDescriptor(d,g):null;E&&(E.get||E.set)?Object.defineProperty(h,g,E):h[g]=d[g]}return h.default=d,a&&a.set(d,h),h}function s(d){return(s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(a){return typeof a}:function(a){return a&&typeof Symbol=="function"&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a})(d)}var o=i.log;function c(d,a){var h=d&&d.navigator;if(h.mediaDevices){var u=function(y){if(s(y)!=="object"||y.mandatory||y.optional)return y;var m={};return Object.keys(y).forEach(function(p){if(p!=="require"&&p!=="advanced"&&p!=="mediaSource"){var f=s(y[p])==="object"?y[p]:{ideal:y[p]};f.exact!==void 0&&typeof f.exact=="number"&&(f.min=f.max=f.exact);var v=function(x,T){return x?x+T.charAt(0).toUpperCase()+T.slice(1):T==="deviceId"?"sourceId":T};if(f.ideal!==void 0){m.optional=m.optional||[];var w={};typeof f.ideal=="number"?(w[v("min",p)]=f.ideal,m.optional.push(w),(w={})[v("max",p)]=f.ideal,m.optional.push(w)):(w[v("",p)]=f.ideal,m.optional.push(w))}f.exact!==void 0&&typeof f.exact!="number"?(m.mandatory=m.mandatory||{},m.mandatory[v("",p)]=f.exact):["min","max"].forEach(function(x){f[x]!==void 0&&(m.mandatory=m.mandatory||{},m.mandatory[v(x,p)]=f[x])})}}),y.advanced&&(m.optional=(m.optional||[]).concat(y.advanced)),m},g=function(y,m){if(a.version>=61)return m(y);if((y=JSON.parse(JSON.stringify(y)))&&s(y.audio)==="object"){var p=function(x,T,R){T in x&&!(R in x)&&(x[R]=x[T],delete x[T])};p((y=JSON.parse(JSON.stringify(y))).audio,"autoGainControl","googAutoGainControl"),p(y.audio,"noiseSuppression","googNoiseSuppression"),y.audio=u(y.audio)}if(y&&s(y.video)==="object"){var f=y.video.facingMode;f=f&&(s(f)==="object"?f:{ideal:f});var v,w=a.version<66;if(f&&(f.exact==="user"||f.exact==="environment"||f.ideal==="user"||f.ideal==="environment")&&(!h.mediaDevices.getSupportedConstraints||!h.mediaDevices.getSupportedConstraints().facingMode||w)&&(delete y.video.facingMode,f.exact==="environment"||f.ideal==="environment"?v=["back","rear"]:f.exact!=="user"&&f.ideal!=="user"||(v=["front"]),v))return h.mediaDevices.enumerateDevices().then(function(x){var T=(x=x.filter(function(R){return R.kind==="videoinput"})).find(function(R){return v.some(function(C){return R.label.toLowerCase().includes(C)})});return!T&&x.length&&v.includes("back")&&(T=x[x.length-1]),T&&(y.video.deviceId=f.exact?{exact:T.deviceId}:{ideal:T.deviceId}),y.video=u(y.video),o("chrome: "+JSON.stringify(y)),m(y)});y.video=u(y.video)}return o("chrome: "+JSON.stringify(y)),m(y)},E=function(y){return a.version>=64?y:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[y.name]||y.name,message:y.message,constraint:y.constraint||y.constraintName,toString:function(){return this.name+(this.message&&": ")+this.message}}};if(h.getUserMedia=function(y,m,p){g(y,function(f){h.webkitGetUserMedia(f,m,function(v){p&&p(E(v))})})}.bind(h),h.mediaDevices.getUserMedia){var b=h.mediaDevices.getUserMedia.bind(h.mediaDevices);h.mediaDevices.getUserMedia=function(y){return g(y,function(m){return b(m).then(function(p){if(m.audio&&!p.getAudioTracks().length||m.video&&!p.getVideoTracks().length)throw p.getTracks().forEach(function(f){f.stop()}),new DOMException("","NotFoundError");return p},function(p){return Promise.reject(E(p))})})}}}}},{"../utils.js":"iSxC"}],VHa8:[function(l,e,t){"use strict";function i(n,r){n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||n.navigator.mediaDevices&&(typeof r=="function"?n.navigator.mediaDevices.getDisplayMedia=function(s){return r(s).then(function(o){var c=s.video&&s.video.width,d=s.video&&s.video.height,a=s.video&&s.video.frameRate;return s.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:o,maxFrameRate:a||3}},c&&(s.video.mandatory.maxWidth=c),d&&(s.video.mandatory.maxHeight=d),n.navigator.mediaDevices.getUserMedia(s)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetDisplayMedia=i},{}],uI5X:[function(l,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimMediaStream=a,t.shimOnTrack=h,t.shimGetSendersWithDtmf=u,t.shimGetStats=g,t.shimSenderReceiverGetStats=E,t.shimAddTrackRemoveTrackWithNative=b,t.shimAddTrackRemoveTrack=y,t.shimPeerConnection=m,t.fixNegotiationNeeded=p,Object.defineProperty(t,"shimGetUserMedia",{enumerable:!0,get:function(){return n.shimGetUserMedia}}),Object.defineProperty(t,"shimGetDisplayMedia",{enumerable:!0,get:function(){return r.shimGetDisplayMedia}});var i=o(l("../utils.js")),n=l("./getusermedia"),r=l("./getdisplaymedia");function s(){if(typeof WeakMap!="function")return null;var f=new WeakMap;return s=function(){return f},f}function o(f){if(f&&f.__esModule)return f;if(f===null||typeof f!="object"&&typeof f!="function")return{default:f};var v=s();if(v&&v.has(f))return v.get(f);var w={},x=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var T in f)if(Object.prototype.hasOwnProperty.call(f,T)){var R=x?Object.getOwnPropertyDescriptor(f,T):null;R&&(R.get||R.set)?Object.defineProperty(w,T,R):w[T]=f[T]}return w.default=f,v&&v.set(f,w),w}function c(f,v,w){return v in f?Object.defineProperty(f,v,{value:w,enumerable:!0,configurable:!0,writable:!0}):f[v]=w,f}function d(f){return(d=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(v){return typeof v}:function(v){return v&&typeof Symbol=="function"&&v.constructor===Symbol&&v!==Symbol.prototype?"symbol":typeof v})(f)}function a(f){f.MediaStream=f.MediaStream||f.webkitMediaStream}function h(f){if(d(f)!=="object"||!f.RTCPeerConnection||"ontrack"in f.RTCPeerConnection.prototype)i.wrapPeerConnectionEvent(f,"track",function(w){return w.transceiver||Object.defineProperty(w,"transceiver",{value:{receiver:w.receiver}}),w});else{Object.defineProperty(f.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(w){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=w)},enumerable:!0,configurable:!0});var v=f.RTCPeerConnection.prototype.setRemoteDescription;f.RTCPeerConnection.prototype.setRemoteDescription=function(){var w=this;return this._ontrackpoly||(this._ontrackpoly=function(x){x.stream.addEventListener("addtrack",function(T){var R;R=f.RTCPeerConnection.prototype.getReceivers?w.getReceivers().find(function(P){return P.track&&P.track.id===T.track.id}):{track:T.track};var C=new Event("track");C.track=T.track,C.receiver=R,C.transceiver={receiver:R},C.streams=[x.stream],w.dispatchEvent(C)}),x.stream.getTracks().forEach(function(T){var R;R=f.RTCPeerConnection.prototype.getReceivers?w.getReceivers().find(function(P){return P.track&&P.track.id===T.id}):{track:T};var C=new Event("track");C.track=T,C.receiver=R,C.transceiver={receiver:R},C.streams=[x.stream],w.dispatchEvent(C)})},this.addEventListener("addstream",this._ontrackpoly)),v.apply(this,arguments)}}}function u(f){if(d(f)==="object"&&f.RTCPeerConnection&&!("getSenders"in f.RTCPeerConnection.prototype)&&"createDTMFSender"in f.RTCPeerConnection.prototype){var v=function(P,S){return{track:S,get dtmf(){return this._dtmf===void 0&&(S.kind==="audio"?this._dtmf=P.createDTMFSender(S):this._dtmf=null),this._dtmf},_pc:P}};if(!f.RTCPeerConnection.prototype.getSenders){f.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};var w=f.RTCPeerConnection.prototype.addTrack;f.RTCPeerConnection.prototype.addTrack=function(P,S){var L=w.apply(this,arguments);return L||(L=v(this,P),this._senders.push(L)),L};var x=f.RTCPeerConnection.prototype.removeTrack;f.RTCPeerConnection.prototype.removeTrack=function(P){x.apply(this,arguments);var S=this._senders.indexOf(P);S!==-1&&this._senders.splice(S,1)}}var T=f.RTCPeerConnection.prototype.addStream;f.RTCPeerConnection.prototype.addStream=function(P){var S=this;this._senders=this._senders||[],T.apply(this,[P]),P.getTracks().forEach(function(L){S._senders.push(v(S,L))})};var R=f.RTCPeerConnection.prototype.removeStream;f.RTCPeerConnection.prototype.removeStream=function(P){var S=this;this._senders=this._senders||[],R.apply(this,[P]),P.getTracks().forEach(function(L){var I=S._senders.find(function(j){return j.track===L});I&&S._senders.splice(S._senders.indexOf(I),1)})}}else if(d(f)==="object"&&f.RTCPeerConnection&&"getSenders"in f.RTCPeerConnection.prototype&&"createDTMFSender"in f.RTCPeerConnection.prototype&&f.RTCRtpSender&&!("dtmf"in f.RTCRtpSender.prototype)){var C=f.RTCPeerConnection.prototype.getSenders;f.RTCPeerConnection.prototype.getSenders=function(){var P=this,S=C.apply(this,[]);return S.forEach(function(L){return L._pc=P}),S},Object.defineProperty(f.RTCRtpSender.prototype,"dtmf",{get:function(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function g(f){if(f.RTCPeerConnection){var v=f.RTCPeerConnection.prototype.getStats;f.RTCPeerConnection.prototype.getStats=function(){var w=this,[x,T,R]=arguments;if(arguments.length>0&&typeof x=="function")return v.apply(this,arguments);if(v.length===0&&(arguments.length===0||typeof x!="function"))return v.apply(this,[]);var C=function(S){var L={};return S.result().forEach(function(I){var j={id:I.id,timestamp:I.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[I.type]||I.type};I.names().forEach(function(H){j[H]=I.stat(H)}),L[j.id]=j}),L},P=function(S){return new Map(Object.keys(S).map(function(L){return[L,S[L]]}))};return arguments.length>=2?v.apply(this,[function(S){T(P(C(S)))},x]):new Promise(function(S,L){v.apply(w,[function(I){S(P(C(I)))},L])}).then(T,R)}}}function E(f){if(d(f)==="object"&&f.RTCPeerConnection&&f.RTCRtpSender&&f.RTCRtpReceiver){if(!("getStats"in f.RTCRtpSender.prototype)){var v=f.RTCPeerConnection.prototype.getSenders;v&&(f.RTCPeerConnection.prototype.getSenders=function(){var R=this,C=v.apply(this,[]);return C.forEach(function(P){return P._pc=R}),C});var w=f.RTCPeerConnection.prototype.addTrack;w&&(f.RTCPeerConnection.prototype.addTrack=function(){var R=w.apply(this,arguments);return R._pc=this,R}),f.RTCRtpSender.prototype.getStats=function(){var R=this;return this._pc.getStats().then(function(C){return i.filterStats(C,R.track,!0)})}}if(!("getStats"in f.RTCRtpReceiver.prototype)){var x=f.RTCPeerConnection.prototype.getReceivers;x&&(f.RTCPeerConnection.prototype.getReceivers=function(){var R=this,C=x.apply(this,[]);return C.forEach(function(P){return P._pc=R}),C}),i.wrapPeerConnectionEvent(f,"track",function(R){return R.receiver._pc=R.srcElement,R}),f.RTCRtpReceiver.prototype.getStats=function(){var R=this;return this._pc.getStats().then(function(C){return i.filterStats(C,R.track,!1)})}}if("getStats"in f.RTCRtpSender.prototype&&"getStats"in f.RTCRtpReceiver.prototype){var T=f.RTCPeerConnection.prototype.getStats;f.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof f.MediaStreamTrack){var R,C,P,S=arguments[0];return this.getSenders().forEach(function(L){L.track===S&&(R?P=!0:R=L)}),this.getReceivers().forEach(function(L){return L.track===S&&(C?P=!0:C=L),L.track===S}),P||R&&C?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):R?R.getStats():C?C.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return T.apply(this,arguments)}}}}function b(f){f.RTCPeerConnection.prototype.getLocalStreams=function(){var R=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(function(C){return R._shimmedLocalStreams[C][0]})};var v=f.RTCPeerConnection.prototype.addTrack;f.RTCPeerConnection.prototype.addTrack=function(R,C){if(!C)return v.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var P=v.apply(this,arguments);return this._shimmedLocalStreams[C.id]?this._shimmedLocalStreams[C.id].indexOf(P)===-1&&this._shimmedLocalStreams[C.id].push(P):this._shimmedLocalStreams[C.id]=[C,P],P};var w=f.RTCPeerConnection.prototype.addStream;f.RTCPeerConnection.prototype.addStream=function(R){var C=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},R.getTracks().forEach(function(L){if(C.getSenders().find(function(I){return I.track===L}))throw new DOMException("Track already exists.","InvalidAccessError")});var P=this.getSenders();w.apply(this,arguments);var S=this.getSenders().filter(function(L){return P.indexOf(L)===-1});this._shimmedLocalStreams[R.id]=[R].concat(S)};var x=f.RTCPeerConnection.prototype.removeStream;f.RTCPeerConnection.prototype.removeStream=function(R){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[R.id],x.apply(this,arguments)};var T=f.RTCPeerConnection.prototype.removeTrack;f.RTCPeerConnection.prototype.removeTrack=function(R){var C=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},R&&Object.keys(this._shimmedLocalStreams).forEach(function(P){var S=C._shimmedLocalStreams[P].indexOf(R);S!==-1&&C._shimmedLocalStreams[P].splice(S,1),C._shimmedLocalStreams[P].length===1&&delete C._shimmedLocalStreams[P]}),T.apply(this,arguments)}}function y(f,v){if(f.RTCPeerConnection){if(f.RTCPeerConnection.prototype.addTrack&&v.version>=65)return b(f);var w=f.RTCPeerConnection.prototype.getLocalStreams;f.RTCPeerConnection.prototype.getLocalStreams=function(){var S=this,L=w.apply(this);return this._reverseStreams=this._reverseStreams||{},L.map(function(I){return S._reverseStreams[I.id]})};var x=f.RTCPeerConnection.prototype.addStream;f.RTCPeerConnection.prototype.addStream=function(S){var L=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},S.getTracks().forEach(function(j){if(L.getSenders().find(function(H){return H.track===j}))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[S.id]){var I=new f.MediaStream(S.getTracks());this._streams[S.id]=I,this._reverseStreams[I.id]=S,S=I}x.apply(this,[S])};var T=f.RTCPeerConnection.prototype.removeStream;f.RTCPeerConnection.prototype.removeStream=function(S){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},T.apply(this,[this._streams[S.id]||S]),delete this._reverseStreams[this._streams[S.id]?this._streams[S.id].id:S.id],delete this._streams[S.id]},f.RTCPeerConnection.prototype.addTrack=function(S,L){var I=this;if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var j=[].slice.call(arguments,1);if(j.length!==1||!j[0].getTracks().find(function(U){return U===S}))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(function(U){return U.track===S}))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var H=this._streams[L.id];if(H)H.addTrack(S),Promise.resolve().then(function(){I.dispatchEvent(new Event("negotiationneeded"))});else{var F=new f.MediaStream([S]);this._streams[L.id]=F,this._reverseStreams[F.id]=L,this.addStream(F)}return this.getSenders().find(function(U){return U.track===S})},["createOffer","createAnswer"].forEach(function(S){var L=f.RTCPeerConnection.prototype[S],I=c({},S,function(){var j=this,H=arguments;return arguments.length&&typeof arguments[0]=="function"?L.apply(this,[function(F){var U=P(j,F);H[0].apply(null,[U])},function(F){H[1]&&H[1].apply(null,F)},arguments[2]]):L.apply(this,arguments).then(function(F){return P(j,F)})});f.RTCPeerConnection.prototype[S]=I[S]});var R=f.RTCPeerConnection.prototype.setLocalDescription;f.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=(S=this,L=arguments[0],I=L.sdp,Object.keys(S._reverseStreams||[]).forEach(function(j){var H=S._reverseStreams[j],F=S._streams[H.id];I=I.replace(new RegExp(H.id,"g"),F.id)}),new RTCSessionDescription({type:L.type,sdp:I})),R.apply(this,arguments)):R.apply(this,arguments);var S,L,I};var C=Object.getOwnPropertyDescriptor(f.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(f.RTCPeerConnection.prototype,"localDescription",{get:function(){var S=C.get.apply(this);return S.type===""?S:P(this,S)}}),f.RTCPeerConnection.prototype.removeTrack=function(S){var L,I=this;if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!S._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(S._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{},Object.keys(this._streams).forEach(function(j){I._streams[j].getTracks().find(function(H){return S.track===H})&&(L=I._streams[j])}),L&&(L.getTracks().length===1?this.removeStream(this._reverseStreams[L.id]):L.removeTrack(S.track),this.dispatchEvent(new Event("negotiationneeded")))}}function P(S,L){var I=L.sdp;return Object.keys(S._reverseStreams||[]).forEach(function(j){var H=S._reverseStreams[j],F=S._streams[H.id];I=I.replace(new RegExp(F.id,"g"),H.id)}),new RTCSessionDescription({type:L.type,sdp:I})}}function m(f,v){!f.RTCPeerConnection&&f.webkitRTCPeerConnection&&(f.RTCPeerConnection=f.webkitRTCPeerConnection),f.RTCPeerConnection&&v.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(w){var x=f.RTCPeerConnection.prototype[w],T=c({},w,function(){return arguments[0]=new(w==="addIceCandidate"?f.RTCIceCandidate:f.RTCSessionDescription)(arguments[0]),x.apply(this,arguments)});f.RTCPeerConnection.prototype[w]=T[w]})}function p(f,v){i.wrapPeerConnectionEvent(f,"negotiationneeded",function(w){var x=w.target;if(!(v.version<72||x.getConfiguration&&x.getConfiguration().sdpSemantics==="plan-b")||x.signalingState==="stable")return w})}},{"../utils.js":"iSxC","./getusermedia":"s6SN","./getdisplaymedia":"VHa8"}],NZ1C:[function(l,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterIceServers=s;var i=r(l("../utils"));function n(){if(typeof WeakMap!="function")return null;var o=new WeakMap;return n=function(){return o},o}function r(o){if(o&&o.__esModule)return o;if(o===null||typeof o!="object"&&typeof o!="function")return{default:o};var c=n();if(c&&c.has(o))return c.get(o);var d={},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var h in o)if(Object.prototype.hasOwnProperty.call(o,h)){var u=a?Object.getOwnPropertyDescriptor(o,h):null;u&&(u.get||u.set)?Object.defineProperty(d,h,u):d[h]=o[h]}return d.default=o,c&&c.set(o,d),d}function s(o,c){var d=!1;return(o=JSON.parse(JSON.stringify(o))).filter(function(a){if(a&&(a.urls||a.url)){var h=a.urls||a.url;a.url&&!a.urls&&i.deprecated("RTCIceServer.url","RTCIceServer.urls");var u=typeof h=="string";return u&&(h=[h]),h=h.filter(function(g){if(g.indexOf("stun:")===0)return!1;var E=g.startsWith("turn")&&!g.startsWith("turn:[")&&g.includes("transport=udp");return E&&!d?(d=!0,!0):E&&!d}),delete a.url,a.urls=u?h[0]:h,!!h.length}})}},{"../utils":"iSxC"}],YHvh:[function(l,e,t){"use strict";var i={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};i.localCName=i.generateIdentifier(),i.splitLines=function(n){return n.trim().split(`
1
+ var Of=Object.create;var qo=Object.defineProperty;var rh=Object.getOwnPropertyDescriptor;var Af=Object.getOwnPropertyNames;var kf=Object.getPrototypeOf,If=Object.prototype.hasOwnProperty;var Mf=(l,e,t)=>e in l?qo(l,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):l[e]=t;var bl=(l=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(l,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):l)(function(l){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+l+'" is not supported')});var Xo=(l,e)=>()=>(e||l((e={exports:{}}).exports,e),e.exports),oh=(l,e)=>{for(var t in e)qo(l,t,{get:e[t],enumerable:!0})},Lf=(l,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Af(e))!If.call(l,n)&&n!==t&&qo(l,n,{get:()=>e[n],enumerable:!(i=rh(e,n))||i.enumerable});return l};var vl=(l,e,t)=>(t=l!=null?Of(kf(l)):{},Lf(e||!l||!l.__esModule?qo(t,"default",{value:l,enumerable:!0}):t,l));var k=(l,e,t,i)=>{for(var n=i>1?void 0:i?rh(e,t):e,r=l.length-1,o;r>=0;r--)(o=l[r])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&qo(e,t,n),n};var z=(l,e,t)=>(Mf(l,typeof e!="symbol"?e+"":e,t),t);var wc=Xo((Xu,Ec)=>{parcelRequire=function(l,e,t,i){var n,r=typeof parcelRequire=="function"&&parcelRequire,o=typeof bl=="function"&&bl;function s(a,h){if(!e[a]){if(!l[a]){var u=typeof parcelRequire=="function"&&parcelRequire;if(!h&&u)return u(a,!0);if(r)return r(a,!0);if(o&&typeof a=="string")return o(a);var f=new Error("Cannot find module '"+a+"'");throw f.code="MODULE_NOT_FOUND",f}b.resolve=function(y){return l[a][1][y]||y},b.cache={};var E=e[a]=new s.Module(a);l[a][0].call(E.exports,b,E,E.exports,this)}return e[a].exports;function b(y){return s(b.resolve(y))}}s.isParcelRequire=!0,s.Module=function(a){this.id=a,this.bundle=s,this.exports={}},s.modules=l,s.cache=e,s.parent=r,s.register=function(a,h){l[a]=[function(u,f){f.exports=h},{}]};for(var c=0;c<t.length;c++)try{s(t[c])}catch(a){n||(n=a)}if(t.length){var d=s(t[t.length-1]);typeof Xu=="object"&&typeof Ec<"u"?Ec.exports=d:typeof define=="function"&&define.amd?define(function(){return d}):i&&(this[i]=d)}if(parcelRequire=s,n)throw n;return s}({EgBh:[function(l,e,t){var i={};i.useBlobBuilder=function(){try{return new Blob([]),!1}catch{return!0}}(),i.useArrayBufferView=!i.useBlobBuilder&&function(){try{return new Blob([new Uint8Array([])]).size===0}catch{return!0}}(),e.exports.binaryFeatures=i;var n=e.exports.BlobBuilder;function r(){this._pieces=[],this._parts=[]}typeof window<"u"&&(n=e.exports.BlobBuilder=window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder||window.BlobBuilder),r.prototype.append=function(o){typeof o=="number"?this._pieces.push(o):(this.flush(),this._parts.push(o))},r.prototype.flush=function(){if(this._pieces.length>0){var o=new Uint8Array(this._pieces);i.useArrayBufferView||(o=o.buffer),this._parts.push(o),this._pieces=[]}},r.prototype.getBuffer=function(){if(this.flush(),i.useBlobBuilder){for(var o=new n,s=0,c=this._parts.length;s<c;s++)o.append(this._parts[s]);return o.getBlob()}return new Blob(this._parts)},e.exports.BufferBuilder=r},{}],kdPp:[function(l,e,t){var i=l("./bufferbuilder").BufferBuilder,n=l("./bufferbuilder").binaryFeatures,r={unpack:function(a){return new o(a).unpack()},pack:function(a){var h=new s;return h.pack(a),h.getBuffer()}};function o(a){this.index=0,this.dataBuffer=a,this.dataView=new Uint8Array(this.dataBuffer),this.length=this.dataBuffer.byteLength}function s(){this.bufferBuilder=new i}function c(a){var h=a.charCodeAt(0);return h<=2047?"00":h<=65535?"000":h<=2097151?"0000":h<=67108863?"00000":"000000"}function d(a){return a.length>600?new Blob([a]).size:a.replace(/[^\u0000-\u007F]/g,c).length}e.exports=r,o.prototype.unpack=function(){var a,h=this.unpack_uint8();if(h<128)return h;if((224^h)<32)return(224^h)-32;if((a=160^h)<=15)return this.unpack_raw(a);if((a=176^h)<=15)return this.unpack_string(a);if((a=144^h)<=15)return this.unpack_array(a);if((a=128^h)<=15)return this.unpack_map(a);switch(h){case 192:return null;case 193:return;case 194:return!1;case 195:return!0;case 202:return this.unpack_float();case 203:return this.unpack_double();case 204:return this.unpack_uint8();case 205:return this.unpack_uint16();case 206:return this.unpack_uint32();case 207:return this.unpack_uint64();case 208:return this.unpack_int8();case 209:return this.unpack_int16();case 210:return this.unpack_int32();case 211:return this.unpack_int64();case 212:case 213:case 214:case 215:return;case 216:return a=this.unpack_uint16(),this.unpack_string(a);case 217:return a=this.unpack_uint32(),this.unpack_string(a);case 218:return a=this.unpack_uint16(),this.unpack_raw(a);case 219:return a=this.unpack_uint32(),this.unpack_raw(a);case 220:return a=this.unpack_uint16(),this.unpack_array(a);case 221:return a=this.unpack_uint32(),this.unpack_array(a);case 222:return a=this.unpack_uint16(),this.unpack_map(a);case 223:return a=this.unpack_uint32(),this.unpack_map(a)}},o.prototype.unpack_uint8=function(){var a=255&this.dataView[this.index];return this.index++,a},o.prototype.unpack_uint16=function(){var a=this.read(2),h=256*(255&a[0])+(255&a[1]);return this.index+=2,h},o.prototype.unpack_uint32=function(){var a=this.read(4),h=256*(256*(256*a[0]+a[1])+a[2])+a[3];return this.index+=4,h},o.prototype.unpack_uint64=function(){var a=this.read(8),h=256*(256*(256*(256*(256*(256*(256*a[0]+a[1])+a[2])+a[3])+a[4])+a[5])+a[6])+a[7];return this.index+=8,h},o.prototype.unpack_int8=function(){var a=this.unpack_uint8();return a<128?a:a-256},o.prototype.unpack_int16=function(){var a=this.unpack_uint16();return a<32768?a:a-65536},o.prototype.unpack_int32=function(){var a=this.unpack_uint32();return a<Math.pow(2,31)?a:a-Math.pow(2,32)},o.prototype.unpack_int64=function(){var a=this.unpack_uint64();return a<Math.pow(2,63)?a:a-Math.pow(2,64)},o.prototype.unpack_raw=function(a){if(this.length<this.index+a)throw new Error("BinaryPackFailure: index is out of range "+this.index+" "+a+" "+this.length);var h=this.dataBuffer.slice(this.index,this.index+a);return this.index+=a,h},o.prototype.unpack_string=function(a){for(var h,u,f=this.read(a),E=0,b="";E<a;)(h=f[E])<128?(b+=String.fromCharCode(h),E++):(192^h)<32?(u=(192^h)<<6|63&f[E+1],b+=String.fromCharCode(u),E+=2):(u=(15&h)<<12|(63&f[E+1])<<6|63&f[E+2],b+=String.fromCharCode(u),E+=3);return this.index+=a,b},o.prototype.unpack_array=function(a){for(var h=new Array(a),u=0;u<a;u++)h[u]=this.unpack();return h},o.prototype.unpack_map=function(a){for(var h={},u=0;u<a;u++){var f=this.unpack(),E=this.unpack();h[f]=E}return h},o.prototype.unpack_float=function(){var a=this.unpack_uint32(),h=(a>>23&255)-127;return(a>>31===0?1:-1)*(8388607&a|8388608)*Math.pow(2,h-23)},o.prototype.unpack_double=function(){var a=this.unpack_uint32(),h=this.unpack_uint32(),u=(a>>20&2047)-1023;return(a>>31===0?1:-1)*((1048575&a|1048576)*Math.pow(2,u-20)+h*Math.pow(2,u-52))},o.prototype.read=function(a){var h=this.index;if(h+a<=this.length)return this.dataView.subarray(h,h+a);throw new Error("BinaryPackFailure: read index out of range")},s.prototype.getBuffer=function(){return this.bufferBuilder.getBuffer()},s.prototype.pack=function(a){var h=typeof a;if(h==="string")this.pack_string(a);else if(h==="number")Math.floor(a)===a?this.pack_integer(a):this.pack_double(a);else if(h==="boolean")a===!0?this.bufferBuilder.append(195):a===!1&&this.bufferBuilder.append(194);else if(h==="undefined")this.bufferBuilder.append(192);else{if(h!=="object")throw new Error('Type "'+h+'" not yet supported');if(a===null)this.bufferBuilder.append(192);else{var u=a.constructor;if(u==Array)this.pack_array(a);else if(u==Blob||u==File||a instanceof Blob||a instanceof File)this.pack_bin(a);else if(u==ArrayBuffer)n.useArrayBufferView?this.pack_bin(new Uint8Array(a)):this.pack_bin(a);else if("BYTES_PER_ELEMENT"in a)n.useArrayBufferView?this.pack_bin(new Uint8Array(a.buffer)):this.pack_bin(a.buffer);else if(u==Object||u.toString().startsWith("class"))this.pack_object(a);else if(u==Date)this.pack_string(a.toString());else{if(typeof a.toBinaryPack!="function")throw new Error('Type "'+u.toString()+'" not yet supported');this.bufferBuilder.append(a.toBinaryPack())}}}this.bufferBuilder.flush()},s.prototype.pack_bin=function(a){var h=a.length||a.byteLength||a.size;if(h<=15)this.pack_uint8(160+h);else if(h<=65535)this.bufferBuilder.append(218),this.pack_uint16(h);else{if(!(h<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(219),this.pack_uint32(h)}this.bufferBuilder.append(a)},s.prototype.pack_string=function(a){var h=d(a);if(h<=15)this.pack_uint8(176+h);else if(h<=65535)this.bufferBuilder.append(216),this.pack_uint16(h);else{if(!(h<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(217),this.pack_uint32(h)}this.bufferBuilder.append(a)},s.prototype.pack_array=function(a){var h=a.length;if(h<=15)this.pack_uint8(144+h);else if(h<=65535)this.bufferBuilder.append(220),this.pack_uint16(h);else{if(!(h<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(221),this.pack_uint32(h)}for(var u=0;u<h;u++)this.pack(a[u])},s.prototype.pack_integer=function(a){if(a>=-32&&a<=127)this.bufferBuilder.append(255&a);else if(a>=0&&a<=255)this.bufferBuilder.append(204),this.pack_uint8(a);else if(a>=-128&&a<=127)this.bufferBuilder.append(208),this.pack_int8(a);else if(a>=0&&a<=65535)this.bufferBuilder.append(205),this.pack_uint16(a);else if(a>=-32768&&a<=32767)this.bufferBuilder.append(209),this.pack_int16(a);else if(a>=0&&a<=4294967295)this.bufferBuilder.append(206),this.pack_uint32(a);else if(a>=-2147483648&&a<=2147483647)this.bufferBuilder.append(210),this.pack_int32(a);else if(a>=-9223372036854776e3&&a<=9223372036854776e3)this.bufferBuilder.append(211),this.pack_int64(a);else{if(!(a>=0&&a<=18446744073709552e3))throw new Error("Invalid integer");this.bufferBuilder.append(207),this.pack_uint64(a)}},s.prototype.pack_double=function(a){var h=0;a<0&&(h=1,a=-a);var u=Math.floor(Math.log(a)/Math.LN2),f=a/Math.pow(2,u)-1,E=Math.floor(f*Math.pow(2,52)),b=Math.pow(2,32),y=h<<31|u+1023<<20|E/b&1048575,g=E%b;this.bufferBuilder.append(203),this.pack_int32(y),this.pack_int32(g)},s.prototype.pack_object=function(a){var h=Object.keys(a).length;if(h<=15)this.pack_uint8(128+h);else if(h<=65535)this.bufferBuilder.append(222),this.pack_uint16(h);else{if(!(h<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(223),this.pack_uint32(h)}for(var u in a)a.hasOwnProperty(u)&&(this.pack(u),this.pack(a[u]))},s.prototype.pack_uint8=function(a){this.bufferBuilder.append(a)},s.prototype.pack_uint16=function(a){this.bufferBuilder.append(a>>8),this.bufferBuilder.append(255&a)},s.prototype.pack_uint32=function(a){var h=4294967295&a;this.bufferBuilder.append((4278190080&h)>>>24),this.bufferBuilder.append((16711680&h)>>>16),this.bufferBuilder.append((65280&h)>>>8),this.bufferBuilder.append(255&h)},s.prototype.pack_uint64=function(a){var h=a/Math.pow(2,32),u=a%Math.pow(2,32);this.bufferBuilder.append((4278190080&h)>>>24),this.bufferBuilder.append((16711680&h)>>>16),this.bufferBuilder.append((65280&h)>>>8),this.bufferBuilder.append(255&h),this.bufferBuilder.append((4278190080&u)>>>24),this.bufferBuilder.append((16711680&u)>>>16),this.bufferBuilder.append((65280&u)>>>8),this.bufferBuilder.append(255&u)},s.prototype.pack_int8=function(a){this.bufferBuilder.append(255&a)},s.prototype.pack_int16=function(a){this.bufferBuilder.append((65280&a)>>8),this.bufferBuilder.append(255&a)},s.prototype.pack_int32=function(a){this.bufferBuilder.append(a>>>24&255),this.bufferBuilder.append((16711680&a)>>>16),this.bufferBuilder.append((65280&a)>>>8),this.bufferBuilder.append(255&a)},s.prototype.pack_int64=function(a){var h=Math.floor(a/Math.pow(2,32)),u=a%Math.pow(2,32);this.bufferBuilder.append((4278190080&h)>>>24),this.bufferBuilder.append((16711680&h)>>>16),this.bufferBuilder.append((65280&h)>>>8),this.bufferBuilder.append(255&h),this.bufferBuilder.append((4278190080&u)>>>24),this.bufferBuilder.append((16711680&u)>>>16),this.bufferBuilder.append((65280&u)>>>8),this.bufferBuilder.append(255&u)}},{"./bufferbuilder":"EgBh"}],iSxC:[function(l,e,t){"use strict";function i(p,m,v){return m in p?Object.defineProperty(p,m,{value:v,enumerable:!0,configurable:!0,writable:!0}):p[m]=v,p}function n(p){return(n=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(m){return typeof m}:function(m){return m&&typeof Symbol=="function"&&m.constructor===Symbol&&m!==Symbol.prototype?"symbol":typeof m})(p)}Object.defineProperty(t,"__esModule",{value:!0}),t.extractVersion=s,t.wrapPeerConnectionEvent=c,t.disableLog=d,t.disableWarnings=a,t.log=h,t.deprecated=u,t.detectBrowser=f,t.compactObject=b,t.walkStats=y,t.filterStats=g;var r=!0,o=!0;function s(p,m,v){var w=p.match(m);return w&&w.length>=v&&parseInt(w[v],10)}function c(p,m,v){if(p.RTCPeerConnection){var w=p.RTCPeerConnection.prototype,x=w.addEventListener;w.addEventListener=function(R,C){if(R!==m)return x.apply(this,arguments);var P=function(S){var L=v(S);L&&(C.handleEvent?C.handleEvent(L):C(L))};return this._eventMap=this._eventMap||{},this._eventMap[m]||(this._eventMap[m]=new Map),this._eventMap[m].set(C,P),x.apply(this,[R,P])};var T=w.removeEventListener;w.removeEventListener=function(R,C){if(R!==m||!this._eventMap||!this._eventMap[m])return T.apply(this,arguments);if(!this._eventMap[m].has(C))return T.apply(this,arguments);var P=this._eventMap[m].get(C);return this._eventMap[m].delete(C),this._eventMap[m].size===0&&delete this._eventMap[m],Object.keys(this._eventMap).length===0&&delete this._eventMap,T.apply(this,[R,P])},Object.defineProperty(w,"on"+m,{get:function(){return this["_on"+m]},set:function(R){this["_on"+m]&&(this.removeEventListener(m,this["_on"+m]),delete this["_on"+m]),R&&this.addEventListener(m,this["_on"+m]=R)},enumerable:!0,configurable:!0})}}function d(p){return typeof p!="boolean"?new Error("Argument type: "+n(p)+". Please use a boolean."):(r=p,p?"adapter.js logging disabled":"adapter.js logging enabled")}function a(p){return typeof p!="boolean"?new Error("Argument type: "+n(p)+". Please use a boolean."):(o=!p,"adapter.js deprecation warnings "+(p?"disabled":"enabled"))}function h(){if((typeof window>"u"?"undefined":n(window))==="object"){if(r)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function u(p,m){o&&console.warn(p+" is deprecated, please use "+m+" instead.")}function f(p){var m={browser:null,version:null};if(p===void 0||!p.navigator)return m.browser="Not a browser.",m;var{navigator:v}=p;if(v.mozGetUserMedia)m.browser="firefox",m.version=s(v.userAgent,/Firefox\/(\d+)\./,1);else if(v.webkitGetUserMedia||p.isSecureContext===!1&&p.webkitRTCPeerConnection&&!p.RTCIceGatherer)m.browser="chrome",m.version=s(v.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(v.mediaDevices&&v.userAgent.match(/Edge\/(\d+).(\d+)$/))m.browser="edge",m.version=s(v.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!p.RTCPeerConnection||!v.userAgent.match(/AppleWebKit\/(\d+)\./))return m.browser="Not a supported browser.",m;m.browser="safari",m.version=s(v.userAgent,/AppleWebKit\/(\d+)\./,1),m.supportsUnifiedPlan=p.RTCRtpTransceiver&&"currentDirection"in p.RTCRtpTransceiver.prototype}return m}function E(p){return Object.prototype.toString.call(p)==="[object Object]"}function b(p){return E(p)?Object.keys(p).reduce(function(m,v){var w=E(p[v]),x=w?b(p[v]):p[v],T=w&&!Object.keys(x).length;return x===void 0||T?m:Object.assign(m,i({},v,x))},{}):p}function y(p,m,v){m&&!v.has(m.id)&&(v.set(m.id,m),Object.keys(m).forEach(function(w){w.endsWith("Id")?y(p,p.get(m[w]),v):w.endsWith("Ids")&&m[w].forEach(function(x){y(p,p.get(x),v)})}))}function g(p,m,v){var w=v?"outbound-rtp":"inbound-rtp",x=new Map;if(m===null)return x;var T=[];return p.forEach(function(R){R.type==="track"&&R.trackIdentifier===m.id&&T.push(R)}),T.forEach(function(R){p.forEach(function(C){C.type===w&&C.trackId===R.id&&y(p,C,x)})}),x}},{}],s6SN:[function(l,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetUserMedia=c;var i=r(l("../utils.js"));function n(){if(typeof WeakMap!="function")return null;var d=new WeakMap;return n=function(){return d},d}function r(d){if(d&&d.__esModule)return d;if(d===null||typeof d!="object"&&typeof d!="function")return{default:d};var a=n();if(a&&a.has(d))return a.get(d);var h={},u=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var f in d)if(Object.prototype.hasOwnProperty.call(d,f)){var E=u?Object.getOwnPropertyDescriptor(d,f):null;E&&(E.get||E.set)?Object.defineProperty(h,f,E):h[f]=d[f]}return h.default=d,a&&a.set(d,h),h}function o(d){return(o=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(a){return typeof a}:function(a){return a&&typeof Symbol=="function"&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a})(d)}var s=i.log;function c(d,a){var h=d&&d.navigator;if(h.mediaDevices){var u=function(y){if(o(y)!=="object"||y.mandatory||y.optional)return y;var g={};return Object.keys(y).forEach(function(p){if(p!=="require"&&p!=="advanced"&&p!=="mediaSource"){var m=o(y[p])==="object"?y[p]:{ideal:y[p]};m.exact!==void 0&&typeof m.exact=="number"&&(m.min=m.max=m.exact);var v=function(x,T){return x?x+T.charAt(0).toUpperCase()+T.slice(1):T==="deviceId"?"sourceId":T};if(m.ideal!==void 0){g.optional=g.optional||[];var w={};typeof m.ideal=="number"?(w[v("min",p)]=m.ideal,g.optional.push(w),(w={})[v("max",p)]=m.ideal,g.optional.push(w)):(w[v("",p)]=m.ideal,g.optional.push(w))}m.exact!==void 0&&typeof m.exact!="number"?(g.mandatory=g.mandatory||{},g.mandatory[v("",p)]=m.exact):["min","max"].forEach(function(x){m[x]!==void 0&&(g.mandatory=g.mandatory||{},g.mandatory[v(x,p)]=m[x])})}}),y.advanced&&(g.optional=(g.optional||[]).concat(y.advanced)),g},f=function(y,g){if(a.version>=61)return g(y);if((y=JSON.parse(JSON.stringify(y)))&&o(y.audio)==="object"){var p=function(x,T,R){T in x&&!(R in x)&&(x[R]=x[T],delete x[T])};p((y=JSON.parse(JSON.stringify(y))).audio,"autoGainControl","googAutoGainControl"),p(y.audio,"noiseSuppression","googNoiseSuppression"),y.audio=u(y.audio)}if(y&&o(y.video)==="object"){var m=y.video.facingMode;m=m&&(o(m)==="object"?m:{ideal:m});var v,w=a.version<66;if(m&&(m.exact==="user"||m.exact==="environment"||m.ideal==="user"||m.ideal==="environment")&&(!h.mediaDevices.getSupportedConstraints||!h.mediaDevices.getSupportedConstraints().facingMode||w)&&(delete y.video.facingMode,m.exact==="environment"||m.ideal==="environment"?v=["back","rear"]:m.exact!=="user"&&m.ideal!=="user"||(v=["front"]),v))return h.mediaDevices.enumerateDevices().then(function(x){var T=(x=x.filter(function(R){return R.kind==="videoinput"})).find(function(R){return v.some(function(C){return R.label.toLowerCase().includes(C)})});return!T&&x.length&&v.includes("back")&&(T=x[x.length-1]),T&&(y.video.deviceId=m.exact?{exact:T.deviceId}:{ideal:T.deviceId}),y.video=u(y.video),s("chrome: "+JSON.stringify(y)),g(y)});y.video=u(y.video)}return s("chrome: "+JSON.stringify(y)),g(y)},E=function(y){return a.version>=64?y:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[y.name]||y.name,message:y.message,constraint:y.constraint||y.constraintName,toString:function(){return this.name+(this.message&&": ")+this.message}}};if(h.getUserMedia=function(y,g,p){f(y,function(m){h.webkitGetUserMedia(m,g,function(v){p&&p(E(v))})})}.bind(h),h.mediaDevices.getUserMedia){var b=h.mediaDevices.getUserMedia.bind(h.mediaDevices);h.mediaDevices.getUserMedia=function(y){return f(y,function(g){return b(g).then(function(p){if(g.audio&&!p.getAudioTracks().length||g.video&&!p.getVideoTracks().length)throw p.getTracks().forEach(function(m){m.stop()}),new DOMException("","NotFoundError");return p},function(p){return Promise.reject(E(p))})})}}}}},{"../utils.js":"iSxC"}],VHa8:[function(l,e,t){"use strict";function i(n,r){n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||n.navigator.mediaDevices&&(typeof r=="function"?n.navigator.mediaDevices.getDisplayMedia=function(o){return r(o).then(function(s){var c=o.video&&o.video.width,d=o.video&&o.video.height,a=o.video&&o.video.frameRate;return o.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:s,maxFrameRate:a||3}},c&&(o.video.mandatory.maxWidth=c),d&&(o.video.mandatory.maxHeight=d),n.navigator.mediaDevices.getUserMedia(o)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetDisplayMedia=i},{}],uI5X:[function(l,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimMediaStream=a,t.shimOnTrack=h,t.shimGetSendersWithDtmf=u,t.shimGetStats=f,t.shimSenderReceiverGetStats=E,t.shimAddTrackRemoveTrackWithNative=b,t.shimAddTrackRemoveTrack=y,t.shimPeerConnection=g,t.fixNegotiationNeeded=p,Object.defineProperty(t,"shimGetUserMedia",{enumerable:!0,get:function(){return n.shimGetUserMedia}}),Object.defineProperty(t,"shimGetDisplayMedia",{enumerable:!0,get:function(){return r.shimGetDisplayMedia}});var i=s(l("../utils.js")),n=l("./getusermedia"),r=l("./getdisplaymedia");function o(){if(typeof WeakMap!="function")return null;var m=new WeakMap;return o=function(){return m},m}function s(m){if(m&&m.__esModule)return m;if(m===null||typeof m!="object"&&typeof m!="function")return{default:m};var v=o();if(v&&v.has(m))return v.get(m);var w={},x=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var T in m)if(Object.prototype.hasOwnProperty.call(m,T)){var R=x?Object.getOwnPropertyDescriptor(m,T):null;R&&(R.get||R.set)?Object.defineProperty(w,T,R):w[T]=m[T]}return w.default=m,v&&v.set(m,w),w}function c(m,v,w){return v in m?Object.defineProperty(m,v,{value:w,enumerable:!0,configurable:!0,writable:!0}):m[v]=w,m}function d(m){return(d=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(v){return typeof v}:function(v){return v&&typeof Symbol=="function"&&v.constructor===Symbol&&v!==Symbol.prototype?"symbol":typeof v})(m)}function a(m){m.MediaStream=m.MediaStream||m.webkitMediaStream}function h(m){if(d(m)!=="object"||!m.RTCPeerConnection||"ontrack"in m.RTCPeerConnection.prototype)i.wrapPeerConnectionEvent(m,"track",function(w){return w.transceiver||Object.defineProperty(w,"transceiver",{value:{receiver:w.receiver}}),w});else{Object.defineProperty(m.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(w){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=w)},enumerable:!0,configurable:!0});var v=m.RTCPeerConnection.prototype.setRemoteDescription;m.RTCPeerConnection.prototype.setRemoteDescription=function(){var w=this;return this._ontrackpoly||(this._ontrackpoly=function(x){x.stream.addEventListener("addtrack",function(T){var R;R=m.RTCPeerConnection.prototype.getReceivers?w.getReceivers().find(function(P){return P.track&&P.track.id===T.track.id}):{track:T.track};var C=new Event("track");C.track=T.track,C.receiver=R,C.transceiver={receiver:R},C.streams=[x.stream],w.dispatchEvent(C)}),x.stream.getTracks().forEach(function(T){var R;R=m.RTCPeerConnection.prototype.getReceivers?w.getReceivers().find(function(P){return P.track&&P.track.id===T.id}):{track:T};var C=new Event("track");C.track=T,C.receiver=R,C.transceiver={receiver:R},C.streams=[x.stream],w.dispatchEvent(C)})},this.addEventListener("addstream",this._ontrackpoly)),v.apply(this,arguments)}}}function u(m){if(d(m)==="object"&&m.RTCPeerConnection&&!("getSenders"in m.RTCPeerConnection.prototype)&&"createDTMFSender"in m.RTCPeerConnection.prototype){var v=function(P,S){return{track:S,get dtmf(){return this._dtmf===void 0&&(S.kind==="audio"?this._dtmf=P.createDTMFSender(S):this._dtmf=null),this._dtmf},_pc:P}};if(!m.RTCPeerConnection.prototype.getSenders){m.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};var w=m.RTCPeerConnection.prototype.addTrack;m.RTCPeerConnection.prototype.addTrack=function(P,S){var L=w.apply(this,arguments);return L||(L=v(this,P),this._senders.push(L)),L};var x=m.RTCPeerConnection.prototype.removeTrack;m.RTCPeerConnection.prototype.removeTrack=function(P){x.apply(this,arguments);var S=this._senders.indexOf(P);S!==-1&&this._senders.splice(S,1)}}var T=m.RTCPeerConnection.prototype.addStream;m.RTCPeerConnection.prototype.addStream=function(P){var S=this;this._senders=this._senders||[],T.apply(this,[P]),P.getTracks().forEach(function(L){S._senders.push(v(S,L))})};var R=m.RTCPeerConnection.prototype.removeStream;m.RTCPeerConnection.prototype.removeStream=function(P){var S=this;this._senders=this._senders||[],R.apply(this,[P]),P.getTracks().forEach(function(L){var I=S._senders.find(function(j){return j.track===L});I&&S._senders.splice(S._senders.indexOf(I),1)})}}else if(d(m)==="object"&&m.RTCPeerConnection&&"getSenders"in m.RTCPeerConnection.prototype&&"createDTMFSender"in m.RTCPeerConnection.prototype&&m.RTCRtpSender&&!("dtmf"in m.RTCRtpSender.prototype)){var C=m.RTCPeerConnection.prototype.getSenders;m.RTCPeerConnection.prototype.getSenders=function(){var P=this,S=C.apply(this,[]);return S.forEach(function(L){return L._pc=P}),S},Object.defineProperty(m.RTCRtpSender.prototype,"dtmf",{get:function(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function f(m){if(m.RTCPeerConnection){var v=m.RTCPeerConnection.prototype.getStats;m.RTCPeerConnection.prototype.getStats=function(){var w=this,[x,T,R]=arguments;if(arguments.length>0&&typeof x=="function")return v.apply(this,arguments);if(v.length===0&&(arguments.length===0||typeof x!="function"))return v.apply(this,[]);var C=function(S){var L={};return S.result().forEach(function(I){var j={id:I.id,timestamp:I.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[I.type]||I.type};I.names().forEach(function(H){j[H]=I.stat(H)}),L[j.id]=j}),L},P=function(S){return new Map(Object.keys(S).map(function(L){return[L,S[L]]}))};return arguments.length>=2?v.apply(this,[function(S){T(P(C(S)))},x]):new Promise(function(S,L){v.apply(w,[function(I){S(P(C(I)))},L])}).then(T,R)}}}function E(m){if(d(m)==="object"&&m.RTCPeerConnection&&m.RTCRtpSender&&m.RTCRtpReceiver){if(!("getStats"in m.RTCRtpSender.prototype)){var v=m.RTCPeerConnection.prototype.getSenders;v&&(m.RTCPeerConnection.prototype.getSenders=function(){var R=this,C=v.apply(this,[]);return C.forEach(function(P){return P._pc=R}),C});var w=m.RTCPeerConnection.prototype.addTrack;w&&(m.RTCPeerConnection.prototype.addTrack=function(){var R=w.apply(this,arguments);return R._pc=this,R}),m.RTCRtpSender.prototype.getStats=function(){var R=this;return this._pc.getStats().then(function(C){return i.filterStats(C,R.track,!0)})}}if(!("getStats"in m.RTCRtpReceiver.prototype)){var x=m.RTCPeerConnection.prototype.getReceivers;x&&(m.RTCPeerConnection.prototype.getReceivers=function(){var R=this,C=x.apply(this,[]);return C.forEach(function(P){return P._pc=R}),C}),i.wrapPeerConnectionEvent(m,"track",function(R){return R.receiver._pc=R.srcElement,R}),m.RTCRtpReceiver.prototype.getStats=function(){var R=this;return this._pc.getStats().then(function(C){return i.filterStats(C,R.track,!1)})}}if("getStats"in m.RTCRtpSender.prototype&&"getStats"in m.RTCRtpReceiver.prototype){var T=m.RTCPeerConnection.prototype.getStats;m.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof m.MediaStreamTrack){var R,C,P,S=arguments[0];return this.getSenders().forEach(function(L){L.track===S&&(R?P=!0:R=L)}),this.getReceivers().forEach(function(L){return L.track===S&&(C?P=!0:C=L),L.track===S}),P||R&&C?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):R?R.getStats():C?C.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return T.apply(this,arguments)}}}}function b(m){m.RTCPeerConnection.prototype.getLocalStreams=function(){var R=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(function(C){return R._shimmedLocalStreams[C][0]})};var v=m.RTCPeerConnection.prototype.addTrack;m.RTCPeerConnection.prototype.addTrack=function(R,C){if(!C)return v.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var P=v.apply(this,arguments);return this._shimmedLocalStreams[C.id]?this._shimmedLocalStreams[C.id].indexOf(P)===-1&&this._shimmedLocalStreams[C.id].push(P):this._shimmedLocalStreams[C.id]=[C,P],P};var w=m.RTCPeerConnection.prototype.addStream;m.RTCPeerConnection.prototype.addStream=function(R){var C=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},R.getTracks().forEach(function(L){if(C.getSenders().find(function(I){return I.track===L}))throw new DOMException("Track already exists.","InvalidAccessError")});var P=this.getSenders();w.apply(this,arguments);var S=this.getSenders().filter(function(L){return P.indexOf(L)===-1});this._shimmedLocalStreams[R.id]=[R].concat(S)};var x=m.RTCPeerConnection.prototype.removeStream;m.RTCPeerConnection.prototype.removeStream=function(R){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[R.id],x.apply(this,arguments)};var T=m.RTCPeerConnection.prototype.removeTrack;m.RTCPeerConnection.prototype.removeTrack=function(R){var C=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},R&&Object.keys(this._shimmedLocalStreams).forEach(function(P){var S=C._shimmedLocalStreams[P].indexOf(R);S!==-1&&C._shimmedLocalStreams[P].splice(S,1),C._shimmedLocalStreams[P].length===1&&delete C._shimmedLocalStreams[P]}),T.apply(this,arguments)}}function y(m,v){if(m.RTCPeerConnection){if(m.RTCPeerConnection.prototype.addTrack&&v.version>=65)return b(m);var w=m.RTCPeerConnection.prototype.getLocalStreams;m.RTCPeerConnection.prototype.getLocalStreams=function(){var S=this,L=w.apply(this);return this._reverseStreams=this._reverseStreams||{},L.map(function(I){return S._reverseStreams[I.id]})};var x=m.RTCPeerConnection.prototype.addStream;m.RTCPeerConnection.prototype.addStream=function(S){var L=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},S.getTracks().forEach(function(j){if(L.getSenders().find(function(H){return H.track===j}))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[S.id]){var I=new m.MediaStream(S.getTracks());this._streams[S.id]=I,this._reverseStreams[I.id]=S,S=I}x.apply(this,[S])};var T=m.RTCPeerConnection.prototype.removeStream;m.RTCPeerConnection.prototype.removeStream=function(S){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},T.apply(this,[this._streams[S.id]||S]),delete this._reverseStreams[this._streams[S.id]?this._streams[S.id].id:S.id],delete this._streams[S.id]},m.RTCPeerConnection.prototype.addTrack=function(S,L){var I=this;if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var j=[].slice.call(arguments,1);if(j.length!==1||!j[0].getTracks().find(function(U){return U===S}))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(function(U){return U.track===S}))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var H=this._streams[L.id];if(H)H.addTrack(S),Promise.resolve().then(function(){I.dispatchEvent(new Event("negotiationneeded"))});else{var F=new m.MediaStream([S]);this._streams[L.id]=F,this._reverseStreams[F.id]=L,this.addStream(F)}return this.getSenders().find(function(U){return U.track===S})},["createOffer","createAnswer"].forEach(function(S){var L=m.RTCPeerConnection.prototype[S],I=c({},S,function(){var j=this,H=arguments;return arguments.length&&typeof arguments[0]=="function"?L.apply(this,[function(F){var U=P(j,F);H[0].apply(null,[U])},function(F){H[1]&&H[1].apply(null,F)},arguments[2]]):L.apply(this,arguments).then(function(F){return P(j,F)})});m.RTCPeerConnection.prototype[S]=I[S]});var R=m.RTCPeerConnection.prototype.setLocalDescription;m.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=(S=this,L=arguments[0],I=L.sdp,Object.keys(S._reverseStreams||[]).forEach(function(j){var H=S._reverseStreams[j],F=S._streams[H.id];I=I.replace(new RegExp(H.id,"g"),F.id)}),new RTCSessionDescription({type:L.type,sdp:I})),R.apply(this,arguments)):R.apply(this,arguments);var S,L,I};var C=Object.getOwnPropertyDescriptor(m.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(m.RTCPeerConnection.prototype,"localDescription",{get:function(){var S=C.get.apply(this);return S.type===""?S:P(this,S)}}),m.RTCPeerConnection.prototype.removeTrack=function(S){var L,I=this;if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!S._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(S._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{},Object.keys(this._streams).forEach(function(j){I._streams[j].getTracks().find(function(H){return S.track===H})&&(L=I._streams[j])}),L&&(L.getTracks().length===1?this.removeStream(this._reverseStreams[L.id]):L.removeTrack(S.track),this.dispatchEvent(new Event("negotiationneeded")))}}function P(S,L){var I=L.sdp;return Object.keys(S._reverseStreams||[]).forEach(function(j){var H=S._reverseStreams[j],F=S._streams[H.id];I=I.replace(new RegExp(F.id,"g"),H.id)}),new RTCSessionDescription({type:L.type,sdp:I})}}function g(m,v){!m.RTCPeerConnection&&m.webkitRTCPeerConnection&&(m.RTCPeerConnection=m.webkitRTCPeerConnection),m.RTCPeerConnection&&v.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(w){var x=m.RTCPeerConnection.prototype[w],T=c({},w,function(){return arguments[0]=new(w==="addIceCandidate"?m.RTCIceCandidate:m.RTCSessionDescription)(arguments[0]),x.apply(this,arguments)});m.RTCPeerConnection.prototype[w]=T[w]})}function p(m,v){i.wrapPeerConnectionEvent(m,"negotiationneeded",function(w){var x=w.target;if(!(v.version<72||x.getConfiguration&&x.getConfiguration().sdpSemantics==="plan-b")||x.signalingState==="stable")return w})}},{"../utils.js":"iSxC","./getusermedia":"s6SN","./getdisplaymedia":"VHa8"}],NZ1C:[function(l,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterIceServers=o;var i=r(l("../utils"));function n(){if(typeof WeakMap!="function")return null;var s=new WeakMap;return n=function(){return s},s}function r(s){if(s&&s.__esModule)return s;if(s===null||typeof s!="object"&&typeof s!="function")return{default:s};var c=n();if(c&&c.has(s))return c.get(s);var d={},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var h in s)if(Object.prototype.hasOwnProperty.call(s,h)){var u=a?Object.getOwnPropertyDescriptor(s,h):null;u&&(u.get||u.set)?Object.defineProperty(d,h,u):d[h]=s[h]}return d.default=s,c&&c.set(s,d),d}function o(s,c){var d=!1;return(s=JSON.parse(JSON.stringify(s))).filter(function(a){if(a&&(a.urls||a.url)){var h=a.urls||a.url;a.url&&!a.urls&&i.deprecated("RTCIceServer.url","RTCIceServer.urls");var u=typeof h=="string";return u&&(h=[h]),h=h.filter(function(f){if(f.indexOf("stun:")===0)return!1;var E=f.startsWith("turn")&&!f.startsWith("turn:[")&&f.includes("transport=udp");return E&&!d?(d=!0,!0):E&&!d}),delete a.url,a.urls=u?h[0]:h,!!h.length}})}},{"../utils":"iSxC"}],YHvh:[function(l,e,t){"use strict";var i={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};i.localCName=i.generateIdentifier(),i.splitLines=function(n){return n.trim().split(`
2
2
  `).map(function(r){return r.trim()})},i.splitSections=function(n){return n.split(`
3
- m=`).map(function(r,s){return(s>0?"m="+r:r).trim()+`\r
4
- `})},i.getDescription=function(n){var r=i.splitSections(n);return r&&r[0]},i.getMediaSections=function(n){var r=i.splitSections(n);return r.shift(),r},i.matchPrefix=function(n,r){return i.splitLines(n).filter(function(s){return s.indexOf(r)===0})},i.parseCandidate=function(n){for(var r,s={foundation:(r=n.indexOf("a=candidate:")===0?n.substring(12).split(" "):n.substring(10).split(" "))[0],component:parseInt(r[1],10),protocol:r[2].toLowerCase(),priority:parseInt(r[3],10),ip:r[4],address:r[4],port:parseInt(r[5],10),type:r[7]},o=8;o<r.length;o+=2)switch(r[o]){case"raddr":s.relatedAddress=r[o+1];break;case"rport":s.relatedPort=parseInt(r[o+1],10);break;case"tcptype":s.tcpType=r[o+1];break;case"ufrag":s.ufrag=r[o+1],s.usernameFragment=r[o+1];break;default:s[r[o]]=r[o+1]}return s},i.writeCandidate=function(n){var r=[];r.push(n.foundation),r.push(n.component),r.push(n.protocol.toUpperCase()),r.push(n.priority),r.push(n.address||n.ip),r.push(n.port);var s=n.type;return r.push("typ"),r.push(s),s!=="host"&&n.relatedAddress&&n.relatedPort&&(r.push("raddr"),r.push(n.relatedAddress),r.push("rport"),r.push(n.relatedPort)),n.tcpType&&n.protocol.toLowerCase()==="tcp"&&(r.push("tcptype"),r.push(n.tcpType)),(n.usernameFragment||n.ufrag)&&(r.push("ufrag"),r.push(n.usernameFragment||n.ufrag)),"candidate:"+r.join(" ")},i.parseIceOptions=function(n){return n.substr(14).split(" ")},i.parseRtpMap=function(n){var r=n.substr(9).split(" "),s={payloadType:parseInt(r.shift(),10)};return r=r[0].split("/"),s.name=r[0],s.clockRate=parseInt(r[1],10),s.channels=r.length===3?parseInt(r[2],10):1,s.numChannels=s.channels,s},i.writeRtpMap=function(n){var r=n.payloadType;n.preferredPayloadType!==void 0&&(r=n.preferredPayloadType);var s=n.channels||n.numChannels||1;return"a=rtpmap:"+r+" "+n.name+"/"+n.clockRate+(s!==1?"/"+s:"")+`\r
3
+ m=`).map(function(r,o){return(o>0?"m="+r:r).trim()+`\r
4
+ `})},i.getDescription=function(n){var r=i.splitSections(n);return r&&r[0]},i.getMediaSections=function(n){var r=i.splitSections(n);return r.shift(),r},i.matchPrefix=function(n,r){return i.splitLines(n).filter(function(o){return o.indexOf(r)===0})},i.parseCandidate=function(n){for(var r,o={foundation:(r=n.indexOf("a=candidate:")===0?n.substring(12).split(" "):n.substring(10).split(" "))[0],component:parseInt(r[1],10),protocol:r[2].toLowerCase(),priority:parseInt(r[3],10),ip:r[4],address:r[4],port:parseInt(r[5],10),type:r[7]},s=8;s<r.length;s+=2)switch(r[s]){case"raddr":o.relatedAddress=r[s+1];break;case"rport":o.relatedPort=parseInt(r[s+1],10);break;case"tcptype":o.tcpType=r[s+1];break;case"ufrag":o.ufrag=r[s+1],o.usernameFragment=r[s+1];break;default:o[r[s]]=r[s+1]}return o},i.writeCandidate=function(n){var r=[];r.push(n.foundation),r.push(n.component),r.push(n.protocol.toUpperCase()),r.push(n.priority),r.push(n.address||n.ip),r.push(n.port);var o=n.type;return r.push("typ"),r.push(o),o!=="host"&&n.relatedAddress&&n.relatedPort&&(r.push("raddr"),r.push(n.relatedAddress),r.push("rport"),r.push(n.relatedPort)),n.tcpType&&n.protocol.toLowerCase()==="tcp"&&(r.push("tcptype"),r.push(n.tcpType)),(n.usernameFragment||n.ufrag)&&(r.push("ufrag"),r.push(n.usernameFragment||n.ufrag)),"candidate:"+r.join(" ")},i.parseIceOptions=function(n){return n.substr(14).split(" ")},i.parseRtpMap=function(n){var r=n.substr(9).split(" "),o={payloadType:parseInt(r.shift(),10)};return r=r[0].split("/"),o.name=r[0],o.clockRate=parseInt(r[1],10),o.channels=r.length===3?parseInt(r[2],10):1,o.numChannels=o.channels,o},i.writeRtpMap=function(n){var r=n.payloadType;n.preferredPayloadType!==void 0&&(r=n.preferredPayloadType);var o=n.channels||n.numChannels||1;return"a=rtpmap:"+r+" "+n.name+"/"+n.clockRate+(o!==1?"/"+o:"")+`\r
5
5
  `},i.parseExtmap=function(n){var r=n.substr(9).split(" ");return{id:parseInt(r[0],10),direction:r[0].indexOf("/")>0?r[0].split("/")[1]:"sendrecv",uri:r[1]}},i.writeExtmap=function(n){return"a=extmap:"+(n.id||n.preferredId)+(n.direction&&n.direction!=="sendrecv"?"/"+n.direction:"")+" "+n.uri+`\r
6
- `},i.parseFmtp=function(n){for(var r,s={},o=n.substr(n.indexOf(" ")+1).split(";"),c=0;c<o.length;c++)s[(r=o[c].trim().split("="))[0].trim()]=r[1];return s},i.writeFmtp=function(n){var r="",s=n.payloadType;if(n.preferredPayloadType!==void 0&&(s=n.preferredPayloadType),n.parameters&&Object.keys(n.parameters).length){var o=[];Object.keys(n.parameters).forEach(function(c){n.parameters[c]?o.push(c+"="+n.parameters[c]):o.push(c)}),r+="a=fmtp:"+s+" "+o.join(";")+`\r
7
- `}return r},i.parseRtcpFb=function(n){var r=n.substr(n.indexOf(" ")+1).split(" ");return{type:r.shift(),parameter:r.join(" ")}},i.writeRtcpFb=function(n){var r="",s=n.payloadType;return n.preferredPayloadType!==void 0&&(s=n.preferredPayloadType),n.rtcpFeedback&&n.rtcpFeedback.length&&n.rtcpFeedback.forEach(function(o){r+="a=rtcp-fb:"+s+" "+o.type+(o.parameter&&o.parameter.length?" "+o.parameter:"")+`\r
8
- `}),r},i.parseSsrcMedia=function(n){var r=n.indexOf(" "),s={ssrc:parseInt(n.substr(7,r-7),10)},o=n.indexOf(":",r);return o>-1?(s.attribute=n.substr(r+1,o-r-1),s.value=n.substr(o+1)):s.attribute=n.substr(r+1),s},i.parseSsrcGroup=function(n){var r=n.substr(13).split(" ");return{semantics:r.shift(),ssrcs:r.map(function(s){return parseInt(s,10)})}},i.getMid=function(n){var r=i.matchPrefix(n,"a=mid:")[0];if(r)return r.substr(6)},i.parseFingerprint=function(n){var r=n.substr(14).split(" ");return{algorithm:r[0].toLowerCase(),value:r[1]}},i.getDtlsParameters=function(n,r){return{role:"auto",fingerprints:i.matchPrefix(n+r,"a=fingerprint:").map(i.parseFingerprint)}},i.writeDtlsParameters=function(n,r){var s="a=setup:"+r+`\r
9
- `;return n.fingerprints.forEach(function(o){s+="a=fingerprint:"+o.algorithm+" "+o.value+`\r
10
- `}),s},i.parseCryptoLine=function(n){var r=n.substr(9).split(" ");return{tag:parseInt(r[0],10),cryptoSuite:r[1],keyParams:r[2],sessionParams:r.slice(3)}},i.writeCryptoLine=function(n){return"a=crypto:"+n.tag+" "+n.cryptoSuite+" "+(typeof n.keyParams=="object"?i.writeCryptoKeyParams(n.keyParams):n.keyParams)+(n.sessionParams?" "+n.sessionParams.join(" "):"")+`\r
11
- `},i.parseCryptoKeyParams=function(n){if(n.indexOf("inline:")!==0)return null;var r=n.substr(7).split("|");return{keyMethod:"inline",keySalt:r[0],lifeTime:r[1],mkiValue:r[2]?r[2].split(":")[0]:void 0,mkiLength:r[2]?r[2].split(":")[1]:void 0}},i.writeCryptoKeyParams=function(n){return n.keyMethod+":"+n.keySalt+(n.lifeTime?"|"+n.lifeTime:"")+(n.mkiValue&&n.mkiLength?"|"+n.mkiValue+":"+n.mkiLength:"")},i.getCryptoParameters=function(n,r){return i.matchPrefix(n+r,"a=crypto:").map(i.parseCryptoLine)},i.getIceParameters=function(n,r){var s=i.matchPrefix(n+r,"a=ice-ufrag:")[0],o=i.matchPrefix(n+r,"a=ice-pwd:")[0];return s&&o?{usernameFragment:s.substr(12),password:o.substr(10)}:null},i.writeIceParameters=function(n){return"a=ice-ufrag:"+n.usernameFragment+`\r
6
+ `},i.parseFmtp=function(n){for(var r,o={},s=n.substr(n.indexOf(" ")+1).split(";"),c=0;c<s.length;c++)o[(r=s[c].trim().split("="))[0].trim()]=r[1];return o},i.writeFmtp=function(n){var r="",o=n.payloadType;if(n.preferredPayloadType!==void 0&&(o=n.preferredPayloadType),n.parameters&&Object.keys(n.parameters).length){var s=[];Object.keys(n.parameters).forEach(function(c){n.parameters[c]?s.push(c+"="+n.parameters[c]):s.push(c)}),r+="a=fmtp:"+o+" "+s.join(";")+`\r
7
+ `}return r},i.parseRtcpFb=function(n){var r=n.substr(n.indexOf(" ")+1).split(" ");return{type:r.shift(),parameter:r.join(" ")}},i.writeRtcpFb=function(n){var r="",o=n.payloadType;return n.preferredPayloadType!==void 0&&(o=n.preferredPayloadType),n.rtcpFeedback&&n.rtcpFeedback.length&&n.rtcpFeedback.forEach(function(s){r+="a=rtcp-fb:"+o+" "+s.type+(s.parameter&&s.parameter.length?" "+s.parameter:"")+`\r
8
+ `}),r},i.parseSsrcMedia=function(n){var r=n.indexOf(" "),o={ssrc:parseInt(n.substr(7,r-7),10)},s=n.indexOf(":",r);return s>-1?(o.attribute=n.substr(r+1,s-r-1),o.value=n.substr(s+1)):o.attribute=n.substr(r+1),o},i.parseSsrcGroup=function(n){var r=n.substr(13).split(" ");return{semantics:r.shift(),ssrcs:r.map(function(o){return parseInt(o,10)})}},i.getMid=function(n){var r=i.matchPrefix(n,"a=mid:")[0];if(r)return r.substr(6)},i.parseFingerprint=function(n){var r=n.substr(14).split(" ");return{algorithm:r[0].toLowerCase(),value:r[1]}},i.getDtlsParameters=function(n,r){return{role:"auto",fingerprints:i.matchPrefix(n+r,"a=fingerprint:").map(i.parseFingerprint)}},i.writeDtlsParameters=function(n,r){var o="a=setup:"+r+`\r
9
+ `;return n.fingerprints.forEach(function(s){o+="a=fingerprint:"+s.algorithm+" "+s.value+`\r
10
+ `}),o},i.parseCryptoLine=function(n){var r=n.substr(9).split(" ");return{tag:parseInt(r[0],10),cryptoSuite:r[1],keyParams:r[2],sessionParams:r.slice(3)}},i.writeCryptoLine=function(n){return"a=crypto:"+n.tag+" "+n.cryptoSuite+" "+(typeof n.keyParams=="object"?i.writeCryptoKeyParams(n.keyParams):n.keyParams)+(n.sessionParams?" "+n.sessionParams.join(" "):"")+`\r
11
+ `},i.parseCryptoKeyParams=function(n){if(n.indexOf("inline:")!==0)return null;var r=n.substr(7).split("|");return{keyMethod:"inline",keySalt:r[0],lifeTime:r[1],mkiValue:r[2]?r[2].split(":")[0]:void 0,mkiLength:r[2]?r[2].split(":")[1]:void 0}},i.writeCryptoKeyParams=function(n){return n.keyMethod+":"+n.keySalt+(n.lifeTime?"|"+n.lifeTime:"")+(n.mkiValue&&n.mkiLength?"|"+n.mkiValue+":"+n.mkiLength:"")},i.getCryptoParameters=function(n,r){return i.matchPrefix(n+r,"a=crypto:").map(i.parseCryptoLine)},i.getIceParameters=function(n,r){var o=i.matchPrefix(n+r,"a=ice-ufrag:")[0],s=i.matchPrefix(n+r,"a=ice-pwd:")[0];return o&&s?{usernameFragment:o.substr(12),password:s.substr(10)}:null},i.writeIceParameters=function(n){return"a=ice-ufrag:"+n.usernameFragment+`\r
12
12
  a=ice-pwd:`+n.password+`\r
13
- `},i.parseRtpParameters=function(n){for(var r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},s=i.splitLines(n)[0].split(" "),o=3;o<s.length;o++){var c=s[o],d=i.matchPrefix(n,"a=rtpmap:"+c+" ")[0];if(d){var a=i.parseRtpMap(d),h=i.matchPrefix(n,"a=fmtp:"+c+" ");switch(a.parameters=h.length?i.parseFmtp(h[0]):{},a.rtcpFeedback=i.matchPrefix(n,"a=rtcp-fb:"+c+" ").map(i.parseRtcpFb),r.codecs.push(a),a.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(a.name.toUpperCase())}}}return i.matchPrefix(n,"a=extmap:").forEach(function(u){r.headerExtensions.push(i.parseExtmap(u))}),r},i.writeRtpDescription=function(n,r){var s="";s+="m="+n+" ",s+=r.codecs.length>0?"9":"0",s+=" UDP/TLS/RTP/SAVPF ",s+=r.codecs.map(function(c){return c.preferredPayloadType!==void 0?c.preferredPayloadType:c.payloadType}).join(" ")+`\r
14
- `,s+=`c=IN IP4 0.0.0.0\r
15
- `,s+=`a=rtcp:9 IN IP4 0.0.0.0\r
16
- `,r.codecs.forEach(function(c){s+=i.writeRtpMap(c),s+=i.writeFmtp(c),s+=i.writeRtcpFb(c)});var o=0;return r.codecs.forEach(function(c){c.maxptime>o&&(o=c.maxptime)}),o>0&&(s+="a=maxptime:"+o+`\r
17
- `),s+=`a=rtcp-mux\r
18
- `,r.headerExtensions&&r.headerExtensions.forEach(function(c){s+=i.writeExtmap(c)}),s},i.parseRtpEncodingParameters=function(n){var r,s=[],o=i.parseRtpParameters(n),c=o.fecMechanisms.indexOf("RED")!==-1,d=o.fecMechanisms.indexOf("ULPFEC")!==-1,a=i.matchPrefix(n,"a=ssrc:").map(function(E){return i.parseSsrcMedia(E)}).filter(function(E){return E.attribute==="cname"}),h=a.length>0&&a[0].ssrc,u=i.matchPrefix(n,"a=ssrc-group:FID").map(function(E){return E.substr(17).split(" ").map(function(b){return parseInt(b,10)})});u.length>0&&u[0].length>1&&u[0][0]===h&&(r=u[0][1]),o.codecs.forEach(function(E){if(E.name.toUpperCase()==="RTX"&&E.parameters.apt){var b={ssrc:h,codecPayloadType:parseInt(E.parameters.apt,10)};h&&r&&(b.rtx={ssrc:r}),s.push(b),c&&((b=JSON.parse(JSON.stringify(b))).fec={ssrc:h,mechanism:d?"red+ulpfec":"red"},s.push(b))}}),s.length===0&&h&&s.push({ssrc:h});var g=i.matchPrefix(n,"b=");return g.length&&(g=g[0].indexOf("b=TIAS:")===0?parseInt(g[0].substr(7),10):g[0].indexOf("b=AS:")===0?1e3*parseInt(g[0].substr(5),10)*.95-16e3:void 0,s.forEach(function(E){E.maxBitrate=g})),s},i.parseRtcpParameters=function(n){var r={},s=i.matchPrefix(n,"a=ssrc:").map(function(d){return i.parseSsrcMedia(d)}).filter(function(d){return d.attribute==="cname"})[0];s&&(r.cname=s.value,r.ssrc=s.ssrc);var o=i.matchPrefix(n,"a=rtcp-rsize");r.reducedSize=o.length>0,r.compound=o.length===0;var c=i.matchPrefix(n,"a=rtcp-mux");return r.mux=c.length>0,r},i.parseMsid=function(n){var r,s=i.matchPrefix(n,"a=msid:");if(s.length===1)return{stream:(r=s[0].substr(7).split(" "))[0],track:r[1]};var o=i.matchPrefix(n,"a=ssrc:").map(function(c){return i.parseSsrcMedia(c)}).filter(function(c){return c.attribute==="msid"});return o.length>0?{stream:(r=o[0].value.split(" "))[0],track:r[1]}:void 0},i.parseSctpDescription=function(n){var r,s=i.parseMLine(n),o=i.matchPrefix(n,"a=max-message-size:");o.length>0&&(r=parseInt(o[0].substr(19),10)),isNaN(r)&&(r=65536);var c=i.matchPrefix(n,"a=sctp-port:");if(c.length>0)return{port:parseInt(c[0].substr(12),10),protocol:s.fmt,maxMessageSize:r};if(i.matchPrefix(n,"a=sctpmap:").length>0){var d=i.matchPrefix(n,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(d[0],10),protocol:d[1],maxMessageSize:r}}},i.writeSctpDescription=function(n,r){var s=[];return s=n.protocol!=="DTLS/SCTP"?["m="+n.kind+" 9 "+n.protocol+" "+r.protocol+`\r
13
+ `},i.parseRtpParameters=function(n){for(var r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},o=i.splitLines(n)[0].split(" "),s=3;s<o.length;s++){var c=o[s],d=i.matchPrefix(n,"a=rtpmap:"+c+" ")[0];if(d){var a=i.parseRtpMap(d),h=i.matchPrefix(n,"a=fmtp:"+c+" ");switch(a.parameters=h.length?i.parseFmtp(h[0]):{},a.rtcpFeedback=i.matchPrefix(n,"a=rtcp-fb:"+c+" ").map(i.parseRtcpFb),r.codecs.push(a),a.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(a.name.toUpperCase())}}}return i.matchPrefix(n,"a=extmap:").forEach(function(u){r.headerExtensions.push(i.parseExtmap(u))}),r},i.writeRtpDescription=function(n,r){var o="";o+="m="+n+" ",o+=r.codecs.length>0?"9":"0",o+=" UDP/TLS/RTP/SAVPF ",o+=r.codecs.map(function(c){return c.preferredPayloadType!==void 0?c.preferredPayloadType:c.payloadType}).join(" ")+`\r
14
+ `,o+=`c=IN IP4 0.0.0.0\r
15
+ `,o+=`a=rtcp:9 IN IP4 0.0.0.0\r
16
+ `,r.codecs.forEach(function(c){o+=i.writeRtpMap(c),o+=i.writeFmtp(c),o+=i.writeRtcpFb(c)});var s=0;return r.codecs.forEach(function(c){c.maxptime>s&&(s=c.maxptime)}),s>0&&(o+="a=maxptime:"+s+`\r
17
+ `),o+=`a=rtcp-mux\r
18
+ `,r.headerExtensions&&r.headerExtensions.forEach(function(c){o+=i.writeExtmap(c)}),o},i.parseRtpEncodingParameters=function(n){var r,o=[],s=i.parseRtpParameters(n),c=s.fecMechanisms.indexOf("RED")!==-1,d=s.fecMechanisms.indexOf("ULPFEC")!==-1,a=i.matchPrefix(n,"a=ssrc:").map(function(E){return i.parseSsrcMedia(E)}).filter(function(E){return E.attribute==="cname"}),h=a.length>0&&a[0].ssrc,u=i.matchPrefix(n,"a=ssrc-group:FID").map(function(E){return E.substr(17).split(" ").map(function(b){return parseInt(b,10)})});u.length>0&&u[0].length>1&&u[0][0]===h&&(r=u[0][1]),s.codecs.forEach(function(E){if(E.name.toUpperCase()==="RTX"&&E.parameters.apt){var b={ssrc:h,codecPayloadType:parseInt(E.parameters.apt,10)};h&&r&&(b.rtx={ssrc:r}),o.push(b),c&&((b=JSON.parse(JSON.stringify(b))).fec={ssrc:h,mechanism:d?"red+ulpfec":"red"},o.push(b))}}),o.length===0&&h&&o.push({ssrc:h});var f=i.matchPrefix(n,"b=");return f.length&&(f=f[0].indexOf("b=TIAS:")===0?parseInt(f[0].substr(7),10):f[0].indexOf("b=AS:")===0?1e3*parseInt(f[0].substr(5),10)*.95-16e3:void 0,o.forEach(function(E){E.maxBitrate=f})),o},i.parseRtcpParameters=function(n){var r={},o=i.matchPrefix(n,"a=ssrc:").map(function(d){return i.parseSsrcMedia(d)}).filter(function(d){return d.attribute==="cname"})[0];o&&(r.cname=o.value,r.ssrc=o.ssrc);var s=i.matchPrefix(n,"a=rtcp-rsize");r.reducedSize=s.length>0,r.compound=s.length===0;var c=i.matchPrefix(n,"a=rtcp-mux");return r.mux=c.length>0,r},i.parseMsid=function(n){var r,o=i.matchPrefix(n,"a=msid:");if(o.length===1)return{stream:(r=o[0].substr(7).split(" "))[0],track:r[1]};var s=i.matchPrefix(n,"a=ssrc:").map(function(c){return i.parseSsrcMedia(c)}).filter(function(c){return c.attribute==="msid"});return s.length>0?{stream:(r=s[0].value.split(" "))[0],track:r[1]}:void 0},i.parseSctpDescription=function(n){var r,o=i.parseMLine(n),s=i.matchPrefix(n,"a=max-message-size:");s.length>0&&(r=parseInt(s[0].substr(19),10)),isNaN(r)&&(r=65536);var c=i.matchPrefix(n,"a=sctp-port:");if(c.length>0)return{port:parseInt(c[0].substr(12),10),protocol:o.fmt,maxMessageSize:r};if(i.matchPrefix(n,"a=sctpmap:").length>0){var d=i.matchPrefix(n,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(d[0],10),protocol:d[1],maxMessageSize:r}}},i.writeSctpDescription=function(n,r){var o=[];return o=n.protocol!=="DTLS/SCTP"?["m="+n.kind+" 9 "+n.protocol+" "+r.protocol+`\r
19
19
  `,`c=IN IP4 0.0.0.0\r
20
20
  `,"a=sctp-port:"+r.port+`\r
21
21
  `]:["m="+n.kind+" 9 "+n.protocol+" "+r.port+`\r
22
22
  `,`c=IN IP4 0.0.0.0\r
23
23
  `,"a=sctpmap:"+r.port+" "+r.protocol+` 65535\r
24
- `],r.maxMessageSize!==void 0&&s.push("a=max-message-size:"+r.maxMessageSize+`\r
25
- `),s.join("")},i.generateSessionId=function(){return Math.random().toString().substr(2,21)},i.writeSessionBoilerplate=function(n,r,s){var o=r!==void 0?r:2;return`v=0\r
26
- o=`+(s||"thisisadapterortc")+" "+(n||i.generateSessionId())+" "+o+` IN IP4 127.0.0.1\r
24
+ `],r.maxMessageSize!==void 0&&o.push("a=max-message-size:"+r.maxMessageSize+`\r
25
+ `),o.join("")},i.generateSessionId=function(){return Math.random().toString().substr(2,21)},i.writeSessionBoilerplate=function(n,r,o){var s=r!==void 0?r:2;return`v=0\r
26
+ o=`+(o||"thisisadapterortc")+" "+(n||i.generateSessionId())+" "+s+` IN IP4 127.0.0.1\r
27
27
  s=-\r
28
28
  t=0 0\r
29
- `},i.writeMediaSection=function(n,r,s,o){var c=i.writeRtpDescription(n.kind,r);if(c+=i.writeIceParameters(n.iceGatherer.getLocalParameters()),c+=i.writeDtlsParameters(n.dtlsTransport.getLocalParameters(),s==="offer"?"actpass":"active"),c+="a=mid:"+n.mid+`\r
29
+ `},i.writeMediaSection=function(n,r,o,s){var c=i.writeRtpDescription(n.kind,r);if(c+=i.writeIceParameters(n.iceGatherer.getLocalParameters()),c+=i.writeDtlsParameters(n.dtlsTransport.getLocalParameters(),o==="offer"?"actpass":"active"),c+="a=mid:"+n.mid+`\r
30
30
  `,n.direction?c+="a="+n.direction+`\r
31
31
  `:n.rtpSender&&n.rtpReceiver?c+=`a=sendrecv\r
32
32
  `:n.rtpSender?c+=`a=sendonly\r
33
33
  `:n.rtpReceiver?c+=`a=recvonly\r
34
34
  `:c+=`a=inactive\r
35
- `,n.rtpSender){var d="msid:"+o.id+" "+n.rtpSender.track.id+`\r
35
+ `,n.rtpSender){var d="msid:"+s.id+" "+n.rtpSender.track.id+`\r
36
36
  `;c+="a="+d,c+="a=ssrc:"+n.sendEncodingParameters[0].ssrc+" "+d,n.sendEncodingParameters[0].rtx&&(c+="a=ssrc:"+n.sendEncodingParameters[0].rtx.ssrc+" "+d,c+="a=ssrc-group:FID "+n.sendEncodingParameters[0].ssrc+" "+n.sendEncodingParameters[0].rtx.ssrc+`\r
37
37
  `)}return c+="a=ssrc:"+n.sendEncodingParameters[0].ssrc+" cname:"+i.localCName+`\r
38
38
  `,n.rtpSender&&n.sendEncodingParameters[0].rtx&&(c+="a=ssrc:"+n.sendEncodingParameters[0].rtx.ssrc+" cname:"+i.localCName+`\r
39
- `),c},i.getDirection=function(n,r){for(var s=i.splitLines(n),o=0;o<s.length;o++)switch(s[o]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return s[o].substr(2)}return r?i.getDirection(r):"sendrecv"},i.getKind=function(n){return i.splitLines(n)[0].split(" ")[0].substr(2)},i.isRejected=function(n){return n.split(" ",2)[1]==="0"},i.parseMLine=function(n){var r=i.splitLines(n)[0].substr(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},i.parseOLine=function(n){var r=i.matchPrefix(n,"o=")[0].substr(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},i.isValidSDP=function(n){if(typeof n!="string"||n.length===0)return!1;for(var r=i.splitLines(n),s=0;s<r.length;s++)if(r[s].length<2||r[s].charAt(1)!=="=")return!1;return!0},typeof e=="object"&&(e.exports=i)},{}],NJ2u:[function(l,e,t){"use strict";var i=l("sdp");function n(h){return{inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[h.type]||h.type}function r(h,u,g,E,b){var y=i.writeRtpDescription(h.kind,u);if(y+=i.writeIceParameters(h.iceGatherer.getLocalParameters()),y+=i.writeDtlsParameters(h.dtlsTransport.getLocalParameters(),g==="offer"?"actpass":b||"active"),y+="a=mid:"+h.mid+`\r
39
+ `),c},i.getDirection=function(n,r){for(var o=i.splitLines(n),s=0;s<o.length;s++)switch(o[s]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return o[s].substr(2)}return r?i.getDirection(r):"sendrecv"},i.getKind=function(n){return i.splitLines(n)[0].split(" ")[0].substr(2)},i.isRejected=function(n){return n.split(" ",2)[1]==="0"},i.parseMLine=function(n){var r=i.splitLines(n)[0].substr(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},i.parseOLine=function(n){var r=i.matchPrefix(n,"o=")[0].substr(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},i.isValidSDP=function(n){if(typeof n!="string"||n.length===0)return!1;for(var r=i.splitLines(n),o=0;o<r.length;o++)if(r[o].length<2||r[o].charAt(1)!=="=")return!1;return!0},typeof e=="object"&&(e.exports=i)},{}],NJ2u:[function(l,e,t){"use strict";var i=l("sdp");function n(h){return{inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[h.type]||h.type}function r(h,u,f,E,b){var y=i.writeRtpDescription(h.kind,u);if(y+=i.writeIceParameters(h.iceGatherer.getLocalParameters()),y+=i.writeDtlsParameters(h.dtlsTransport.getLocalParameters(),f==="offer"?"actpass":b||"active"),y+="a=mid:"+h.mid+`\r
40
40
  `,h.rtpSender&&h.rtpReceiver?y+=`a=sendrecv\r
41
41
  `:h.rtpSender?y+=`a=sendonly\r
42
42
  `:h.rtpReceiver?y+=`a=recvonly\r
43
43
  `:y+=`a=inactive\r
44
- `,h.rtpSender){var m=h.rtpSender._initialTrackId||h.rtpSender.track.id;h.rtpSender._initialTrackId=m;var p="msid:"+(E?E.id:"-")+" "+m+`\r
44
+ `,h.rtpSender){var g=h.rtpSender._initialTrackId||h.rtpSender.track.id;h.rtpSender._initialTrackId=g;var p="msid:"+(E?E.id:"-")+" "+g+`\r
45
45
  `;y+="a="+p,y+="a=ssrc:"+h.sendEncodingParameters[0].ssrc+" "+p,h.sendEncodingParameters[0].rtx&&(y+="a=ssrc:"+h.sendEncodingParameters[0].rtx.ssrc+" "+p,y+="a=ssrc-group:FID "+h.sendEncodingParameters[0].ssrc+" "+h.sendEncodingParameters[0].rtx.ssrc+`\r
46
46
  `)}return y+="a=ssrc:"+h.sendEncodingParameters[0].ssrc+" cname:"+i.localCName+`\r
47
47
  `,h.rtpSender&&h.sendEncodingParameters[0].rtx&&(y+="a=ssrc:"+h.sendEncodingParameters[0].rtx.ssrc+" cname:"+i.localCName+`\r
48
- `),y}function s(h,u){var g=!1;return(h=JSON.parse(JSON.stringify(h))).filter(function(E){if(E&&(E.urls||E.url)){var b=E.urls||E.url;E.url&&!E.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var y=typeof b=="string";return y&&(b=[b]),b=b.filter(function(m){return m.indexOf("turn:")===0&&m.indexOf("transport=udp")!==-1&&m.indexOf("turn:[")===-1&&!g?(g=!0,!0):m.indexOf("stun:")===0&&u>=14393&&m.indexOf("?transport=udp")===-1}),delete E.url,E.urls=y?b[0]:b,!!b.length}})}function o(h,u){var g={codecs:[],headerExtensions:[],fecMechanisms:[]},E=function(y,m){y=parseInt(y,10);for(var p=0;p<m.length;p++)if(m[p].payloadType===y||m[p].preferredPayloadType===y)return m[p]},b=function(y,m,p,f){var v=E(y.parameters.apt,p),w=E(m.parameters.apt,f);return v&&w&&v.name.toLowerCase()===w.name.toLowerCase()};return h.codecs.forEach(function(y){for(var m=0;m<u.codecs.length;m++){var p=u.codecs[m];if(y.name.toLowerCase()===p.name.toLowerCase()&&y.clockRate===p.clockRate){if(y.name.toLowerCase()==="rtx"&&y.parameters&&p.parameters.apt&&!b(y,p,h.codecs,u.codecs))continue;(p=JSON.parse(JSON.stringify(p))).numChannels=Math.min(y.numChannels,p.numChannels),g.codecs.push(p),p.rtcpFeedback=p.rtcpFeedback.filter(function(f){for(var v=0;v<y.rtcpFeedback.length;v++)if(y.rtcpFeedback[v].type===f.type&&y.rtcpFeedback[v].parameter===f.parameter)return!0;return!1});break}}}),h.headerExtensions.forEach(function(y){for(var m=0;m<u.headerExtensions.length;m++){var p=u.headerExtensions[m];if(y.uri===p.uri){g.headerExtensions.push(p);break}}}),g}function c(h,u,g){return{offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}}[u][h].indexOf(g)!==-1}function d(h,u){var g=h.getRemoteCandidates().find(function(E){return u.foundation===E.foundation&&u.ip===E.ip&&u.port===E.port&&u.priority===E.priority&&u.protocol===E.protocol&&u.type===E.type});return g||h.addRemoteCandidate(u),!g}function a(h,u){var g=new Error(u);return g.name=h,g.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[h],g}e.exports=function(h,u){function g(m,p){p.addTrack(m),p.dispatchEvent(new h.MediaStreamTrackEvent("addtrack",{track:m}))}function E(m,p,f,v){var w=new Event("track");w.track=p,w.receiver=f,w.transceiver={receiver:f},w.streams=v,h.setTimeout(function(){m._dispatchEvent("track",w)})}var b=function(m){var p=this,f=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach(function(w){p[w]=f[w].bind(f)}),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",m=JSON.parse(JSON.stringify(m||{})),this.usingBundle=m.bundlePolicy==="max-bundle",m.rtcpMuxPolicy==="negotiate")throw a("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(m.rtcpMuxPolicy||(m.rtcpMuxPolicy="require"),m.iceTransportPolicy){case"all":case"relay":break;default:m.iceTransportPolicy="all"}switch(m.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:m.bundlePolicy="balanced"}if(m.iceServers=s(m.iceServers||[],u),this._iceGatherers=[],m.iceCandidatePoolSize)for(var v=m.iceCandidatePoolSize;v>0;v--)this._iceGatherers.push(new h.RTCIceGatherer({iceServers:m.iceServers,gatherPolicy:m.iceTransportPolicy}));else m.iceCandidatePoolSize=0;this._config=m,this.transceivers=[],this._sdpSessionId=i.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(b.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(b.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),b.prototype.onicecandidate=null,b.prototype.onaddstream=null,b.prototype.ontrack=null,b.prototype.onremovestream=null,b.prototype.onsignalingstatechange=null,b.prototype.oniceconnectionstatechange=null,b.prototype.onconnectionstatechange=null,b.prototype.onicegatheringstatechange=null,b.prototype.onnegotiationneeded=null,b.prototype.ondatachannel=null,b.prototype._dispatchEvent=function(m,p){this._isClosed||(this.dispatchEvent(p),typeof this["on"+m]=="function"&&this["on"+m](p))},b.prototype._emitGatheringStateChange=function(){var m=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",m)},b.prototype.getConfiguration=function(){return this._config},b.prototype.getLocalStreams=function(){return this.localStreams},b.prototype.getRemoteStreams=function(){return this.remoteStreams},b.prototype._createTransceiver=function(m,p){var f=this.transceivers.length>0,v={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:m,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&f)v.iceTransport=this.transceivers[0].iceTransport,v.dtlsTransport=this.transceivers[0].dtlsTransport;else{var w=this._createIceAndDtlsTransports();v.iceTransport=w.iceTransport,v.dtlsTransport=w.dtlsTransport}return p||this.transceivers.push(v),v},b.prototype.addTrack=function(m,p){if(this._isClosed)throw a("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var f;if(this.transceivers.find(function(w){return w.track===m}))throw a("InvalidAccessError","Track already exists.");for(var v=0;v<this.transceivers.length;v++)this.transceivers[v].track||this.transceivers[v].kind!==m.kind||(f=this.transceivers[v]);return f||(f=this._createTransceiver(m.kind)),this._maybeFireNegotiationNeeded(),this.localStreams.indexOf(p)===-1&&this.localStreams.push(p),f.track=m,f.stream=p,f.rtpSender=new h.RTCRtpSender(m,f.dtlsTransport),f.rtpSender},b.prototype.addStream=function(m){var p=this;if(u>=15025)m.getTracks().forEach(function(v){p.addTrack(v,m)});else{var f=m.clone();m.getTracks().forEach(function(v,w){var x=f.getTracks()[w];v.addEventListener("enabled",function(T){x.enabled=T.enabled})}),f.getTracks().forEach(function(v){p.addTrack(v,f)})}},b.prototype.removeTrack=function(m){if(this._isClosed)throw a("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(m instanceof h.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var p=this.transceivers.find(function(v){return v.rtpSender===m});if(!p)throw a("InvalidAccessError","Sender was not created by this connection.");var f=p.stream;p.rtpSender.stop(),p.rtpSender=null,p.track=null,p.stream=null,this.transceivers.map(function(v){return v.stream}).indexOf(f)===-1&&this.localStreams.indexOf(f)>-1&&this.localStreams.splice(this.localStreams.indexOf(f),1),this._maybeFireNegotiationNeeded()},b.prototype.removeStream=function(m){var p=this;m.getTracks().forEach(function(f){var v=p.getSenders().find(function(w){return w.track===f});v&&p.removeTrack(v)})},b.prototype.getSenders=function(){return this.transceivers.filter(function(m){return!!m.rtpSender}).map(function(m){return m.rtpSender})},b.prototype.getReceivers=function(){return this.transceivers.filter(function(m){return!!m.rtpReceiver}).map(function(m){return m.rtpReceiver})},b.prototype._createIceGatherer=function(m,p){var f=this;if(p&&m>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var v=new h.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(v,"state",{value:"new",writable:!0}),this.transceivers[m].bufferedCandidateEvents=[],this.transceivers[m].bufferCandidates=function(w){var x=!w.candidate||Object.keys(w.candidate).length===0;v.state=x?"completed":"gathering",f.transceivers[m].bufferedCandidateEvents!==null&&f.transceivers[m].bufferedCandidateEvents.push(w)},v.addEventListener("localcandidate",this.transceivers[m].bufferCandidates),v},b.prototype._gather=function(m,p){var f=this,v=this.transceivers[p].iceGatherer;if(!v.onlocalcandidate){var w=this.transceivers[p].bufferedCandidateEvents;this.transceivers[p].bufferedCandidateEvents=null,v.removeEventListener("localcandidate",this.transceivers[p].bufferCandidates),v.onlocalcandidate=function(x){if(!(f.usingBundle&&p>0)){var T=new Event("icecandidate");T.candidate={sdpMid:m,sdpMLineIndex:p};var R=x.candidate,C=!R||Object.keys(R).length===0;if(C)v.state!=="new"&&v.state!=="gathering"||(v.state="completed");else{v.state==="new"&&(v.state="gathering"),R.component=1,R.ufrag=v.getLocalParameters().usernameFragment;var P=i.writeCandidate(R);T.candidate=Object.assign(T.candidate,i.parseCandidate(P)),T.candidate.candidate=P,T.candidate.toJSON=function(){return{candidate:T.candidate.candidate,sdpMid:T.candidate.sdpMid,sdpMLineIndex:T.candidate.sdpMLineIndex,usernameFragment:T.candidate.usernameFragment}}}var S=i.getMediaSections(f._localDescription.sdp);S[T.candidate.sdpMLineIndex]+=C?`a=end-of-candidates\r
48
+ `),y}function o(h,u){var f=!1;return(h=JSON.parse(JSON.stringify(h))).filter(function(E){if(E&&(E.urls||E.url)){var b=E.urls||E.url;E.url&&!E.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var y=typeof b=="string";return y&&(b=[b]),b=b.filter(function(g){return g.indexOf("turn:")===0&&g.indexOf("transport=udp")!==-1&&g.indexOf("turn:[")===-1&&!f?(f=!0,!0):g.indexOf("stun:")===0&&u>=14393&&g.indexOf("?transport=udp")===-1}),delete E.url,E.urls=y?b[0]:b,!!b.length}})}function s(h,u){var f={codecs:[],headerExtensions:[],fecMechanisms:[]},E=function(y,g){y=parseInt(y,10);for(var p=0;p<g.length;p++)if(g[p].payloadType===y||g[p].preferredPayloadType===y)return g[p]},b=function(y,g,p,m){var v=E(y.parameters.apt,p),w=E(g.parameters.apt,m);return v&&w&&v.name.toLowerCase()===w.name.toLowerCase()};return h.codecs.forEach(function(y){for(var g=0;g<u.codecs.length;g++){var p=u.codecs[g];if(y.name.toLowerCase()===p.name.toLowerCase()&&y.clockRate===p.clockRate){if(y.name.toLowerCase()==="rtx"&&y.parameters&&p.parameters.apt&&!b(y,p,h.codecs,u.codecs))continue;(p=JSON.parse(JSON.stringify(p))).numChannels=Math.min(y.numChannels,p.numChannels),f.codecs.push(p),p.rtcpFeedback=p.rtcpFeedback.filter(function(m){for(var v=0;v<y.rtcpFeedback.length;v++)if(y.rtcpFeedback[v].type===m.type&&y.rtcpFeedback[v].parameter===m.parameter)return!0;return!1});break}}}),h.headerExtensions.forEach(function(y){for(var g=0;g<u.headerExtensions.length;g++){var p=u.headerExtensions[g];if(y.uri===p.uri){f.headerExtensions.push(p);break}}}),f}function c(h,u,f){return{offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}}[u][h].indexOf(f)!==-1}function d(h,u){var f=h.getRemoteCandidates().find(function(E){return u.foundation===E.foundation&&u.ip===E.ip&&u.port===E.port&&u.priority===E.priority&&u.protocol===E.protocol&&u.type===E.type});return f||h.addRemoteCandidate(u),!f}function a(h,u){var f=new Error(u);return f.name=h,f.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[h],f}e.exports=function(h,u){function f(g,p){p.addTrack(g),p.dispatchEvent(new h.MediaStreamTrackEvent("addtrack",{track:g}))}function E(g,p,m,v){var w=new Event("track");w.track=p,w.receiver=m,w.transceiver={receiver:m},w.streams=v,h.setTimeout(function(){g._dispatchEvent("track",w)})}var b=function(g){var p=this,m=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach(function(w){p[w]=m[w].bind(m)}),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",g=JSON.parse(JSON.stringify(g||{})),this.usingBundle=g.bundlePolicy==="max-bundle",g.rtcpMuxPolicy==="negotiate")throw a("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(g.rtcpMuxPolicy||(g.rtcpMuxPolicy="require"),g.iceTransportPolicy){case"all":case"relay":break;default:g.iceTransportPolicy="all"}switch(g.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:g.bundlePolicy="balanced"}if(g.iceServers=o(g.iceServers||[],u),this._iceGatherers=[],g.iceCandidatePoolSize)for(var v=g.iceCandidatePoolSize;v>0;v--)this._iceGatherers.push(new h.RTCIceGatherer({iceServers:g.iceServers,gatherPolicy:g.iceTransportPolicy}));else g.iceCandidatePoolSize=0;this._config=g,this.transceivers=[],this._sdpSessionId=i.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(b.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(b.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),b.prototype.onicecandidate=null,b.prototype.onaddstream=null,b.prototype.ontrack=null,b.prototype.onremovestream=null,b.prototype.onsignalingstatechange=null,b.prototype.oniceconnectionstatechange=null,b.prototype.onconnectionstatechange=null,b.prototype.onicegatheringstatechange=null,b.prototype.onnegotiationneeded=null,b.prototype.ondatachannel=null,b.prototype._dispatchEvent=function(g,p){this._isClosed||(this.dispatchEvent(p),typeof this["on"+g]=="function"&&this["on"+g](p))},b.prototype._emitGatheringStateChange=function(){var g=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",g)},b.prototype.getConfiguration=function(){return this._config},b.prototype.getLocalStreams=function(){return this.localStreams},b.prototype.getRemoteStreams=function(){return this.remoteStreams},b.prototype._createTransceiver=function(g,p){var m=this.transceivers.length>0,v={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:g,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&m)v.iceTransport=this.transceivers[0].iceTransport,v.dtlsTransport=this.transceivers[0].dtlsTransport;else{var w=this._createIceAndDtlsTransports();v.iceTransport=w.iceTransport,v.dtlsTransport=w.dtlsTransport}return p||this.transceivers.push(v),v},b.prototype.addTrack=function(g,p){if(this._isClosed)throw a("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var m;if(this.transceivers.find(function(w){return w.track===g}))throw a("InvalidAccessError","Track already exists.");for(var v=0;v<this.transceivers.length;v++)this.transceivers[v].track||this.transceivers[v].kind!==g.kind||(m=this.transceivers[v]);return m||(m=this._createTransceiver(g.kind)),this._maybeFireNegotiationNeeded(),this.localStreams.indexOf(p)===-1&&this.localStreams.push(p),m.track=g,m.stream=p,m.rtpSender=new h.RTCRtpSender(g,m.dtlsTransport),m.rtpSender},b.prototype.addStream=function(g){var p=this;if(u>=15025)g.getTracks().forEach(function(v){p.addTrack(v,g)});else{var m=g.clone();g.getTracks().forEach(function(v,w){var x=m.getTracks()[w];v.addEventListener("enabled",function(T){x.enabled=T.enabled})}),m.getTracks().forEach(function(v){p.addTrack(v,m)})}},b.prototype.removeTrack=function(g){if(this._isClosed)throw a("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(g instanceof h.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var p=this.transceivers.find(function(v){return v.rtpSender===g});if(!p)throw a("InvalidAccessError","Sender was not created by this connection.");var m=p.stream;p.rtpSender.stop(),p.rtpSender=null,p.track=null,p.stream=null,this.transceivers.map(function(v){return v.stream}).indexOf(m)===-1&&this.localStreams.indexOf(m)>-1&&this.localStreams.splice(this.localStreams.indexOf(m),1),this._maybeFireNegotiationNeeded()},b.prototype.removeStream=function(g){var p=this;g.getTracks().forEach(function(m){var v=p.getSenders().find(function(w){return w.track===m});v&&p.removeTrack(v)})},b.prototype.getSenders=function(){return this.transceivers.filter(function(g){return!!g.rtpSender}).map(function(g){return g.rtpSender})},b.prototype.getReceivers=function(){return this.transceivers.filter(function(g){return!!g.rtpReceiver}).map(function(g){return g.rtpReceiver})},b.prototype._createIceGatherer=function(g,p){var m=this;if(p&&g>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var v=new h.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(v,"state",{value:"new",writable:!0}),this.transceivers[g].bufferedCandidateEvents=[],this.transceivers[g].bufferCandidates=function(w){var x=!w.candidate||Object.keys(w.candidate).length===0;v.state=x?"completed":"gathering",m.transceivers[g].bufferedCandidateEvents!==null&&m.transceivers[g].bufferedCandidateEvents.push(w)},v.addEventListener("localcandidate",this.transceivers[g].bufferCandidates),v},b.prototype._gather=function(g,p){var m=this,v=this.transceivers[p].iceGatherer;if(!v.onlocalcandidate){var w=this.transceivers[p].bufferedCandidateEvents;this.transceivers[p].bufferedCandidateEvents=null,v.removeEventListener("localcandidate",this.transceivers[p].bufferCandidates),v.onlocalcandidate=function(x){if(!(m.usingBundle&&p>0)){var T=new Event("icecandidate");T.candidate={sdpMid:g,sdpMLineIndex:p};var R=x.candidate,C=!R||Object.keys(R).length===0;if(C)v.state!=="new"&&v.state!=="gathering"||(v.state="completed");else{v.state==="new"&&(v.state="gathering"),R.component=1,R.ufrag=v.getLocalParameters().usernameFragment;var P=i.writeCandidate(R);T.candidate=Object.assign(T.candidate,i.parseCandidate(P)),T.candidate.candidate=P,T.candidate.toJSON=function(){return{candidate:T.candidate.candidate,sdpMid:T.candidate.sdpMid,sdpMLineIndex:T.candidate.sdpMLineIndex,usernameFragment:T.candidate.usernameFragment}}}var S=i.getMediaSections(m._localDescription.sdp);S[T.candidate.sdpMLineIndex]+=C?`a=end-of-candidates\r
49
49
  `:"a="+T.candidate.candidate+`\r
50
- `,f._localDescription.sdp=i.getDescription(f._localDescription.sdp)+S.join("");var L=f.transceivers.every(function(I){return I.iceGatherer&&I.iceGatherer.state==="completed"});f.iceGatheringState!=="gathering"&&(f.iceGatheringState="gathering",f._emitGatheringStateChange()),C||f._dispatchEvent("icecandidate",T),L&&(f._dispatchEvent("icecandidate",new Event("icecandidate")),f.iceGatheringState="complete",f._emitGatheringStateChange())}},h.setTimeout(function(){w.forEach(function(x){v.onlocalcandidate(x)})},0)}},b.prototype._createIceAndDtlsTransports=function(){var m=this,p=new h.RTCIceTransport(null);p.onicestatechange=function(){m._updateIceConnectionState(),m._updateConnectionState()};var f=new h.RTCDtlsTransport(p);return f.ondtlsstatechange=function(){m._updateConnectionState()},f.onerror=function(){Object.defineProperty(f,"state",{value:"failed",writable:!0}),m._updateConnectionState()},{iceTransport:p,dtlsTransport:f}},b.prototype._disposeIceAndDtlsTransports=function(m){var p=this.transceivers[m].iceGatherer;p&&(delete p.onlocalcandidate,delete this.transceivers[m].iceGatherer);var f=this.transceivers[m].iceTransport;f&&(delete f.onicestatechange,delete this.transceivers[m].iceTransport);var v=this.transceivers[m].dtlsTransport;v&&(delete v.ondtlsstatechange,delete v.onerror,delete this.transceivers[m].dtlsTransport)},b.prototype._transceive=function(m,p,f){var v=o(m.localCapabilities,m.remoteCapabilities);p&&m.rtpSender&&(v.encodings=m.sendEncodingParameters,v.rtcp={cname:i.localCName,compound:m.rtcpParameters.compound},m.recvEncodingParameters.length&&(v.rtcp.ssrc=m.recvEncodingParameters[0].ssrc),m.rtpSender.send(v)),f&&m.rtpReceiver&&v.codecs.length>0&&(m.kind==="video"&&m.recvEncodingParameters&&u<15019&&m.recvEncodingParameters.forEach(function(w){delete w.rtx}),m.recvEncodingParameters.length?v.encodings=m.recvEncodingParameters:v.encodings=[{}],v.rtcp={compound:m.rtcpParameters.compound},m.rtcpParameters.cname&&(v.rtcp.cname=m.rtcpParameters.cname),m.sendEncodingParameters.length&&(v.rtcp.ssrc=m.sendEncodingParameters[0].ssrc),m.rtpReceiver.receive(v))},b.prototype.setLocalDescription=function(m){var p,f,v=this;if(["offer","answer"].indexOf(m.type)===-1)return Promise.reject(a("TypeError",'Unsupported type "'+m.type+'"'));if(!c("setLocalDescription",m.type,v.signalingState)||v._isClosed)return Promise.reject(a("InvalidStateError","Can not set local "+m.type+" in state "+v.signalingState));if(m.type==="offer")p=i.splitSections(m.sdp),f=p.shift(),p.forEach(function(x,T){var R=i.parseRtpParameters(x);v.transceivers[T].localCapabilities=R}),v.transceivers.forEach(function(x,T){v._gather(x.mid,T)});else if(m.type==="answer"){p=i.splitSections(v._remoteDescription.sdp),f=p.shift();var w=i.matchPrefix(f,"a=ice-lite").length>0;p.forEach(function(x,T){var R=v.transceivers[T],C=R.iceGatherer,P=R.iceTransport,S=R.dtlsTransport,L=R.localCapabilities,I=R.remoteCapabilities;if(!(i.isRejected(x)&&i.matchPrefix(x,"a=bundle-only").length===0)&&!R.rejected){var j=i.getIceParameters(x,f),H=i.getDtlsParameters(x,f);w&&(H.role="server"),v.usingBundle&&T!==0||(v._gather(R.mid,T),P.state==="new"&&P.start(C,j,w?"controlling":"controlled"),S.state==="new"&&S.start(H));var F=o(L,I);v._transceive(R,F.codecs.length>0,!1)}})}return v._localDescription={type:m.type,sdp:m.sdp},m.type==="offer"?v._updateSignalingState("have-local-offer"):v._updateSignalingState("stable"),Promise.resolve()},b.prototype.setRemoteDescription=function(m){var p=this;if(["offer","answer"].indexOf(m.type)===-1)return Promise.reject(a("TypeError",'Unsupported type "'+m.type+'"'));if(!c("setRemoteDescription",m.type,p.signalingState)||p._isClosed)return Promise.reject(a("InvalidStateError","Can not set remote "+m.type+" in state "+p.signalingState));var f={};p.remoteStreams.forEach(function(P){f[P.id]=P});var v=[],w=i.splitSections(m.sdp),x=w.shift(),T=i.matchPrefix(x,"a=ice-lite").length>0,R=i.matchPrefix(x,"a=group:BUNDLE ").length>0;p.usingBundle=R;var C=i.matchPrefix(x,"a=ice-options:")[0];return p.canTrickleIceCandidates=!!C&&C.substr(14).split(" ").indexOf("trickle")>=0,w.forEach(function(P,S){var L=i.splitLines(P),I=i.getKind(P),j=i.isRejected(P)&&i.matchPrefix(P,"a=bundle-only").length===0,H=L[0].substr(2).split(" ")[2],F=i.getDirection(P,x),U=i.parseMsid(P),J=i.getMid(P)||i.generateIdentifier();if(j||I==="application"&&(H==="DTLS/SCTP"||H==="UDP/DTLS/SCTP"))p.transceivers[S]={mid:J,kind:I,protocol:H,rejected:!0};else{var W,ze,ge,X,qe,ln,zn,Pi,Pt;!j&&p.transceivers[S]&&p.transceivers[S].rejected&&(p.transceivers[S]=p._createTransceiver(I,!0));var Ud,qd,Xd=i.parseRtpParameters(P);j||(Ud=i.getIceParameters(P,x),(qd=i.getDtlsParameters(P,x)).role="client"),zn=i.parseRtpEncodingParameters(P);var Qd=i.parseRtcpParameters(P),Yd=i.matchPrefix(P,"a=end-of-candidates",x).length>0,xr=i.matchPrefix(P,"a=candidate:").map(function(rt){return i.parseCandidate(rt)}).filter(function(rt){return rt.component===1});if((m.type==="offer"||m.type==="answer")&&!j&&R&&S>0&&p.transceivers[S]&&(p._disposeIceAndDtlsTransports(S),p.transceivers[S].iceGatherer=p.transceivers[0].iceGatherer,p.transceivers[S].iceTransport=p.transceivers[0].iceTransport,p.transceivers[S].dtlsTransport=p.transceivers[0].dtlsTransport,p.transceivers[S].rtpSender&&p.transceivers[S].rtpSender.setTransport(p.transceivers[0].dtlsTransport),p.transceivers[S].rtpReceiver&&p.transceivers[S].rtpReceiver.setTransport(p.transceivers[0].dtlsTransport)),m.type!=="offer"||j)m.type==="answer"&&!j&&(ze=(W=p.transceivers[S]).iceGatherer,ge=W.iceTransport,X=W.dtlsTransport,qe=W.rtpReceiver,ln=W.sendEncodingParameters,Pi=W.localCapabilities,p.transceivers[S].recvEncodingParameters=zn,p.transceivers[S].remoteCapabilities=Xd,p.transceivers[S].rtcpParameters=Qd,xr.length&&ge.state==="new"&&(!T&&!Yd||R&&S!==0?xr.forEach(function(rt){d(W.iceTransport,rt)}):ge.setRemoteCandidates(xr)),R&&S!==0||(ge.state==="new"&&ge.start(ze,Ud,"controlling"),X.state==="new"&&X.start(qd)),!o(W.localCapabilities,W.remoteCapabilities).codecs.filter(function(rt){return rt.name.toLowerCase()==="rtx"}).length&&W.sendEncodingParameters[0].rtx&&delete W.sendEncodingParameters[0].rtx,p._transceive(W,F==="sendrecv"||F==="recvonly",F==="sendrecv"||F==="sendonly"),!qe||F!=="sendrecv"&&F!=="sendonly"?delete W.rtpReceiver:(Pt=qe.track,U?(f[U.stream]||(f[U.stream]=new h.MediaStream),g(Pt,f[U.stream]),v.push([Pt,qe,f[U.stream]])):(f.default||(f.default=new h.MediaStream),g(Pt,f.default),v.push([Pt,qe,f.default]))));else{(W=p.transceivers[S]||p._createTransceiver(I)).mid=J,W.iceGatherer||(W.iceGatherer=p._createIceGatherer(S,R)),xr.length&&W.iceTransport.state==="new"&&(!Yd||R&&S!==0?xr.forEach(function(rt){d(W.iceTransport,rt)}):W.iceTransport.setRemoteCandidates(xr)),Pi=h.RTCRtpReceiver.getCapabilities(I),u<15019&&(Pi.codecs=Pi.codecs.filter(function(rt){return rt.name!=="rtx"})),ln=W.sendEncodingParameters||[{ssrc:1001*(2*S+2)}];var Tr,ml=!1;F==="sendrecv"||F==="sendonly"?(ml=!W.rtpReceiver,qe=W.rtpReceiver||new h.RTCRtpReceiver(W.dtlsTransport,I),ml&&(Pt=qe.track,U&&U.stream==="-"||(U?(f[U.stream]||(f[U.stream]=new h.MediaStream,Object.defineProperty(f[U.stream],"id",{get:function(){return U.stream}})),Object.defineProperty(Pt,"id",{get:function(){return U.track}}),Tr=f[U.stream]):(f.default||(f.default=new h.MediaStream),Tr=f.default)),Tr&&(g(Pt,Tr),W.associatedRemoteMediaStreams.push(Tr)),v.push([Pt,qe,Tr]))):W.rtpReceiver&&W.rtpReceiver.track&&(W.associatedRemoteMediaStreams.forEach(function(rt){var gl,Zd,Jd=rt.getTracks().find(function(_f){return _f.id===W.rtpReceiver.track.id});Jd&&(gl=Jd,(Zd=rt).removeTrack(gl),Zd.dispatchEvent(new h.MediaStreamTrackEvent("removetrack",{track:gl})))}),W.associatedRemoteMediaStreams=[]),W.localCapabilities=Pi,W.remoteCapabilities=Xd,W.rtpReceiver=qe,W.rtcpParameters=Qd,W.sendEncodingParameters=ln,W.recvEncodingParameters=zn,p._transceive(p.transceivers[S],!1,ml)}}}),p._dtlsRole===void 0&&(p._dtlsRole=m.type==="offer"?"active":"passive"),p._remoteDescription={type:m.type,sdp:m.sdp},m.type==="offer"?p._updateSignalingState("have-remote-offer"):p._updateSignalingState("stable"),Object.keys(f).forEach(function(P){var S=f[P];if(S.getTracks().length){if(p.remoteStreams.indexOf(S)===-1){p.remoteStreams.push(S);var L=new Event("addstream");L.stream=S,h.setTimeout(function(){p._dispatchEvent("addstream",L)})}v.forEach(function(I){var j=I[0],H=I[1];S.id===I[2].id&&E(p,j,H,[S])})}}),v.forEach(function(P){P[2]||E(p,P[0],P[1],[])}),h.setTimeout(function(){p&&p.transceivers&&p.transceivers.forEach(function(P){P.iceTransport&&P.iceTransport.state==="new"&&P.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),P.iceTransport.addRemoteCandidate({}))})},4e3),Promise.resolve()},b.prototype.close=function(){this.transceivers.forEach(function(m){m.iceTransport&&m.iceTransport.stop(),m.dtlsTransport&&m.dtlsTransport.stop(),m.rtpSender&&m.rtpSender.stop(),m.rtpReceiver&&m.rtpReceiver.stop()}),this._isClosed=!0,this._updateSignalingState("closed")},b.prototype._updateSignalingState=function(m){this.signalingState=m;var p=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",p)},b.prototype._maybeFireNegotiationNeeded=function(){var m=this;this.signalingState==="stable"&&this.needNegotiation!==!0&&(this.needNegotiation=!0,h.setTimeout(function(){if(m.needNegotiation){m.needNegotiation=!1;var p=new Event("negotiationneeded");m._dispatchEvent("negotiationneeded",p)}},0))},b.prototype._updateIceConnectionState=function(){var m,p={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(v){v.iceTransport&&!v.rejected&&p[v.iceTransport.state]++}),m="new",p.failed>0?m="failed":p.checking>0?m="checking":p.disconnected>0?m="disconnected":p.new>0?m="new":p.connected>0?m="connected":p.completed>0&&(m="completed"),m!==this.iceConnectionState){this.iceConnectionState=m;var f=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",f)}},b.prototype._updateConnectionState=function(){var m,p={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(v){v.iceTransport&&v.dtlsTransport&&!v.rejected&&(p[v.iceTransport.state]++,p[v.dtlsTransport.state]++)}),p.connected+=p.completed,m="new",p.failed>0?m="failed":p.connecting>0?m="connecting":p.disconnected>0?m="disconnected":p.new>0?m="new":p.connected>0&&(m="connected"),m!==this.connectionState){this.connectionState=m;var f=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",f)}},b.prototype.createOffer=function(){var m=this;if(m._isClosed)return Promise.reject(a("InvalidStateError","Can not call createOffer after close"));var p=m.transceivers.filter(function(T){return T.kind==="audio"}).length,f=m.transceivers.filter(function(T){return T.kind==="video"}).length,v=arguments[0];if(v){if(v.mandatory||v.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");v.offerToReceiveAudio!==void 0&&(p=v.offerToReceiveAudio===!0?1:v.offerToReceiveAudio===!1?0:v.offerToReceiveAudio),v.offerToReceiveVideo!==void 0&&(f=v.offerToReceiveVideo===!0?1:v.offerToReceiveVideo===!1?0:v.offerToReceiveVideo)}for(m.transceivers.forEach(function(T){T.kind==="audio"?--p<0&&(T.wantReceive=!1):T.kind==="video"&&--f<0&&(T.wantReceive=!1)});p>0||f>0;)p>0&&(m._createTransceiver("audio"),p--),f>0&&(m._createTransceiver("video"),f--);var w=i.writeSessionBoilerplate(m._sdpSessionId,m._sdpSessionVersion++);m.transceivers.forEach(function(T,R){var C=T.track,P=T.kind,S=T.mid||i.generateIdentifier();T.mid=S,T.iceGatherer||(T.iceGatherer=m._createIceGatherer(R,m.usingBundle));var L=h.RTCRtpSender.getCapabilities(P);u<15019&&(L.codecs=L.codecs.filter(function(j){return j.name!=="rtx"})),L.codecs.forEach(function(j){j.name==="H264"&&j.parameters["level-asymmetry-allowed"]===void 0&&(j.parameters["level-asymmetry-allowed"]="1"),T.remoteCapabilities&&T.remoteCapabilities.codecs&&T.remoteCapabilities.codecs.forEach(function(H){j.name.toLowerCase()===H.name.toLowerCase()&&j.clockRate===H.clockRate&&(j.preferredPayloadType=H.payloadType)})}),L.headerExtensions.forEach(function(j){(T.remoteCapabilities&&T.remoteCapabilities.headerExtensions||[]).forEach(function(H){j.uri===H.uri&&(j.id=H.id)})});var I=T.sendEncodingParameters||[{ssrc:1001*(2*R+1)}];C&&u>=15019&&P==="video"&&!I[0].rtx&&(I[0].rtx={ssrc:I[0].ssrc+1}),T.wantReceive&&(T.rtpReceiver=new h.RTCRtpReceiver(T.dtlsTransport,P)),T.localCapabilities=L,T.sendEncodingParameters=I}),m._config.bundlePolicy!=="max-compat"&&(w+="a=group:BUNDLE "+m.transceivers.map(function(T){return T.mid}).join(" ")+`\r
50
+ `,m._localDescription.sdp=i.getDescription(m._localDescription.sdp)+S.join("");var L=m.transceivers.every(function(I){return I.iceGatherer&&I.iceGatherer.state==="completed"});m.iceGatheringState!=="gathering"&&(m.iceGatheringState="gathering",m._emitGatheringStateChange()),C||m._dispatchEvent("icecandidate",T),L&&(m._dispatchEvent("icecandidate",new Event("icecandidate")),m.iceGatheringState="complete",m._emitGatheringStateChange())}},h.setTimeout(function(){w.forEach(function(x){v.onlocalcandidate(x)})},0)}},b.prototype._createIceAndDtlsTransports=function(){var g=this,p=new h.RTCIceTransport(null);p.onicestatechange=function(){g._updateIceConnectionState(),g._updateConnectionState()};var m=new h.RTCDtlsTransport(p);return m.ondtlsstatechange=function(){g._updateConnectionState()},m.onerror=function(){Object.defineProperty(m,"state",{value:"failed",writable:!0}),g._updateConnectionState()},{iceTransport:p,dtlsTransport:m}},b.prototype._disposeIceAndDtlsTransports=function(g){var p=this.transceivers[g].iceGatherer;p&&(delete p.onlocalcandidate,delete this.transceivers[g].iceGatherer);var m=this.transceivers[g].iceTransport;m&&(delete m.onicestatechange,delete this.transceivers[g].iceTransport);var v=this.transceivers[g].dtlsTransport;v&&(delete v.ondtlsstatechange,delete v.onerror,delete this.transceivers[g].dtlsTransport)},b.prototype._transceive=function(g,p,m){var v=s(g.localCapabilities,g.remoteCapabilities);p&&g.rtpSender&&(v.encodings=g.sendEncodingParameters,v.rtcp={cname:i.localCName,compound:g.rtcpParameters.compound},g.recvEncodingParameters.length&&(v.rtcp.ssrc=g.recvEncodingParameters[0].ssrc),g.rtpSender.send(v)),m&&g.rtpReceiver&&v.codecs.length>0&&(g.kind==="video"&&g.recvEncodingParameters&&u<15019&&g.recvEncodingParameters.forEach(function(w){delete w.rtx}),g.recvEncodingParameters.length?v.encodings=g.recvEncodingParameters:v.encodings=[{}],v.rtcp={compound:g.rtcpParameters.compound},g.rtcpParameters.cname&&(v.rtcp.cname=g.rtcpParameters.cname),g.sendEncodingParameters.length&&(v.rtcp.ssrc=g.sendEncodingParameters[0].ssrc),g.rtpReceiver.receive(v))},b.prototype.setLocalDescription=function(g){var p,m,v=this;if(["offer","answer"].indexOf(g.type)===-1)return Promise.reject(a("TypeError",'Unsupported type "'+g.type+'"'));if(!c("setLocalDescription",g.type,v.signalingState)||v._isClosed)return Promise.reject(a("InvalidStateError","Can not set local "+g.type+" in state "+v.signalingState));if(g.type==="offer")p=i.splitSections(g.sdp),m=p.shift(),p.forEach(function(x,T){var R=i.parseRtpParameters(x);v.transceivers[T].localCapabilities=R}),v.transceivers.forEach(function(x,T){v._gather(x.mid,T)});else if(g.type==="answer"){p=i.splitSections(v._remoteDescription.sdp),m=p.shift();var w=i.matchPrefix(m,"a=ice-lite").length>0;p.forEach(function(x,T){var R=v.transceivers[T],C=R.iceGatherer,P=R.iceTransport,S=R.dtlsTransport,L=R.localCapabilities,I=R.remoteCapabilities;if(!(i.isRejected(x)&&i.matchPrefix(x,"a=bundle-only").length===0)&&!R.rejected){var j=i.getIceParameters(x,m),H=i.getDtlsParameters(x,m);w&&(H.role="server"),v.usingBundle&&T!==0||(v._gather(R.mid,T),P.state==="new"&&P.start(C,j,w?"controlling":"controlled"),S.state==="new"&&S.start(H));var F=s(L,I);v._transceive(R,F.codecs.length>0,!1)}})}return v._localDescription={type:g.type,sdp:g.sdp},g.type==="offer"?v._updateSignalingState("have-local-offer"):v._updateSignalingState("stable"),Promise.resolve()},b.prototype.setRemoteDescription=function(g){var p=this;if(["offer","answer"].indexOf(g.type)===-1)return Promise.reject(a("TypeError",'Unsupported type "'+g.type+'"'));if(!c("setRemoteDescription",g.type,p.signalingState)||p._isClosed)return Promise.reject(a("InvalidStateError","Can not set remote "+g.type+" in state "+p.signalingState));var m={};p.remoteStreams.forEach(function(P){m[P.id]=P});var v=[],w=i.splitSections(g.sdp),x=w.shift(),T=i.matchPrefix(x,"a=ice-lite").length>0,R=i.matchPrefix(x,"a=group:BUNDLE ").length>0;p.usingBundle=R;var C=i.matchPrefix(x,"a=ice-options:")[0];return p.canTrickleIceCandidates=!!C&&C.substr(14).split(" ").indexOf("trickle")>=0,w.forEach(function(P,S){var L=i.splitLines(P),I=i.getKind(P),j=i.isRejected(P)&&i.matchPrefix(P,"a=bundle-only").length===0,H=L[0].substr(2).split(" ")[2],F=i.getDirection(P,x),U=i.parseMsid(P),J=i.getMid(P)||i.generateIdentifier();if(j||I==="application"&&(H==="DTLS/SCTP"||H==="UDP/DTLS/SCTP"))p.transceivers[S]={mid:J,kind:I,protocol:H,rejected:!0};else{var W,ze,ge,X,qe,cn,Vn,Oi,Pt;!j&&p.transceivers[S]&&p.transceivers[S].rejected&&(p.transceivers[S]=p._createTransceiver(I,!0));var Jd,$d,Kd=i.parseRtpParameters(P);j||(Jd=i.getIceParameters(P,x),($d=i.getDtlsParameters(P,x)).role="client"),Vn=i.parseRtpEncodingParameters(P);var eh=i.parseRtcpParameters(P),th=i.matchPrefix(P,"a=end-of-candidates",x).length>0,Sr=i.matchPrefix(P,"a=candidate:").map(function(rt){return i.parseCandidate(rt)}).filter(function(rt){return rt.component===1});if((g.type==="offer"||g.type==="answer")&&!j&&R&&S>0&&p.transceivers[S]&&(p._disposeIceAndDtlsTransports(S),p.transceivers[S].iceGatherer=p.transceivers[0].iceGatherer,p.transceivers[S].iceTransport=p.transceivers[0].iceTransport,p.transceivers[S].dtlsTransport=p.transceivers[0].dtlsTransport,p.transceivers[S].rtpSender&&p.transceivers[S].rtpSender.setTransport(p.transceivers[0].dtlsTransport),p.transceivers[S].rtpReceiver&&p.transceivers[S].rtpReceiver.setTransport(p.transceivers[0].dtlsTransport)),g.type!=="offer"||j)g.type==="answer"&&!j&&(ze=(W=p.transceivers[S]).iceGatherer,ge=W.iceTransport,X=W.dtlsTransport,qe=W.rtpReceiver,cn=W.sendEncodingParameters,Oi=W.localCapabilities,p.transceivers[S].recvEncodingParameters=Vn,p.transceivers[S].remoteCapabilities=Kd,p.transceivers[S].rtcpParameters=eh,Sr.length&&ge.state==="new"&&(!T&&!th||R&&S!==0?Sr.forEach(function(rt){d(W.iceTransport,rt)}):ge.setRemoteCandidates(Sr)),R&&S!==0||(ge.state==="new"&&ge.start(ze,Jd,"controlling"),X.state==="new"&&X.start($d)),!s(W.localCapabilities,W.remoteCapabilities).codecs.filter(function(rt){return rt.name.toLowerCase()==="rtx"}).length&&W.sendEncodingParameters[0].rtx&&delete W.sendEncodingParameters[0].rtx,p._transceive(W,F==="sendrecv"||F==="recvonly",F==="sendrecv"||F==="sendonly"),!qe||F!=="sendrecv"&&F!=="sendonly"?delete W.rtpReceiver:(Pt=qe.track,U?(m[U.stream]||(m[U.stream]=new h.MediaStream),f(Pt,m[U.stream]),v.push([Pt,qe,m[U.stream]])):(m.default||(m.default=new h.MediaStream),f(Pt,m.default),v.push([Pt,qe,m.default]))));else{(W=p.transceivers[S]||p._createTransceiver(I)).mid=J,W.iceGatherer||(W.iceGatherer=p._createIceGatherer(S,R)),Sr.length&&W.iceTransport.state==="new"&&(!th||R&&S!==0?Sr.forEach(function(rt){d(W.iceTransport,rt)}):W.iceTransport.setRemoteCandidates(Sr)),Oi=h.RTCRtpReceiver.getCapabilities(I),u<15019&&(Oi.codecs=Oi.codecs.filter(function(rt){return rt.name!=="rtx"})),cn=W.sendEncodingParameters||[{ssrc:1001*(2*S+2)}];var Pr,ml=!1;F==="sendrecv"||F==="sendonly"?(ml=!W.rtpReceiver,qe=W.rtpReceiver||new h.RTCRtpReceiver(W.dtlsTransport,I),ml&&(Pt=qe.track,U&&U.stream==="-"||(U?(m[U.stream]||(m[U.stream]=new h.MediaStream,Object.defineProperty(m[U.stream],"id",{get:function(){return U.stream}})),Object.defineProperty(Pt,"id",{get:function(){return U.track}}),Pr=m[U.stream]):(m.default||(m.default=new h.MediaStream),Pr=m.default)),Pr&&(f(Pt,Pr),W.associatedRemoteMediaStreams.push(Pr)),v.push([Pt,qe,Pr]))):W.rtpReceiver&&W.rtpReceiver.track&&(W.associatedRemoteMediaStreams.forEach(function(rt){var gl,ih,nh=rt.getTracks().find(function(Pf){return Pf.id===W.rtpReceiver.track.id});nh&&(gl=nh,(ih=rt).removeTrack(gl),ih.dispatchEvent(new h.MediaStreamTrackEvent("removetrack",{track:gl})))}),W.associatedRemoteMediaStreams=[]),W.localCapabilities=Oi,W.remoteCapabilities=Kd,W.rtpReceiver=qe,W.rtcpParameters=eh,W.sendEncodingParameters=cn,W.recvEncodingParameters=Vn,p._transceive(p.transceivers[S],!1,ml)}}}),p._dtlsRole===void 0&&(p._dtlsRole=g.type==="offer"?"active":"passive"),p._remoteDescription={type:g.type,sdp:g.sdp},g.type==="offer"?p._updateSignalingState("have-remote-offer"):p._updateSignalingState("stable"),Object.keys(m).forEach(function(P){var S=m[P];if(S.getTracks().length){if(p.remoteStreams.indexOf(S)===-1){p.remoteStreams.push(S);var L=new Event("addstream");L.stream=S,h.setTimeout(function(){p._dispatchEvent("addstream",L)})}v.forEach(function(I){var j=I[0],H=I[1];S.id===I[2].id&&E(p,j,H,[S])})}}),v.forEach(function(P){P[2]||E(p,P[0],P[1],[])}),h.setTimeout(function(){p&&p.transceivers&&p.transceivers.forEach(function(P){P.iceTransport&&P.iceTransport.state==="new"&&P.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),P.iceTransport.addRemoteCandidate({}))})},4e3),Promise.resolve()},b.prototype.close=function(){this.transceivers.forEach(function(g){g.iceTransport&&g.iceTransport.stop(),g.dtlsTransport&&g.dtlsTransport.stop(),g.rtpSender&&g.rtpSender.stop(),g.rtpReceiver&&g.rtpReceiver.stop()}),this._isClosed=!0,this._updateSignalingState("closed")},b.prototype._updateSignalingState=function(g){this.signalingState=g;var p=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",p)},b.prototype._maybeFireNegotiationNeeded=function(){var g=this;this.signalingState==="stable"&&this.needNegotiation!==!0&&(this.needNegotiation=!0,h.setTimeout(function(){if(g.needNegotiation){g.needNegotiation=!1;var p=new Event("negotiationneeded");g._dispatchEvent("negotiationneeded",p)}},0))},b.prototype._updateIceConnectionState=function(){var g,p={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(v){v.iceTransport&&!v.rejected&&p[v.iceTransport.state]++}),g="new",p.failed>0?g="failed":p.checking>0?g="checking":p.disconnected>0?g="disconnected":p.new>0?g="new":p.connected>0?g="connected":p.completed>0&&(g="completed"),g!==this.iceConnectionState){this.iceConnectionState=g;var m=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",m)}},b.prototype._updateConnectionState=function(){var g,p={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(v){v.iceTransport&&v.dtlsTransport&&!v.rejected&&(p[v.iceTransport.state]++,p[v.dtlsTransport.state]++)}),p.connected+=p.completed,g="new",p.failed>0?g="failed":p.connecting>0?g="connecting":p.disconnected>0?g="disconnected":p.new>0?g="new":p.connected>0&&(g="connected"),g!==this.connectionState){this.connectionState=g;var m=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",m)}},b.prototype.createOffer=function(){var g=this;if(g._isClosed)return Promise.reject(a("InvalidStateError","Can not call createOffer after close"));var p=g.transceivers.filter(function(T){return T.kind==="audio"}).length,m=g.transceivers.filter(function(T){return T.kind==="video"}).length,v=arguments[0];if(v){if(v.mandatory||v.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");v.offerToReceiveAudio!==void 0&&(p=v.offerToReceiveAudio===!0?1:v.offerToReceiveAudio===!1?0:v.offerToReceiveAudio),v.offerToReceiveVideo!==void 0&&(m=v.offerToReceiveVideo===!0?1:v.offerToReceiveVideo===!1?0:v.offerToReceiveVideo)}for(g.transceivers.forEach(function(T){T.kind==="audio"?--p<0&&(T.wantReceive=!1):T.kind==="video"&&--m<0&&(T.wantReceive=!1)});p>0||m>0;)p>0&&(g._createTransceiver("audio"),p--),m>0&&(g._createTransceiver("video"),m--);var w=i.writeSessionBoilerplate(g._sdpSessionId,g._sdpSessionVersion++);g.transceivers.forEach(function(T,R){var C=T.track,P=T.kind,S=T.mid||i.generateIdentifier();T.mid=S,T.iceGatherer||(T.iceGatherer=g._createIceGatherer(R,g.usingBundle));var L=h.RTCRtpSender.getCapabilities(P);u<15019&&(L.codecs=L.codecs.filter(function(j){return j.name!=="rtx"})),L.codecs.forEach(function(j){j.name==="H264"&&j.parameters["level-asymmetry-allowed"]===void 0&&(j.parameters["level-asymmetry-allowed"]="1"),T.remoteCapabilities&&T.remoteCapabilities.codecs&&T.remoteCapabilities.codecs.forEach(function(H){j.name.toLowerCase()===H.name.toLowerCase()&&j.clockRate===H.clockRate&&(j.preferredPayloadType=H.payloadType)})}),L.headerExtensions.forEach(function(j){(T.remoteCapabilities&&T.remoteCapabilities.headerExtensions||[]).forEach(function(H){j.uri===H.uri&&(j.id=H.id)})});var I=T.sendEncodingParameters||[{ssrc:1001*(2*R+1)}];C&&u>=15019&&P==="video"&&!I[0].rtx&&(I[0].rtx={ssrc:I[0].ssrc+1}),T.wantReceive&&(T.rtpReceiver=new h.RTCRtpReceiver(T.dtlsTransport,P)),T.localCapabilities=L,T.sendEncodingParameters=I}),g._config.bundlePolicy!=="max-compat"&&(w+="a=group:BUNDLE "+g.transceivers.map(function(T){return T.mid}).join(" ")+`\r
51
51
  `),w+=`a=ice-options:trickle\r
52
- `,m.transceivers.forEach(function(T,R){w+=r(T,T.localCapabilities,"offer",T.stream,m._dtlsRole),w+=`a=rtcp-rsize\r
53
- `,!T.iceGatherer||m.iceGatheringState==="new"||R!==0&&m.usingBundle||(T.iceGatherer.getLocalCandidates().forEach(function(C){C.component=1,w+="a="+i.writeCandidate(C)+`\r
52
+ `,g.transceivers.forEach(function(T,R){w+=r(T,T.localCapabilities,"offer",T.stream,g._dtlsRole),w+=`a=rtcp-rsize\r
53
+ `,!T.iceGatherer||g.iceGatheringState==="new"||R!==0&&g.usingBundle||(T.iceGatherer.getLocalCandidates().forEach(function(C){C.component=1,w+="a="+i.writeCandidate(C)+`\r
54
54
  `}),T.iceGatherer.state==="completed"&&(w+=`a=end-of-candidates\r
55
- `))});var x=new h.RTCSessionDescription({type:"offer",sdp:w});return Promise.resolve(x)},b.prototype.createAnswer=function(){var m=this;if(m._isClosed)return Promise.reject(a("InvalidStateError","Can not call createAnswer after close"));if(m.signalingState!=="have-remote-offer"&&m.signalingState!=="have-local-pranswer")return Promise.reject(a("InvalidStateError","Can not call createAnswer in signalingState "+m.signalingState));var p=i.writeSessionBoilerplate(m._sdpSessionId,m._sdpSessionVersion++);m.usingBundle&&(p+="a=group:BUNDLE "+m.transceivers.map(function(w){return w.mid}).join(" ")+`\r
55
+ `))});var x=new h.RTCSessionDescription({type:"offer",sdp:w});return Promise.resolve(x)},b.prototype.createAnswer=function(){var g=this;if(g._isClosed)return Promise.reject(a("InvalidStateError","Can not call createAnswer after close"));if(g.signalingState!=="have-remote-offer"&&g.signalingState!=="have-local-pranswer")return Promise.reject(a("InvalidStateError","Can not call createAnswer in signalingState "+g.signalingState));var p=i.writeSessionBoilerplate(g._sdpSessionId,g._sdpSessionVersion++);g.usingBundle&&(p+="a=group:BUNDLE "+g.transceivers.map(function(w){return w.mid}).join(" ")+`\r
56
56
  `),p+=`a=ice-options:trickle\r
57
- `;var f=i.getMediaSections(m._remoteDescription.sdp).length;m.transceivers.forEach(function(w,x){if(!(x+1>f)){if(w.rejected)return w.kind==="application"?w.protocol==="DTLS/SCTP"?p+=`m=application 0 DTLS/SCTP 5000\r
57
+ `;var m=i.getMediaSections(g._remoteDescription.sdp).length;g.transceivers.forEach(function(w,x){if(!(x+1>m)){if(w.rejected)return w.kind==="application"?w.protocol==="DTLS/SCTP"?p+=`m=application 0 DTLS/SCTP 5000\r
58
58
  `:p+="m=application 0 "+w.protocol+` webrtc-datachannel\r
59
59
  `:w.kind==="audio"?p+=`m=audio 0 UDP/TLS/RTP/SAVPF 0\r
60
60
  a=rtpmap:0 PCMU/8000\r
@@ -63,19 +63,19 @@ a=rtpmap:120 VP8/90000\r
63
63
  `),void(p+=`c=IN IP4 0.0.0.0\r
64
64
  a=inactive\r
65
65
  a=mid:`+w.mid+`\r
66
- `);var T;w.stream&&(w.kind==="audio"?T=w.stream.getAudioTracks()[0]:w.kind==="video"&&(T=w.stream.getVideoTracks()[0]),T&&u>=15019&&w.kind==="video"&&!w.sendEncodingParameters[0].rtx&&(w.sendEncodingParameters[0].rtx={ssrc:w.sendEncodingParameters[0].ssrc+1}));var R=o(w.localCapabilities,w.remoteCapabilities);!R.codecs.filter(function(C){return C.name.toLowerCase()==="rtx"}).length&&w.sendEncodingParameters[0].rtx&&delete w.sendEncodingParameters[0].rtx,p+=r(w,R,"answer",w.stream,m._dtlsRole),w.rtcpParameters&&w.rtcpParameters.reducedSize&&(p+=`a=rtcp-rsize\r
67
- `)}});var v=new h.RTCSessionDescription({type:"answer",sdp:p});return Promise.resolve(v)},b.prototype.addIceCandidate=function(m){var p,f=this;return m&&m.sdpMLineIndex===void 0&&!m.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise(function(v,w){if(!f._remoteDescription)return w(a("InvalidStateError","Can not add ICE candidate without a remote description"));if(m&&m.candidate!==""){var x=m.sdpMLineIndex;if(m.sdpMid){for(var T=0;T<f.transceivers.length;T++)if(f.transceivers[T].mid===m.sdpMid){x=T;break}}var R=f.transceivers[x];if(!R)return w(a("OperationError","Can not add ICE candidate"));if(R.rejected)return v();var C=Object.keys(m.candidate).length>0?i.parseCandidate(m.candidate):{};if(C.protocol==="tcp"&&(C.port===0||C.port===9)||C.component&&C.component!==1)return v();if((x===0||x>0&&R.iceTransport!==f.transceivers[0].iceTransport)&&!d(R.iceTransport,C))return w(a("OperationError","Can not add ICE candidate"));var P=m.candidate.trim();P.indexOf("a=")===0&&(P=P.substr(2)),(p=i.getMediaSections(f._remoteDescription.sdp))[x]+="a="+(C.type?P:"end-of-candidates")+`\r
68
- `,f._remoteDescription.sdp=i.getDescription(f._remoteDescription.sdp)+p.join("")}else for(var S=0;S<f.transceivers.length&&(f.transceivers[S].rejected||(f.transceivers[S].iceTransport.addRemoteCandidate({}),(p=i.getMediaSections(f._remoteDescription.sdp))[S]+=`a=end-of-candidates\r
69
- `,f._remoteDescription.sdp=i.getDescription(f._remoteDescription.sdp)+p.join(""),!f.usingBundle));S++);v()})},b.prototype.getStats=function(m){if(m&&m instanceof h.MediaStreamTrack){var p=null;if(this.transceivers.forEach(function(v){v.rtpSender&&v.rtpSender.track===m?p=v.rtpSender:v.rtpReceiver&&v.rtpReceiver.track===m&&(p=v.rtpReceiver)}),!p)throw a("InvalidAccessError","Invalid selector.");return p.getStats()}var f=[];return this.transceivers.forEach(function(v){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach(function(w){v[w]&&f.push(v[w].getStats())})}),Promise.all(f).then(function(v){var w=new Map;return v.forEach(function(x){x.forEach(function(T){w.set(T.id,T)})}),w})},["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach(function(m){var p=h[m];if(p&&p.prototype&&p.prototype.getStats){var f=p.prototype.getStats;p.prototype.getStats=function(){return f.apply(this).then(function(v){var w=new Map;return Object.keys(v).forEach(function(x){v[x].type=n(v[x]),w.set(x,v[x])}),w})}}});var y=["createOffer","createAnswer"];return y.forEach(function(m){var p=b.prototype[m];b.prototype[m]=function(){var f=arguments;return typeof f[0]=="function"||typeof f[1]=="function"?p.apply(this,[arguments[2]]).then(function(v){typeof f[0]=="function"&&f[0].apply(null,[v])},function(v){typeof f[1]=="function"&&f[1].apply(null,[v])}):p.apply(this,arguments)}}),(y=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach(function(m){var p=b.prototype[m];b.prototype[m]=function(){var f=arguments;return typeof f[1]=="function"||typeof f[2]=="function"?p.apply(this,arguments).then(function(){typeof f[1]=="function"&&f[1].apply(null)},function(v){typeof f[2]=="function"&&f[2].apply(null,[v])}):p.apply(this,arguments)}}),["getStats"].forEach(function(m){var p=b.prototype[m];b.prototype[m]=function(){var f=arguments;return typeof f[1]=="function"?p.apply(this,arguments).then(function(){typeof f[1]=="function"&&f[1].apply(null)}):p.apply(this,arguments)}}),b}},{sdp:"YHvh"}],YdKx:[function(l,e,t){"use strict";function i(n){var r=n&&n.navigator,s=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(o){return s(o).catch(function(c){return Promise.reject(function(d){return{name:{PermissionDeniedError:"NotAllowedError"}[d.name]||d.name,message:d.message,constraint:d.constraint,toString:function(){return this.name}}}(c))})}}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetUserMedia=i},{}],P3bV:[function(l,e,t){"use strict";function i(n){"getDisplayMedia"in n.navigator&&n.navigator.mediaDevices&&(n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||(n.navigator.mediaDevices.getDisplayMedia=n.navigator.getDisplayMedia.bind(n.navigator)))}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetDisplayMedia=i},{}],XRic:[function(l,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimPeerConnection=h,t.shimReplaceTrack=u,Object.defineProperty(t,"shimGetUserMedia",{enumerable:!0,get:function(){return s.shimGetUserMedia}}),Object.defineProperty(t,"shimGetDisplayMedia",{enumerable:!0,get:function(){return o.shimGetDisplayMedia}});var i=a(l("../utils")),n=l("./filtericeservers"),r=c(l("rtcpeerconnection-shim")),s=l("./getusermedia"),o=l("./getdisplaymedia");function c(g){return g&&g.__esModule?g:{default:g}}function d(){if(typeof WeakMap!="function")return null;var g=new WeakMap;return d=function(){return g},g}function a(g){if(g&&g.__esModule)return g;if(g===null||typeof g!="object"&&typeof g!="function")return{default:g};var E=d();if(E&&E.has(g))return E.get(g);var b={},y=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var m in g)if(Object.prototype.hasOwnProperty.call(g,m)){var p=y?Object.getOwnPropertyDescriptor(g,m):null;p&&(p.get||p.set)?Object.defineProperty(b,m,p):b[m]=g[m]}return b.default=g,E&&E.set(g,b),b}function h(g,E){if(g.RTCIceGatherer&&(g.RTCIceCandidate||(g.RTCIceCandidate=function(m){return m}),g.RTCSessionDescription||(g.RTCSessionDescription=function(m){return m}),E.version<15025)){var b=Object.getOwnPropertyDescriptor(g.MediaStreamTrack.prototype,"enabled");Object.defineProperty(g.MediaStreamTrack.prototype,"enabled",{set:function(m){b.set.call(this,m);var p=new Event("enabled");p.enabled=m,this.dispatchEvent(p)}})}!g.RTCRtpSender||"dtmf"in g.RTCRtpSender.prototype||Object.defineProperty(g.RTCRtpSender.prototype,"dtmf",{get:function(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=new g.RTCDtmfSender(this):this.track.kind==="video"&&(this._dtmf=null)),this._dtmf}}),g.RTCDtmfSender&&!g.RTCDTMFSender&&(g.RTCDTMFSender=g.RTCDtmfSender);var y=(0,r.default)(g,E.version);g.RTCPeerConnection=function(m){return m&&m.iceServers&&(m.iceServers=(0,n.filterIceServers)(m.iceServers,E.version),i.log("ICE servers after filtering:",m.iceServers)),new y(m)},g.RTCPeerConnection.prototype=y.prototype}function u(g){!g.RTCRtpSender||"replaceTrack"in g.RTCRtpSender.prototype||(g.RTCRtpSender.prototype.replaceTrack=g.RTCRtpSender.prototype.setTrack)}},{"../utils":"iSxC","./filtericeservers":"NZ1C","rtcpeerconnection-shim":"NJ2u","./getusermedia":"YdKx","./getdisplaymedia":"P3bV"}],GzSv:[function(l,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetUserMedia=o;var i=r(l("../utils"));function n(){if(typeof WeakMap!="function")return null;var c=new WeakMap;return n=function(){return c},c}function r(c){if(c&&c.__esModule)return c;if(c===null||typeof c!="object"&&typeof c!="function")return{default:c};var d=n();if(d&&d.has(c))return d.get(c);var a={},h=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var u in c)if(Object.prototype.hasOwnProperty.call(c,u)){var g=h?Object.getOwnPropertyDescriptor(c,u):null;g&&(g.get||g.set)?Object.defineProperty(a,u,g):a[u]=c[u]}return a.default=c,d&&d.set(c,a),a}function s(c){return(s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(d){return typeof d}:function(d){return d&&typeof Symbol=="function"&&d.constructor===Symbol&&d!==Symbol.prototype?"symbol":typeof d})(c)}function o(c,d){var a=c&&c.navigator,h=c&&c.MediaStreamTrack;if(a.getUserMedia=function(y,m,p){i.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),a.mediaDevices.getUserMedia(y).then(m,p)},!(d.version>55&&"autoGainControl"in a.mediaDevices.getSupportedConstraints())){var u=function(y,m,p){m in y&&!(p in y)&&(y[p]=y[m],delete y[m])},g=a.mediaDevices.getUserMedia.bind(a.mediaDevices);if(a.mediaDevices.getUserMedia=function(y){return s(y)==="object"&&s(y.audio)==="object"&&(y=JSON.parse(JSON.stringify(y)),u(y.audio,"autoGainControl","mozAutoGainControl"),u(y.audio,"noiseSuppression","mozNoiseSuppression")),g(y)},h&&h.prototype.getSettings){var E=h.prototype.getSettings;h.prototype.getSettings=function(){var y=E.apply(this,arguments);return u(y,"mozAutoGainControl","autoGainControl"),u(y,"mozNoiseSuppression","noiseSuppression"),y}}if(h&&h.prototype.applyConstraints){var b=h.prototype.applyConstraints;h.prototype.applyConstraints=function(y){return this.kind==="audio"&&s(y)==="object"&&(y=JSON.parse(JSON.stringify(y)),u(y,"autoGainControl","mozAutoGainControl"),u(y,"noiseSuppression","mozNoiseSuppression")),b.apply(this,[y])}}}}},{"../utils":"iSxC"}],UuGU:[function(l,e,t){"use strict";function i(n,r){n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||n.navigator.mediaDevices&&(n.navigator.mediaDevices.getDisplayMedia=function(s){if(!s||!s.video){var o=new DOMException("getDisplayMedia without video constraints is undefined");return o.name="NotFoundError",o.code=8,Promise.reject(o)}return s.video===!0?s.video={mediaSource:r}:s.video.mediaSource=r,n.navigator.mediaDevices.getUserMedia(s)})}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetDisplayMedia=i},{}],Fzdr:[function(l,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimOnTrack=a,t.shimPeerConnection=h,t.shimSenderGetStats=u,t.shimReceiverGetStats=g,t.shimRemoveStream=E,t.shimRTCDataChannel=b,t.shimAddTransceiver=y,t.shimGetParameters=m,t.shimCreateOffer=p,t.shimCreateAnswer=f,Object.defineProperty(t,"shimGetUserMedia",{enumerable:!0,get:function(){return n.shimGetUserMedia}}),Object.defineProperty(t,"shimGetDisplayMedia",{enumerable:!0,get:function(){return r.shimGetDisplayMedia}});var i=o(l("../utils")),n=l("./getusermedia"),r=l("./getdisplaymedia");function s(){if(typeof WeakMap!="function")return null;var v=new WeakMap;return s=function(){return v},v}function o(v){if(v&&v.__esModule)return v;if(v===null||typeof v!="object"&&typeof v!="function")return{default:v};var w=s();if(w&&w.has(v))return w.get(v);var x={},T=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var R in v)if(Object.prototype.hasOwnProperty.call(v,R)){var C=T?Object.getOwnPropertyDescriptor(v,R):null;C&&(C.get||C.set)?Object.defineProperty(x,R,C):x[R]=v[R]}return x.default=v,w&&w.set(v,x),x}function c(v,w,x){return w in v?Object.defineProperty(v,w,{value:x,enumerable:!0,configurable:!0,writable:!0}):v[w]=x,v}function d(v){return(d=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(w){return typeof w}:function(w){return w&&typeof Symbol=="function"&&w.constructor===Symbol&&w!==Symbol.prototype?"symbol":typeof w})(v)}function a(v){d(v)==="object"&&v.RTCTrackEvent&&"receiver"in v.RTCTrackEvent.prototype&&!("transceiver"in v.RTCTrackEvent.prototype)&&Object.defineProperty(v.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})}function h(v,w){if(d(v)==="object"&&(v.RTCPeerConnection||v.mozRTCPeerConnection)){!v.RTCPeerConnection&&v.mozRTCPeerConnection&&(v.RTCPeerConnection=v.mozRTCPeerConnection),w.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(R){var C=v.RTCPeerConnection.prototype[R],P=c({},R,function(){return arguments[0]=new(R==="addIceCandidate"?v.RTCIceCandidate:v.RTCSessionDescription)(arguments[0]),C.apply(this,arguments)});v.RTCPeerConnection.prototype[R]=P[R]});var x={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},T=v.RTCPeerConnection.prototype.getStats;v.RTCPeerConnection.prototype.getStats=function(){var[R,C,P]=arguments;return T.apply(this,[R||null]).then(function(S){if(w.version<53&&!C)try{S.forEach(function(L){L.type=x[L.type]||L.type})}catch(L){if(L.name!=="TypeError")throw L;S.forEach(function(I,j){S.set(j,Object.assign({},I,{type:x[I.type]||I.type}))})}return S}).then(C,P)}}}function u(v){if(d(v)==="object"&&v.RTCPeerConnection&&v.RTCRtpSender&&!(v.RTCRtpSender&&"getStats"in v.RTCRtpSender.prototype)){var w=v.RTCPeerConnection.prototype.getSenders;w&&(v.RTCPeerConnection.prototype.getSenders=function(){var T=this,R=w.apply(this,[]);return R.forEach(function(C){return C._pc=T}),R});var x=v.RTCPeerConnection.prototype.addTrack;x&&(v.RTCPeerConnection.prototype.addTrack=function(){var T=x.apply(this,arguments);return T._pc=this,T}),v.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}}function g(v){if(d(v)==="object"&&v.RTCPeerConnection&&v.RTCRtpSender&&!(v.RTCRtpSender&&"getStats"in v.RTCRtpReceiver.prototype)){var w=v.RTCPeerConnection.prototype.getReceivers;w&&(v.RTCPeerConnection.prototype.getReceivers=function(){var x=this,T=w.apply(this,[]);return T.forEach(function(R){return R._pc=x}),T}),i.wrapPeerConnectionEvent(v,"track",function(x){return x.receiver._pc=x.srcElement,x}),v.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}}function E(v){!v.RTCPeerConnection||"removeStream"in v.RTCPeerConnection.prototype||(v.RTCPeerConnection.prototype.removeStream=function(w){var x=this;i.deprecated("removeStream","removeTrack"),this.getSenders().forEach(function(T){T.track&&w.getTracks().includes(T.track)&&x.removeTrack(T)})})}function b(v){v.DataChannel&&!v.RTCDataChannel&&(v.RTCDataChannel=v.DataChannel)}function y(v){if(d(v)==="object"&&v.RTCPeerConnection){var w=v.RTCPeerConnection.prototype.addTransceiver;w&&(v.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];var x=arguments[1],T=x&&"sendEncodings"in x;T&&x.sendEncodings.forEach(function(S){if("rid"in S&&!/^[a-z0-9]{0,16}$/i.test(S.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in S&&!(parseFloat(S.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in S&&!(parseFloat(S.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});var R=w.apply(this,arguments);if(T){var{sender:C}=R,P=C.getParameters();"encodings"in P&&(P.encodings.length!==1||Object.keys(P.encodings[0]).length!==0)||(P.encodings=x.sendEncodings,C.sendEncodings=x.sendEncodings,this.setParametersPromises.push(C.setParameters(P).then(function(){delete C.sendEncodings}).catch(function(){delete C.sendEncodings})))}return R})}}function m(v){if(d(v)==="object"&&v.RTCRtpSender){var w=v.RTCRtpSender.prototype.getParameters;w&&(v.RTCRtpSender.prototype.getParameters=function(){var x=w.apply(this,arguments);return"encodings"in x||(x.encodings=[].concat(this.sendEncodings||[{}])),x})}}function p(v){if(d(v)==="object"&&v.RTCPeerConnection){var w=v.RTCPeerConnection.prototype.createOffer;v.RTCPeerConnection.prototype.createOffer=function(){var x=arguments,T=this;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return w.apply(T,x)}).finally(function(){T.setParametersPromises=[]}):w.apply(this,arguments)}}}function f(v){if(d(v)==="object"&&v.RTCPeerConnection){var w=v.RTCPeerConnection.prototype.createAnswer;v.RTCPeerConnection.prototype.createAnswer=function(){var x=arguments,T=this;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return w.apply(T,x)}).finally(function(){T.setParametersPromises=[]}):w.apply(this,arguments)}}}},{"../utils":"iSxC","./getusermedia":"GzSv","./getdisplaymedia":"UuGU"}],t1lL:[function(l,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimLocalStreamsAPI=o,t.shimRemoteStreamsAPI=c,t.shimCallbacksAPI=d,t.shimGetUserMedia=a,t.shimConstraints=h,t.shimRTCIceServerUrls=u,t.shimTrackEventTransceiver=g,t.shimCreateOfferLegacy=E,t.shimAudioContext=b;var i=r(l("../utils"));function n(){if(typeof WeakMap!="function")return null;var y=new WeakMap;return n=function(){return y},y}function r(y){if(y&&y.__esModule)return y;if(y===null||typeof y!="object"&&typeof y!="function")return{default:y};var m=n();if(m&&m.has(y))return m.get(y);var p={},f=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var v in y)if(Object.prototype.hasOwnProperty.call(y,v)){var w=f?Object.getOwnPropertyDescriptor(y,v):null;w&&(w.get||w.set)?Object.defineProperty(p,v,w):p[v]=y[v]}return p.default=y,m&&m.set(y,p),p}function s(y){return(s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(m){return typeof m}:function(m){return m&&typeof Symbol=="function"&&m.constructor===Symbol&&m!==Symbol.prototype?"symbol":typeof m})(y)}function o(y){if(s(y)==="object"&&y.RTCPeerConnection){if("getLocalStreams"in y.RTCPeerConnection.prototype||(y.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in y.RTCPeerConnection.prototype)){var m=y.RTCPeerConnection.prototype.addTrack;y.RTCPeerConnection.prototype.addStream=function(p){var f=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(p)||this._localStreams.push(p),p.getAudioTracks().forEach(function(v){return m.call(f,v,p)}),p.getVideoTracks().forEach(function(v){return m.call(f,v,p)})},y.RTCPeerConnection.prototype.addTrack=function(p){for(var f=this,v=arguments.length,w=new Array(v>1?v-1:0),x=1;x<v;x++)w[x-1]=arguments[x];return w&&w.forEach(function(T){f._localStreams?f._localStreams.includes(T)||f._localStreams.push(T):f._localStreams=[T]}),m.apply(this,arguments)}}"removeStream"in y.RTCPeerConnection.prototype||(y.RTCPeerConnection.prototype.removeStream=function(p){var f=this;this._localStreams||(this._localStreams=[]);var v=this._localStreams.indexOf(p);if(v!==-1){this._localStreams.splice(v,1);var w=p.getTracks();this.getSenders().forEach(function(x){w.includes(x.track)&&f.removeTrack(x)})}})}}function c(y){if(s(y)==="object"&&y.RTCPeerConnection&&("getRemoteStreams"in y.RTCPeerConnection.prototype||(y.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in y.RTCPeerConnection.prototype))){Object.defineProperty(y.RTCPeerConnection.prototype,"onaddstream",{get:function(){return this._onaddstream},set:function(p){var f=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=p),this.addEventListener("track",this._onaddstreampoly=function(v){v.streams.forEach(function(w){if(f._remoteStreams||(f._remoteStreams=[]),!f._remoteStreams.includes(w)){f._remoteStreams.push(w);var x=new Event("addstream");x.stream=w,f.dispatchEvent(x)}})})}});var m=y.RTCPeerConnection.prototype.setRemoteDescription;y.RTCPeerConnection.prototype.setRemoteDescription=function(){var p=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(f){f.streams.forEach(function(v){if(p._remoteStreams||(p._remoteStreams=[]),!(p._remoteStreams.indexOf(v)>=0)){p._remoteStreams.push(v);var w=new Event("addstream");w.stream=v,p.dispatchEvent(w)}})}),m.apply(p,arguments)}}}function d(y){if(s(y)==="object"&&y.RTCPeerConnection){var m=y.RTCPeerConnection.prototype,p=m.createOffer,f=m.createAnswer,v=m.setLocalDescription,w=m.setRemoteDescription,x=m.addIceCandidate;m.createOffer=function(R,C){var P=arguments.length>=2?arguments[2]:arguments[0],S=p.apply(this,[P]);return C?(S.then(R,C),Promise.resolve()):S},m.createAnswer=function(R,C){var P=arguments.length>=2?arguments[2]:arguments[0],S=f.apply(this,[P]);return C?(S.then(R,C),Promise.resolve()):S};var T=function(R,C,P){var S=v.apply(this,[R]);return P?(S.then(C,P),Promise.resolve()):S};m.setLocalDescription=T,T=function(R,C,P){var S=w.apply(this,[R]);return P?(S.then(C,P),Promise.resolve()):S},m.setRemoteDescription=T,T=function(R,C,P){var S=x.apply(this,[R]);return P?(S.then(C,P),Promise.resolve()):S},m.addIceCandidate=T}}function a(y){var m=y&&y.navigator;if(m.mediaDevices&&m.mediaDevices.getUserMedia){var p=m.mediaDevices,f=p.getUserMedia.bind(p);m.mediaDevices.getUserMedia=function(v){return f(h(v))}}!m.getUserMedia&&m.mediaDevices&&m.mediaDevices.getUserMedia&&(m.getUserMedia=function(v,w,x){m.mediaDevices.getUserMedia(v).then(w,x)}.bind(m))}function h(y){return y&&y.video!==void 0?Object.assign({},y,{video:i.compactObject(y.video)}):y}function u(y){if(y.RTCPeerConnection){var m=y.RTCPeerConnection;y.RTCPeerConnection=function(p,f){if(p&&p.iceServers){for(var v=[],w=0;w<p.iceServers.length;w++){var x=p.iceServers[w];!x.hasOwnProperty("urls")&&x.hasOwnProperty("url")?(i.deprecated("RTCIceServer.url","RTCIceServer.urls"),(x=JSON.parse(JSON.stringify(x))).urls=x.url,delete x.url,v.push(x)):v.push(p.iceServers[w])}p.iceServers=v}return new m(p,f)},y.RTCPeerConnection.prototype=m.prototype,"generateCertificate"in m&&Object.defineProperty(y.RTCPeerConnection,"generateCertificate",{get:function(){return m.generateCertificate}})}}function g(y){s(y)==="object"&&y.RTCTrackEvent&&"receiver"in y.RTCTrackEvent.prototype&&!("transceiver"in y.RTCTrackEvent.prototype)&&Object.defineProperty(y.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})}function E(y){var m=y.RTCPeerConnection.prototype.createOffer;y.RTCPeerConnection.prototype.createOffer=function(p){if(p){p.offerToReceiveAudio!==void 0&&(p.offerToReceiveAudio=!!p.offerToReceiveAudio);var f=this.getTransceivers().find(function(w){return w.receiver.track.kind==="audio"});p.offerToReceiveAudio===!1&&f?f.direction==="sendrecv"?f.setDirection?f.setDirection("sendonly"):f.direction="sendonly":f.direction==="recvonly"&&(f.setDirection?f.setDirection("inactive"):f.direction="inactive"):p.offerToReceiveAudio!==!0||f||this.addTransceiver("audio"),p.offerToReceiveVideo!==void 0&&(p.offerToReceiveVideo=!!p.offerToReceiveVideo);var v=this.getTransceivers().find(function(w){return w.receiver.track.kind==="video"});p.offerToReceiveVideo===!1&&v?v.direction==="sendrecv"?v.setDirection?v.setDirection("sendonly"):v.direction="sendonly":v.direction==="recvonly"&&(v.setDirection?v.setDirection("inactive"):v.direction="inactive"):p.offerToReceiveVideo!==!0||v||this.addTransceiver("video")}return m.apply(this,arguments)}}function b(y){s(y)!=="object"||y.AudioContext||(y.AudioContext=y.webkitAudioContext)}},{"../utils":"iSxC"}],GOQK:[function(l,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimRTCIceCandidate=d,t.shimMaxMessageSize=a,t.shimSendThrowTypeError=h,t.shimConnectionState=u,t.removeExtmapAllowMixed=g,t.shimAddIceCandidateNullOrEmpty=E;var i=o(l("sdp")),n=s(l("./utils"));function r(){if(typeof WeakMap!="function")return null;var b=new WeakMap;return r=function(){return b},b}function s(b){if(b&&b.__esModule)return b;if(b===null||typeof b!="object"&&typeof b!="function")return{default:b};var y=r();if(y&&y.has(b))return y.get(b);var m={},p=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var f in b)if(Object.prototype.hasOwnProperty.call(b,f)){var v=p?Object.getOwnPropertyDescriptor(b,f):null;v&&(v.get||v.set)?Object.defineProperty(m,f,v):m[f]=b[f]}return m.default=b,y&&y.set(b,m),m}function o(b){return b&&b.__esModule?b:{default:b}}function c(b){return(c=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(y){return typeof y}:function(y){return y&&typeof Symbol=="function"&&y.constructor===Symbol&&y!==Symbol.prototype?"symbol":typeof y})(b)}function d(b){if(b.RTCIceCandidate&&!(b.RTCIceCandidate&&"foundation"in b.RTCIceCandidate.prototype)){var y=b.RTCIceCandidate;b.RTCIceCandidate=function(m){if(c(m)==="object"&&m.candidate&&m.candidate.indexOf("a=")===0&&((m=JSON.parse(JSON.stringify(m))).candidate=m.candidate.substr(2)),m.candidate&&m.candidate.length){var p=new y(m),f=i.default.parseCandidate(m.candidate),v=Object.assign(p,f);return v.toJSON=function(){return{candidate:v.candidate,sdpMid:v.sdpMid,sdpMLineIndex:v.sdpMLineIndex,usernameFragment:v.usernameFragment}},v}return new y(m)},b.RTCIceCandidate.prototype=y.prototype,n.wrapPeerConnectionEvent(b,"icecandidate",function(m){return m.candidate&&Object.defineProperty(m,"candidate",{value:new b.RTCIceCandidate(m.candidate),writable:"false"}),m})}}function a(b,y){if(b.RTCPeerConnection){"sctp"in b.RTCPeerConnection.prototype||Object.defineProperty(b.RTCPeerConnection.prototype,"sctp",{get:function(){return this._sctp===void 0?null:this._sctp}});var m=b.RTCPeerConnection.prototype.setRemoteDescription;b.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,y.browser==="chrome"&&y.version>=76){var{sdpSemantics:p}=this.getConfiguration();p==="plan-b"&&Object.defineProperty(this,"sctp",{get:function(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0})}if(function(P){if(!P||!P.sdp)return!1;var S=i.default.splitSections(P.sdp);return S.shift(),S.some(function(L){var I=i.default.parseMLine(L);return I&&I.kind==="application"&&I.protocol.indexOf("SCTP")!==-1})}(arguments[0])){var f,v=function(P){var S=P.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(S===null||S.length<2)return-1;var L=parseInt(S[1],10);return L!=L?-1:L}(arguments[0]),w=(R=v,C=65536,y.browser==="firefox"&&(C=y.version<57?R===-1?16384:2147483637:y.version<60?y.version===57?65535:65536:2147483637),C),x=function(P,S){var L=65536;y.browser==="firefox"&&y.version===57&&(L=65535);var I=i.default.matchPrefix(P.sdp,"a=max-message-size:");return I.length>0?L=parseInt(I[0].substr(19),10):y.browser==="firefox"&&S!==-1&&(L=2147483637),L}(arguments[0],v);f=w===0&&x===0?Number.POSITIVE_INFINITY:w===0||x===0?Math.max(w,x):Math.min(w,x);var T={};Object.defineProperty(T,"maxMessageSize",{get:function(){return f}}),this._sctp=T}var R,C;return m.apply(this,arguments)}}}function h(b){if(b.RTCPeerConnection&&"createDataChannel"in b.RTCPeerConnection.prototype){var y=b.RTCPeerConnection.prototype.createDataChannel;b.RTCPeerConnection.prototype.createDataChannel=function(){var p=y.apply(this,arguments);return m(p,this),p},n.wrapPeerConnectionEvent(b,"datachannel",function(p){return m(p.channel,p.target),p})}function m(p,f){var v=p.send;p.send=function(){var w=arguments[0],x=w.length||w.size||w.byteLength;if(p.readyState==="open"&&f.sctp&&x>f.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+f.sctp.maxMessageSize+" bytes)");return v.apply(p,arguments)}}}function u(b){if(b.RTCPeerConnection&&!("connectionState"in b.RTCPeerConnection.prototype)){var y=b.RTCPeerConnection.prototype;Object.defineProperty(y,"connectionState",{get:function(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(y,"onconnectionstatechange",{get:function(){return this._onconnectionstatechange||null},set:function(m){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),m&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=m)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(function(m){var p=y[m];y[m]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(f){var v=f.target;if(v._lastConnectionState!==v.connectionState){v._lastConnectionState=v.connectionState;var w=new Event("connectionstatechange",f);v.dispatchEvent(w)}return f},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),p.apply(this,arguments)}})}}function g(b,y){if(b.RTCPeerConnection&&!(y.browser==="chrome"&&y.version>=71||y.browser==="safari"&&y.version>=605)){var m=b.RTCPeerConnection.prototype.setRemoteDescription;b.RTCPeerConnection.prototype.setRemoteDescription=function(p){if(p&&p.sdp&&p.sdp.indexOf(`
70
- a=extmap-allow-mixed`)!==-1){var f=p.sdp.split(`
66
+ `);var T;w.stream&&(w.kind==="audio"?T=w.stream.getAudioTracks()[0]:w.kind==="video"&&(T=w.stream.getVideoTracks()[0]),T&&u>=15019&&w.kind==="video"&&!w.sendEncodingParameters[0].rtx&&(w.sendEncodingParameters[0].rtx={ssrc:w.sendEncodingParameters[0].ssrc+1}));var R=s(w.localCapabilities,w.remoteCapabilities);!R.codecs.filter(function(C){return C.name.toLowerCase()==="rtx"}).length&&w.sendEncodingParameters[0].rtx&&delete w.sendEncodingParameters[0].rtx,p+=r(w,R,"answer",w.stream,g._dtlsRole),w.rtcpParameters&&w.rtcpParameters.reducedSize&&(p+=`a=rtcp-rsize\r
67
+ `)}});var v=new h.RTCSessionDescription({type:"answer",sdp:p});return Promise.resolve(v)},b.prototype.addIceCandidate=function(g){var p,m=this;return g&&g.sdpMLineIndex===void 0&&!g.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise(function(v,w){if(!m._remoteDescription)return w(a("InvalidStateError","Can not add ICE candidate without a remote description"));if(g&&g.candidate!==""){var x=g.sdpMLineIndex;if(g.sdpMid){for(var T=0;T<m.transceivers.length;T++)if(m.transceivers[T].mid===g.sdpMid){x=T;break}}var R=m.transceivers[x];if(!R)return w(a("OperationError","Can not add ICE candidate"));if(R.rejected)return v();var C=Object.keys(g.candidate).length>0?i.parseCandidate(g.candidate):{};if(C.protocol==="tcp"&&(C.port===0||C.port===9)||C.component&&C.component!==1)return v();if((x===0||x>0&&R.iceTransport!==m.transceivers[0].iceTransport)&&!d(R.iceTransport,C))return w(a("OperationError","Can not add ICE candidate"));var P=g.candidate.trim();P.indexOf("a=")===0&&(P=P.substr(2)),(p=i.getMediaSections(m._remoteDescription.sdp))[x]+="a="+(C.type?P:"end-of-candidates")+`\r
68
+ `,m._remoteDescription.sdp=i.getDescription(m._remoteDescription.sdp)+p.join("")}else for(var S=0;S<m.transceivers.length&&(m.transceivers[S].rejected||(m.transceivers[S].iceTransport.addRemoteCandidate({}),(p=i.getMediaSections(m._remoteDescription.sdp))[S]+=`a=end-of-candidates\r
69
+ `,m._remoteDescription.sdp=i.getDescription(m._remoteDescription.sdp)+p.join(""),!m.usingBundle));S++);v()})},b.prototype.getStats=function(g){if(g&&g instanceof h.MediaStreamTrack){var p=null;if(this.transceivers.forEach(function(v){v.rtpSender&&v.rtpSender.track===g?p=v.rtpSender:v.rtpReceiver&&v.rtpReceiver.track===g&&(p=v.rtpReceiver)}),!p)throw a("InvalidAccessError","Invalid selector.");return p.getStats()}var m=[];return this.transceivers.forEach(function(v){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach(function(w){v[w]&&m.push(v[w].getStats())})}),Promise.all(m).then(function(v){var w=new Map;return v.forEach(function(x){x.forEach(function(T){w.set(T.id,T)})}),w})},["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach(function(g){var p=h[g];if(p&&p.prototype&&p.prototype.getStats){var m=p.prototype.getStats;p.prototype.getStats=function(){return m.apply(this).then(function(v){var w=new Map;return Object.keys(v).forEach(function(x){v[x].type=n(v[x]),w.set(x,v[x])}),w})}}});var y=["createOffer","createAnswer"];return y.forEach(function(g){var p=b.prototype[g];b.prototype[g]=function(){var m=arguments;return typeof m[0]=="function"||typeof m[1]=="function"?p.apply(this,[arguments[2]]).then(function(v){typeof m[0]=="function"&&m[0].apply(null,[v])},function(v){typeof m[1]=="function"&&m[1].apply(null,[v])}):p.apply(this,arguments)}}),(y=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach(function(g){var p=b.prototype[g];b.prototype[g]=function(){var m=arguments;return typeof m[1]=="function"||typeof m[2]=="function"?p.apply(this,arguments).then(function(){typeof m[1]=="function"&&m[1].apply(null)},function(v){typeof m[2]=="function"&&m[2].apply(null,[v])}):p.apply(this,arguments)}}),["getStats"].forEach(function(g){var p=b.prototype[g];b.prototype[g]=function(){var m=arguments;return typeof m[1]=="function"?p.apply(this,arguments).then(function(){typeof m[1]=="function"&&m[1].apply(null)}):p.apply(this,arguments)}}),b}},{sdp:"YHvh"}],YdKx:[function(l,e,t){"use strict";function i(n){var r=n&&n.navigator,o=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(s){return o(s).catch(function(c){return Promise.reject(function(d){return{name:{PermissionDeniedError:"NotAllowedError"}[d.name]||d.name,message:d.message,constraint:d.constraint,toString:function(){return this.name}}}(c))})}}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetUserMedia=i},{}],P3bV:[function(l,e,t){"use strict";function i(n){"getDisplayMedia"in n.navigator&&n.navigator.mediaDevices&&(n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||(n.navigator.mediaDevices.getDisplayMedia=n.navigator.getDisplayMedia.bind(n.navigator)))}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetDisplayMedia=i},{}],XRic:[function(l,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimPeerConnection=h,t.shimReplaceTrack=u,Object.defineProperty(t,"shimGetUserMedia",{enumerable:!0,get:function(){return o.shimGetUserMedia}}),Object.defineProperty(t,"shimGetDisplayMedia",{enumerable:!0,get:function(){return s.shimGetDisplayMedia}});var i=a(l("../utils")),n=l("./filtericeservers"),r=c(l("rtcpeerconnection-shim")),o=l("./getusermedia"),s=l("./getdisplaymedia");function c(f){return f&&f.__esModule?f:{default:f}}function d(){if(typeof WeakMap!="function")return null;var f=new WeakMap;return d=function(){return f},f}function a(f){if(f&&f.__esModule)return f;if(f===null||typeof f!="object"&&typeof f!="function")return{default:f};var E=d();if(E&&E.has(f))return E.get(f);var b={},y=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var g in f)if(Object.prototype.hasOwnProperty.call(f,g)){var p=y?Object.getOwnPropertyDescriptor(f,g):null;p&&(p.get||p.set)?Object.defineProperty(b,g,p):b[g]=f[g]}return b.default=f,E&&E.set(f,b),b}function h(f,E){if(f.RTCIceGatherer&&(f.RTCIceCandidate||(f.RTCIceCandidate=function(g){return g}),f.RTCSessionDescription||(f.RTCSessionDescription=function(g){return g}),E.version<15025)){var b=Object.getOwnPropertyDescriptor(f.MediaStreamTrack.prototype,"enabled");Object.defineProperty(f.MediaStreamTrack.prototype,"enabled",{set:function(g){b.set.call(this,g);var p=new Event("enabled");p.enabled=g,this.dispatchEvent(p)}})}!f.RTCRtpSender||"dtmf"in f.RTCRtpSender.prototype||Object.defineProperty(f.RTCRtpSender.prototype,"dtmf",{get:function(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=new f.RTCDtmfSender(this):this.track.kind==="video"&&(this._dtmf=null)),this._dtmf}}),f.RTCDtmfSender&&!f.RTCDTMFSender&&(f.RTCDTMFSender=f.RTCDtmfSender);var y=(0,r.default)(f,E.version);f.RTCPeerConnection=function(g){return g&&g.iceServers&&(g.iceServers=(0,n.filterIceServers)(g.iceServers,E.version),i.log("ICE servers after filtering:",g.iceServers)),new y(g)},f.RTCPeerConnection.prototype=y.prototype}function u(f){!f.RTCRtpSender||"replaceTrack"in f.RTCRtpSender.prototype||(f.RTCRtpSender.prototype.replaceTrack=f.RTCRtpSender.prototype.setTrack)}},{"../utils":"iSxC","./filtericeservers":"NZ1C","rtcpeerconnection-shim":"NJ2u","./getusermedia":"YdKx","./getdisplaymedia":"P3bV"}],GzSv:[function(l,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetUserMedia=s;var i=r(l("../utils"));function n(){if(typeof WeakMap!="function")return null;var c=new WeakMap;return n=function(){return c},c}function r(c){if(c&&c.__esModule)return c;if(c===null||typeof c!="object"&&typeof c!="function")return{default:c};var d=n();if(d&&d.has(c))return d.get(c);var a={},h=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var u in c)if(Object.prototype.hasOwnProperty.call(c,u)){var f=h?Object.getOwnPropertyDescriptor(c,u):null;f&&(f.get||f.set)?Object.defineProperty(a,u,f):a[u]=c[u]}return a.default=c,d&&d.set(c,a),a}function o(c){return(o=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(d){return typeof d}:function(d){return d&&typeof Symbol=="function"&&d.constructor===Symbol&&d!==Symbol.prototype?"symbol":typeof d})(c)}function s(c,d){var a=c&&c.navigator,h=c&&c.MediaStreamTrack;if(a.getUserMedia=function(y,g,p){i.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),a.mediaDevices.getUserMedia(y).then(g,p)},!(d.version>55&&"autoGainControl"in a.mediaDevices.getSupportedConstraints())){var u=function(y,g,p){g in y&&!(p in y)&&(y[p]=y[g],delete y[g])},f=a.mediaDevices.getUserMedia.bind(a.mediaDevices);if(a.mediaDevices.getUserMedia=function(y){return o(y)==="object"&&o(y.audio)==="object"&&(y=JSON.parse(JSON.stringify(y)),u(y.audio,"autoGainControl","mozAutoGainControl"),u(y.audio,"noiseSuppression","mozNoiseSuppression")),f(y)},h&&h.prototype.getSettings){var E=h.prototype.getSettings;h.prototype.getSettings=function(){var y=E.apply(this,arguments);return u(y,"mozAutoGainControl","autoGainControl"),u(y,"mozNoiseSuppression","noiseSuppression"),y}}if(h&&h.prototype.applyConstraints){var b=h.prototype.applyConstraints;h.prototype.applyConstraints=function(y){return this.kind==="audio"&&o(y)==="object"&&(y=JSON.parse(JSON.stringify(y)),u(y,"autoGainControl","mozAutoGainControl"),u(y,"noiseSuppression","mozNoiseSuppression")),b.apply(this,[y])}}}}},{"../utils":"iSxC"}],UuGU:[function(l,e,t){"use strict";function i(n,r){n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||n.navigator.mediaDevices&&(n.navigator.mediaDevices.getDisplayMedia=function(o){if(!o||!o.video){var s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return o.video===!0?o.video={mediaSource:r}:o.video.mediaSource=r,n.navigator.mediaDevices.getUserMedia(o)})}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetDisplayMedia=i},{}],Fzdr:[function(l,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimOnTrack=a,t.shimPeerConnection=h,t.shimSenderGetStats=u,t.shimReceiverGetStats=f,t.shimRemoveStream=E,t.shimRTCDataChannel=b,t.shimAddTransceiver=y,t.shimGetParameters=g,t.shimCreateOffer=p,t.shimCreateAnswer=m,Object.defineProperty(t,"shimGetUserMedia",{enumerable:!0,get:function(){return n.shimGetUserMedia}}),Object.defineProperty(t,"shimGetDisplayMedia",{enumerable:!0,get:function(){return r.shimGetDisplayMedia}});var i=s(l("../utils")),n=l("./getusermedia"),r=l("./getdisplaymedia");function o(){if(typeof WeakMap!="function")return null;var v=new WeakMap;return o=function(){return v},v}function s(v){if(v&&v.__esModule)return v;if(v===null||typeof v!="object"&&typeof v!="function")return{default:v};var w=o();if(w&&w.has(v))return w.get(v);var x={},T=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var R in v)if(Object.prototype.hasOwnProperty.call(v,R)){var C=T?Object.getOwnPropertyDescriptor(v,R):null;C&&(C.get||C.set)?Object.defineProperty(x,R,C):x[R]=v[R]}return x.default=v,w&&w.set(v,x),x}function c(v,w,x){return w in v?Object.defineProperty(v,w,{value:x,enumerable:!0,configurable:!0,writable:!0}):v[w]=x,v}function d(v){return(d=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(w){return typeof w}:function(w){return w&&typeof Symbol=="function"&&w.constructor===Symbol&&w!==Symbol.prototype?"symbol":typeof w})(v)}function a(v){d(v)==="object"&&v.RTCTrackEvent&&"receiver"in v.RTCTrackEvent.prototype&&!("transceiver"in v.RTCTrackEvent.prototype)&&Object.defineProperty(v.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})}function h(v,w){if(d(v)==="object"&&(v.RTCPeerConnection||v.mozRTCPeerConnection)){!v.RTCPeerConnection&&v.mozRTCPeerConnection&&(v.RTCPeerConnection=v.mozRTCPeerConnection),w.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(R){var C=v.RTCPeerConnection.prototype[R],P=c({},R,function(){return arguments[0]=new(R==="addIceCandidate"?v.RTCIceCandidate:v.RTCSessionDescription)(arguments[0]),C.apply(this,arguments)});v.RTCPeerConnection.prototype[R]=P[R]});var x={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},T=v.RTCPeerConnection.prototype.getStats;v.RTCPeerConnection.prototype.getStats=function(){var[R,C,P]=arguments;return T.apply(this,[R||null]).then(function(S){if(w.version<53&&!C)try{S.forEach(function(L){L.type=x[L.type]||L.type})}catch(L){if(L.name!=="TypeError")throw L;S.forEach(function(I,j){S.set(j,Object.assign({},I,{type:x[I.type]||I.type}))})}return S}).then(C,P)}}}function u(v){if(d(v)==="object"&&v.RTCPeerConnection&&v.RTCRtpSender&&!(v.RTCRtpSender&&"getStats"in v.RTCRtpSender.prototype)){var w=v.RTCPeerConnection.prototype.getSenders;w&&(v.RTCPeerConnection.prototype.getSenders=function(){var T=this,R=w.apply(this,[]);return R.forEach(function(C){return C._pc=T}),R});var x=v.RTCPeerConnection.prototype.addTrack;x&&(v.RTCPeerConnection.prototype.addTrack=function(){var T=x.apply(this,arguments);return T._pc=this,T}),v.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}}function f(v){if(d(v)==="object"&&v.RTCPeerConnection&&v.RTCRtpSender&&!(v.RTCRtpSender&&"getStats"in v.RTCRtpReceiver.prototype)){var w=v.RTCPeerConnection.prototype.getReceivers;w&&(v.RTCPeerConnection.prototype.getReceivers=function(){var x=this,T=w.apply(this,[]);return T.forEach(function(R){return R._pc=x}),T}),i.wrapPeerConnectionEvent(v,"track",function(x){return x.receiver._pc=x.srcElement,x}),v.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}}function E(v){!v.RTCPeerConnection||"removeStream"in v.RTCPeerConnection.prototype||(v.RTCPeerConnection.prototype.removeStream=function(w){var x=this;i.deprecated("removeStream","removeTrack"),this.getSenders().forEach(function(T){T.track&&w.getTracks().includes(T.track)&&x.removeTrack(T)})})}function b(v){v.DataChannel&&!v.RTCDataChannel&&(v.RTCDataChannel=v.DataChannel)}function y(v){if(d(v)==="object"&&v.RTCPeerConnection){var w=v.RTCPeerConnection.prototype.addTransceiver;w&&(v.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];var x=arguments[1],T=x&&"sendEncodings"in x;T&&x.sendEncodings.forEach(function(S){if("rid"in S&&!/^[a-z0-9]{0,16}$/i.test(S.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in S&&!(parseFloat(S.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in S&&!(parseFloat(S.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});var R=w.apply(this,arguments);if(T){var{sender:C}=R,P=C.getParameters();"encodings"in P&&(P.encodings.length!==1||Object.keys(P.encodings[0]).length!==0)||(P.encodings=x.sendEncodings,C.sendEncodings=x.sendEncodings,this.setParametersPromises.push(C.setParameters(P).then(function(){delete C.sendEncodings}).catch(function(){delete C.sendEncodings})))}return R})}}function g(v){if(d(v)==="object"&&v.RTCRtpSender){var w=v.RTCRtpSender.prototype.getParameters;w&&(v.RTCRtpSender.prototype.getParameters=function(){var x=w.apply(this,arguments);return"encodings"in x||(x.encodings=[].concat(this.sendEncodings||[{}])),x})}}function p(v){if(d(v)==="object"&&v.RTCPeerConnection){var w=v.RTCPeerConnection.prototype.createOffer;v.RTCPeerConnection.prototype.createOffer=function(){var x=arguments,T=this;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return w.apply(T,x)}).finally(function(){T.setParametersPromises=[]}):w.apply(this,arguments)}}}function m(v){if(d(v)==="object"&&v.RTCPeerConnection){var w=v.RTCPeerConnection.prototype.createAnswer;v.RTCPeerConnection.prototype.createAnswer=function(){var x=arguments,T=this;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return w.apply(T,x)}).finally(function(){T.setParametersPromises=[]}):w.apply(this,arguments)}}}},{"../utils":"iSxC","./getusermedia":"GzSv","./getdisplaymedia":"UuGU"}],t1lL:[function(l,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimLocalStreamsAPI=s,t.shimRemoteStreamsAPI=c,t.shimCallbacksAPI=d,t.shimGetUserMedia=a,t.shimConstraints=h,t.shimRTCIceServerUrls=u,t.shimTrackEventTransceiver=f,t.shimCreateOfferLegacy=E,t.shimAudioContext=b;var i=r(l("../utils"));function n(){if(typeof WeakMap!="function")return null;var y=new WeakMap;return n=function(){return y},y}function r(y){if(y&&y.__esModule)return y;if(y===null||typeof y!="object"&&typeof y!="function")return{default:y};var g=n();if(g&&g.has(y))return g.get(y);var p={},m=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var v in y)if(Object.prototype.hasOwnProperty.call(y,v)){var w=m?Object.getOwnPropertyDescriptor(y,v):null;w&&(w.get||w.set)?Object.defineProperty(p,v,w):p[v]=y[v]}return p.default=y,g&&g.set(y,p),p}function o(y){return(o=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(g){return typeof g}:function(g){return g&&typeof Symbol=="function"&&g.constructor===Symbol&&g!==Symbol.prototype?"symbol":typeof g})(y)}function s(y){if(o(y)==="object"&&y.RTCPeerConnection){if("getLocalStreams"in y.RTCPeerConnection.prototype||(y.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in y.RTCPeerConnection.prototype)){var g=y.RTCPeerConnection.prototype.addTrack;y.RTCPeerConnection.prototype.addStream=function(p){var m=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(p)||this._localStreams.push(p),p.getAudioTracks().forEach(function(v){return g.call(m,v,p)}),p.getVideoTracks().forEach(function(v){return g.call(m,v,p)})},y.RTCPeerConnection.prototype.addTrack=function(p){for(var m=this,v=arguments.length,w=new Array(v>1?v-1:0),x=1;x<v;x++)w[x-1]=arguments[x];return w&&w.forEach(function(T){m._localStreams?m._localStreams.includes(T)||m._localStreams.push(T):m._localStreams=[T]}),g.apply(this,arguments)}}"removeStream"in y.RTCPeerConnection.prototype||(y.RTCPeerConnection.prototype.removeStream=function(p){var m=this;this._localStreams||(this._localStreams=[]);var v=this._localStreams.indexOf(p);if(v!==-1){this._localStreams.splice(v,1);var w=p.getTracks();this.getSenders().forEach(function(x){w.includes(x.track)&&m.removeTrack(x)})}})}}function c(y){if(o(y)==="object"&&y.RTCPeerConnection&&("getRemoteStreams"in y.RTCPeerConnection.prototype||(y.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in y.RTCPeerConnection.prototype))){Object.defineProperty(y.RTCPeerConnection.prototype,"onaddstream",{get:function(){return this._onaddstream},set:function(p){var m=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=p),this.addEventListener("track",this._onaddstreampoly=function(v){v.streams.forEach(function(w){if(m._remoteStreams||(m._remoteStreams=[]),!m._remoteStreams.includes(w)){m._remoteStreams.push(w);var x=new Event("addstream");x.stream=w,m.dispatchEvent(x)}})})}});var g=y.RTCPeerConnection.prototype.setRemoteDescription;y.RTCPeerConnection.prototype.setRemoteDescription=function(){var p=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(m){m.streams.forEach(function(v){if(p._remoteStreams||(p._remoteStreams=[]),!(p._remoteStreams.indexOf(v)>=0)){p._remoteStreams.push(v);var w=new Event("addstream");w.stream=v,p.dispatchEvent(w)}})}),g.apply(p,arguments)}}}function d(y){if(o(y)==="object"&&y.RTCPeerConnection){var g=y.RTCPeerConnection.prototype,p=g.createOffer,m=g.createAnswer,v=g.setLocalDescription,w=g.setRemoteDescription,x=g.addIceCandidate;g.createOffer=function(R,C){var P=arguments.length>=2?arguments[2]:arguments[0],S=p.apply(this,[P]);return C?(S.then(R,C),Promise.resolve()):S},g.createAnswer=function(R,C){var P=arguments.length>=2?arguments[2]:arguments[0],S=m.apply(this,[P]);return C?(S.then(R,C),Promise.resolve()):S};var T=function(R,C,P){var S=v.apply(this,[R]);return P?(S.then(C,P),Promise.resolve()):S};g.setLocalDescription=T,T=function(R,C,P){var S=w.apply(this,[R]);return P?(S.then(C,P),Promise.resolve()):S},g.setRemoteDescription=T,T=function(R,C,P){var S=x.apply(this,[R]);return P?(S.then(C,P),Promise.resolve()):S},g.addIceCandidate=T}}function a(y){var g=y&&y.navigator;if(g.mediaDevices&&g.mediaDevices.getUserMedia){var p=g.mediaDevices,m=p.getUserMedia.bind(p);g.mediaDevices.getUserMedia=function(v){return m(h(v))}}!g.getUserMedia&&g.mediaDevices&&g.mediaDevices.getUserMedia&&(g.getUserMedia=function(v,w,x){g.mediaDevices.getUserMedia(v).then(w,x)}.bind(g))}function h(y){return y&&y.video!==void 0?Object.assign({},y,{video:i.compactObject(y.video)}):y}function u(y){if(y.RTCPeerConnection){var g=y.RTCPeerConnection;y.RTCPeerConnection=function(p,m){if(p&&p.iceServers){for(var v=[],w=0;w<p.iceServers.length;w++){var x=p.iceServers[w];!x.hasOwnProperty("urls")&&x.hasOwnProperty("url")?(i.deprecated("RTCIceServer.url","RTCIceServer.urls"),(x=JSON.parse(JSON.stringify(x))).urls=x.url,delete x.url,v.push(x)):v.push(p.iceServers[w])}p.iceServers=v}return new g(p,m)},y.RTCPeerConnection.prototype=g.prototype,"generateCertificate"in g&&Object.defineProperty(y.RTCPeerConnection,"generateCertificate",{get:function(){return g.generateCertificate}})}}function f(y){o(y)==="object"&&y.RTCTrackEvent&&"receiver"in y.RTCTrackEvent.prototype&&!("transceiver"in y.RTCTrackEvent.prototype)&&Object.defineProperty(y.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})}function E(y){var g=y.RTCPeerConnection.prototype.createOffer;y.RTCPeerConnection.prototype.createOffer=function(p){if(p){p.offerToReceiveAudio!==void 0&&(p.offerToReceiveAudio=!!p.offerToReceiveAudio);var m=this.getTransceivers().find(function(w){return w.receiver.track.kind==="audio"});p.offerToReceiveAudio===!1&&m?m.direction==="sendrecv"?m.setDirection?m.setDirection("sendonly"):m.direction="sendonly":m.direction==="recvonly"&&(m.setDirection?m.setDirection("inactive"):m.direction="inactive"):p.offerToReceiveAudio!==!0||m||this.addTransceiver("audio"),p.offerToReceiveVideo!==void 0&&(p.offerToReceiveVideo=!!p.offerToReceiveVideo);var v=this.getTransceivers().find(function(w){return w.receiver.track.kind==="video"});p.offerToReceiveVideo===!1&&v?v.direction==="sendrecv"?v.setDirection?v.setDirection("sendonly"):v.direction="sendonly":v.direction==="recvonly"&&(v.setDirection?v.setDirection("inactive"):v.direction="inactive"):p.offerToReceiveVideo!==!0||v||this.addTransceiver("video")}return g.apply(this,arguments)}}function b(y){o(y)!=="object"||y.AudioContext||(y.AudioContext=y.webkitAudioContext)}},{"../utils":"iSxC"}],GOQK:[function(l,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimRTCIceCandidate=d,t.shimMaxMessageSize=a,t.shimSendThrowTypeError=h,t.shimConnectionState=u,t.removeExtmapAllowMixed=f,t.shimAddIceCandidateNullOrEmpty=E;var i=s(l("sdp")),n=o(l("./utils"));function r(){if(typeof WeakMap!="function")return null;var b=new WeakMap;return r=function(){return b},b}function o(b){if(b&&b.__esModule)return b;if(b===null||typeof b!="object"&&typeof b!="function")return{default:b};var y=r();if(y&&y.has(b))return y.get(b);var g={},p=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var m in b)if(Object.prototype.hasOwnProperty.call(b,m)){var v=p?Object.getOwnPropertyDescriptor(b,m):null;v&&(v.get||v.set)?Object.defineProperty(g,m,v):g[m]=b[m]}return g.default=b,y&&y.set(b,g),g}function s(b){return b&&b.__esModule?b:{default:b}}function c(b){return(c=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(y){return typeof y}:function(y){return y&&typeof Symbol=="function"&&y.constructor===Symbol&&y!==Symbol.prototype?"symbol":typeof y})(b)}function d(b){if(b.RTCIceCandidate&&!(b.RTCIceCandidate&&"foundation"in b.RTCIceCandidate.prototype)){var y=b.RTCIceCandidate;b.RTCIceCandidate=function(g){if(c(g)==="object"&&g.candidate&&g.candidate.indexOf("a=")===0&&((g=JSON.parse(JSON.stringify(g))).candidate=g.candidate.substr(2)),g.candidate&&g.candidate.length){var p=new y(g),m=i.default.parseCandidate(g.candidate),v=Object.assign(p,m);return v.toJSON=function(){return{candidate:v.candidate,sdpMid:v.sdpMid,sdpMLineIndex:v.sdpMLineIndex,usernameFragment:v.usernameFragment}},v}return new y(g)},b.RTCIceCandidate.prototype=y.prototype,n.wrapPeerConnectionEvent(b,"icecandidate",function(g){return g.candidate&&Object.defineProperty(g,"candidate",{value:new b.RTCIceCandidate(g.candidate),writable:"false"}),g})}}function a(b,y){if(b.RTCPeerConnection){"sctp"in b.RTCPeerConnection.prototype||Object.defineProperty(b.RTCPeerConnection.prototype,"sctp",{get:function(){return this._sctp===void 0?null:this._sctp}});var g=b.RTCPeerConnection.prototype.setRemoteDescription;b.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,y.browser==="chrome"&&y.version>=76){var{sdpSemantics:p}=this.getConfiguration();p==="plan-b"&&Object.defineProperty(this,"sctp",{get:function(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0})}if(function(P){if(!P||!P.sdp)return!1;var S=i.default.splitSections(P.sdp);return S.shift(),S.some(function(L){var I=i.default.parseMLine(L);return I&&I.kind==="application"&&I.protocol.indexOf("SCTP")!==-1})}(arguments[0])){var m,v=function(P){var S=P.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(S===null||S.length<2)return-1;var L=parseInt(S[1],10);return L!=L?-1:L}(arguments[0]),w=(R=v,C=65536,y.browser==="firefox"&&(C=y.version<57?R===-1?16384:2147483637:y.version<60?y.version===57?65535:65536:2147483637),C),x=function(P,S){var L=65536;y.browser==="firefox"&&y.version===57&&(L=65535);var I=i.default.matchPrefix(P.sdp,"a=max-message-size:");return I.length>0?L=parseInt(I[0].substr(19),10):y.browser==="firefox"&&S!==-1&&(L=2147483637),L}(arguments[0],v);m=w===0&&x===0?Number.POSITIVE_INFINITY:w===0||x===0?Math.max(w,x):Math.min(w,x);var T={};Object.defineProperty(T,"maxMessageSize",{get:function(){return m}}),this._sctp=T}var R,C;return g.apply(this,arguments)}}}function h(b){if(b.RTCPeerConnection&&"createDataChannel"in b.RTCPeerConnection.prototype){var y=b.RTCPeerConnection.prototype.createDataChannel;b.RTCPeerConnection.prototype.createDataChannel=function(){var p=y.apply(this,arguments);return g(p,this),p},n.wrapPeerConnectionEvent(b,"datachannel",function(p){return g(p.channel,p.target),p})}function g(p,m){var v=p.send;p.send=function(){var w=arguments[0],x=w.length||w.size||w.byteLength;if(p.readyState==="open"&&m.sctp&&x>m.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+m.sctp.maxMessageSize+" bytes)");return v.apply(p,arguments)}}}function u(b){if(b.RTCPeerConnection&&!("connectionState"in b.RTCPeerConnection.prototype)){var y=b.RTCPeerConnection.prototype;Object.defineProperty(y,"connectionState",{get:function(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(y,"onconnectionstatechange",{get:function(){return this._onconnectionstatechange||null},set:function(g){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),g&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=g)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(function(g){var p=y[g];y[g]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(m){var v=m.target;if(v._lastConnectionState!==v.connectionState){v._lastConnectionState=v.connectionState;var w=new Event("connectionstatechange",m);v.dispatchEvent(w)}return m},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),p.apply(this,arguments)}})}}function f(b,y){if(b.RTCPeerConnection&&!(y.browser==="chrome"&&y.version>=71||y.browser==="safari"&&y.version>=605)){var g=b.RTCPeerConnection.prototype.setRemoteDescription;b.RTCPeerConnection.prototype.setRemoteDescription=function(p){if(p&&p.sdp&&p.sdp.indexOf(`
70
+ a=extmap-allow-mixed`)!==-1){var m=p.sdp.split(`
71
71
  `).filter(function(v){return v.trim()!=="a=extmap-allow-mixed"}).join(`
72
- `);b.RTCSessionDescription&&p instanceof b.RTCSessionDescription?arguments[0]=new b.RTCSessionDescription({type:p.type,sdp:f}):p.sdp=f}return m.apply(this,arguments)}}}function E(b,y){if(b.RTCPeerConnection&&b.RTCPeerConnection.prototype){var m=b.RTCPeerConnection.prototype.addIceCandidate;m&&m.length!==0&&(b.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(y.browser==="chrome"&&y.version<78||y.browser==="firefox"&&y.version<68||y.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():m.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}}},{sdp:"YHvh","./utils":"iSxC"}],KtlG:[function(l,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.adapterFactory=h;var i=a(l("./utils")),n=a(l("./chrome/chrome_shim")),r=a(l("./edge/edge_shim")),s=a(l("./firefox/firefox_shim")),o=a(l("./safari/safari_shim")),c=a(l("./common_shim"));function d(){if(typeof WeakMap!="function")return null;var u=new WeakMap;return d=function(){return u},u}function a(u){if(u&&u.__esModule)return u;if(u===null||typeof u!="object"&&typeof u!="function")return{default:u};var g=d();if(g&&g.has(u))return g.get(u);var E={},b=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var y in u)if(Object.prototype.hasOwnProperty.call(u,y)){var m=b?Object.getOwnPropertyDescriptor(u,y):null;m&&(m.get||m.set)?Object.defineProperty(E,y,m):E[y]=u[y]}return E.default=u,g&&g.set(u,E),E}function h(){var{window:u}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0},E=i.log,b=i.detectBrowser(u),y={browserDetails:b,commonShim:c,extractVersion:i.extractVersion,disableLog:i.disableLog,disableWarnings:i.disableWarnings};switch(b.browser){case"chrome":if(!n||!n.shimPeerConnection||!g.shimChrome)return E("Chrome shim is not included in this adapter release."),y;if(b.version===null)return E("Chrome shim can not determine version, not shimming."),y;E("adapter.js shimming chrome."),y.browserShim=n,c.shimAddIceCandidateNullOrEmpty(u,b),n.shimGetUserMedia(u,b),n.shimMediaStream(u,b),n.shimPeerConnection(u,b),n.shimOnTrack(u,b),n.shimAddTrackRemoveTrack(u,b),n.shimGetSendersWithDtmf(u,b),n.shimGetStats(u,b),n.shimSenderReceiverGetStats(u,b),n.fixNegotiationNeeded(u,b),c.shimRTCIceCandidate(u,b),c.shimConnectionState(u,b),c.shimMaxMessageSize(u,b),c.shimSendThrowTypeError(u,b),c.removeExtmapAllowMixed(u,b);break;case"firefox":if(!s||!s.shimPeerConnection||!g.shimFirefox)return E("Firefox shim is not included in this adapter release."),y;E("adapter.js shimming firefox."),y.browserShim=s,c.shimAddIceCandidateNullOrEmpty(u,b),s.shimGetUserMedia(u,b),s.shimPeerConnection(u,b),s.shimOnTrack(u,b),s.shimRemoveStream(u,b),s.shimSenderGetStats(u,b),s.shimReceiverGetStats(u,b),s.shimRTCDataChannel(u,b),s.shimAddTransceiver(u,b),s.shimGetParameters(u,b),s.shimCreateOffer(u,b),s.shimCreateAnswer(u,b),c.shimRTCIceCandidate(u,b),c.shimConnectionState(u,b),c.shimMaxMessageSize(u,b),c.shimSendThrowTypeError(u,b);break;case"edge":if(!r||!r.shimPeerConnection||!g.shimEdge)return E("MS edge shim is not included in this adapter release."),y;E("adapter.js shimming edge."),y.browserShim=r,r.shimGetUserMedia(u,b),r.shimGetDisplayMedia(u,b),r.shimPeerConnection(u,b),r.shimReplaceTrack(u,b),c.shimMaxMessageSize(u,b),c.shimSendThrowTypeError(u,b);break;case"safari":if(!o||!g.shimSafari)return E("Safari shim is not included in this adapter release."),y;E("adapter.js shimming safari."),y.browserShim=o,c.shimAddIceCandidateNullOrEmpty(u,b),o.shimRTCIceServerUrls(u,b),o.shimCreateOfferLegacy(u,b),o.shimCallbacksAPI(u,b),o.shimLocalStreamsAPI(u,b),o.shimRemoteStreamsAPI(u,b),o.shimTrackEventTransceiver(u,b),o.shimGetUserMedia(u,b),o.shimAudioContext(u,b),c.shimRTCIceCandidate(u,b),c.shimMaxMessageSize(u,b),c.shimSendThrowTypeError(u,b),c.removeExtmapAllowMixed(u,b);break;default:E("Unsupported browser!")}return y}},{"./utils":"iSxC","./chrome/chrome_shim":"uI5X","./edge/edge_shim":"XRic","./firefox/firefox_shim":"Fzdr","./safari/safari_shim":"t1lL","./common_shim":"GOQK"}],tI1X:[function(l,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var i=l("./adapter_factory.js"),n=(0,i.adapterFactory)({window:typeof window>"u"?void 0:window}),r=n;t.default=r},{"./adapter_factory.js":"KtlG"}],sXtV:[function(l,e,t){"use strict";var i=this&&this.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(t,"__esModule",{value:!0}),t.webRTCAdapter=void 0;var n=i(l("webrtc-adapter"));t.webRTCAdapter=n.default},{"webrtc-adapter":"tI1X"}],I31f:[function(l,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Supports=void 0;var i=l("./adapter");t.Supports=new(function(){function n(){this.isIOS=["iPad","iPhone","iPod"].includes(navigator.platform),this.supportedBrowsers=["firefox","chrome","safari"],this.minFirefoxVersion=59,this.minChromeVersion=72,this.minSafariVersion=605}return n.prototype.isWebRTCSupported=function(){return typeof RTCPeerConnection<"u"},n.prototype.isBrowserSupported=function(){var r=this.getBrowser(),s=this.getVersion();return!!this.supportedBrowsers.includes(r)&&(r==="chrome"?s>=this.minChromeVersion:r==="firefox"?s>=this.minFirefoxVersion:r==="safari"&&!this.isIOS&&s>=this.minSafariVersion)},n.prototype.getBrowser=function(){return i.webRTCAdapter.browserDetails.browser},n.prototype.getVersion=function(){return i.webRTCAdapter.browserDetails.version||0},n.prototype.isUnifiedPlanSupported=function(){var r,s=this.getBrowser(),o=i.webRTCAdapter.browserDetails.version||0;if(s==="chrome"&&o<72)return!1;if(s==="firefox"&&o>=59)return!0;if(!(window.RTCRtpTransceiver&&"currentDirection"in RTCRtpTransceiver.prototype))return!1;var c=!1;try{(r=new RTCPeerConnection).addTransceiver("audio"),c=!0}catch{}finally{r&&r.close()}return c},n.prototype.toString=function(){return`Supports:
72
+ `);b.RTCSessionDescription&&p instanceof b.RTCSessionDescription?arguments[0]=new b.RTCSessionDescription({type:p.type,sdp:m}):p.sdp=m}return g.apply(this,arguments)}}}function E(b,y){if(b.RTCPeerConnection&&b.RTCPeerConnection.prototype){var g=b.RTCPeerConnection.prototype.addIceCandidate;g&&g.length!==0&&(b.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(y.browser==="chrome"&&y.version<78||y.browser==="firefox"&&y.version<68||y.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():g.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}}},{sdp:"YHvh","./utils":"iSxC"}],KtlG:[function(l,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.adapterFactory=h;var i=a(l("./utils")),n=a(l("./chrome/chrome_shim")),r=a(l("./edge/edge_shim")),o=a(l("./firefox/firefox_shim")),s=a(l("./safari/safari_shim")),c=a(l("./common_shim"));function d(){if(typeof WeakMap!="function")return null;var u=new WeakMap;return d=function(){return u},u}function a(u){if(u&&u.__esModule)return u;if(u===null||typeof u!="object"&&typeof u!="function")return{default:u};var f=d();if(f&&f.has(u))return f.get(u);var E={},b=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var y in u)if(Object.prototype.hasOwnProperty.call(u,y)){var g=b?Object.getOwnPropertyDescriptor(u,y):null;g&&(g.get||g.set)?Object.defineProperty(E,y,g):E[y]=u[y]}return E.default=u,f&&f.set(u,E),E}function h(){var{window:u}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},f=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0},E=i.log,b=i.detectBrowser(u),y={browserDetails:b,commonShim:c,extractVersion:i.extractVersion,disableLog:i.disableLog,disableWarnings:i.disableWarnings};switch(b.browser){case"chrome":if(!n||!n.shimPeerConnection||!f.shimChrome)return E("Chrome shim is not included in this adapter release."),y;if(b.version===null)return E("Chrome shim can not determine version, not shimming."),y;E("adapter.js shimming chrome."),y.browserShim=n,c.shimAddIceCandidateNullOrEmpty(u,b),n.shimGetUserMedia(u,b),n.shimMediaStream(u,b),n.shimPeerConnection(u,b),n.shimOnTrack(u,b),n.shimAddTrackRemoveTrack(u,b),n.shimGetSendersWithDtmf(u,b),n.shimGetStats(u,b),n.shimSenderReceiverGetStats(u,b),n.fixNegotiationNeeded(u,b),c.shimRTCIceCandidate(u,b),c.shimConnectionState(u,b),c.shimMaxMessageSize(u,b),c.shimSendThrowTypeError(u,b),c.removeExtmapAllowMixed(u,b);break;case"firefox":if(!o||!o.shimPeerConnection||!f.shimFirefox)return E("Firefox shim is not included in this adapter release."),y;E("adapter.js shimming firefox."),y.browserShim=o,c.shimAddIceCandidateNullOrEmpty(u,b),o.shimGetUserMedia(u,b),o.shimPeerConnection(u,b),o.shimOnTrack(u,b),o.shimRemoveStream(u,b),o.shimSenderGetStats(u,b),o.shimReceiverGetStats(u,b),o.shimRTCDataChannel(u,b),o.shimAddTransceiver(u,b),o.shimGetParameters(u,b),o.shimCreateOffer(u,b),o.shimCreateAnswer(u,b),c.shimRTCIceCandidate(u,b),c.shimConnectionState(u,b),c.shimMaxMessageSize(u,b),c.shimSendThrowTypeError(u,b);break;case"edge":if(!r||!r.shimPeerConnection||!f.shimEdge)return E("MS edge shim is not included in this adapter release."),y;E("adapter.js shimming edge."),y.browserShim=r,r.shimGetUserMedia(u,b),r.shimGetDisplayMedia(u,b),r.shimPeerConnection(u,b),r.shimReplaceTrack(u,b),c.shimMaxMessageSize(u,b),c.shimSendThrowTypeError(u,b);break;case"safari":if(!s||!f.shimSafari)return E("Safari shim is not included in this adapter release."),y;E("adapter.js shimming safari."),y.browserShim=s,c.shimAddIceCandidateNullOrEmpty(u,b),s.shimRTCIceServerUrls(u,b),s.shimCreateOfferLegacy(u,b),s.shimCallbacksAPI(u,b),s.shimLocalStreamsAPI(u,b),s.shimRemoteStreamsAPI(u,b),s.shimTrackEventTransceiver(u,b),s.shimGetUserMedia(u,b),s.shimAudioContext(u,b),c.shimRTCIceCandidate(u,b),c.shimMaxMessageSize(u,b),c.shimSendThrowTypeError(u,b),c.removeExtmapAllowMixed(u,b);break;default:E("Unsupported browser!")}return y}},{"./utils":"iSxC","./chrome/chrome_shim":"uI5X","./edge/edge_shim":"XRic","./firefox/firefox_shim":"Fzdr","./safari/safari_shim":"t1lL","./common_shim":"GOQK"}],tI1X:[function(l,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var i=l("./adapter_factory.js"),n=(0,i.adapterFactory)({window:typeof window>"u"?void 0:window}),r=n;t.default=r},{"./adapter_factory.js":"KtlG"}],sXtV:[function(l,e,t){"use strict";var i=this&&this.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(t,"__esModule",{value:!0}),t.webRTCAdapter=void 0;var n=i(l("webrtc-adapter"));t.webRTCAdapter=n.default},{"webrtc-adapter":"tI1X"}],I31f:[function(l,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Supports=void 0;var i=l("./adapter");t.Supports=new(function(){function n(){this.isIOS=["iPad","iPhone","iPod"].includes(navigator.platform),this.supportedBrowsers=["firefox","chrome","safari"],this.minFirefoxVersion=59,this.minChromeVersion=72,this.minSafariVersion=605}return n.prototype.isWebRTCSupported=function(){return typeof RTCPeerConnection<"u"},n.prototype.isBrowserSupported=function(){var r=this.getBrowser(),o=this.getVersion();return!!this.supportedBrowsers.includes(r)&&(r==="chrome"?o>=this.minChromeVersion:r==="firefox"?o>=this.minFirefoxVersion:r==="safari"&&!this.isIOS&&o>=this.minSafariVersion)},n.prototype.getBrowser=function(){return i.webRTCAdapter.browserDetails.browser},n.prototype.getVersion=function(){return i.webRTCAdapter.browserDetails.version||0},n.prototype.isUnifiedPlanSupported=function(){var r,o=this.getBrowser(),s=i.webRTCAdapter.browserDetails.version||0;if(o==="chrome"&&s<72)return!1;if(o==="firefox"&&s>=59)return!0;if(!(window.RTCRtpTransceiver&&"currentDirection"in RTCRtpTransceiver.prototype))return!1;var c=!1;try{(r=new RTCPeerConnection).addTransceiver("audio"),c=!0}catch{}finally{r&&r.close()}return c},n.prototype.toString=function(){return`Supports:
73
73
  browser:`+this.getBrowser()+`
74
74
  version:`+this.getVersion()+`
75
75
  isIOS:`+this.isIOS+`
76
76
  isWebRTCSupported:`+this.isWebRTCSupported()+`
77
77
  isBrowserSupported:`+this.isBrowserSupported()+`
78
- isUnifiedPlanSupported:`+this.isUnifiedPlanSupported()},n}())},{"./adapter":"sXtV"}],BHXf:[function(l,e,t){"use strict";var i=this&&this.__createBinding||(Object.create?function(d,a,h,u){u===void 0&&(u=h),Object.defineProperty(d,u,{enumerable:!0,get:function(){return a[h]}})}:function(d,a,h,u){u===void 0&&(u=h),d[u]=a[h]}),n=this&&this.__setModuleDefault||(Object.create?function(d,a){Object.defineProperty(d,"default",{enumerable:!0,value:a})}:function(d,a){d.default=a}),r=this&&this.__importStar||function(d){if(d&&d.__esModule)return d;var a={};if(d!=null)for(var h in d)h!=="default"&&Object.prototype.hasOwnProperty.call(d,h)&&i(a,d,h);return n(a,d),a};Object.defineProperty(t,"__esModule",{value:!0}),t.util=void 0;var s=r(l("peerjs-js-binarypack")),o=l("./supports"),c={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"turn:0.peerjs.com:3478",username:"peerjs",credential:"peerjsp"}],sdpSemantics:"unified-plan"};t.util=new(function(){function d(){this.CLOUD_HOST="0.peerjs.com",this.CLOUD_PORT=443,this.chunkedBrowsers={Chrome:1,chrome:1},this.chunkedMTU=16300,this.defaultConfig=c,this.browser=o.Supports.getBrowser(),this.browserVersion=o.Supports.getVersion(),this.supports=function(){var a,h={browser:o.Supports.isBrowserSupported(),webRTC:o.Supports.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!h.webRTC)return h;try{a=new RTCPeerConnection(c),h.audioVideo=!0;var u=void 0;try{u=a.createDataChannel("_PEERJSTEST",{ordered:!0}),h.data=!0,h.reliable=!!u.ordered;try{u.binaryType="blob",h.binaryBlob=!o.Supports.isIOS}catch{}}catch{}finally{u&&u.close()}}catch{}finally{a&&a.close()}return h}(),this.pack=s.pack,this.unpack=s.unpack,this._dataCount=1}return d.prototype.noop=function(){},d.prototype.validateId=function(a){return!a||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(a)},d.prototype.chunk=function(a){for(var h=[],u=a.size,g=Math.ceil(u/t.util.chunkedMTU),E=0,b=0;b<u;){var y=Math.min(u,b+t.util.chunkedMTU),m=a.slice(b,y),p={__peerData:this._dataCount,n:E,data:m,total:g};h.push(p),b=y,E++}return this._dataCount++,h},d.prototype.blobToArrayBuffer=function(a,h){var u=new FileReader;return u.onload=function(g){g.target&&h(g.target.result)},u.readAsArrayBuffer(a),u},d.prototype.binaryStringToArrayBuffer=function(a){for(var h=new Uint8Array(a.length),u=0;u<a.length;u++)h[u]=255&a.charCodeAt(u);return h.buffer},d.prototype.randomToken=function(){return Math.random().toString(36).substr(2)},d.prototype.isSecure=function(){return location.protocol==="https:"},d}())},{"peerjs-js-binarypack":"kdPp","./supports":"I31f"}],JJlS:[function(l,e,t){"use strict";var i=Object.prototype.hasOwnProperty,n="~";function r(){}function s(a,h,u){this.fn=a,this.context=h,this.once=u||!1}function o(a,h,u,g,E){if(typeof u!="function")throw new TypeError("The listener must be a function");var b=new s(u,g||a,E),y=n?n+h:h;return a._events[y]?a._events[y].fn?a._events[y]=[a._events[y],b]:a._events[y].push(b):(a._events[y]=b,a._eventsCount++),a}function c(a,h){--a._eventsCount==0?a._events=new r:delete a._events[h]}function d(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1)),d.prototype.eventNames=function(){var a,h,u=[];if(this._eventsCount===0)return u;for(h in a=this._events)i.call(a,h)&&u.push(n?h.slice(1):h);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(a)):u},d.prototype.listeners=function(a){var h=n?n+a:a,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var g=0,E=u.length,b=new Array(E);g<E;g++)b[g]=u[g].fn;return b},d.prototype.listenerCount=function(a){var h=n?n+a:a,u=this._events[h];return u?u.fn?1:u.length:0},d.prototype.emit=function(a,h,u,g,E,b){var y=n?n+a:a;if(!this._events[y])return!1;var m,p,f=this._events[y],v=arguments.length;if(f.fn){switch(f.once&&this.removeListener(a,f.fn,void 0,!0),v){case 1:return f.fn.call(f.context),!0;case 2:return f.fn.call(f.context,h),!0;case 3:return f.fn.call(f.context,h,u),!0;case 4:return f.fn.call(f.context,h,u,g),!0;case 5:return f.fn.call(f.context,h,u,g,E),!0;case 6:return f.fn.call(f.context,h,u,g,E,b),!0}for(p=1,m=new Array(v-1);p<v;p++)m[p-1]=arguments[p];f.fn.apply(f.context,m)}else{var w,x=f.length;for(p=0;p<x;p++)switch(f[p].once&&this.removeListener(a,f[p].fn,void 0,!0),v){case 1:f[p].fn.call(f[p].context);break;case 2:f[p].fn.call(f[p].context,h);break;case 3:f[p].fn.call(f[p].context,h,u);break;case 4:f[p].fn.call(f[p].context,h,u,g);break;default:if(!m)for(w=1,m=new Array(v-1);w<v;w++)m[w-1]=arguments[w];f[p].fn.apply(f[p].context,m)}}return!0},d.prototype.on=function(a,h,u){return o(this,a,h,u,!1)},d.prototype.once=function(a,h,u){return o(this,a,h,u,!0)},d.prototype.removeListener=function(a,h,u,g){var E=n?n+a:a;if(!this._events[E])return this;if(!h)return c(this,E),this;var b=this._events[E];if(b.fn)b.fn!==h||g&&!b.once||u&&b.context!==u||c(this,E);else{for(var y=0,m=[],p=b.length;y<p;y++)(b[y].fn!==h||g&&!b[y].once||u&&b[y].context!==u)&&m.push(b[y]);m.length?this._events[E]=m.length===1?m[0]:m:c(this,E)}return this},d.prototype.removeAllListeners=function(a){var h;return a?(h=n?n+a:a,this._events[h]&&c(this,h)):(this._events=new r,this._eventsCount=0),this},d.prototype.off=d.prototype.removeListener,d.prototype.addListener=d.prototype.on,d.prefixed=n,d.EventEmitter=d,typeof e<"u"&&(e.exports=d)},{}],WOs9:[function(l,e,t){"use strict";var i=this&&this.__read||function(c,d){var a=typeof Symbol=="function"&&c[Symbol.iterator];if(!a)return c;var h,u,g=a.call(c),E=[];try{for(;(d===void 0||d-- >0)&&!(h=g.next()).done;)E.push(h.value)}catch(b){u={error:b}}finally{try{h&&!h.done&&(a=g.return)&&a.call(g)}finally{if(u)throw u.error}}return E},n=this&&this.__spreadArray||function(c,d){for(var a=0,h=d.length,u=c.length;a<h;a++,u++)c[u]=d[a];return c};Object.defineProperty(t,"__esModule",{value:!0}),t.LogLevel=void 0;var r,s="PeerJS: ";(function(c){c[c.Disabled=0]="Disabled",c[c.Errors=1]="Errors",c[c.Warnings=2]="Warnings",c[c.All=3]="All"})(r=t.LogLevel||(t.LogLevel={}));var o=function(){function c(){this._logLevel=r.Disabled}return Object.defineProperty(c.prototype,"logLevel",{get:function(){return this._logLevel},set:function(d){this._logLevel=d},enumerable:!1,configurable:!0}),c.prototype.log=function(){for(var d=[],a=0;a<arguments.length;a++)d[a]=arguments[a];this._logLevel>=r.All&&this._print.apply(this,n([r.All],i(d)))},c.prototype.warn=function(){for(var d=[],a=0;a<arguments.length;a++)d[a]=arguments[a];this._logLevel>=r.Warnings&&this._print.apply(this,n([r.Warnings],i(d)))},c.prototype.error=function(){for(var d=[],a=0;a<arguments.length;a++)d[a]=arguments[a];this._logLevel>=r.Errors&&this._print.apply(this,n([r.Errors],i(d)))},c.prototype.setLogFunction=function(d){this._print=d},c.prototype._print=function(d){for(var a=[],h=1;h<arguments.length;h++)a[h-1]=arguments[h];var u=n([s],i(a));for(var g in u)u[g]instanceof Error&&(u[g]="("+u[g].name+") "+u[g].message);d>=r.All?console.log.apply(console,n([],i(u))):d>=r.Warnings?console.warn.apply(console,n(["WARNING"],i(u))):d>=r.Errors&&console.error.apply(console,n(["ERROR"],i(u)))},c}();t.default=new o},{}],ZRYf:[function(l,e,t){"use strict";var i,n,r,s,o,c,d;Object.defineProperty(t,"__esModule",{value:!0}),t.ServerMessageType=t.SocketEventType=t.SerializationType=t.PeerErrorType=t.PeerEventType=t.ConnectionType=t.ConnectionEventType=void 0,function(a){a.Open="open",a.Stream="stream",a.Data="data",a.Close="close",a.Error="error",a.IceStateChanged="iceStateChanged"}(i=t.ConnectionEventType||(t.ConnectionEventType={})),function(a){a.Data="data",a.Media="media"}(n=t.ConnectionType||(t.ConnectionType={})),function(a){a.Open="open",a.Close="close",a.Connection="connection",a.Call="call",a.Disconnected="disconnected",a.Error="error"}(r=t.PeerEventType||(t.PeerEventType={})),function(a){a.BrowserIncompatible="browser-incompatible",a.Disconnected="disconnected",a.InvalidID="invalid-id",a.InvalidKey="invalid-key",a.Network="network",a.PeerUnavailable="peer-unavailable",a.SslUnavailable="ssl-unavailable",a.ServerError="server-error",a.SocketError="socket-error",a.SocketClosed="socket-closed",a.UnavailableID="unavailable-id",a.WebRTC="webrtc"}(s=t.PeerErrorType||(t.PeerErrorType={})),function(a){a.Binary="binary",a.BinaryUTF8="binary-utf8",a.JSON="json"}(o=t.SerializationType||(t.SerializationType={})),function(a){a.Message="message",a.Disconnected="disconnected",a.Error="error",a.Close="close"}(c=t.SocketEventType||(t.SocketEventType={})),function(a){a.Heartbeat="HEARTBEAT",a.Candidate="CANDIDATE",a.Offer="OFFER",a.Answer="ANSWER",a.Open="OPEN",a.Error="ERROR",a.IdTaken="ID-TAKEN",a.InvalidKey="INVALID-KEY",a.Leave="LEAVE",a.Expire="EXPIRE"}(d=t.ServerMessageType||(t.ServerMessageType={}))},{}],wJlv:[function(l,e,t){"use strict";var i=this&&this.__extends||function(){var u=function(g,E){return(u=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,y){b.__proto__=y}||function(b,y){for(var m in y)Object.prototype.hasOwnProperty.call(y,m)&&(b[m]=y[m])})(g,E)};return function(g,E){if(typeof E!="function"&&E!==null)throw new TypeError("Class extends value "+String(E)+" is not a constructor or null");function b(){this.constructor=g}u(g,E),g.prototype=E===null?Object.create(E):(b.prototype=E.prototype,new b)}}(),n=this&&this.__read||function(u,g){var E=typeof Symbol=="function"&&u[Symbol.iterator];if(!E)return u;var b,y,m=E.call(u),p=[];try{for(;(g===void 0||g-- >0)&&!(b=m.next()).done;)p.push(b.value)}catch(f){y={error:f}}finally{try{b&&!b.done&&(E=m.return)&&E.call(m)}finally{if(y)throw y.error}}return p},r=this&&this.__spreadArray||function(u,g){for(var E=0,b=g.length,y=u.length;E<b;E++,y++)u[y]=g[E];return u},s=this&&this.__values||function(u){var g=typeof Symbol=="function"&&Symbol.iterator,E=g&&u[g],b=0;if(E)return E.call(u);if(u&&typeof u.length=="number")return{next:function(){return u&&b>=u.length&&(u=void 0),{value:u&&u[b++],done:!u}}};throw new TypeError(g?"Object is not iterable.":"Symbol.iterator is not defined.")},o=this&&this.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(t,"__esModule",{value:!0}),t.Socket=void 0;var c=l("eventemitter3"),d=o(l("./logger")),a=l("./enums"),h=function(u){function g(E,b,y,m,p,f){f===void 0&&(f=5e3);var v=u.call(this)||this;v.pingInterval=f,v._disconnected=!0,v._messagesQueue=[];var w=E?"wss://":"ws://";return v._baseUrl=w+b+":"+y+m+"peerjs?key="+p,v}return i(g,u),g.prototype.start=function(E,b){var y=this;this._id=E;var m=this._baseUrl+"&id="+E+"&token="+b;!this._socket&&this._disconnected&&(this._socket=new WebSocket(m),this._disconnected=!1,this._socket.onmessage=function(p){var f;try{f=JSON.parse(p.data),d.default.log("Server message received:",f)}catch{return void d.default.log("Invalid server message",p.data)}y.emit(a.SocketEventType.Message,f)},this._socket.onclose=function(p){y._disconnected||(d.default.log("Socket closed.",p),y._cleanup(),y._disconnected=!0,y.emit(a.SocketEventType.Disconnected))},this._socket.onopen=function(){y._disconnected||(y._sendQueuedMessages(),d.default.log("Socket open"),y._scheduleHeartbeat())})},g.prototype._scheduleHeartbeat=function(){var E=this;this._wsPingTimer=setTimeout(function(){E._sendHeartbeat()},this.pingInterval)},g.prototype._sendHeartbeat=function(){if(this._wsOpen()){var E=JSON.stringify({type:a.ServerMessageType.Heartbeat});this._socket.send(E),this._scheduleHeartbeat()}else d.default.log("Cannot send heartbeat, because socket closed")},g.prototype._wsOpen=function(){return!!this._socket&&this._socket.readyState===1},g.prototype._sendQueuedMessages=function(){var E,b,y=r([],n(this._messagesQueue));this._messagesQueue=[];try{for(var m=s(y),p=m.next();!p.done;p=m.next()){var f=p.value;this.send(f)}}catch(v){E={error:v}}finally{try{p&&!p.done&&(b=m.return)&&b.call(m)}finally{if(E)throw E.error}}},g.prototype.send=function(E){if(!this._disconnected)if(this._id)if(E.type){if(this._wsOpen()){var b=JSON.stringify(E);this._socket.send(b)}}else this.emit(a.SocketEventType.Error,"Invalid message");else this._messagesQueue.push(E)},g.prototype.close=function(){this._disconnected||(this._cleanup(),this._disconnected=!0)},g.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)},g}(c.EventEmitter);t.Socket=h},{eventemitter3:"JJlS","./logger":"WOs9","./enums":"ZRYf"}],HCdX:[function(l,e,t){"use strict";var i=this&&this.__assign||function(){return(i=Object.assign||function(h){for(var u,g=1,E=arguments.length;g<E;g++)for(var b in u=arguments[g])Object.prototype.hasOwnProperty.call(u,b)&&(h[b]=u[b]);return h}).apply(this,arguments)},n=this&&this.__awaiter||function(h,u,g,E){return new(g||(g=Promise))(function(b,y){function m(v){try{f(E.next(v))}catch(w){y(w)}}function p(v){try{f(E.throw(v))}catch(w){y(w)}}function f(v){var w;v.done?b(v.value):(w=v.value,w instanceof g?w:new g(function(x){x(w)})).then(m,p)}f((E=E.apply(h,u||[])).next())})},r=this&&this.__generator||function(h,u){var g,E,b,y,m={label:0,sent:function(){if(1&b[0])throw b[1];return b[1]},trys:[],ops:[]};return y={next:p(0),throw:p(1),return:p(2)},typeof Symbol=="function"&&(y[Symbol.iterator]=function(){return this}),y;function p(f){return function(v){return function(w){if(g)throw new TypeError("Generator is already executing.");for(;m;)try{if(g=1,E&&(b=2&w[0]?E.return:w[0]?E.throw||((b=E.return)&&b.call(E),0):E.next)&&!(b=b.call(E,w[1])).done)return b;switch(E=0,b&&(w=[2&w[0],b.value]),w[0]){case 0:case 1:b=w;break;case 4:return m.label++,{value:w[1],done:!1};case 5:m.label++,E=w[1],w=[0];continue;case 7:w=m.ops.pop(),m.trys.pop();continue;default:if(!(b=(b=m.trys).length>0&&b[b.length-1])&&(w[0]===6||w[0]===2)){m=0;continue}if(w[0]===3&&(!b||w[1]>b[0]&&w[1]<b[3])){m.label=w[1];break}if(w[0]===6&&m.label<b[1]){m.label=b[1],b=w;break}if(b&&m.label<b[2]){m.label=b[2],m.ops.push(w);break}b[2]&&m.ops.pop(),m.trys.pop();continue}w=u.call(h,m)}catch(x){w=[6,x],E=0}finally{g=b=0}if(5&w[0])throw w[1];return{value:w[0]?w[1]:void 0,done:!0}}([f,v])}}},s=this&&this.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(t,"__esModule",{value:!0}),t.Negotiator=void 0;var o=l("./util"),c=s(l("./logger")),d=l("./enums"),a=function(){function h(u){this.connection=u}return h.prototype.startConnection=function(u){var g=this._startPeerConnection();if(this.connection.peerConnection=g,this.connection.type===d.ConnectionType.Media&&u._stream&&this._addTracksToConnection(u._stream,g),u.originator){if(this.connection.type===d.ConnectionType.Data){var E=this.connection,b={ordered:!!u.reliable},y=g.createDataChannel(E.label,b);E.initialize(y)}this._makeOffer()}else this.handleSDP("OFFER",u.sdp)},h.prototype._startPeerConnection=function(){c.default.log("Creating RTCPeerConnection.");var u=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(u),u},h.prototype._setupListeners=function(u){var g=this,E=this.connection.peer,b=this.connection.connectionId,y=this.connection.type,m=this.connection.provider;c.default.log("Listening for ICE candidates."),u.onicecandidate=function(p){p.candidate&&p.candidate.candidate&&(c.default.log("Received ICE candidates for "+E+":",p.candidate),m.socket.send({type:d.ServerMessageType.Candidate,payload:{candidate:p.candidate,type:y,connectionId:b},dst:E}))},u.oniceconnectionstatechange=function(){switch(u.iceConnectionState){case"failed":c.default.log("iceConnectionState is failed, closing connections to "+E),g.connection.emit(d.ConnectionEventType.Error,new Error("Negotiation of connection to "+E+" failed.")),g.connection.close();break;case"closed":c.default.log("iceConnectionState is closed, closing connections to "+E),g.connection.emit(d.ConnectionEventType.Error,new Error("Connection to "+E+" closed.")),g.connection.close();break;case"disconnected":c.default.log("iceConnectionState changed to disconnected on the connection with "+E);break;case"completed":u.onicecandidate=o.util.noop}g.connection.emit(d.ConnectionEventType.IceStateChanged,u.iceConnectionState)},c.default.log("Listening for data channel"),u.ondatachannel=function(p){c.default.log("Received data channel");var f=p.channel;m.getConnection(E,b).initialize(f)},c.default.log("Listening for remote stream"),u.ontrack=function(p){c.default.log("Received remote stream");var f=p.streams[0],v=m.getConnection(E,b);if(v.type===d.ConnectionType.Media){var w=v;g._addStreamToMediaConnection(f,w)}}},h.prototype.cleanup=function(){c.default.log("Cleaning up PeerConnection to "+this.connection.peer);var u=this.connection.peerConnection;if(u){this.connection.peerConnection=null,u.onicecandidate=u.oniceconnectionstatechange=u.ondatachannel=u.ontrack=function(){};var g=u.signalingState!=="closed",E=!1;if(this.connection.type===d.ConnectionType.Data){var b=this.connection.dataChannel;b&&(E=!!b.readyState&&b.readyState!=="closed")}(g||E)&&u.close()}},h.prototype._makeOffer=function(){return n(this,void 0,Promise,function(){var u,g,E,b,y,m,p;return r(this,function(f){switch(f.label){case 0:u=this.connection.peerConnection,g=this.connection.provider,f.label=1;case 1:return f.trys.push([1,7,,8]),[4,u.createOffer(this.connection.options.constraints)];case 2:E=f.sent(),c.default.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(E.sdp=this.connection.options.sdpTransform(E.sdp)||E.sdp),f.label=3;case 3:return f.trys.push([3,5,,6]),[4,u.setLocalDescription(E)];case 4:return f.sent(),c.default.log("Set localDescription:",E,"for:"+this.connection.peer),b={sdp:E,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata,browser:o.util.browser},this.connection.type===d.ConnectionType.Data&&(y=this.connection,b=i(i({},b),{label:y.label,reliable:y.reliable,serialization:y.serialization})),g.socket.send({type:d.ServerMessageType.Offer,payload:b,dst:this.connection.peer}),[3,6];case 5:return(m=f.sent())!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(g.emitError(d.PeerErrorType.WebRTC,m),c.default.log("Failed to setLocalDescription, ",m)),[3,6];case 6:return[3,8];case 7:return p=f.sent(),g.emitError(d.PeerErrorType.WebRTC,p),c.default.log("Failed to createOffer, ",p),[3,8];case 8:return[2]}})})},h.prototype._makeAnswer=function(){return n(this,void 0,Promise,function(){var u,g,E,b,y;return r(this,function(m){switch(m.label){case 0:u=this.connection.peerConnection,g=this.connection.provider,m.label=1;case 1:return m.trys.push([1,7,,8]),[4,u.createAnswer()];case 2:E=m.sent(),c.default.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(E.sdp=this.connection.options.sdpTransform(E.sdp)||E.sdp),m.label=3;case 3:return m.trys.push([3,5,,6]),[4,u.setLocalDescription(E)];case 4:return m.sent(),c.default.log("Set localDescription:",E,"for:"+this.connection.peer),g.socket.send({type:d.ServerMessageType.Answer,payload:{sdp:E,type:this.connection.type,connectionId:this.connection.connectionId,browser:o.util.browser},dst:this.connection.peer}),[3,6];case 5:return b=m.sent(),g.emitError(d.PeerErrorType.WebRTC,b),c.default.log("Failed to setLocalDescription, ",b),[3,6];case 6:return[3,8];case 7:return y=m.sent(),g.emitError(d.PeerErrorType.WebRTC,y),c.default.log("Failed to create answer, ",y),[3,8];case 8:return[2]}})})},h.prototype.handleSDP=function(u,g){return n(this,void 0,Promise,function(){var E,b,y,m;return r(this,function(p){switch(p.label){case 0:g=new RTCSessionDescription(g),E=this.connection.peerConnection,b=this.connection.provider,c.default.log("Setting remote description",g),y=this,p.label=1;case 1:return p.trys.push([1,5,,6]),[4,E.setRemoteDescription(g)];case 2:return p.sent(),c.default.log("Set remoteDescription:"+u+" for:"+this.connection.peer),u!=="OFFER"?[3,4]:[4,y._makeAnswer()];case 3:p.sent(),p.label=4;case 4:return[3,6];case 5:return m=p.sent(),b.emitError(d.PeerErrorType.WebRTC,m),c.default.log("Failed to setRemoteDescription, ",m),[3,6];case 6:return[2]}})})},h.prototype.handleCandidate=function(u){return n(this,void 0,Promise,function(){var g,E,b,y,m,p;return r(this,function(f){switch(f.label){case 0:c.default.log("handleCandidate:",u),g=u.candidate,E=u.sdpMLineIndex,b=u.sdpMid,y=this.connection.peerConnection,m=this.connection.provider,f.label=1;case 1:return f.trys.push([1,3,,4]),[4,y.addIceCandidate(new RTCIceCandidate({sdpMid:b,sdpMLineIndex:E,candidate:g}))];case 2:return f.sent(),c.default.log("Added ICE candidate for:"+this.connection.peer),[3,4];case 3:return p=f.sent(),m.emitError(d.PeerErrorType.WebRTC,p),c.default.log("Failed to handleCandidate, ",p),[3,4];case 4:return[2]}})})},h.prototype._addTracksToConnection=function(u,g){if(c.default.log("add tracks from stream "+u.id+" to peer connection"),!g.addTrack)return c.default.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");u.getTracks().forEach(function(E){g.addTrack(E,u)})},h.prototype._addStreamToMediaConnection=function(u,g){c.default.log("add stream "+u.id+" to media connection "+g.connectionId),g.addStream(u)},h}();t.Negotiator=a},{"./util":"BHXf","./logger":"WOs9","./enums":"ZRYf"}],tQFK:[function(l,e,t){"use strict";var i=this&&this.__extends||function(){var s=function(o,c){return(s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,a){d.__proto__=a}||function(d,a){for(var h in a)Object.prototype.hasOwnProperty.call(a,h)&&(d[h]=a[h])})(o,c)};return function(o,c){if(typeof c!="function"&&c!==null)throw new TypeError("Class extends value "+String(c)+" is not a constructor or null");function d(){this.constructor=o}s(o,c),o.prototype=c===null?Object.create(c):(d.prototype=c.prototype,new d)}}();Object.defineProperty(t,"__esModule",{value:!0}),t.BaseConnection=void 0;var n=l("eventemitter3"),r=function(s){function o(c,d,a){var h=s.call(this)||this;return h.peer=c,h.provider=d,h.options=a,h._open=!1,h.metadata=a.metadata,h}return i(o,s),Object.defineProperty(o.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),o}(n.EventEmitter);t.BaseConnection=r},{eventemitter3:"JJlS"}],dbHP:[function(l,e,t){"use strict";var i=this&&this.__extends||function(){var g=function(E,b){return(g=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(y,m){y.__proto__=m}||function(y,m){for(var p in m)Object.prototype.hasOwnProperty.call(m,p)&&(y[p]=m[p])})(E,b)};return function(E,b){if(typeof b!="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");function y(){this.constructor=E}g(E,b),E.prototype=b===null?Object.create(b):(y.prototype=b.prototype,new y)}}(),n=this&&this.__assign||function(){return(n=Object.assign||function(g){for(var E,b=1,y=arguments.length;b<y;b++)for(var m in E=arguments[b])Object.prototype.hasOwnProperty.call(E,m)&&(g[m]=E[m]);return g}).apply(this,arguments)},r=this&&this.__values||function(g){var E=typeof Symbol=="function"&&Symbol.iterator,b=E&&g[E],y=0;if(b)return b.call(g);if(g&&typeof g.length=="number")return{next:function(){return g&&y>=g.length&&(g=void 0),{value:g&&g[y++],done:!g}}};throw new TypeError(E?"Object is not iterable.":"Symbol.iterator is not defined.")},s=this&&this.__importDefault||function(g){return g&&g.__esModule?g:{default:g}};Object.defineProperty(t,"__esModule",{value:!0}),t.MediaConnection=void 0;var o=l("./util"),c=s(l("./logger")),d=l("./negotiator"),a=l("./enums"),h=l("./baseconnection"),u=function(g){function E(b,y,m){var p=g.call(this,b,y,m)||this;return p._localStream=p.options._stream,p.connectionId=p.options.connectionId||E.ID_PREFIX+o.util.randomToken(),p._negotiator=new d.Negotiator(p),p._localStream&&p._negotiator.startConnection({_stream:p._localStream,originator:!0}),p}return i(E,g),Object.defineProperty(E.prototype,"type",{get:function(){return a.ConnectionType.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(b){c.default.log("Receiving stream",b),this._remoteStream=b,g.prototype.emit.call(this,a.ConnectionEventType.Stream,b)},E.prototype.handleMessage=function(b){var y=b.type,m=b.payload;switch(b.type){case a.ServerMessageType.Answer:this._negotiator.handleSDP(y,m.sdp),this._open=!0;break;case a.ServerMessageType.Candidate:this._negotiator.handleCandidate(m.candidate);break;default:c.default.warn("Unrecognized message type:"+y+" from peer:"+this.peer)}},E.prototype.answer=function(b,y){var m,p;if(y===void 0&&(y={}),this._localStream)c.default.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");else{this._localStream=b,y&&y.sdpTransform&&(this.options.sdpTransform=y.sdpTransform),this._negotiator.startConnection(n(n({},this.options._payload),{_stream:b}));var f=this.provider._getMessages(this.connectionId);try{for(var v=r(f),w=v.next();!w.done;w=v.next()){var x=w.value;this.handleMessage(x)}}catch(T){m={error:T}}finally{try{w&&!w.done&&(p=v.return)&&p.call(v)}finally{if(m)throw m.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,g.prototype.emit.call(this,a.ConnectionEventType.Close))},E.ID_PREFIX="mc_",E}(h.BaseConnection);t.MediaConnection=u},{"./util":"BHXf","./logger":"WOs9","./negotiator":"HCdX","./enums":"ZRYf","./baseconnection":"tQFK"}],GGp6:[function(l,e,t){"use strict";var i=this&&this.__extends||function(){var c=function(d,a){return(c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(h,u){h.__proto__=u}||function(h,u){for(var g in u)Object.prototype.hasOwnProperty.call(u,g)&&(h[g]=u[g])})(d,a)};return function(d,a){if(typeof a!="function"&&a!==null)throw new TypeError("Class extends value "+String(a)+" is not a constructor or null");function h(){this.constructor=d}c(d,a),d.prototype=a===null?Object.create(a):(h.prototype=a.prototype,new h)}}(),n=this&&this.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(t,"__esModule",{value:!0}),t.EncodingQueue=void 0;var r=l("eventemitter3"),s=n(l("./logger")),o=function(c){function d(){var a=c.call(this)||this;return a.fileReader=new FileReader,a._queue=[],a._processing=!1,a.fileReader.onload=function(h){a._processing=!1,h.target&&a.emit("done",h.target.result),a.doNextTask()},a.fileReader.onerror=function(h){s.default.error("EncodingQueue error:",h),a._processing=!1,a.destroy(),a.emit("error",h)},a}return i(d,c),Object.defineProperty(d.prototype,"queue",{get:function(){return this._queue},enumerable:!1,configurable:!0}),Object.defineProperty(d.prototype,"size",{get:function(){return this.queue.length},enumerable:!1,configurable:!0}),Object.defineProperty(d.prototype,"processing",{get:function(){return this._processing},enumerable:!1,configurable:!0}),d.prototype.enque=function(a){this.queue.push(a),this.processing||this.doNextTask()},d.prototype.destroy=function(){this.fileReader.abort(),this._queue=[]},d.prototype.doNextTask=function(){this.size!==0&&(this.processing||(this._processing=!0,this.fileReader.readAsArrayBuffer(this.queue.shift())))},d}(r.EventEmitter);t.EncodingQueue=o},{eventemitter3:"JJlS","./logger":"WOs9"}],GBTQ:[function(l,e,t){"use strict";var i=this&&this.__extends||function(){var g=function(E,b){return(g=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(y,m){y.__proto__=m}||function(y,m){for(var p in m)Object.prototype.hasOwnProperty.call(m,p)&&(y[p]=m[p])})(E,b)};return function(E,b){if(typeof b!="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");function y(){this.constructor=E}g(E,b),E.prototype=b===null?Object.create(b):(y.prototype=b.prototype,new y)}}(),n=this&&this.__values||function(g){var E=typeof Symbol=="function"&&Symbol.iterator,b=E&&g[E],y=0;if(b)return b.call(g);if(g&&typeof g.length=="number")return{next:function(){return g&&y>=g.length&&(g=void 0),{value:g&&g[y++],done:!g}}};throw new TypeError(E?"Object is not iterable.":"Symbol.iterator is not defined.")},r=this&&this.__importDefault||function(g){return g&&g.__esModule?g:{default:g}};Object.defineProperty(t,"__esModule",{value:!0}),t.DataConnection=void 0;var s=l("./util"),o=r(l("./logger")),c=l("./negotiator"),d=l("./enums"),a=l("./baseconnection"),h=l("./encodingQueue"),u=function(g){function E(b,y,m){var p=g.call(this,b,y,m)||this;return p.stringify=JSON.stringify,p.parse=JSON.parse,p._buffer=[],p._bufferSize=0,p._buffering=!1,p._chunkedData={},p._encodingQueue=new h.EncodingQueue,p.connectionId=p.options.connectionId||E.ID_PREFIX+s.util.randomToken(),p.label=p.options.label||p.connectionId,p.serialization=p.options.serialization||d.SerializationType.Binary,p.reliable=!!p.options.reliable,p._encodingQueue.on("done",function(f){p._bufferedSend(f)}),p._encodingQueue.on("error",function(){o.default.error("DC#"+p.connectionId+": Error occured in encoding from blob to arraybuffer, close DC"),p.close()}),p._negotiator=new c.Negotiator(p),p._negotiator.startConnection(p.options._payload||{originator:!0}),p}return i(E,g),Object.defineProperty(E.prototype,"type",{get:function(){return d.ConnectionType.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(b){this._dc=b,this._configureDataChannel()},E.prototype._configureDataChannel=function(){var b=this;s.util.supports.binaryBlob&&!s.util.supports.reliable||(this.dataChannel.binaryType="arraybuffer"),this.dataChannel.onopen=function(){o.default.log("DC#"+b.connectionId+" dc connection success"),b._open=!0,b.emit(d.ConnectionEventType.Open)},this.dataChannel.onmessage=function(y){o.default.log("DC#"+b.connectionId+" dc onmessage:",y.data),b._handleDataMessage(y)},this.dataChannel.onclose=function(){o.default.log("DC#"+b.connectionId+" dc closed for:",b.peer),b.close()}},E.prototype._handleDataMessage=function(b){var y=this,m=b.data,p=m.constructor,f=m;if(this.serialization===d.SerializationType.Binary||this.serialization===d.SerializationType.BinaryUTF8){if(p===Blob)return void s.util.blobToArrayBuffer(m,function(w){var x=s.util.unpack(w);y.emit(d.ConnectionEventType.Data,x)});if(p===ArrayBuffer)f=s.util.unpack(m);else if(p===String){var v=s.util.binaryStringToArrayBuffer(m);f=s.util.unpack(v)}}else this.serialization===d.SerializationType.JSON&&(f=this.parse(m));f.__peerData?this._handleChunk(f):g.prototype.emit.call(this,d.ConnectionEventType.Data,f)},E.prototype._handleChunk=function(b){var y=b.__peerData,m=this._chunkedData[y]||{data:[],count:0,total:b.total};if(m.data[b.n]=b.data,m.count++,this._chunkedData[y]=m,m.total===m.count){delete this._chunkedData[y];var p=new Blob(m.data);this._handleDataMessage({data:p})}},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,g.prototype.emit.call(this,d.ConnectionEventType.Close))},E.prototype.send=function(b,y){if(this.open)if(this.serialization===d.SerializationType.JSON)this._bufferedSend(this.stringify(b));else if(this.serialization===d.SerializationType.Binary||this.serialization===d.SerializationType.BinaryUTF8){var m=s.util.pack(b);if(!y&&m.size>s.util.chunkedMTU)return void this._sendChunks(m);s.util.supports.binaryBlob?this._bufferedSend(m):this._encodingQueue.enque(m)}else this._bufferedSend(b);else g.prototype.emit.call(this,d.ConnectionEventType.Error,new Error("Connection is not open. You should listen for the `open` event before sending messages."))},E.prototype._bufferedSend=function(b){!this._buffering&&this._trySend(b)||(this._buffer.push(b),this._bufferSize=this._buffer.length)},E.prototype._trySend=function(b){var y=this;if(!this.open)return!1;if(this.dataChannel.bufferedAmount>E.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(function(){y._buffering=!1,y._tryBuffer()},50),!1;try{this.dataChannel.send(b)}catch(m){return o.default.error("DC#:"+this.connectionId+" Error when sending:",m),this._buffering=!0,this.close(),!1}return!0},E.prototype._tryBuffer=function(){if(this.open&&this._buffer.length!==0){var b=this._buffer[0];this._trySend(b)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}},E.prototype._sendChunks=function(b){var y,m,p=s.util.chunk(b);o.default.log("DC#"+this.connectionId+" Try to send "+p.length+" chunks...");try{for(var f=n(p),v=f.next();!v.done;v=f.next()){var w=v.value;this.send(w,!0)}}catch(x){y={error:x}}finally{try{v&&!v.done&&(m=f.return)&&m.call(f)}finally{if(y)throw y.error}}},E.prototype.handleMessage=function(b){var y=b.payload;switch(b.type){case d.ServerMessageType.Answer:this._negotiator.handleSDP(b.type,y.sdp);break;case d.ServerMessageType.Candidate:this._negotiator.handleCandidate(y.candidate);break;default:o.default.warn("Unrecognized message type:",b.type,"from peer:",this.peer)}},E.ID_PREFIX="dc_",E.MAX_BUFFERED_AMOUNT=8388608,E}(a.BaseConnection);t.DataConnection=u},{"./util":"BHXf","./logger":"WOs9","./negotiator":"HCdX","./enums":"ZRYf","./baseconnection":"tQFK","./encodingQueue":"GGp6"}],in7L:[function(l,e,t){"use strict";var i=this&&this.__awaiter||function(d,a,h,u){return new(h||(h=Promise))(function(g,E){function b(p){try{m(u.next(p))}catch(f){E(f)}}function y(p){try{m(u.throw(p))}catch(f){E(f)}}function m(p){var f;p.done?g(p.value):(f=p.value,f instanceof h?f:new h(function(v){v(f)})).then(b,y)}m((u=u.apply(d,a||[])).next())})},n=this&&this.__generator||function(d,a){var h,u,g,E,b={label:0,sent:function(){if(1&g[0])throw g[1];return g[1]},trys:[],ops:[]};return E={next:y(0),throw:y(1),return:y(2)},typeof Symbol=="function"&&(E[Symbol.iterator]=function(){return this}),E;function y(m){return function(p){return function(f){if(h)throw new TypeError("Generator is already executing.");for(;b;)try{if(h=1,u&&(g=2&f[0]?u.return:f[0]?u.throw||((g=u.return)&&g.call(u),0):u.next)&&!(g=g.call(u,f[1])).done)return g;switch(u=0,g&&(f=[2&f[0],g.value]),f[0]){case 0:case 1:g=f;break;case 4:return b.label++,{value:f[1],done:!1};case 5:b.label++,u=f[1],f=[0];continue;case 7:f=b.ops.pop(),b.trys.pop();continue;default:if(!(g=(g=b.trys).length>0&&g[g.length-1])&&(f[0]===6||f[0]===2)){b=0;continue}if(f[0]===3&&(!g||f[1]>g[0]&&f[1]<g[3])){b.label=f[1];break}if(f[0]===6&&b.label<g[1]){b.label=g[1],g=f;break}if(g&&b.label<g[2]){b.label=g[2],b.ops.push(f);break}g[2]&&b.ops.pop(),b.trys.pop();continue}f=a.call(d,b)}catch(v){f=[6,v],u=0}finally{h=g=0}if(5&f[0])throw f[1];return{value:f[0]?f[1]:void 0,done:!0}}([m,p])}}},r=this&&this.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(t,"__esModule",{value:!0}),t.API=void 0;var s=l("./util"),o=r(l("./logger")),c=function(){function d(a){this._options=a}return d.prototype._buildUrl=function(a){var h=(this._options.secure?"https://":"http://")+this._options.host+":"+this._options.port+this._options.path+this._options.key+"/"+a;return h+="?ts="+new Date().getTime()+Math.random()},d.prototype.retrieveId=function(){return i(this,void 0,Promise,function(){var a,h,u,g;return n(this,function(E){switch(E.label){case 0:a=this._buildUrl("id"),E.label=1;case 1:return E.trys.push([1,3,,4]),[4,fetch(a)];case 2:if((h=E.sent()).status!==200)throw new Error("Error. Status:"+h.status);return[2,h.text()];case 3:throw u=E.sent(),o.default.error("Error retrieving ID",u),g="",this._options.path==="/"&&this._options.host!==s.util.CLOUD_HOST&&(g=" 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."+g);case 4:return[2]}})})},d.prototype.listAllPeers=function(){return i(this,void 0,Promise,function(){var a,h,u,g;return n(this,function(E){switch(E.label){case 0:a=this._buildUrl("peers"),E.label=1;case 1:return E.trys.push([1,3,,4]),[4,fetch(a)];case 2:if((h=E.sent()).status!==200)throw h.status===401?(u="",u=this._options.host===s.util.CLOUD_HOST?"It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":"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. "+u)):new Error("Error. Status:"+h.status);return[2,h.json()];case 3:throw g=E.sent(),o.default.error("Error retrieving list peers",g),new Error("Could not get list peers from the server."+g);case 4:return[2]}})})},d}();t.API=c},{"./util":"BHXf","./logger":"WOs9"}],Hxpd:[function(l,e,t){"use strict";var i=this&&this.__extends||function(){var p=function(f,v){return(p=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(w,x){w.__proto__=x}||function(w,x){for(var T in x)Object.prototype.hasOwnProperty.call(x,T)&&(w[T]=x[T])})(f,v)};return function(f,v){if(typeof v!="function"&&v!==null)throw new TypeError("Class extends value "+String(v)+" is not a constructor or null");function w(){this.constructor=f}p(f,v),f.prototype=v===null?Object.create(v):(w.prototype=v.prototype,new w)}}(),n=this&&this.__assign||function(){return(n=Object.assign||function(p){for(var f,v=1,w=arguments.length;v<w;v++)for(var x in f=arguments[v])Object.prototype.hasOwnProperty.call(f,x)&&(p[x]=f[x]);return p}).apply(this,arguments)},r=this&&this.__values||function(p){var f=typeof Symbol=="function"&&Symbol.iterator,v=f&&p[f],w=0;if(v)return v.call(p);if(p&&typeof p.length=="number")return{next:function(){return p&&w>=p.length&&(p=void 0),{value:p&&p[w++],done:!p}}};throw new TypeError(f?"Object is not iterable.":"Symbol.iterator is not defined.")},s=this&&this.__read||function(p,f){var v=typeof Symbol=="function"&&p[Symbol.iterator];if(!v)return p;var w,x,T=v.call(p),R=[];try{for(;(f===void 0||f-- >0)&&!(w=T.next()).done;)R.push(w.value)}catch(C){x={error:C}}finally{try{w&&!w.done&&(v=T.return)&&v.call(T)}finally{if(x)throw x.error}}return R},o=this&&this.__importDefault||function(p){return p&&p.__esModule?p:{default:p}};Object.defineProperty(t,"__esModule",{value:!0}),t.Peer=void 0;var c=l("eventemitter3"),d=l("./util"),a=o(l("./logger")),h=l("./socket"),u=l("./mediaconnection"),g=l("./dataconnection"),E=l("./enums"),b=l("./api"),y=function(){return function(){}}(),m=function(p){function f(v,w){var x,T=p.call(this)||this;return T._id=null,T._lastServerId=null,T._destroyed=!1,T._disconnected=!1,T._open=!1,T._connections=new Map,T._lostMessages=new Map,v&&v.constructor==Object?w=v:v&&(x=v.toString()),w=n({debug:0,host:d.util.CLOUD_HOST,port:d.util.CLOUD_PORT,path:"/",key:f.DEFAULT_KEY,token:d.util.randomToken(),config:d.util.defaultConfig},w),T._options=w,T._options.host==="/"&&(T._options.host=window.location.hostname),T._options.path&&(T._options.path[0]!=="/"&&(T._options.path="/"+T._options.path),T._options.path[T._options.path.length-1]!=="/"&&(T._options.path+="/")),T._options.secure===void 0&&T._options.host!==d.util.CLOUD_HOST?T._options.secure=d.util.isSecure():T._options.host==d.util.CLOUD_HOST&&(T._options.secure=!0),T._options.logFunction&&a.default.setLogFunction(T._options.logFunction),a.default.logLevel=T._options.debug||0,T._api=new b.API(w),T._socket=T._createServerConnection(),d.util.supports.audioVideo||d.util.supports.data?x&&!d.util.validateId(x)?(T._delayedAbort(E.PeerErrorType.InvalidID,'ID "'+x+'" is invalid'),T):(x?T._initialize(x):T._api.retrieveId().then(function(R){return T._initialize(R)}).catch(function(R){return T._abort(E.PeerErrorType.ServerError,R)}),T):(T._delayedAbort(E.PeerErrorType.BrowserIncompatible,"The current browser does not support WebRTC"),T)}return i(f,p),Object.defineProperty(f.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(f.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),Object.defineProperty(f.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),Object.defineProperty(f.prototype,"socket",{get:function(){return this._socket},enumerable:!1,configurable:!0}),Object.defineProperty(f.prototype,"connections",{get:function(){var v,w,x=Object.create(null);try{for(var T=r(this._connections),R=T.next();!R.done;R=T.next()){var C=s(R.value,2),P=C[0],S=C[1];x[P]=S}}catch(L){v={error:L}}finally{try{R&&!R.done&&(w=T.return)&&w.call(T)}finally{if(v)throw v.error}}return x},enumerable:!1,configurable:!0}),Object.defineProperty(f.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!1,configurable:!0}),Object.defineProperty(f.prototype,"disconnected",{get:function(){return this._disconnected},enumerable:!1,configurable:!0}),f.prototype._createServerConnection=function(){var v=this,w=new h.Socket(this._options.secure,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval);return w.on(E.SocketEventType.Message,function(x){v._handleMessage(x)}),w.on(E.SocketEventType.Error,function(x){v._abort(E.PeerErrorType.SocketError,x)}),w.on(E.SocketEventType.Disconnected,function(){v.disconnected||(v.emitError(E.PeerErrorType.Network,"Lost connection to server."),v.disconnect())}),w.on(E.SocketEventType.Close,function(){v.disconnected||v._abort(E.PeerErrorType.SocketClosed,"Underlying socket is already closed.")}),w},f.prototype._initialize=function(v){this._id=v,this.socket.start(v,this._options.token)},f.prototype._handleMessage=function(v){var w,x,T=v.type,R=v.payload,C=v.src;switch(T){case E.ServerMessageType.Open:this._lastServerId=this.id,this._open=!0,this.emit(E.PeerEventType.Open,this.id);break;case E.ServerMessageType.Error:this._abort(E.PeerErrorType.ServerError,R.msg);break;case E.ServerMessageType.IdTaken:this._abort(E.PeerErrorType.UnavailableID,'ID "'+this.id+'" is taken');break;case E.ServerMessageType.InvalidKey:this._abort(E.PeerErrorType.InvalidKey,'API KEY "'+this._options.key+'" is invalid');break;case E.ServerMessageType.Leave:a.default.log("Received leave message from "+C),this._cleanupPeer(C),this._connections.delete(C);break;case E.ServerMessageType.Expire:this.emitError(E.PeerErrorType.PeerUnavailable,"Could not connect to peer "+C);break;case E.ServerMessageType.Offer:var P=R.connectionId;if((H=this.getConnection(C,P))&&(H.close(),a.default.warn("Offer received for existing Connection ID:"+P)),R.type===E.ConnectionType.Media)H=new u.MediaConnection(C,this,{connectionId:P,_payload:R,metadata:R.metadata}),this._addConnection(C,H),this.emit(E.PeerEventType.Call,H);else{if(R.type!==E.ConnectionType.Data)return void a.default.warn("Received malformed connection type:"+R.type);H=new g.DataConnection(C,this,{connectionId:P,_payload:R,metadata:R.metadata,label:R.label,serialization:R.serialization,reliable:R.reliable}),this._addConnection(C,H),this.emit(E.PeerEventType.Connection,H)}var S=this._getMessages(P);try{for(var L=r(S),I=L.next();!I.done;I=L.next()){var j=I.value;H.handleMessage(j)}}catch(F){w={error:F}}finally{try{I&&!I.done&&(x=L.return)&&x.call(L)}finally{if(w)throw w.error}}break;default:if(!R)return void a.default.warn("You received a malformed message from "+C+" of type "+T);var H;P=R.connectionId,(H=this.getConnection(C,P))&&H.peerConnection?H.handleMessage(v):P?this._storeMessage(P,v):a.default.warn("You received an unrecognized message:",v)}},f.prototype._storeMessage=function(v,w){this._lostMessages.has(v)||this._lostMessages.set(v,[]),this._lostMessages.get(v).push(w)},f.prototype._getMessages=function(v){var w=this._lostMessages.get(v);return w?(this._lostMessages.delete(v),w):[]},f.prototype.connect=function(v,w){if(w===void 0&&(w={}),this.disconnected)return a.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."),void this.emitError(E.PeerErrorType.Disconnected,"Cannot connect to new Peer after disconnecting from server.");var x=new g.DataConnection(v,this,w);return this._addConnection(v,x),x},f.prototype.call=function(v,w,x){if(x===void 0&&(x={}),this.disconnected)return a.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."),void this.emitError(E.PeerErrorType.Disconnected,"Cannot connect to new Peer after disconnecting from server.");if(w){x._stream=w;var T=new u.MediaConnection(v,this,x);return this._addConnection(v,T),T}a.default.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.")},f.prototype._addConnection=function(v,w){a.default.log("add connection "+w.type+":"+w.connectionId+" to peerId:"+v),this._connections.has(v)||this._connections.set(v,[]),this._connections.get(v).push(w)},f.prototype._removeConnection=function(v){var w=this._connections.get(v.peer);if(w){var x=w.indexOf(v);x!==-1&&w.splice(x,1)}this._lostMessages.delete(v.connectionId)},f.prototype.getConnection=function(v,w){var x,T,R=this._connections.get(v);if(!R)return null;try{for(var C=r(R),P=C.next();!P.done;P=C.next()){var S=P.value;if(S.connectionId===w)return S}}catch(L){x={error:L}}finally{try{P&&!P.done&&(T=C.return)&&T.call(C)}finally{if(x)throw x.error}}return null},f.prototype._delayedAbort=function(v,w){var x=this;setTimeout(function(){x._abort(v,w)},0)},f.prototype._abort=function(v,w){a.default.error("Aborting!"),this.emitError(v,w),this._lastServerId?this.disconnect():this.destroy()},f.prototype.emitError=function(v,w){var x;a.default.error("Error:",w),(x=typeof w=="string"?new Error(w):w).type=v,this.emit(E.PeerEventType.Error,x)},f.prototype.destroy=function(){this.destroyed||(a.default.log("Destroy peer with ID:"+this.id),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit(E.PeerEventType.Close))},f.prototype._cleanup=function(){var v,w;try{for(var x=r(this._connections.keys()),T=x.next();!T.done;T=x.next()){var R=T.value;this._cleanupPeer(R),this._connections.delete(R)}}catch(C){v={error:C}}finally{try{T&&!T.done&&(w=x.return)&&w.call(x)}finally{if(v)throw v.error}}this.socket.removeAllListeners()},f.prototype._cleanupPeer=function(v){var w,x,T=this._connections.get(v);if(T)try{for(var R=r(T),C=R.next();!C.done;C=R.next())C.value.close()}catch(P){w={error:P}}finally{try{C&&!C.done&&(x=R.return)&&x.call(R)}finally{if(w)throw w.error}}},f.prototype.disconnect=function(){if(!this.disconnected){var v=this.id;a.default.log("Disconnect peer with ID:"+v),this._disconnected=!0,this._open=!1,this.socket.close(),this._lastServerId=v,this._id=null,this.emit(E.PeerEventType.Disconnected,v)}},f.prototype.reconnect=function(){if(this.disconnected&&!this.destroyed)a.default.log("Attempting reconnection to server with ID "+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)throw new Error("Peer "+this.id+" cannot reconnect because it is not disconnected from the server!");a.default.error("In a hurry? We're still trying to make the initial connection!")}},f.prototype.listAllPeers=function(v){var w=this;v===void 0&&(v=function(x){}),this._api.listAllPeers().then(function(x){return v(x)}).catch(function(x){return w._abort(E.PeerErrorType.ServerError,x)})},f.DEFAULT_KEY="peerjs",f}(c.EventEmitter);t.Peer=m},{eventemitter3:"JJlS","./util":"BHXf","./logger":"WOs9","./socket":"wJlv","./mediaconnection":"dbHP","./dataconnection":"GBTQ","./enums":"ZRYf","./api":"in7L"}],iTK6:[function(l,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.peerjs=void 0;var i=l("./util"),n=l("./peer");t.peerjs={Peer:n.Peer,util:i.util},t.default=n.Peer,window.peerjs=t.peerjs,window.Peer=n.Peer},{"./util":"BHXf","./peer":"Hxpd"}]},{},["iTK6"],null)});var Ju=Gs((tR,Zu)=>{(function(){var l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e={rotl:function(t,i){return t<<i|t>>>32-i},rotr:function(t,i){return t<<32-i|t>>>i},endian:function(t){if(t.constructor==Number)return e.rotl(t,8)&16711935|e.rotl(t,24)&4278255360;for(var i=0;i<t.length;i++)t[i]=e.endian(t[i]);return t},randomBytes:function(t){for(var i=[];t>0;t--)i.push(Math.floor(Math.random()*256));return i},bytesToWords:function(t){for(var i=[],n=0,r=0;n<t.length;n++,r+=8)i[r>>>5]|=t[n]<<24-r%32;return i},wordsToBytes:function(t){for(var i=[],n=0;n<t.length*32;n+=8)i.push(t[n>>>5]>>>24-n%32&255);return i},bytesToHex:function(t){for(var i=[],n=0;n<t.length;n++)i.push((t[n]>>>4).toString(16)),i.push((t[n]&15).toString(16));return i.join("")},hexToBytes:function(t){for(var i=[],n=0;n<t.length;n+=2)i.push(parseInt(t.substr(n,2),16));return i},bytesToBase64:function(t){for(var i=[],n=0;n<t.length;n+=3)for(var r=t[n]<<16|t[n+1]<<8|t[n+2],s=0;s<4;s++)n*8+s*6<=t.length*8?i.push(l.charAt(r>>>6*(3-s)&63)):i.push("=");return i.join("")},base64ToBytes:function(t){t=t.replace(/[^A-Z0-9+\/]/ig,"");for(var i=[],n=0,r=0;n<t.length;r=++n%4)r!=0&&i.push((l.indexOf(t.charAt(n-1))&Math.pow(2,-2*r+8)-1)<<r*2|l.indexOf(t.charAt(n))>>>6-r*2);return i}};Zu.exports=e})()});var Lc=Gs((iR,$u)=>{var Mc={utf8:{stringToBytes:function(l){return Mc.bin.stringToBytes(unescape(encodeURIComponent(l)))},bytesToString:function(l){return decodeURIComponent(escape(Mc.bin.bytesToString(l)))}},bin:{stringToBytes:function(l){for(var e=[],t=0;t<l.length;t++)e.push(l.charCodeAt(t)&255);return e},bytesToString:function(l){for(var e=[],t=0;t<l.length;t++)e.push(String.fromCharCode(l[t]));return e.join("")}}};$u.exports=Mc});var tp=Gs((nR,ep)=>{ep.exports=function(l){return l!=null&&(Ku(l)||wv(l)||!!l._isBuffer)};function Ku(l){return!!l.constructor&&typeof l.constructor.isBuffer=="function"&&l.constructor.isBuffer(l)}function wv(l){return typeof l.readFloatLE=="function"&&typeof l.slice=="function"&&Ku(l.slice(0,0))}});var np=Gs((rR,ip)=>{(function(){var l=Ju(),e=Lc().utf8,t=tp(),i=Lc().bin,n=function(r,s){r.constructor==String?s&&s.encoding==="binary"?r=i.stringToBytes(r):r=e.stringToBytes(r):t(r)?r=Array.prototype.slice.call(r,0):!Array.isArray(r)&&r.constructor!==Uint8Array&&(r=r.toString());for(var o=l.bytesToWords(r),c=r.length*8,d=1732584193,a=-271733879,h=-1732584194,u=271733878,g=0;g<o.length;g++)o[g]=(o[g]<<8|o[g]>>>24)&16711935|(o[g]<<24|o[g]>>>8)&4278255360;o[c>>>5]|=128<<c%32,o[(c+64>>>9<<4)+14]=c;for(var E=n._ff,b=n._gg,y=n._hh,m=n._ii,g=0;g<o.length;g+=16){var p=d,f=a,v=h,w=u;d=E(d,a,h,u,o[g+0],7,-680876936),u=E(u,d,a,h,o[g+1],12,-389564586),h=E(h,u,d,a,o[g+2],17,606105819),a=E(a,h,u,d,o[g+3],22,-1044525330),d=E(d,a,h,u,o[g+4],7,-176418897),u=E(u,d,a,h,o[g+5],12,1200080426),h=E(h,u,d,a,o[g+6],17,-1473231341),a=E(a,h,u,d,o[g+7],22,-45705983),d=E(d,a,h,u,o[g+8],7,1770035416),u=E(u,d,a,h,o[g+9],12,-1958414417),h=E(h,u,d,a,o[g+10],17,-42063),a=E(a,h,u,d,o[g+11],22,-1990404162),d=E(d,a,h,u,o[g+12],7,1804603682),u=E(u,d,a,h,o[g+13],12,-40341101),h=E(h,u,d,a,o[g+14],17,-1502002290),a=E(a,h,u,d,o[g+15],22,1236535329),d=b(d,a,h,u,o[g+1],5,-165796510),u=b(u,d,a,h,o[g+6],9,-1069501632),h=b(h,u,d,a,o[g+11],14,643717713),a=b(a,h,u,d,o[g+0],20,-373897302),d=b(d,a,h,u,o[g+5],5,-701558691),u=b(u,d,a,h,o[g+10],9,38016083),h=b(h,u,d,a,o[g+15],14,-660478335),a=b(a,h,u,d,o[g+4],20,-405537848),d=b(d,a,h,u,o[g+9],5,568446438),u=b(u,d,a,h,o[g+14],9,-1019803690),h=b(h,u,d,a,o[g+3],14,-187363961),a=b(a,h,u,d,o[g+8],20,1163531501),d=b(d,a,h,u,o[g+13],5,-1444681467),u=b(u,d,a,h,o[g+2],9,-51403784),h=b(h,u,d,a,o[g+7],14,1735328473),a=b(a,h,u,d,o[g+12],20,-1926607734),d=y(d,a,h,u,o[g+5],4,-378558),u=y(u,d,a,h,o[g+8],11,-2022574463),h=y(h,u,d,a,o[g+11],16,1839030562),a=y(a,h,u,d,o[g+14],23,-35309556),d=y(d,a,h,u,o[g+1],4,-1530992060),u=y(u,d,a,h,o[g+4],11,1272893353),h=y(h,u,d,a,o[g+7],16,-155497632),a=y(a,h,u,d,o[g+10],23,-1094730640),d=y(d,a,h,u,o[g+13],4,681279174),u=y(u,d,a,h,o[g+0],11,-358537222),h=y(h,u,d,a,o[g+3],16,-722521979),a=y(a,h,u,d,o[g+6],23,76029189),d=y(d,a,h,u,o[g+9],4,-640364487),u=y(u,d,a,h,o[g+12],11,-421815835),h=y(h,u,d,a,o[g+15],16,530742520),a=y(a,h,u,d,o[g+2],23,-995338651),d=m(d,a,h,u,o[g+0],6,-198630844),u=m(u,d,a,h,o[g+7],10,1126891415),h=m(h,u,d,a,o[g+14],15,-1416354905),a=m(a,h,u,d,o[g+5],21,-57434055),d=m(d,a,h,u,o[g+12],6,1700485571),u=m(u,d,a,h,o[g+3],10,-1894986606),h=m(h,u,d,a,o[g+10],15,-1051523),a=m(a,h,u,d,o[g+1],21,-2054922799),d=m(d,a,h,u,o[g+8],6,1873313359),u=m(u,d,a,h,o[g+15],10,-30611744),h=m(h,u,d,a,o[g+6],15,-1560198380),a=m(a,h,u,d,o[g+13],21,1309151649),d=m(d,a,h,u,o[g+4],6,-145523070),u=m(u,d,a,h,o[g+11],10,-1120210379),h=m(h,u,d,a,o[g+2],15,718787259),a=m(a,h,u,d,o[g+9],21,-343485551),d=d+p>>>0,a=a+f>>>0,h=h+v>>>0,u=u+w>>>0}return l.endian([d,a,h,u])};n._ff=function(r,s,o,c,d,a,h){var u=r+(s&o|~s&c)+(d>>>0)+h;return(u<<a|u>>>32-a)+s},n._gg=function(r,s,o,c,d,a,h){var u=r+(s&c|o&~c)+(d>>>0)+h;return(u<<a|u>>>32-a)+s},n._hh=function(r,s,o,c,d,a,h){var u=r+(s^o^c)+(d>>>0)+h;return(u<<a|u>>>32-a)+s},n._ii=function(r,s,o,c,d,a,h){var u=r+(o^(s|~c))+(d>>>0)+h;return(u<<a|u>>>32-a)+s},n._blocksize=16,n._digestsize=16,ip.exports=function(r,s){if(r==null)throw new Error("Illegal argument "+r);var o=l.wordsToBytes(n(r,s));return s&&s.asBytes?o:s&&s.asString?i.bytesToString(o):l.bytesToHex(o)}})()});import{DepthTexture as _E,WebGLRenderer as xE}from"three";import*as De from"three";var Hl={};Kd(Hl,{Behaviour:()=>M,Component:()=>st,GameObject:()=>O,HideFlags:()=>Lh,InstantiateOptions:()=>ye});import*as ae from"three";var cn="__isActiveInHierarchy",Gn="builtin_components";function Vn(l,e){try{e?l(e):l()}catch(t){return console.error(t),!1}return!0}var El=()=>l=>l;var wl=!1,yl=[];setTimeout(()=>{wl&&console.log(yl)},100);function _l(){return new URLSearchParams(window.location.search)}function N(l){wl&&!yl.includes(l)&&yl.push(l);let e=_l();if(e.has(l)){let t=e.get(l);return t||!0}return!1}wl=N("help")===!0;function Rr(l,e,t){l.has(e)?l.set(e,t.toString()):l.append(e,t.toString())}function ih(l,e){window.history.replaceState(null,l,"?"+e.toString())}function nh(l,e){return Math.floor(Math.random()*(e-l+1))+l}var eh=["smol","tiny","giant","interesting","smart","bright","dull","extreme","beautiful","pretty","dark","epic","salty","silly","funny","lame","lazy","loud","lucky","mad","mean","mighty","mysterious","nasty","odd","old","powerful","quiet","rapid","scary","shiny","shy","silly","smooth","sour","spicy","stupid","sweet","tasty","terrible","ugly","unusual","vast","wet","wild","witty","wrong","zany","zealous","zippy","zombie","zorro"],th=["cat","dog","mouse","pig","cow","horse","sheep","chicken","duck","goat","panda","tiger","lion","elephant","monkey","bird","fish","snake","frog","turtle","hamster","penguin","kangaroo","whale","dolphin","crocodile","snail","ant","bee","beetle","butterfly","dragon","eagle","fish","giraffe","lizard","panda","penguin","rabbit","snake","spider","tiger","zebra"];function rh(){let l=eh[Math.floor(Math.random()*eh.length)],e=th[Math.floor(Math.random()*th.length)];return l+"_"+e}function sh(l){return l=l.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),l.trim()}function dn(l,e,t=!0,i=!1){if(e==null)return null;if(e.userData&&e.userData.guid===l)return e;if(e.guid==l)return e;if(i&&e.userData?.components){for(let n of e.userData.components)if(n.guid===l)return n}if(t){if(e.scenes)for(let n in e.scenes){let r=e.scenes[n],s=dn(l,r,t,i);if(s)return s}if(e.children)for(let n in e.children){let r=e.children[n],s=dn(l,r,t,i);if(s)return s}}}function Vs(l,e){if(l!=null&&typeof l=="object"){let t;Array.isArray(l)?t=[]:(t=Object.create(l),Object.assign(t,l));for(let i of Object.keys(l)){let n=l[i];e&&!e(l,i,n)?t[i]=n:n?.clone!==void 0&&typeof n.clone=="function"?t[i]=n.clone():t[i]=Vs(n,e)}return t}return l}function oh(l){return new Promise((e,t)=>{setTimeout(e,l)})}function Ao(l,e){if(e&&l&&!e.includes("/")){let t=l.lastIndexOf("/");if(t>=0)return l.substring(0,t+1)+e}return e}var Oo=class{subscribeWrite(e){this.writeCallbacks.push(e)}writeCallbacks=[];constructor(e,t){this._object=e,this._prop=t,this._wrapperProp="__$_NEEDLE_"+t,this.apply()}_applied=!1;_object;_prop;_wrapperProp;apply(){if(this._applied||!this._object)return;let e=this._object,t=this._prop;if(e[t]===void 0)return;this._applied=!0,e[this._wrapperProp]!==void 0&&console.warn("Watcher is being applied to an object that already has a wrapper property. This is not (yet) supported");let i=e[t];e[this._wrapperProp]=i,Object.defineProperty(e,t,{get:()=>e[this._wrapperProp],set:s=>{e[this._wrapperProp]=s;for(let o of this.writeCallbacks)o(s)}})}revoke(){if(!this._applied||!this._object)return;this._applied=!1;let e=this._object,t=this._prop;Reflect.deleteProperty(e,t);let i=e[this._wrapperProp];e[t]=i,Reflect.deleteProperty(e,this._wrapperProp)}dispose(){this.revoke(),this.writeCallbacks.length=0,this._object=null}};var kf=N("debugnewscripts"),be=[];function Ai(l){if(!(l.new_scripts.length<=0)){if(kf&&console.log("Register new components",l.new_scripts.length,l.alias?"element: "+l.alias:""),l.new_scripts_pre_setup_callbacks.length>0){for(let e of l.new_scripts_pre_setup_callbacks)!e||e();l.new_scripts_pre_setup_callbacks.length=0}be.length=0,l.new_scripts.length>0&&be.push(...l.new_scripts),l.new_scripts.length=0;for(let e=0;e<be.length;e++)try{let t=be[e];if(t.destroyed)continue;if(!t.gameObject){console.error("MISSING GAMEOBJECT - will ignore",t),be.splice(e,1),e--;continue}t.context=l,Wn(t.gameObject),xl(t,l)}catch(t){console.error(t),Oi(be[e],l),be.splice(e,1),e--}for(let e=0;e<be.length;e++)try{let t=be[e];if(t.destroyed){Oi(be[e],l),be.splice(e,1),e--;continue}t.__internalAwake!==void 0&&(t.gameObject||console.error("MISSING GAMEOBJECT",t,t.gameObject),Wn(t.gameObject),t.activeAndEnabled&&Vn(t.__internalAwake.bind(t)))}catch(t){console.error(t),Oi(be[e],l),be.splice(e,1),e--}for(let e=0;e<be.length;e++)try{let t=be[e];if(t.destroyed||t.enabled===!1||(Wn(t.gameObject),t.activeAndEnabled===!1))continue;t.__internalEnable!==void 0&&(t.enabled=!0,Vn(t.__internalEnable.bind(t)))}catch(t){console.error(t),Oi(be[e],l),be.splice(e,1),e--}for(let e=0;e<be.length;e++)try{let t=be[e];if(t.destroyed||!t.gameObject)continue;l.new_script_start.push(t)}catch(t){console.error(t),Oi(be[e],l),be.splice(e,1),e--}be.length=0;for(let e of l.new_scripts_post_setup_callbacks)e&&e();l.new_scripts_post_setup_callbacks.length=0}}function lh(l){!l||(l.__internalDisable(),Oi(l,l.context))}function ch(l){for(let e=0;e<l.new_script_start.length;e++)try{let t=l.new_script_start[e];if(t.destroyed||t.activeAndEnabled===!1)continue;Vn(t.__internalAwake.bind(t)),Vn(t.__internalEnable.bind(t)),Vn(t.__internalStart.bind(t)),l.new_script_start.splice(e,1),e--}catch(t){console.error(t),Oi(l.new_script_start[e],l),l.new_script_start.splice(e,1),e--}}function xl(l,e){e.scripts.indexOf(l)===-1&&(e.scripts.push(l),l.earlyUpdate&&e.scripts_earlyUpdate.push(l),l.update&&e.scripts_update.push(l),l.lateUpdate&&e.scripts_lateUpdate.push(l),l.onBeforeRender&&e.scripts_onBeforeRender.push(l),l.onAfterRender&&e.scripts_onAfterRender.push(l))}function Oi(l,e){hn(l,e.new_scripts),hn(l,e.new_script_start),hn(l,e.scripts),hn(l,e.scripts_earlyUpdate),hn(l,e.scripts_update),hn(l,e.scripts_lateUpdate),hn(l,e.scripts_onBeforeRender),hn(l,e.scripts_onAfterRender),e.stopAllCoroutinesFrom(l)}function hn(l,e){let t=e.indexOf(l);t>=0&&e.splice(t,1)}var If={},ah={};function dh(){if(!Z.Current){console.trace("Invalid call - no current context.");return}hh(Z.Current.scene,Z.Current.scene.visible,!0)}function hh(l,e,t){let i=!1,n=O.isActiveSelf(l);if(If[l.uuid]=n,e&&(e=O.isActiveSelf(l)),l[cn]=e,!i){let r=ah[l.uuid];r!==void 0&&r!==e&&t&&Mf(l,s=>{e?(Vn(s.__internalAwake.bind(s)),s.onEnable()):s.onDisable()})}if(ah[l.uuid]=e,l.children)for(let r of l.children)hh(r,e,t)}function Wn(l){let e=!0,t=l,i=!1;for(;t&&t;){if(t.type==="Scene"&&(i=!0),!O.isActiveSelf(t)){e=!1;break}t=t.parent}if(!l){console.error("GO is null");return}l[cn]=e&&i}function Mf(l,e){if(l.userData?.components)for(let t of l.userData.components)e(t)}var Rl=N("debuggetcomponent");function Cl(l,e){if(!l)return;let t=e?.new_scripts??Z.Current.new_scripts;t.includes(l)||t.push(l)}var uh=function(l,e){if(!l||!l.userData.components)return;let t=l.userData.components.indexOf(e);t<0||(e.gameObject=null,l.userData.components.splice(t,1))},ko=function(l,e,t=!0){e.userData||(e.userData={}),e.userData.components||(e.userData.components=[]),e.userData.components.push(l),l.gameObject=e,Cl(l);try{l.__internalAwake&&t&&(Wn(e),l.__internalAwake())}catch(i){console.error(i)}},ph=function(l,e){if(l.gameObject!==e){if(l.gameObject&&l.gameObject.userData.components){let t=l.gameObject.userData.components.indexOf(l);l.gameObject.userData.components.splice(t,1)}if(!e.userData.components)e.userData.components=[];else if(e.userData.components.includes(l))return;e.userData.components.push(l),l.gameObject=e}},fh=function(l){if(l.gameObject&&l.gameObject.userData.components){let e=l.gameObject.userData.components.indexOf(l);l.gameObject.userData.components.splice(e,1)}l.__internalDisable&&l.__internalDisable(),l.onDestroy&&l.onDestroy(),Oi(l,l.context??Z.Current),l.__destroyed=!0,l.gameObject=null},mh=function(l,e,t){if(!e?.userData?.components)return null;Rl&&console.log("FIND",l);for(let i=0;i<e.userData.components.length;i++){let n=e.userData.components[i];if(l===null||n.constructor.name===l.name||n.constructor.name===l)if(Rl&&console.log("MATCH BY NAME",n),t)t.push(n);else return n}for(let i=0;i<e.userData.components.length;i++){let n=e.userData.components[i],r=Object.getPrototypeOf(n.constructor);do{if(r===l)if(Rl&&console.log("MATCH BY PROTOYPE",r),t)t.push(n);else return n;r=Object.getPrototypeOf(r)}while(r)}return t},Io=function(l,e){return mh(l,e,null)},Mo=function(l,e,t){return t||(t=[]),mh(l,e,t)},Lo=function(l,e,t){let i=Io(l,e);if(t===!1&&i.enabled===!1)return null;if(i)return i;for(let n=0;n<e?.children?.length;n++){let r=Lo(l,e.children[n]);if(r)return r}return null},Do=function(l,e,t){t||(t=[]),Mo(l,e,t);for(let i=0;i<e?.children?.length;i++)Do(l,e.children[i],t);return t},Sl=function(l,e){if(!e)return null;let t=Io(l,e);return t||Sl(l,e.parent)},Pl=function(l,e,t){return t||(t=[]),e?(Mo(l,e,t),Pl(l,e.parent,t)):t},gh=function(l,e,t){if(!l)return null;if(!e&&(e=Z.Current,!e))return console.error("Can not search object without any needle context or scene!!!"),null;let i=e.isScene===!0||e.isObject3D===!0?e:e?.scene;for(let n in i.children){let r=i.children[n];if(t===!1&&r[cn]===!1)continue;if(r.constructor==l)return r;let s=Lo(l,r);if(s)return s}return null},bh=function(l,e,t){if(!l)return e;if(!t&&(t=Z.Current,!t))return console.error("Can not search object without any needle context or scene!!!"),e;let i=t.isScene===!0||t.isObject3D===!0?t:t?.scene;if(!i)return e;for(let n in i.children){let r=i.children[n];if(r.constructor==l)return r;Do(l,r,e)}return e};var Ol=class{random(){return Math.random()}clamp(e,t,i){return e<t?t:e>i?i:e}clamp01(e){return this.clamp(e,0,1)}lerp(e,t,i){return i=i<0?0:i,i=i>1?1:i,e+(t-e)*i}moveTowards(e,t,i){return e+=i,(i<0&&e<t||i>0&&e>t)&&(e=t),e}toDegrees(e){return e*180/Math.PI}toRadians(e){return e*Math.PI/180}},Q=new Ol;import*as se from"three";import{Vector3 as Df,Quaternion as Hf,Uniform as jf}from"three";var kl=class{_factory;_cache=[];_maxSize;_index=0;constructor(e,t){this._factory=e,this._maxSize=t}get(){let e=this._index++;return e>=this._cache.length&&(e>=this._maxSize?e=this._index=0:this._cache.push(this._factory())),this._cache[e]}},XE=new Hf().setFromAxisAngle(new Df(0,1,0),Math.PI);var Il=new kl(()=>new se.Vector3,100);se.Vector3.prototype.slerp=function(l,e){let t=this.length(),i=l.length(),n=Q.lerp(t,i,e);return this.lerp(l,e).normalize().multiplyScalar(n)};function q(l,e=null,t=!0){let i=e??Il.get();return l?l.parent?(t&&l.updateWorldMatrix(!0,!1),l.matrixWorldNeedsUpdate&&l.updateMatrixWorld(),i.setFromMatrixPosition(l.matrixWorld),i):i.copy(l.position):i.set(0,0,0)}function ie(l,e){if(!l)return;let t=Il.get();e!==t&&t.copy(e),(l?.parent??l).worldToLocal(t),l.position.set(t.x,t.y,t.z)}function Cr(l,e,t,i){let n=Il.get();n.set(e,t,i),ie(l,n)}var Un=new se.Quaternion,Ws=new se.Quaternion,Al=new se.Quaternion;function ve(l,e=null){if(!l)return Ws.set(0,0,0,1);let t=e??Ws;return l.parent?(l.getWorldQuaternion(t),t):t.copy(l.quaternion)}function Ae(l,e){if(!l)return;e!==Un&&Un.copy(e);let t=Un;l?.parent?.getWorldQuaternion(Al),Al.invert();let n=Al.multiply(t);l.quaternion.set(n.x,n.y,n.z,n.w)}function Eh(l,e,t,i,n){Un.set(e,t,i,n),Ae(l,Un)}var Ho=new se.Vector3,QE=new se.Vector3;function wh(l,e=null){return l?l.parent?(l.getWorldScale(e??Ho),e??Ho):Ho.copy(l.position):Ho.set(0,0,0)}var YE=new se.Vector3,ZE=new se.Quaternion;var vh=new se.Euler,yh=new se.Euler,Bf=new se.Vector3;function Ff(l){return l.getWorldQuaternion(Ws),yh.setFromQuaternion(Ws),yh}function _h(l,e){Ae(l,Ws.setFromEuler(e))}function jo(l){let e=Ff(l),t=Bf;return t.set(e.x,e.y,e.z),t.x=Q.toDegrees(t.x),t.y=Q.toDegrees(t.y),t.z=Q.toDegrees(t.z),t}function Bo(l,e,t,i,n=!0){n&&(e=Q.toRadians(e),t=Q.toRadians(t),i=Q.toRadians(i)),vh.set(e,t,i),Un.setFromEuler(vh),Ae(l,Un)}function Us(l,e=!0){!l||(e?function t(i){console.groupCollapsed((i.name?i.name:"(no name : "+i.type+")")+" %o",i),i.children.forEach(t),console.groupEnd()}(l):l.traverse(function(t){for(var i="|___",n=t;n.parent!==null;)i=" "+i,n=n.parent;console.log(i+t.name+" <"+t.type+">")}))}var JE=new se.PlaneGeometry(2,2,1,1),$E=new se.WebGLRenderer({antialias:!1}),KE=new se.PerspectiveCamera,e0=new se.Scene,t0=new se.ShaderMaterial({uniforms:{blitTexture:new jf(null)},vertexShader:`
78
+ isUnifiedPlanSupported:`+this.isUnifiedPlanSupported()},n}())},{"./adapter":"sXtV"}],BHXf:[function(l,e,t){"use strict";var i=this&&this.__createBinding||(Object.create?function(d,a,h,u){u===void 0&&(u=h),Object.defineProperty(d,u,{enumerable:!0,get:function(){return a[h]}})}:function(d,a,h,u){u===void 0&&(u=h),d[u]=a[h]}),n=this&&this.__setModuleDefault||(Object.create?function(d,a){Object.defineProperty(d,"default",{enumerable:!0,value:a})}:function(d,a){d.default=a}),r=this&&this.__importStar||function(d){if(d&&d.__esModule)return d;var a={};if(d!=null)for(var h in d)h!=="default"&&Object.prototype.hasOwnProperty.call(d,h)&&i(a,d,h);return n(a,d),a};Object.defineProperty(t,"__esModule",{value:!0}),t.util=void 0;var o=r(l("peerjs-js-binarypack")),s=l("./supports"),c={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"turn:0.peerjs.com:3478",username:"peerjs",credential:"peerjsp"}],sdpSemantics:"unified-plan"};t.util=new(function(){function d(){this.CLOUD_HOST="0.peerjs.com",this.CLOUD_PORT=443,this.chunkedBrowsers={Chrome:1,chrome:1},this.chunkedMTU=16300,this.defaultConfig=c,this.browser=s.Supports.getBrowser(),this.browserVersion=s.Supports.getVersion(),this.supports=function(){var a,h={browser:s.Supports.isBrowserSupported(),webRTC:s.Supports.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!h.webRTC)return h;try{a=new RTCPeerConnection(c),h.audioVideo=!0;var u=void 0;try{u=a.createDataChannel("_PEERJSTEST",{ordered:!0}),h.data=!0,h.reliable=!!u.ordered;try{u.binaryType="blob",h.binaryBlob=!s.Supports.isIOS}catch{}}catch{}finally{u&&u.close()}}catch{}finally{a&&a.close()}return h}(),this.pack=o.pack,this.unpack=o.unpack,this._dataCount=1}return d.prototype.noop=function(){},d.prototype.validateId=function(a){return!a||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(a)},d.prototype.chunk=function(a){for(var h=[],u=a.size,f=Math.ceil(u/t.util.chunkedMTU),E=0,b=0;b<u;){var y=Math.min(u,b+t.util.chunkedMTU),g=a.slice(b,y),p={__peerData:this._dataCount,n:E,data:g,total:f};h.push(p),b=y,E++}return this._dataCount++,h},d.prototype.blobToArrayBuffer=function(a,h){var u=new FileReader;return u.onload=function(f){f.target&&h(f.target.result)},u.readAsArrayBuffer(a),u},d.prototype.binaryStringToArrayBuffer=function(a){for(var h=new Uint8Array(a.length),u=0;u<a.length;u++)h[u]=255&a.charCodeAt(u);return h.buffer},d.prototype.randomToken=function(){return Math.random().toString(36).substr(2)},d.prototype.isSecure=function(){return location.protocol==="https:"},d}())},{"peerjs-js-binarypack":"kdPp","./supports":"I31f"}],JJlS:[function(l,e,t){"use strict";var i=Object.prototype.hasOwnProperty,n="~";function r(){}function o(a,h,u){this.fn=a,this.context=h,this.once=u||!1}function s(a,h,u,f,E){if(typeof u!="function")throw new TypeError("The listener must be a function");var b=new o(u,f||a,E),y=n?n+h:h;return a._events[y]?a._events[y].fn?a._events[y]=[a._events[y],b]:a._events[y].push(b):(a._events[y]=b,a._eventsCount++),a}function c(a,h){--a._eventsCount==0?a._events=new r:delete a._events[h]}function d(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1)),d.prototype.eventNames=function(){var a,h,u=[];if(this._eventsCount===0)return u;for(h in a=this._events)i.call(a,h)&&u.push(n?h.slice(1):h);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(a)):u},d.prototype.listeners=function(a){var h=n?n+a:a,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var f=0,E=u.length,b=new Array(E);f<E;f++)b[f]=u[f].fn;return b},d.prototype.listenerCount=function(a){var h=n?n+a:a,u=this._events[h];return u?u.fn?1:u.length:0},d.prototype.emit=function(a,h,u,f,E,b){var y=n?n+a:a;if(!this._events[y])return!1;var g,p,m=this._events[y],v=arguments.length;if(m.fn){switch(m.once&&this.removeListener(a,m.fn,void 0,!0),v){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,h),!0;case 3:return m.fn.call(m.context,h,u),!0;case 4:return m.fn.call(m.context,h,u,f),!0;case 5:return m.fn.call(m.context,h,u,f,E),!0;case 6:return m.fn.call(m.context,h,u,f,E,b),!0}for(p=1,g=new Array(v-1);p<v;p++)g[p-1]=arguments[p];m.fn.apply(m.context,g)}else{var w,x=m.length;for(p=0;p<x;p++)switch(m[p].once&&this.removeListener(a,m[p].fn,void 0,!0),v){case 1:m[p].fn.call(m[p].context);break;case 2:m[p].fn.call(m[p].context,h);break;case 3:m[p].fn.call(m[p].context,h,u);break;case 4:m[p].fn.call(m[p].context,h,u,f);break;default:if(!g)for(w=1,g=new Array(v-1);w<v;w++)g[w-1]=arguments[w];m[p].fn.apply(m[p].context,g)}}return!0},d.prototype.on=function(a,h,u){return s(this,a,h,u,!1)},d.prototype.once=function(a,h,u){return s(this,a,h,u,!0)},d.prototype.removeListener=function(a,h,u,f){var E=n?n+a:a;if(!this._events[E])return this;if(!h)return c(this,E),this;var b=this._events[E];if(b.fn)b.fn!==h||f&&!b.once||u&&b.context!==u||c(this,E);else{for(var y=0,g=[],p=b.length;y<p;y++)(b[y].fn!==h||f&&!b[y].once||u&&b[y].context!==u)&&g.push(b[y]);g.length?this._events[E]=g.length===1?g[0]:g:c(this,E)}return this},d.prototype.removeAllListeners=function(a){var h;return a?(h=n?n+a:a,this._events[h]&&c(this,h)):(this._events=new r,this._eventsCount=0),this},d.prototype.off=d.prototype.removeListener,d.prototype.addListener=d.prototype.on,d.prefixed=n,d.EventEmitter=d,typeof e<"u"&&(e.exports=d)},{}],WOs9:[function(l,e,t){"use strict";var i=this&&this.__read||function(c,d){var a=typeof Symbol=="function"&&c[Symbol.iterator];if(!a)return c;var h,u,f=a.call(c),E=[];try{for(;(d===void 0||d-- >0)&&!(h=f.next()).done;)E.push(h.value)}catch(b){u={error:b}}finally{try{h&&!h.done&&(a=f.return)&&a.call(f)}finally{if(u)throw u.error}}return E},n=this&&this.__spreadArray||function(c,d){for(var a=0,h=d.length,u=c.length;a<h;a++,u++)c[u]=d[a];return c};Object.defineProperty(t,"__esModule",{value:!0}),t.LogLevel=void 0;var r,o="PeerJS: ";(function(c){c[c.Disabled=0]="Disabled",c[c.Errors=1]="Errors",c[c.Warnings=2]="Warnings",c[c.All=3]="All"})(r=t.LogLevel||(t.LogLevel={}));var s=function(){function c(){this._logLevel=r.Disabled}return Object.defineProperty(c.prototype,"logLevel",{get:function(){return this._logLevel},set:function(d){this._logLevel=d},enumerable:!1,configurable:!0}),c.prototype.log=function(){for(var d=[],a=0;a<arguments.length;a++)d[a]=arguments[a];this._logLevel>=r.All&&this._print.apply(this,n([r.All],i(d)))},c.prototype.warn=function(){for(var d=[],a=0;a<arguments.length;a++)d[a]=arguments[a];this._logLevel>=r.Warnings&&this._print.apply(this,n([r.Warnings],i(d)))},c.prototype.error=function(){for(var d=[],a=0;a<arguments.length;a++)d[a]=arguments[a];this._logLevel>=r.Errors&&this._print.apply(this,n([r.Errors],i(d)))},c.prototype.setLogFunction=function(d){this._print=d},c.prototype._print=function(d){for(var a=[],h=1;h<arguments.length;h++)a[h-1]=arguments[h];var u=n([o],i(a));for(var f in u)u[f]instanceof Error&&(u[f]="("+u[f].name+") "+u[f].message);d>=r.All?console.log.apply(console,n([],i(u))):d>=r.Warnings?console.warn.apply(console,n(["WARNING"],i(u))):d>=r.Errors&&console.error.apply(console,n(["ERROR"],i(u)))},c}();t.default=new s},{}],ZRYf:[function(l,e,t){"use strict";var i,n,r,o,s,c,d;Object.defineProperty(t,"__esModule",{value:!0}),t.ServerMessageType=t.SocketEventType=t.SerializationType=t.PeerErrorType=t.PeerEventType=t.ConnectionType=t.ConnectionEventType=void 0,function(a){a.Open="open",a.Stream="stream",a.Data="data",a.Close="close",a.Error="error",a.IceStateChanged="iceStateChanged"}(i=t.ConnectionEventType||(t.ConnectionEventType={})),function(a){a.Data="data",a.Media="media"}(n=t.ConnectionType||(t.ConnectionType={})),function(a){a.Open="open",a.Close="close",a.Connection="connection",a.Call="call",a.Disconnected="disconnected",a.Error="error"}(r=t.PeerEventType||(t.PeerEventType={})),function(a){a.BrowserIncompatible="browser-incompatible",a.Disconnected="disconnected",a.InvalidID="invalid-id",a.InvalidKey="invalid-key",a.Network="network",a.PeerUnavailable="peer-unavailable",a.SslUnavailable="ssl-unavailable",a.ServerError="server-error",a.SocketError="socket-error",a.SocketClosed="socket-closed",a.UnavailableID="unavailable-id",a.WebRTC="webrtc"}(o=t.PeerErrorType||(t.PeerErrorType={})),function(a){a.Binary="binary",a.BinaryUTF8="binary-utf8",a.JSON="json"}(s=t.SerializationType||(t.SerializationType={})),function(a){a.Message="message",a.Disconnected="disconnected",a.Error="error",a.Close="close"}(c=t.SocketEventType||(t.SocketEventType={})),function(a){a.Heartbeat="HEARTBEAT",a.Candidate="CANDIDATE",a.Offer="OFFER",a.Answer="ANSWER",a.Open="OPEN",a.Error="ERROR",a.IdTaken="ID-TAKEN",a.InvalidKey="INVALID-KEY",a.Leave="LEAVE",a.Expire="EXPIRE"}(d=t.ServerMessageType||(t.ServerMessageType={}))},{}],wJlv:[function(l,e,t){"use strict";var i=this&&this.__extends||function(){var u=function(f,E){return(u=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,y){b.__proto__=y}||function(b,y){for(var g in y)Object.prototype.hasOwnProperty.call(y,g)&&(b[g]=y[g])})(f,E)};return function(f,E){if(typeof E!="function"&&E!==null)throw new TypeError("Class extends value "+String(E)+" is not a constructor or null");function b(){this.constructor=f}u(f,E),f.prototype=E===null?Object.create(E):(b.prototype=E.prototype,new b)}}(),n=this&&this.__read||function(u,f){var E=typeof Symbol=="function"&&u[Symbol.iterator];if(!E)return u;var b,y,g=E.call(u),p=[];try{for(;(f===void 0||f-- >0)&&!(b=g.next()).done;)p.push(b.value)}catch(m){y={error:m}}finally{try{b&&!b.done&&(E=g.return)&&E.call(g)}finally{if(y)throw y.error}}return p},r=this&&this.__spreadArray||function(u,f){for(var E=0,b=f.length,y=u.length;E<b;E++,y++)u[y]=f[E];return u},o=this&&this.__values||function(u){var f=typeof Symbol=="function"&&Symbol.iterator,E=f&&u[f],b=0;if(E)return E.call(u);if(u&&typeof u.length=="number")return{next:function(){return u&&b>=u.length&&(u=void 0),{value:u&&u[b++],done:!u}}};throw new TypeError(f?"Object is not iterable.":"Symbol.iterator is not defined.")},s=this&&this.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(t,"__esModule",{value:!0}),t.Socket=void 0;var c=l("eventemitter3"),d=s(l("./logger")),a=l("./enums"),h=function(u){function f(E,b,y,g,p,m){m===void 0&&(m=5e3);var v=u.call(this)||this;v.pingInterval=m,v._disconnected=!0,v._messagesQueue=[];var w=E?"wss://":"ws://";return v._baseUrl=w+b+":"+y+g+"peerjs?key="+p,v}return i(f,u),f.prototype.start=function(E,b){var y=this;this._id=E;var g=this._baseUrl+"&id="+E+"&token="+b;!this._socket&&this._disconnected&&(this._socket=new WebSocket(g),this._disconnected=!1,this._socket.onmessage=function(p){var m;try{m=JSON.parse(p.data),d.default.log("Server message received:",m)}catch{return void d.default.log("Invalid server message",p.data)}y.emit(a.SocketEventType.Message,m)},this._socket.onclose=function(p){y._disconnected||(d.default.log("Socket closed.",p),y._cleanup(),y._disconnected=!0,y.emit(a.SocketEventType.Disconnected))},this._socket.onopen=function(){y._disconnected||(y._sendQueuedMessages(),d.default.log("Socket open"),y._scheduleHeartbeat())})},f.prototype._scheduleHeartbeat=function(){var E=this;this._wsPingTimer=setTimeout(function(){E._sendHeartbeat()},this.pingInterval)},f.prototype._sendHeartbeat=function(){if(this._wsOpen()){var E=JSON.stringify({type:a.ServerMessageType.Heartbeat});this._socket.send(E),this._scheduleHeartbeat()}else d.default.log("Cannot send heartbeat, because socket closed")},f.prototype._wsOpen=function(){return!!this._socket&&this._socket.readyState===1},f.prototype._sendQueuedMessages=function(){var E,b,y=r([],n(this._messagesQueue));this._messagesQueue=[];try{for(var g=o(y),p=g.next();!p.done;p=g.next()){var m=p.value;this.send(m)}}catch(v){E={error:v}}finally{try{p&&!p.done&&(b=g.return)&&b.call(g)}finally{if(E)throw E.error}}},f.prototype.send=function(E){if(!this._disconnected)if(this._id)if(E.type){if(this._wsOpen()){var b=JSON.stringify(E);this._socket.send(b)}}else this.emit(a.SocketEventType.Error,"Invalid message");else this._messagesQueue.push(E)},f.prototype.close=function(){this._disconnected||(this._cleanup(),this._disconnected=!0)},f.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)},f}(c.EventEmitter);t.Socket=h},{eventemitter3:"JJlS","./logger":"WOs9","./enums":"ZRYf"}],HCdX:[function(l,e,t){"use strict";var i=this&&this.__assign||function(){return(i=Object.assign||function(h){for(var u,f=1,E=arguments.length;f<E;f++)for(var b in u=arguments[f])Object.prototype.hasOwnProperty.call(u,b)&&(h[b]=u[b]);return h}).apply(this,arguments)},n=this&&this.__awaiter||function(h,u,f,E){return new(f||(f=Promise))(function(b,y){function g(v){try{m(E.next(v))}catch(w){y(w)}}function p(v){try{m(E.throw(v))}catch(w){y(w)}}function m(v){var w;v.done?b(v.value):(w=v.value,w instanceof f?w:new f(function(x){x(w)})).then(g,p)}m((E=E.apply(h,u||[])).next())})},r=this&&this.__generator||function(h,u){var f,E,b,y,g={label:0,sent:function(){if(1&b[0])throw b[1];return b[1]},trys:[],ops:[]};return y={next:p(0),throw:p(1),return:p(2)},typeof Symbol=="function"&&(y[Symbol.iterator]=function(){return this}),y;function p(m){return function(v){return function(w){if(f)throw new TypeError("Generator is already executing.");for(;g;)try{if(f=1,E&&(b=2&w[0]?E.return:w[0]?E.throw||((b=E.return)&&b.call(E),0):E.next)&&!(b=b.call(E,w[1])).done)return b;switch(E=0,b&&(w=[2&w[0],b.value]),w[0]){case 0:case 1:b=w;break;case 4:return g.label++,{value:w[1],done:!1};case 5:g.label++,E=w[1],w=[0];continue;case 7:w=g.ops.pop(),g.trys.pop();continue;default:if(!(b=(b=g.trys).length>0&&b[b.length-1])&&(w[0]===6||w[0]===2)){g=0;continue}if(w[0]===3&&(!b||w[1]>b[0]&&w[1]<b[3])){g.label=w[1];break}if(w[0]===6&&g.label<b[1]){g.label=b[1],b=w;break}if(b&&g.label<b[2]){g.label=b[2],g.ops.push(w);break}b[2]&&g.ops.pop(),g.trys.pop();continue}w=u.call(h,g)}catch(x){w=[6,x],E=0}finally{f=b=0}if(5&w[0])throw w[1];return{value:w[0]?w[1]:void 0,done:!0}}([m,v])}}},o=this&&this.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(t,"__esModule",{value:!0}),t.Negotiator=void 0;var s=l("./util"),c=o(l("./logger")),d=l("./enums"),a=function(){function h(u){this.connection=u}return h.prototype.startConnection=function(u){var f=this._startPeerConnection();if(this.connection.peerConnection=f,this.connection.type===d.ConnectionType.Media&&u._stream&&this._addTracksToConnection(u._stream,f),u.originator){if(this.connection.type===d.ConnectionType.Data){var E=this.connection,b={ordered:!!u.reliable},y=f.createDataChannel(E.label,b);E.initialize(y)}this._makeOffer()}else this.handleSDP("OFFER",u.sdp)},h.prototype._startPeerConnection=function(){c.default.log("Creating RTCPeerConnection.");var u=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(u),u},h.prototype._setupListeners=function(u){var f=this,E=this.connection.peer,b=this.connection.connectionId,y=this.connection.type,g=this.connection.provider;c.default.log("Listening for ICE candidates."),u.onicecandidate=function(p){p.candidate&&p.candidate.candidate&&(c.default.log("Received ICE candidates for "+E+":",p.candidate),g.socket.send({type:d.ServerMessageType.Candidate,payload:{candidate:p.candidate,type:y,connectionId:b},dst:E}))},u.oniceconnectionstatechange=function(){switch(u.iceConnectionState){case"failed":c.default.log("iceConnectionState is failed, closing connections to "+E),f.connection.emit(d.ConnectionEventType.Error,new Error("Negotiation of connection to "+E+" failed.")),f.connection.close();break;case"closed":c.default.log("iceConnectionState is closed, closing connections to "+E),f.connection.emit(d.ConnectionEventType.Error,new Error("Connection to "+E+" closed.")),f.connection.close();break;case"disconnected":c.default.log("iceConnectionState changed to disconnected on the connection with "+E);break;case"completed":u.onicecandidate=s.util.noop}f.connection.emit(d.ConnectionEventType.IceStateChanged,u.iceConnectionState)},c.default.log("Listening for data channel"),u.ondatachannel=function(p){c.default.log("Received data channel");var m=p.channel;g.getConnection(E,b).initialize(m)},c.default.log("Listening for remote stream"),u.ontrack=function(p){c.default.log("Received remote stream");var m=p.streams[0],v=g.getConnection(E,b);if(v.type===d.ConnectionType.Media){var w=v;f._addStreamToMediaConnection(m,w)}}},h.prototype.cleanup=function(){c.default.log("Cleaning up PeerConnection to "+this.connection.peer);var u=this.connection.peerConnection;if(u){this.connection.peerConnection=null,u.onicecandidate=u.oniceconnectionstatechange=u.ondatachannel=u.ontrack=function(){};var f=u.signalingState!=="closed",E=!1;if(this.connection.type===d.ConnectionType.Data){var b=this.connection.dataChannel;b&&(E=!!b.readyState&&b.readyState!=="closed")}(f||E)&&u.close()}},h.prototype._makeOffer=function(){return n(this,void 0,Promise,function(){var u,f,E,b,y,g,p;return r(this,function(m){switch(m.label){case 0:u=this.connection.peerConnection,f=this.connection.provider,m.label=1;case 1:return m.trys.push([1,7,,8]),[4,u.createOffer(this.connection.options.constraints)];case 2:E=m.sent(),c.default.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(E.sdp=this.connection.options.sdpTransform(E.sdp)||E.sdp),m.label=3;case 3:return m.trys.push([3,5,,6]),[4,u.setLocalDescription(E)];case 4:return m.sent(),c.default.log("Set localDescription:",E,"for:"+this.connection.peer),b={sdp:E,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata,browser:s.util.browser},this.connection.type===d.ConnectionType.Data&&(y=this.connection,b=i(i({},b),{label:y.label,reliable:y.reliable,serialization:y.serialization})),f.socket.send({type:d.ServerMessageType.Offer,payload:b,dst:this.connection.peer}),[3,6];case 5:return(g=m.sent())!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(f.emitError(d.PeerErrorType.WebRTC,g),c.default.log("Failed to setLocalDescription, ",g)),[3,6];case 6:return[3,8];case 7:return p=m.sent(),f.emitError(d.PeerErrorType.WebRTC,p),c.default.log("Failed to createOffer, ",p),[3,8];case 8:return[2]}})})},h.prototype._makeAnswer=function(){return n(this,void 0,Promise,function(){var u,f,E,b,y;return r(this,function(g){switch(g.label){case 0:u=this.connection.peerConnection,f=this.connection.provider,g.label=1;case 1:return g.trys.push([1,7,,8]),[4,u.createAnswer()];case 2:E=g.sent(),c.default.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(E.sdp=this.connection.options.sdpTransform(E.sdp)||E.sdp),g.label=3;case 3:return g.trys.push([3,5,,6]),[4,u.setLocalDescription(E)];case 4:return g.sent(),c.default.log("Set localDescription:",E,"for:"+this.connection.peer),f.socket.send({type:d.ServerMessageType.Answer,payload:{sdp:E,type:this.connection.type,connectionId:this.connection.connectionId,browser:s.util.browser},dst:this.connection.peer}),[3,6];case 5:return b=g.sent(),f.emitError(d.PeerErrorType.WebRTC,b),c.default.log("Failed to setLocalDescription, ",b),[3,6];case 6:return[3,8];case 7:return y=g.sent(),f.emitError(d.PeerErrorType.WebRTC,y),c.default.log("Failed to create answer, ",y),[3,8];case 8:return[2]}})})},h.prototype.handleSDP=function(u,f){return n(this,void 0,Promise,function(){var E,b,y,g;return r(this,function(p){switch(p.label){case 0:f=new RTCSessionDescription(f),E=this.connection.peerConnection,b=this.connection.provider,c.default.log("Setting remote description",f),y=this,p.label=1;case 1:return p.trys.push([1,5,,6]),[4,E.setRemoteDescription(f)];case 2:return p.sent(),c.default.log("Set remoteDescription:"+u+" for:"+this.connection.peer),u!=="OFFER"?[3,4]:[4,y._makeAnswer()];case 3:p.sent(),p.label=4;case 4:return[3,6];case 5:return g=p.sent(),b.emitError(d.PeerErrorType.WebRTC,g),c.default.log("Failed to setRemoteDescription, ",g),[3,6];case 6:return[2]}})})},h.prototype.handleCandidate=function(u){return n(this,void 0,Promise,function(){var f,E,b,y,g,p;return r(this,function(m){switch(m.label){case 0:c.default.log("handleCandidate:",u),f=u.candidate,E=u.sdpMLineIndex,b=u.sdpMid,y=this.connection.peerConnection,g=this.connection.provider,m.label=1;case 1:return m.trys.push([1,3,,4]),[4,y.addIceCandidate(new RTCIceCandidate({sdpMid:b,sdpMLineIndex:E,candidate:f}))];case 2:return m.sent(),c.default.log("Added ICE candidate for:"+this.connection.peer),[3,4];case 3:return p=m.sent(),g.emitError(d.PeerErrorType.WebRTC,p),c.default.log("Failed to handleCandidate, ",p),[3,4];case 4:return[2]}})})},h.prototype._addTracksToConnection=function(u,f){if(c.default.log("add tracks from stream "+u.id+" to peer connection"),!f.addTrack)return c.default.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");u.getTracks().forEach(function(E){f.addTrack(E,u)})},h.prototype._addStreamToMediaConnection=function(u,f){c.default.log("add stream "+u.id+" to media connection "+f.connectionId),f.addStream(u)},h}();t.Negotiator=a},{"./util":"BHXf","./logger":"WOs9","./enums":"ZRYf"}],tQFK:[function(l,e,t){"use strict";var i=this&&this.__extends||function(){var o=function(s,c){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,a){d.__proto__=a}||function(d,a){for(var h in a)Object.prototype.hasOwnProperty.call(a,h)&&(d[h]=a[h])})(s,c)};return function(s,c){if(typeof c!="function"&&c!==null)throw new TypeError("Class extends value "+String(c)+" is not a constructor or null");function d(){this.constructor=s}o(s,c),s.prototype=c===null?Object.create(c):(d.prototype=c.prototype,new d)}}();Object.defineProperty(t,"__esModule",{value:!0}),t.BaseConnection=void 0;var n=l("eventemitter3"),r=function(o){function s(c,d,a){var h=o.call(this)||this;return h.peer=c,h.provider=d,h.options=a,h._open=!1,h.metadata=a.metadata,h}return i(s,o),Object.defineProperty(s.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),s}(n.EventEmitter);t.BaseConnection=r},{eventemitter3:"JJlS"}],dbHP:[function(l,e,t){"use strict";var i=this&&this.__extends||function(){var f=function(E,b){return(f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(y,g){y.__proto__=g}||function(y,g){for(var p in g)Object.prototype.hasOwnProperty.call(g,p)&&(y[p]=g[p])})(E,b)};return function(E,b){if(typeof b!="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");function y(){this.constructor=E}f(E,b),E.prototype=b===null?Object.create(b):(y.prototype=b.prototype,new y)}}(),n=this&&this.__assign||function(){return(n=Object.assign||function(f){for(var E,b=1,y=arguments.length;b<y;b++)for(var g in E=arguments[b])Object.prototype.hasOwnProperty.call(E,g)&&(f[g]=E[g]);return f}).apply(this,arguments)},r=this&&this.__values||function(f){var E=typeof Symbol=="function"&&Symbol.iterator,b=E&&f[E],y=0;if(b)return b.call(f);if(f&&typeof f.length=="number")return{next:function(){return f&&y>=f.length&&(f=void 0),{value:f&&f[y++],done:!f}}};throw new TypeError(E?"Object is not iterable.":"Symbol.iterator is not defined.")},o=this&&this.__importDefault||function(f){return f&&f.__esModule?f:{default:f}};Object.defineProperty(t,"__esModule",{value:!0}),t.MediaConnection=void 0;var s=l("./util"),c=o(l("./logger")),d=l("./negotiator"),a=l("./enums"),h=l("./baseconnection"),u=function(f){function E(b,y,g){var p=f.call(this,b,y,g)||this;return p._localStream=p.options._stream,p.connectionId=p.options.connectionId||E.ID_PREFIX+s.util.randomToken(),p._negotiator=new d.Negotiator(p),p._localStream&&p._negotiator.startConnection({_stream:p._localStream,originator:!0}),p}return i(E,f),Object.defineProperty(E.prototype,"type",{get:function(){return a.ConnectionType.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(b){c.default.log("Receiving stream",b),this._remoteStream=b,f.prototype.emit.call(this,a.ConnectionEventType.Stream,b)},E.prototype.handleMessage=function(b){var y=b.type,g=b.payload;switch(b.type){case a.ServerMessageType.Answer:this._negotiator.handleSDP(y,g.sdp),this._open=!0;break;case a.ServerMessageType.Candidate:this._negotiator.handleCandidate(g.candidate);break;default:c.default.warn("Unrecognized message type:"+y+" from peer:"+this.peer)}},E.prototype.answer=function(b,y){var g,p;if(y===void 0&&(y={}),this._localStream)c.default.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");else{this._localStream=b,y&&y.sdpTransform&&(this.options.sdpTransform=y.sdpTransform),this._negotiator.startConnection(n(n({},this.options._payload),{_stream:b}));var m=this.provider._getMessages(this.connectionId);try{for(var v=r(m),w=v.next();!w.done;w=v.next()){var x=w.value;this.handleMessage(x)}}catch(T){g={error:T}}finally{try{w&&!w.done&&(p=v.return)&&p.call(v)}finally{if(g)throw g.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,f.prototype.emit.call(this,a.ConnectionEventType.Close))},E.ID_PREFIX="mc_",E}(h.BaseConnection);t.MediaConnection=u},{"./util":"BHXf","./logger":"WOs9","./negotiator":"HCdX","./enums":"ZRYf","./baseconnection":"tQFK"}],GGp6:[function(l,e,t){"use strict";var i=this&&this.__extends||function(){var c=function(d,a){return(c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(h,u){h.__proto__=u}||function(h,u){for(var f in u)Object.prototype.hasOwnProperty.call(u,f)&&(h[f]=u[f])})(d,a)};return function(d,a){if(typeof a!="function"&&a!==null)throw new TypeError("Class extends value "+String(a)+" is not a constructor or null");function h(){this.constructor=d}c(d,a),d.prototype=a===null?Object.create(a):(h.prototype=a.prototype,new h)}}(),n=this&&this.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(t,"__esModule",{value:!0}),t.EncodingQueue=void 0;var r=l("eventemitter3"),o=n(l("./logger")),s=function(c){function d(){var a=c.call(this)||this;return a.fileReader=new FileReader,a._queue=[],a._processing=!1,a.fileReader.onload=function(h){a._processing=!1,h.target&&a.emit("done",h.target.result),a.doNextTask()},a.fileReader.onerror=function(h){o.default.error("EncodingQueue error:",h),a._processing=!1,a.destroy(),a.emit("error",h)},a}return i(d,c),Object.defineProperty(d.prototype,"queue",{get:function(){return this._queue},enumerable:!1,configurable:!0}),Object.defineProperty(d.prototype,"size",{get:function(){return this.queue.length},enumerable:!1,configurable:!0}),Object.defineProperty(d.prototype,"processing",{get:function(){return this._processing},enumerable:!1,configurable:!0}),d.prototype.enque=function(a){this.queue.push(a),this.processing||this.doNextTask()},d.prototype.destroy=function(){this.fileReader.abort(),this._queue=[]},d.prototype.doNextTask=function(){this.size!==0&&(this.processing||(this._processing=!0,this.fileReader.readAsArrayBuffer(this.queue.shift())))},d}(r.EventEmitter);t.EncodingQueue=s},{eventemitter3:"JJlS","./logger":"WOs9"}],GBTQ:[function(l,e,t){"use strict";var i=this&&this.__extends||function(){var f=function(E,b){return(f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(y,g){y.__proto__=g}||function(y,g){for(var p in g)Object.prototype.hasOwnProperty.call(g,p)&&(y[p]=g[p])})(E,b)};return function(E,b){if(typeof b!="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");function y(){this.constructor=E}f(E,b),E.prototype=b===null?Object.create(b):(y.prototype=b.prototype,new y)}}(),n=this&&this.__values||function(f){var E=typeof Symbol=="function"&&Symbol.iterator,b=E&&f[E],y=0;if(b)return b.call(f);if(f&&typeof f.length=="number")return{next:function(){return f&&y>=f.length&&(f=void 0),{value:f&&f[y++],done:!f}}};throw new TypeError(E?"Object is not iterable.":"Symbol.iterator is not defined.")},r=this&&this.__importDefault||function(f){return f&&f.__esModule?f:{default:f}};Object.defineProperty(t,"__esModule",{value:!0}),t.DataConnection=void 0;var o=l("./util"),s=r(l("./logger")),c=l("./negotiator"),d=l("./enums"),a=l("./baseconnection"),h=l("./encodingQueue"),u=function(f){function E(b,y,g){var p=f.call(this,b,y,g)||this;return p.stringify=JSON.stringify,p.parse=JSON.parse,p._buffer=[],p._bufferSize=0,p._buffering=!1,p._chunkedData={},p._encodingQueue=new h.EncodingQueue,p.connectionId=p.options.connectionId||E.ID_PREFIX+o.util.randomToken(),p.label=p.options.label||p.connectionId,p.serialization=p.options.serialization||d.SerializationType.Binary,p.reliable=!!p.options.reliable,p._encodingQueue.on("done",function(m){p._bufferedSend(m)}),p._encodingQueue.on("error",function(){s.default.error("DC#"+p.connectionId+": Error occured in encoding from blob to arraybuffer, close DC"),p.close()}),p._negotiator=new c.Negotiator(p),p._negotiator.startConnection(p.options._payload||{originator:!0}),p}return i(E,f),Object.defineProperty(E.prototype,"type",{get:function(){return d.ConnectionType.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(b){this._dc=b,this._configureDataChannel()},E.prototype._configureDataChannel=function(){var b=this;o.util.supports.binaryBlob&&!o.util.supports.reliable||(this.dataChannel.binaryType="arraybuffer"),this.dataChannel.onopen=function(){s.default.log("DC#"+b.connectionId+" dc connection success"),b._open=!0,b.emit(d.ConnectionEventType.Open)},this.dataChannel.onmessage=function(y){s.default.log("DC#"+b.connectionId+" dc onmessage:",y.data),b._handleDataMessage(y)},this.dataChannel.onclose=function(){s.default.log("DC#"+b.connectionId+" dc closed for:",b.peer),b.close()}},E.prototype._handleDataMessage=function(b){var y=this,g=b.data,p=g.constructor,m=g;if(this.serialization===d.SerializationType.Binary||this.serialization===d.SerializationType.BinaryUTF8){if(p===Blob)return void o.util.blobToArrayBuffer(g,function(w){var x=o.util.unpack(w);y.emit(d.ConnectionEventType.Data,x)});if(p===ArrayBuffer)m=o.util.unpack(g);else if(p===String){var v=o.util.binaryStringToArrayBuffer(g);m=o.util.unpack(v)}}else this.serialization===d.SerializationType.JSON&&(m=this.parse(g));m.__peerData?this._handleChunk(m):f.prototype.emit.call(this,d.ConnectionEventType.Data,m)},E.prototype._handleChunk=function(b){var y=b.__peerData,g=this._chunkedData[y]||{data:[],count:0,total:b.total};if(g.data[b.n]=b.data,g.count++,this._chunkedData[y]=g,g.total===g.count){delete this._chunkedData[y];var p=new Blob(g.data);this._handleDataMessage({data:p})}},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,f.prototype.emit.call(this,d.ConnectionEventType.Close))},E.prototype.send=function(b,y){if(this.open)if(this.serialization===d.SerializationType.JSON)this._bufferedSend(this.stringify(b));else if(this.serialization===d.SerializationType.Binary||this.serialization===d.SerializationType.BinaryUTF8){var g=o.util.pack(b);if(!y&&g.size>o.util.chunkedMTU)return void this._sendChunks(g);o.util.supports.binaryBlob?this._bufferedSend(g):this._encodingQueue.enque(g)}else this._bufferedSend(b);else f.prototype.emit.call(this,d.ConnectionEventType.Error,new Error("Connection is not open. You should listen for the `open` event before sending messages."))},E.prototype._bufferedSend=function(b){!this._buffering&&this._trySend(b)||(this._buffer.push(b),this._bufferSize=this._buffer.length)},E.prototype._trySend=function(b){var y=this;if(!this.open)return!1;if(this.dataChannel.bufferedAmount>E.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(function(){y._buffering=!1,y._tryBuffer()},50),!1;try{this.dataChannel.send(b)}catch(g){return s.default.error("DC#:"+this.connectionId+" Error when sending:",g),this._buffering=!0,this.close(),!1}return!0},E.prototype._tryBuffer=function(){if(this.open&&this._buffer.length!==0){var b=this._buffer[0];this._trySend(b)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}},E.prototype._sendChunks=function(b){var y,g,p=o.util.chunk(b);s.default.log("DC#"+this.connectionId+" Try to send "+p.length+" chunks...");try{for(var m=n(p),v=m.next();!v.done;v=m.next()){var w=v.value;this.send(w,!0)}}catch(x){y={error:x}}finally{try{v&&!v.done&&(g=m.return)&&g.call(m)}finally{if(y)throw y.error}}},E.prototype.handleMessage=function(b){var y=b.payload;switch(b.type){case d.ServerMessageType.Answer:this._negotiator.handleSDP(b.type,y.sdp);break;case d.ServerMessageType.Candidate:this._negotiator.handleCandidate(y.candidate);break;default:s.default.warn("Unrecognized message type:",b.type,"from peer:",this.peer)}},E.ID_PREFIX="dc_",E.MAX_BUFFERED_AMOUNT=8388608,E}(a.BaseConnection);t.DataConnection=u},{"./util":"BHXf","./logger":"WOs9","./negotiator":"HCdX","./enums":"ZRYf","./baseconnection":"tQFK","./encodingQueue":"GGp6"}],in7L:[function(l,e,t){"use strict";var i=this&&this.__awaiter||function(d,a,h,u){return new(h||(h=Promise))(function(f,E){function b(p){try{g(u.next(p))}catch(m){E(m)}}function y(p){try{g(u.throw(p))}catch(m){E(m)}}function g(p){var m;p.done?f(p.value):(m=p.value,m instanceof h?m:new h(function(v){v(m)})).then(b,y)}g((u=u.apply(d,a||[])).next())})},n=this&&this.__generator||function(d,a){var h,u,f,E,b={label:0,sent:function(){if(1&f[0])throw f[1];return f[1]},trys:[],ops:[]};return E={next:y(0),throw:y(1),return:y(2)},typeof Symbol=="function"&&(E[Symbol.iterator]=function(){return this}),E;function y(g){return function(p){return function(m){if(h)throw new TypeError("Generator is already executing.");for(;b;)try{if(h=1,u&&(f=2&m[0]?u.return:m[0]?u.throw||((f=u.return)&&f.call(u),0):u.next)&&!(f=f.call(u,m[1])).done)return f;switch(u=0,f&&(m=[2&m[0],f.value]),m[0]){case 0:case 1:f=m;break;case 4:return b.label++,{value:m[1],done:!1};case 5:b.label++,u=m[1],m=[0];continue;case 7:m=b.ops.pop(),b.trys.pop();continue;default:if(!(f=(f=b.trys).length>0&&f[f.length-1])&&(m[0]===6||m[0]===2)){b=0;continue}if(m[0]===3&&(!f||m[1]>f[0]&&m[1]<f[3])){b.label=m[1];break}if(m[0]===6&&b.label<f[1]){b.label=f[1],f=m;break}if(f&&b.label<f[2]){b.label=f[2],b.ops.push(m);break}f[2]&&b.ops.pop(),b.trys.pop();continue}m=a.call(d,b)}catch(v){m=[6,v],u=0}finally{h=f=0}if(5&m[0])throw m[1];return{value:m[0]?m[1]:void 0,done:!0}}([g,p])}}},r=this&&this.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(t,"__esModule",{value:!0}),t.API=void 0;var o=l("./util"),s=r(l("./logger")),c=function(){function d(a){this._options=a}return d.prototype._buildUrl=function(a){var h=(this._options.secure?"https://":"http://")+this._options.host+":"+this._options.port+this._options.path+this._options.key+"/"+a;return h+="?ts="+new Date().getTime()+Math.random()},d.prototype.retrieveId=function(){return i(this,void 0,Promise,function(){var a,h,u,f;return n(this,function(E){switch(E.label){case 0:a=this._buildUrl("id"),E.label=1;case 1:return E.trys.push([1,3,,4]),[4,fetch(a)];case 2:if((h=E.sent()).status!==200)throw new Error("Error. Status:"+h.status);return[2,h.text()];case 3:throw u=E.sent(),s.default.error("Error retrieving ID",u),f="",this._options.path==="/"&&this._options.host!==o.util.CLOUD_HOST&&(f=" 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."+f);case 4:return[2]}})})},d.prototype.listAllPeers=function(){return i(this,void 0,Promise,function(){var a,h,u,f;return n(this,function(E){switch(E.label){case 0:a=this._buildUrl("peers"),E.label=1;case 1:return E.trys.push([1,3,,4]),[4,fetch(a)];case 2:if((h=E.sent()).status!==200)throw h.status===401?(u="",u=this._options.host===o.util.CLOUD_HOST?"It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":"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. "+u)):new Error("Error. Status:"+h.status);return[2,h.json()];case 3:throw f=E.sent(),s.default.error("Error retrieving list peers",f),new Error("Could not get list peers from the server."+f);case 4:return[2]}})})},d}();t.API=c},{"./util":"BHXf","./logger":"WOs9"}],Hxpd:[function(l,e,t){"use strict";var i=this&&this.__extends||function(){var p=function(m,v){return(p=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(w,x){w.__proto__=x}||function(w,x){for(var T in x)Object.prototype.hasOwnProperty.call(x,T)&&(w[T]=x[T])})(m,v)};return function(m,v){if(typeof v!="function"&&v!==null)throw new TypeError("Class extends value "+String(v)+" is not a constructor or null");function w(){this.constructor=m}p(m,v),m.prototype=v===null?Object.create(v):(w.prototype=v.prototype,new w)}}(),n=this&&this.__assign||function(){return(n=Object.assign||function(p){for(var m,v=1,w=arguments.length;v<w;v++)for(var x in m=arguments[v])Object.prototype.hasOwnProperty.call(m,x)&&(p[x]=m[x]);return p}).apply(this,arguments)},r=this&&this.__values||function(p){var m=typeof Symbol=="function"&&Symbol.iterator,v=m&&p[m],w=0;if(v)return v.call(p);if(p&&typeof p.length=="number")return{next:function(){return p&&w>=p.length&&(p=void 0),{value:p&&p[w++],done:!p}}};throw new TypeError(m?"Object is not iterable.":"Symbol.iterator is not defined.")},o=this&&this.__read||function(p,m){var v=typeof Symbol=="function"&&p[Symbol.iterator];if(!v)return p;var w,x,T=v.call(p),R=[];try{for(;(m===void 0||m-- >0)&&!(w=T.next()).done;)R.push(w.value)}catch(C){x={error:C}}finally{try{w&&!w.done&&(v=T.return)&&v.call(T)}finally{if(x)throw x.error}}return R},s=this&&this.__importDefault||function(p){return p&&p.__esModule?p:{default:p}};Object.defineProperty(t,"__esModule",{value:!0}),t.Peer=void 0;var c=l("eventemitter3"),d=l("./util"),a=s(l("./logger")),h=l("./socket"),u=l("./mediaconnection"),f=l("./dataconnection"),E=l("./enums"),b=l("./api"),y=function(){return function(){}}(),g=function(p){function m(v,w){var x,T=p.call(this)||this;return T._id=null,T._lastServerId=null,T._destroyed=!1,T._disconnected=!1,T._open=!1,T._connections=new Map,T._lostMessages=new Map,v&&v.constructor==Object?w=v:v&&(x=v.toString()),w=n({debug:0,host:d.util.CLOUD_HOST,port:d.util.CLOUD_PORT,path:"/",key:m.DEFAULT_KEY,token:d.util.randomToken(),config:d.util.defaultConfig},w),T._options=w,T._options.host==="/"&&(T._options.host=window.location.hostname),T._options.path&&(T._options.path[0]!=="/"&&(T._options.path="/"+T._options.path),T._options.path[T._options.path.length-1]!=="/"&&(T._options.path+="/")),T._options.secure===void 0&&T._options.host!==d.util.CLOUD_HOST?T._options.secure=d.util.isSecure():T._options.host==d.util.CLOUD_HOST&&(T._options.secure=!0),T._options.logFunction&&a.default.setLogFunction(T._options.logFunction),a.default.logLevel=T._options.debug||0,T._api=new b.API(w),T._socket=T._createServerConnection(),d.util.supports.audioVideo||d.util.supports.data?x&&!d.util.validateId(x)?(T._delayedAbort(E.PeerErrorType.InvalidID,'ID "'+x+'" is invalid'),T):(x?T._initialize(x):T._api.retrieveId().then(function(R){return T._initialize(R)}).catch(function(R){return T._abort(E.PeerErrorType.ServerError,R)}),T):(T._delayedAbort(E.PeerErrorType.BrowserIncompatible,"The current browser does not support WebRTC"),T)}return i(m,p),Object.defineProperty(m.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(m.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),Object.defineProperty(m.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),Object.defineProperty(m.prototype,"socket",{get:function(){return this._socket},enumerable:!1,configurable:!0}),Object.defineProperty(m.prototype,"connections",{get:function(){var v,w,x=Object.create(null);try{for(var T=r(this._connections),R=T.next();!R.done;R=T.next()){var C=o(R.value,2),P=C[0],S=C[1];x[P]=S}}catch(L){v={error:L}}finally{try{R&&!R.done&&(w=T.return)&&w.call(T)}finally{if(v)throw v.error}}return x},enumerable:!1,configurable:!0}),Object.defineProperty(m.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!1,configurable:!0}),Object.defineProperty(m.prototype,"disconnected",{get:function(){return this._disconnected},enumerable:!1,configurable:!0}),m.prototype._createServerConnection=function(){var v=this,w=new h.Socket(this._options.secure,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval);return w.on(E.SocketEventType.Message,function(x){v._handleMessage(x)}),w.on(E.SocketEventType.Error,function(x){v._abort(E.PeerErrorType.SocketError,x)}),w.on(E.SocketEventType.Disconnected,function(){v.disconnected||(v.emitError(E.PeerErrorType.Network,"Lost connection to server."),v.disconnect())}),w.on(E.SocketEventType.Close,function(){v.disconnected||v._abort(E.PeerErrorType.SocketClosed,"Underlying socket is already closed.")}),w},m.prototype._initialize=function(v){this._id=v,this.socket.start(v,this._options.token)},m.prototype._handleMessage=function(v){var w,x,T=v.type,R=v.payload,C=v.src;switch(T){case E.ServerMessageType.Open:this._lastServerId=this.id,this._open=!0,this.emit(E.PeerEventType.Open,this.id);break;case E.ServerMessageType.Error:this._abort(E.PeerErrorType.ServerError,R.msg);break;case E.ServerMessageType.IdTaken:this._abort(E.PeerErrorType.UnavailableID,'ID "'+this.id+'" is taken');break;case E.ServerMessageType.InvalidKey:this._abort(E.PeerErrorType.InvalidKey,'API KEY "'+this._options.key+'" is invalid');break;case E.ServerMessageType.Leave:a.default.log("Received leave message from "+C),this._cleanupPeer(C),this._connections.delete(C);break;case E.ServerMessageType.Expire:this.emitError(E.PeerErrorType.PeerUnavailable,"Could not connect to peer "+C);break;case E.ServerMessageType.Offer:var P=R.connectionId;if((H=this.getConnection(C,P))&&(H.close(),a.default.warn("Offer received for existing Connection ID:"+P)),R.type===E.ConnectionType.Media)H=new u.MediaConnection(C,this,{connectionId:P,_payload:R,metadata:R.metadata}),this._addConnection(C,H),this.emit(E.PeerEventType.Call,H);else{if(R.type!==E.ConnectionType.Data)return void a.default.warn("Received malformed connection type:"+R.type);H=new f.DataConnection(C,this,{connectionId:P,_payload:R,metadata:R.metadata,label:R.label,serialization:R.serialization,reliable:R.reliable}),this._addConnection(C,H),this.emit(E.PeerEventType.Connection,H)}var S=this._getMessages(P);try{for(var L=r(S),I=L.next();!I.done;I=L.next()){var j=I.value;H.handleMessage(j)}}catch(F){w={error:F}}finally{try{I&&!I.done&&(x=L.return)&&x.call(L)}finally{if(w)throw w.error}}break;default:if(!R)return void a.default.warn("You received a malformed message from "+C+" of type "+T);var H;P=R.connectionId,(H=this.getConnection(C,P))&&H.peerConnection?H.handleMessage(v):P?this._storeMessage(P,v):a.default.warn("You received an unrecognized message:",v)}},m.prototype._storeMessage=function(v,w){this._lostMessages.has(v)||this._lostMessages.set(v,[]),this._lostMessages.get(v).push(w)},m.prototype._getMessages=function(v){var w=this._lostMessages.get(v);return w?(this._lostMessages.delete(v),w):[]},m.prototype.connect=function(v,w){if(w===void 0&&(w={}),this.disconnected)return a.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."),void this.emitError(E.PeerErrorType.Disconnected,"Cannot connect to new Peer after disconnecting from server.");var x=new f.DataConnection(v,this,w);return this._addConnection(v,x),x},m.prototype.call=function(v,w,x){if(x===void 0&&(x={}),this.disconnected)return a.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."),void this.emitError(E.PeerErrorType.Disconnected,"Cannot connect to new Peer after disconnecting from server.");if(w){x._stream=w;var T=new u.MediaConnection(v,this,x);return this._addConnection(v,T),T}a.default.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.")},m.prototype._addConnection=function(v,w){a.default.log("add connection "+w.type+":"+w.connectionId+" to peerId:"+v),this._connections.has(v)||this._connections.set(v,[]),this._connections.get(v).push(w)},m.prototype._removeConnection=function(v){var w=this._connections.get(v.peer);if(w){var x=w.indexOf(v);x!==-1&&w.splice(x,1)}this._lostMessages.delete(v.connectionId)},m.prototype.getConnection=function(v,w){var x,T,R=this._connections.get(v);if(!R)return null;try{for(var C=r(R),P=C.next();!P.done;P=C.next()){var S=P.value;if(S.connectionId===w)return S}}catch(L){x={error:L}}finally{try{P&&!P.done&&(T=C.return)&&T.call(C)}finally{if(x)throw x.error}}return null},m.prototype._delayedAbort=function(v,w){var x=this;setTimeout(function(){x._abort(v,w)},0)},m.prototype._abort=function(v,w){a.default.error("Aborting!"),this.emitError(v,w),this._lastServerId?this.disconnect():this.destroy()},m.prototype.emitError=function(v,w){var x;a.default.error("Error:",w),(x=typeof w=="string"?new Error(w):w).type=v,this.emit(E.PeerEventType.Error,x)},m.prototype.destroy=function(){this.destroyed||(a.default.log("Destroy peer with ID:"+this.id),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit(E.PeerEventType.Close))},m.prototype._cleanup=function(){var v,w;try{for(var x=r(this._connections.keys()),T=x.next();!T.done;T=x.next()){var R=T.value;this._cleanupPeer(R),this._connections.delete(R)}}catch(C){v={error:C}}finally{try{T&&!T.done&&(w=x.return)&&w.call(x)}finally{if(v)throw v.error}}this.socket.removeAllListeners()},m.prototype._cleanupPeer=function(v){var w,x,T=this._connections.get(v);if(T)try{for(var R=r(T),C=R.next();!C.done;C=R.next())C.value.close()}catch(P){w={error:P}}finally{try{C&&!C.done&&(x=R.return)&&x.call(R)}finally{if(w)throw w.error}}},m.prototype.disconnect=function(){if(!this.disconnected){var v=this.id;a.default.log("Disconnect peer with ID:"+v),this._disconnected=!0,this._open=!1,this.socket.close(),this._lastServerId=v,this._id=null,this.emit(E.PeerEventType.Disconnected,v)}},m.prototype.reconnect=function(){if(this.disconnected&&!this.destroyed)a.default.log("Attempting reconnection to server with ID "+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)throw new Error("Peer "+this.id+" cannot reconnect because it is not disconnected from the server!");a.default.error("In a hurry? We're still trying to make the initial connection!")}},m.prototype.listAllPeers=function(v){var w=this;v===void 0&&(v=function(x){}),this._api.listAllPeers().then(function(x){return v(x)}).catch(function(x){return w._abort(E.PeerErrorType.ServerError,x)})},m.DEFAULT_KEY="peerjs",m}(c.EventEmitter);t.Peer=g},{eventemitter3:"JJlS","./util":"BHXf","./logger":"WOs9","./socket":"wJlv","./mediaconnection":"dbHP","./dataconnection":"GBTQ","./enums":"ZRYf","./api":"in7L"}],iTK6:[function(l,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.peerjs=void 0;var i=l("./util"),n=l("./peer");t.peerjs={Peer:n.Peer,util:i.util},t.default=n.Peer,window.peerjs=t.peerjs,window.Peer=n.Peer},{"./util":"BHXf","./peer":"Hxpd"}]},{},["iTK6"],null)});var rp=Xo((oR,np)=>{(function(){var l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e={rotl:function(t,i){return t<<i|t>>>32-i},rotr:function(t,i){return t<<32-i|t>>>i},endian:function(t){if(t.constructor==Number)return e.rotl(t,8)&16711935|e.rotl(t,24)&4278255360;for(var i=0;i<t.length;i++)t[i]=e.endian(t[i]);return t},randomBytes:function(t){for(var i=[];t>0;t--)i.push(Math.floor(Math.random()*256));return i},bytesToWords:function(t){for(var i=[],n=0,r=0;n<t.length;n++,r+=8)i[r>>>5]|=t[n]<<24-r%32;return i},wordsToBytes:function(t){for(var i=[],n=0;n<t.length*32;n+=8)i.push(t[n>>>5]>>>24-n%32&255);return i},bytesToHex:function(t){for(var i=[],n=0;n<t.length;n++)i.push((t[n]>>>4).toString(16)),i.push((t[n]&15).toString(16));return i.join("")},hexToBytes:function(t){for(var i=[],n=0;n<t.length;n+=2)i.push(parseInt(t.substr(n,2),16));return i},bytesToBase64:function(t){for(var i=[],n=0;n<t.length;n+=3)for(var r=t[n]<<16|t[n+1]<<8|t[n+2],o=0;o<4;o++)n*8+o*6<=t.length*8?i.push(l.charAt(r>>>6*(3-o)&63)):i.push("=");return i.join("")},base64ToBytes:function(t){t=t.replace(/[^A-Z0-9+\/]/ig,"");for(var i=[],n=0,r=0;n<t.length;r=++n%4)r!=0&&i.push((l.indexOf(t.charAt(n-1))&Math.pow(2,-2*r+8)-1)<<r*2|l.indexOf(t.charAt(n))>>>6-r*2);return i}};np.exports=e})()});var Fc=Xo((sR,op)=>{var Bc={utf8:{stringToBytes:function(l){return Bc.bin.stringToBytes(unescape(encodeURIComponent(l)))},bytesToString:function(l){return decodeURIComponent(escape(Bc.bin.bytesToString(l)))}},bin:{stringToBytes:function(l){for(var e=[],t=0;t<l.length;t++)e.push(l.charCodeAt(t)&255);return e},bytesToString:function(l){for(var e=[],t=0;t<l.length;t++)e.push(String.fromCharCode(l[t]));return e.join("")}}};op.exports=Bc});var lp=Xo((aR,ap)=>{ap.exports=function(l){return l!=null&&(sp(l)||Tv(l)||!!l._isBuffer)};function sp(l){return!!l.constructor&&typeof l.constructor.isBuffer=="function"&&l.constructor.isBuffer(l)}function Tv(l){return typeof l.readFloatLE=="function"&&typeof l.slice=="function"&&sp(l.slice(0,0))}});var dp=Xo((lR,cp)=>{(function(){var l=rp(),e=Fc().utf8,t=lp(),i=Fc().bin,n=function(r,o){r.constructor==String?o&&o.encoding==="binary"?r=i.stringToBytes(r):r=e.stringToBytes(r):t(r)?r=Array.prototype.slice.call(r,0):!Array.isArray(r)&&r.constructor!==Uint8Array&&(r=r.toString());for(var s=l.bytesToWords(r),c=r.length*8,d=1732584193,a=-271733879,h=-1732584194,u=271733878,f=0;f<s.length;f++)s[f]=(s[f]<<8|s[f]>>>24)&16711935|(s[f]<<24|s[f]>>>8)&4278255360;s[c>>>5]|=128<<c%32,s[(c+64>>>9<<4)+14]=c;for(var E=n._ff,b=n._gg,y=n._hh,g=n._ii,f=0;f<s.length;f+=16){var p=d,m=a,v=h,w=u;d=E(d,a,h,u,s[f+0],7,-680876936),u=E(u,d,a,h,s[f+1],12,-389564586),h=E(h,u,d,a,s[f+2],17,606105819),a=E(a,h,u,d,s[f+3],22,-1044525330),d=E(d,a,h,u,s[f+4],7,-176418897),u=E(u,d,a,h,s[f+5],12,1200080426),h=E(h,u,d,a,s[f+6],17,-1473231341),a=E(a,h,u,d,s[f+7],22,-45705983),d=E(d,a,h,u,s[f+8],7,1770035416),u=E(u,d,a,h,s[f+9],12,-1958414417),h=E(h,u,d,a,s[f+10],17,-42063),a=E(a,h,u,d,s[f+11],22,-1990404162),d=E(d,a,h,u,s[f+12],7,1804603682),u=E(u,d,a,h,s[f+13],12,-40341101),h=E(h,u,d,a,s[f+14],17,-1502002290),a=E(a,h,u,d,s[f+15],22,1236535329),d=b(d,a,h,u,s[f+1],5,-165796510),u=b(u,d,a,h,s[f+6],9,-1069501632),h=b(h,u,d,a,s[f+11],14,643717713),a=b(a,h,u,d,s[f+0],20,-373897302),d=b(d,a,h,u,s[f+5],5,-701558691),u=b(u,d,a,h,s[f+10],9,38016083),h=b(h,u,d,a,s[f+15],14,-660478335),a=b(a,h,u,d,s[f+4],20,-405537848),d=b(d,a,h,u,s[f+9],5,568446438),u=b(u,d,a,h,s[f+14],9,-1019803690),h=b(h,u,d,a,s[f+3],14,-187363961),a=b(a,h,u,d,s[f+8],20,1163531501),d=b(d,a,h,u,s[f+13],5,-1444681467),u=b(u,d,a,h,s[f+2],9,-51403784),h=b(h,u,d,a,s[f+7],14,1735328473),a=b(a,h,u,d,s[f+12],20,-1926607734),d=y(d,a,h,u,s[f+5],4,-378558),u=y(u,d,a,h,s[f+8],11,-2022574463),h=y(h,u,d,a,s[f+11],16,1839030562),a=y(a,h,u,d,s[f+14],23,-35309556),d=y(d,a,h,u,s[f+1],4,-1530992060),u=y(u,d,a,h,s[f+4],11,1272893353),h=y(h,u,d,a,s[f+7],16,-155497632),a=y(a,h,u,d,s[f+10],23,-1094730640),d=y(d,a,h,u,s[f+13],4,681279174),u=y(u,d,a,h,s[f+0],11,-358537222),h=y(h,u,d,a,s[f+3],16,-722521979),a=y(a,h,u,d,s[f+6],23,76029189),d=y(d,a,h,u,s[f+9],4,-640364487),u=y(u,d,a,h,s[f+12],11,-421815835),h=y(h,u,d,a,s[f+15],16,530742520),a=y(a,h,u,d,s[f+2],23,-995338651),d=g(d,a,h,u,s[f+0],6,-198630844),u=g(u,d,a,h,s[f+7],10,1126891415),h=g(h,u,d,a,s[f+14],15,-1416354905),a=g(a,h,u,d,s[f+5],21,-57434055),d=g(d,a,h,u,s[f+12],6,1700485571),u=g(u,d,a,h,s[f+3],10,-1894986606),h=g(h,u,d,a,s[f+10],15,-1051523),a=g(a,h,u,d,s[f+1],21,-2054922799),d=g(d,a,h,u,s[f+8],6,1873313359),u=g(u,d,a,h,s[f+15],10,-30611744),h=g(h,u,d,a,s[f+6],15,-1560198380),a=g(a,h,u,d,s[f+13],21,1309151649),d=g(d,a,h,u,s[f+4],6,-145523070),u=g(u,d,a,h,s[f+11],10,-1120210379),h=g(h,u,d,a,s[f+2],15,718787259),a=g(a,h,u,d,s[f+9],21,-343485551),d=d+p>>>0,a=a+m>>>0,h=h+v>>>0,u=u+w>>>0}return l.endian([d,a,h,u])};n._ff=function(r,o,s,c,d,a,h){var u=r+(o&s|~o&c)+(d>>>0)+h;return(u<<a|u>>>32-a)+o},n._gg=function(r,o,s,c,d,a,h){var u=r+(o&c|s&~c)+(d>>>0)+h;return(u<<a|u>>>32-a)+o},n._hh=function(r,o,s,c,d,a,h){var u=r+(o^s^c)+(d>>>0)+h;return(u<<a|u>>>32-a)+o},n._ii=function(r,o,s,c,d,a,h){var u=r+(s^(o|~c))+(d>>>0)+h;return(u<<a|u>>>32-a)+o},n._blocksize=16,n._digestsize=16,cp.exports=function(r,o){if(r==null)throw new Error("Illegal argument "+r);var s=l.wordsToBytes(n(r,o));return o&&o.asBytes?s:o&&o.asString?i.bytesToString(s):l.bytesToHex(s)}})()});import{DepthTexture as RE,WebGLRenderer as CE}from"three";import*as De from"three";var jl={};oh(jl,{Behaviour:()=>M,Component:()=>ot,GameObject:()=>O,HideFlags:()=>Nh,InstantiateOptions:()=>ye});import*as ae from"three";var dn="__isActiveInHierarchy",Wn="builtin_components";function Un(l,e){try{e?l(e):l()}catch(t){return console.error(t),!1}return!0}var El=()=>l=>l;var wl=!1,yl=[];setTimeout(()=>{wl&&console.log(yl)},100);function _l(){return new URLSearchParams(window.location.search)}function N(l){wl&&!yl.includes(l)&&yl.push(l);let e=_l();if(e.has(l)){let t=e.get(l);return t||!0}return!1}wl=N("help")===!0;function Or(l,e,t){l.has(e)?l.set(e,t.toString()):l.append(e,t.toString())}function lh(l,e){window.history.replaceState(null,l,"?"+e.toString())}function ch(l,e){return Math.floor(Math.random()*(e-l+1))+l}var sh=["smol","tiny","giant","interesting","smart","bright","dull","extreme","beautiful","pretty","dark","epic","salty","silly","funny","lame","lazy","loud","lucky","mad","mean","mighty","mysterious","nasty","odd","old","powerful","quiet","rapid","scary","shiny","shy","silly","smooth","sour","spicy","stupid","sweet","tasty","terrible","ugly","unusual","vast","wet","wild","witty","wrong","zany","zealous","zippy","zombie","zorro"],ah=["cat","dog","mouse","pig","cow","horse","sheep","chicken","duck","goat","panda","tiger","lion","elephant","monkey","bird","fish","snake","frog","turtle","hamster","penguin","kangaroo","whale","dolphin","crocodile","snail","ant","bee","beetle","butterfly","dragon","eagle","fish","giraffe","lizard","panda","penguin","rabbit","snake","spider","tiger","zebra"];function dh(){let l=sh[Math.floor(Math.random()*sh.length)],e=ah[Math.floor(Math.random()*ah.length)];return l+"_"+e}function hh(l){return l=l.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),l.trim()}function hn(l,e,t=!0,i=!1){if(e==null)return null;if(e.userData&&e.userData.guid===l)return e;if(e.guid==l)return e;if(i&&e.userData?.components){for(let n of e.userData.components)if(n.guid===l)return n}if(t){if(e.scenes)for(let n in e.scenes){let r=e.scenes[n],o=hn(l,r,t,i);if(o)return o}if(e.children)for(let n in e.children){let r=e.children[n],o=hn(l,r,t,i);if(o)return o}}}function Qo(l,e){if(l!=null&&typeof l=="object"){let t;Array.isArray(l)?t=[]:(t=Object.create(l),Object.assign(t,l));for(let i of Object.keys(l)){let n=l[i];e&&!e(l,i,n)?t[i]=n:n?.clone!==void 0&&typeof n.clone=="function"?t[i]=n.clone():t[i]=Qo(n,e)}return t}return l}function uh(l){return new Promise((e,t)=>{setTimeout(e,l)})}function Ms(l,e){if(e&&l&&!e.includes("/")){let t=l.lastIndexOf("/");if(t>=0)return l.substring(0,t+1)+e}return e}var Is=class{subscribeWrite(e){this.writeCallbacks.push(e)}writeCallbacks=[];constructor(e,t){this._object=e,this._prop=t,this._wrapperProp="__$_NEEDLE_"+t,this.apply()}_applied=!1;_object;_prop;_wrapperProp;apply(){if(this._applied||!this._object)return;let e=this._object,t=this._prop;if(e[t]===void 0)return;this._applied=!0,e[this._wrapperProp]!==void 0&&console.warn("Watcher is being applied to an object that already has a wrapper property. This is not (yet) supported");let i=e[t];e[this._wrapperProp]=i,Object.defineProperty(e,t,{get:()=>e[this._wrapperProp],set:o=>{e[this._wrapperProp]=o;for(let s of this.writeCallbacks)s(o)}})}revoke(){if(!this._applied||!this._object)return;this._applied=!1;let e=this._object,t=this._prop;Reflect.deleteProperty(e,t);let i=e[this._wrapperProp];e[t]=i,Reflect.deleteProperty(e,this._wrapperProp)}dispose(){this.revoke(),this.writeCallbacks.length=0,this._object=null}};var jf=N("debugnewscripts"),be=[];function ki(l){if(!(l.new_scripts.length<=0)){if(jf&&console.log("Register new components",l.new_scripts.length,l.alias?"element: "+l.alias:""),l.new_scripts_pre_setup_callbacks.length>0){for(let e of l.new_scripts_pre_setup_callbacks)!e||e();l.new_scripts_pre_setup_callbacks.length=0}be.length=0,l.new_scripts.length>0&&be.push(...l.new_scripts),l.new_scripts.length=0;for(let e=0;e<be.length;e++)try{let t=be[e];if(t.destroyed)continue;if(!t.gameObject){console.error("MISSING GAMEOBJECT - will ignore",t),be.splice(e,1),e--;continue}t.context=l,qn(t.gameObject),xl(t,l)}catch(t){console.error(t),Ai(be[e],l),be.splice(e,1),e--}for(let e=0;e<be.length;e++)try{let t=be[e];if(t.destroyed){Ai(be[e],l),be.splice(e,1),e--;continue}t.__internalAwake!==void 0&&(t.gameObject||console.error("MISSING GAMEOBJECT",t,t.gameObject),qn(t.gameObject),t.activeAndEnabled&&Un(t.__internalAwake.bind(t)))}catch(t){console.error(t),Ai(be[e],l),be.splice(e,1),e--}for(let e=0;e<be.length;e++)try{let t=be[e];if(t.destroyed||t.enabled===!1||(qn(t.gameObject),t.activeAndEnabled===!1))continue;t.__internalEnable!==void 0&&(t.enabled=!0,Un(t.__internalEnable.bind(t)))}catch(t){console.error(t),Ai(be[e],l),be.splice(e,1),e--}for(let e=0;e<be.length;e++)try{let t=be[e];if(t.destroyed||!t.gameObject)continue;l.new_script_start.push(t)}catch(t){console.error(t),Ai(be[e],l),be.splice(e,1),e--}be.length=0;for(let e of l.new_scripts_post_setup_callbacks)e&&e();l.new_scripts_post_setup_callbacks.length=0}}function fh(l){!l||(l.__internalDisable(),Ai(l,l.context))}function mh(l){for(let e=0;e<l.new_script_start.length;e++)try{let t=l.new_script_start[e];if(t.destroyed||t.activeAndEnabled===!1)continue;Un(t.__internalAwake.bind(t)),Un(t.__internalEnable.bind(t)),Un(t.__internalStart.bind(t)),l.new_script_start.splice(e,1),e--}catch(t){console.error(t),Ai(l.new_script_start[e],l),l.new_script_start.splice(e,1),e--}}function xl(l,e){e.scripts.indexOf(l)===-1&&(e.scripts.push(l),l.earlyUpdate&&e.scripts_earlyUpdate.push(l),l.update&&e.scripts_update.push(l),l.lateUpdate&&e.scripts_lateUpdate.push(l),l.onBeforeRender&&e.scripts_onBeforeRender.push(l),l.onAfterRender&&e.scripts_onAfterRender.push(l))}function Ai(l,e){un(l,e.new_scripts),un(l,e.new_script_start),un(l,e.scripts),un(l,e.scripts_earlyUpdate),un(l,e.scripts_update),un(l,e.scripts_lateUpdate),un(l,e.scripts_onBeforeRender),un(l,e.scripts_onAfterRender),e.stopAllCoroutinesFrom(l)}function un(l,e){let t=e.indexOf(l);t>=0&&e.splice(t,1)}var Bf={},ph={};function gh(){if(!Z.Current){console.trace("Invalid call - no current context.");return}bh(Z.Current.scene,Z.Current.scene.visible,!0)}function bh(l,e,t){let i=!1,n=O.isActiveSelf(l);if(Bf[l.uuid]=n,e&&(e=O.isActiveSelf(l)),l[dn]=e,!i){let r=ph[l.uuid];r!==void 0&&r!==e&&t&&Ff(l,o=>{e?(Un(o.__internalAwake.bind(o)),o.onEnable()):o.onDisable()})}if(ph[l.uuid]=e,l.children)for(let r of l.children)bh(r,e,t)}function qn(l){let e=!0,t=l,i=!1;for(;t&&t;){if(t.type==="Scene"&&(i=!0),!O.isActiveSelf(t)){e=!1;break}t=t.parent}if(!l){console.error("GO is null");return}l[dn]=e&&i}function Ff(l,e){if(l.userData?.components)for(let t of l.userData.components)e(t)}var Rl=N("debuggetcomponent");function Cl(l,e){if(!l)return;let t=e?.new_scripts??Z.Current.new_scripts;t.includes(l)||t.push(l)}var vh=function(l,e){if(!l||!l.userData.components)return;let t=l.userData.components.indexOf(e);t<0||(e.gameObject=null,l.userData.components.splice(t,1))},Ls=function(l,e,t=!0){e.userData||(e.userData={}),e.userData.components||(e.userData.components=[]),e.userData.components.push(l),l.gameObject=e,Cl(l);try{l.__internalAwake&&t&&(qn(e),l.__internalAwake())}catch(i){console.error(i)}},yh=function(l,e){if(l.gameObject!==e){if(l.gameObject&&l.gameObject.userData.components){let t=l.gameObject.userData.components.indexOf(l);l.gameObject.userData.components.splice(t,1)}if(!e.userData.components)e.userData.components=[];else if(e.userData.components.includes(l))return;e.userData.components.push(l),l.gameObject=e}},Eh=function(l){if(l.gameObject&&l.gameObject.userData.components){let e=l.gameObject.userData.components.indexOf(l);l.gameObject.userData.components.splice(e,1)}l.__internalDisable&&l.__internalDisable(),l.onDestroy&&l.onDestroy(),Ai(l,l.context??Z.Current),l.__destroyed=!0,l.gameObject=null},wh=function(l,e,t){if(!e?.userData?.components)return null;Rl&&console.log("FIND",l);for(let i=0;i<e.userData.components.length;i++){let n=e.userData.components[i];if(l===null||n.constructor.name===l.name||n.constructor.name===l)if(Rl&&console.log("MATCH BY NAME",n),t)t.push(n);else return n}for(let i=0;i<e.userData.components.length;i++){let n=e.userData.components[i],r=Object.getPrototypeOf(n.constructor);do{if(r===l)if(Rl&&console.log("MATCH BY PROTOYPE",r),t)t.push(n);else return n;r=Object.getPrototypeOf(r)}while(r)}return t},Ds=function(l,e){return wh(l,e,null)},Hs=function(l,e,t){return t||(t=[]),wh(l,e,t)},js=function(l,e,t){let i=Ds(l,e);if(t===!1&&i.enabled===!1)return null;if(i)return i;for(let n=0;n<e?.children?.length;n++){let r=js(l,e.children[n]);if(r)return r}return null},Bs=function(l,e,t){t||(t=[]),Hs(l,e,t);for(let i=0;i<e?.children?.length;i++)Bs(l,e.children[i],t);return t},Sl=function(l,e){if(!e)return null;let t=Ds(l,e);return t||Sl(l,e.parent)},Pl=function(l,e,t){return t||(t=[]),e?(Hs(l,e,t),Pl(l,e.parent,t)):t},_h=function(l,e,t){if(!l)return null;if(!e&&(e=Z.Current,!e))return console.error("Can not search object without any needle context or scene!!!"),null;let i=e.isScene===!0||e.isObject3D===!0?e:e?.scene;for(let n in i.children){let r=i.children[n];if(t===!1&&r[dn]===!1)continue;if(r.constructor==l)return r;let o=js(l,r);if(o)return o}return null},xh=function(l,e,t){if(!l)return e;if(!t&&(t=Z.Current,!t))return console.error("Can not search object without any needle context or scene!!!"),e;let i=t.isScene===!0||t.isObject3D===!0?t:t?.scene;if(!i)return e;for(let n in i.children){let r=i.children[n];if(r.constructor==l)return r;Bs(l,r,e)}return e};var Ol=class{random(){return Math.random()}clamp(e,t,i){return e<t?t:e>i?i:e}clamp01(e){return this.clamp(e,0,1)}lerp(e,t,i){return i=i<0?0:i,i=i>1?1:i,e+(t-e)*i}moveTowards(e,t,i){return e+=i,(i<0&&e<t||i>0&&e>t)&&(e=t),e}toDegrees(e){return e*180/Math.PI}toRadians(e){return e*Math.PI/180}},Q=new Ol;import*as oe from"three";import{Vector3 as zf,Quaternion as Gf,Uniform as Vf}from"three";var kl=class{_factory;_cache=[];_maxSize;_index=0;constructor(e,t){this._factory=e,this._maxSize=t}get(){let e=this._index++;return e>=this._cache.length&&(e>=this._maxSize?e=this._index=0:this._cache.push(this._factory())),this._cache[e]}},JE=new Gf().setFromAxisAngle(new zf(0,1,0),Math.PI);var Il=new kl(()=>new oe.Vector3,100);oe.Vector3.prototype.slerp=function(l,e){let t=this.length(),i=l.length(),n=Q.lerp(t,i,e);return this.lerp(l,e).normalize().multiplyScalar(n)};function q(l,e=null,t=!0){let i=e??Il.get();return l?l.parent?(t&&l.updateWorldMatrix(!0,!1),l.matrixWorldNeedsUpdate&&l.updateMatrixWorld(),i.setFromMatrixPosition(l.matrixWorld),i):i.copy(l.position):i.set(0,0,0)}function ie(l,e){if(!l)return;let t=Il.get();e!==t&&t.copy(e),(l?.parent??l).worldToLocal(t),l.position.set(t.x,t.y,t.z)}function Ar(l,e,t,i){let n=Il.get();n.set(e,t,i),ie(l,n)}var Xn=new oe.Quaternion,Yo=new oe.Quaternion,Al=new oe.Quaternion;function ve(l,e=null){if(!l)return Yo.set(0,0,0,1);let t=e??Yo;return l.parent?(l.getWorldQuaternion(t),t):t.copy(l.quaternion)}function Ae(l,e){if(!l)return;e!==Xn&&Xn.copy(e);let t=Xn;l?.parent?.getWorldQuaternion(Al),Al.invert();let n=Al.multiply(t);l.quaternion.set(n.x,n.y,n.z,n.w)}function Ch(l,e,t,i,n){Xn.set(e,t,i,n),Ae(l,Xn)}var Fs=new oe.Vector3,$E=new oe.Vector3;function Sh(l,e=null){return l?l.parent?(l.getWorldScale(e??Fs),e??Fs):Fs.copy(l.position):Fs.set(0,0,0)}var KE=new oe.Vector3,e0=new oe.Quaternion;var Th=new oe.Euler,Rh=new oe.Euler,Wf=new oe.Vector3;function Uf(l){return l.getWorldQuaternion(Yo),Rh.setFromQuaternion(Yo),Rh}function Ph(l,e){Ae(l,Yo.setFromEuler(e))}function Ns(l){let e=Uf(l),t=Wf;return t.set(e.x,e.y,e.z),t.x=Q.toDegrees(t.x),t.y=Q.toDegrees(t.y),t.z=Q.toDegrees(t.z),t}function zs(l,e,t,i,n=!0){n&&(e=Q.toRadians(e),t=Q.toRadians(t),i=Q.toRadians(i)),Th.set(e,t,i),Xn.setFromEuler(Th),Ae(l,Xn)}function Zo(l,e=!0){!l||(e?function t(i){console.groupCollapsed((i.name?i.name:"(no name : "+i.type+")")+" %o",i),i.children.forEach(t),console.groupEnd()}(l):l.traverse(function(t){for(var i="|___",n=t;n.parent!==null;)i=" "+i,n=n.parent;console.log(i+t.name+" <"+t.type+">")}))}var t0=new oe.PlaneGeometry(2,2,1,1),i0=new oe.WebGLRenderer({antialias:!1}),n0=new oe.PerspectiveCamera,r0=new oe.Scene,o0=new oe.ShaderMaterial({uniforms:{blitTexture:new Vf(null)},vertexShader:`
79
79
  varying vec2 vUv;
80
80
  void main(){
81
81
  vUv = uv;
@@ -88,7 +88,7 @@ a=extmap-allow-mixed`)!==-1){var f=p.sdp.split(`
88
88
  uv.y = 1.0 - uv.y;
89
89
  gl_FragColor = vec4(uv.xy, 0, 1);
90
90
  gl_FragColor = texture2D( blitTexture, uv);
91
- }`});import*as qs from"three";var xh=/^(?:[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 Nf(l){return typeof l=="string"&&xh.test(l)}var Fo=Nf;var Ve=[];for(No=0;No<256;++No)Ve.push((No+256).toString(16).substr(1));var No;function zf(l){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,t=(Ve[l[e+0]]+Ve[l[e+1]]+Ve[l[e+2]]+Ve[l[e+3]]+"-"+Ve[l[e+4]]+Ve[l[e+5]]+"-"+Ve[l[e+6]]+Ve[l[e+7]]+"-"+Ve[l[e+8]]+Ve[l[e+9]]+"-"+Ve[l[e+10]]+Ve[l[e+11]]+Ve[l[e+12]]+Ve[l[e+13]]+Ve[l[e+14]]+Ve[l[e+15]]).toLowerCase();if(!Fo(t))throw TypeError("Stringified UUID is invalid");return t}var Th=zf;function Gf(l){if(!Fo(l))throw TypeError("Invalid UUID");var e,t=new Uint8Array(16);return t[0]=(e=parseInt(l.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(l.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(l.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(l.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(l.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}var Rh=Gf;function Vf(l){l=unescape(encodeURIComponent(l));for(var e=[],t=0;t<l.length;++t)e.push(l.charCodeAt(t));return e}var Wf="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Uf="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Ch(l,e,t){function i(n,r,s,o){if(typeof n=="string"&&(n=Vf(n)),typeof r=="string"&&(r=Rh(r)),r.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var c=new Uint8Array(16+n.length);if(c.set(r),c.set(n,r.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,s){o=o||0;for(var d=0;d<16;++d)s[o+d]=c[d];return s}return Th(c)}try{i.name=l}catch{}return i.DNS=Wf,i.URL=Uf,i}function qf(l,e,t,i){switch(l){case 0:return e&t^~e&i;case 1:return e^t^i;case 2:return e&t^e&i^t&i;case 3:return e^t^i}}function Ml(l,e){return l<<e|l>>>32-e}function Xf(l){var e=[1518500249,1859775393,2400959708,3395469782],t=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof l=="string"){var i=unescape(encodeURIComponent(l));l=[];for(var n=0;n<i.length;++n)l.push(i.charCodeAt(n))}else Array.isArray(l)||(l=Array.prototype.slice.call(l));l.push(128);for(var r=l.length/4+2,s=Math.ceil(r/16),o=new Array(s),c=0;c<s;++c){for(var d=new Uint32Array(16),a=0;a<16;++a)d[a]=l[c*64+a*4]<<24|l[c*64+a*4+1]<<16|l[c*64+a*4+2]<<8|l[c*64+a*4+3];o[c]=d}o[s-1][14]=(l.length-1)*8/Math.pow(2,32),o[s-1][14]=Math.floor(o[s-1][14]),o[s-1][15]=(l.length-1)*8&4294967295;for(var h=0;h<s;++h){for(var u=new Uint32Array(80),g=0;g<16;++g)u[g]=o[h][g];for(var E=16;E<80;++E)u[E]=Ml(u[E-3]^u[E-8]^u[E-14]^u[E-16],1);for(var b=t[0],y=t[1],m=t[2],p=t[3],f=t[4],v=0;v<80;++v){var w=Math.floor(v/20),x=Ml(b,5)+qf(w,y,m,p)+f+e[w]+u[v]>>>0;f=p,p=m,m=Ml(y,30)>>>0,y=b,b=x}t[0]=t[0]+b>>>0,t[1]=t[1]+y>>>0,t[2]=t[2]+m>>>0,t[3]=t[3]+p>>>0,t[4]=t[4]+f>>>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]}var Sh=Xf;var Qf=Ch("v5",80,Sh),Ll=Qf;var zo=N("debugcomponents"),Yf="eff8ba80-635d-11ec-90d6-0242ac120003",We=class{get seed(){return this._seed}_originalSeed;_seed;constructor(e){this._originalSeed=e,this._seed=e}generateUUID(){let e=this._seed;return this._seed-=1,Ll(e.toString(),Yf)}static createFromString(e){return new We(this.hash(e))}static hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}};var Go=class{guid;constructor(e){this.guid=e}};function Sr(l,e,t=!0){if(!l)return;let i=l;if(O.destroy(l,t),!e){console.warn("Can not send destroy: No networking connection provided",l.guid);return}if(!e.isConnected){console.warn("Can not send destroy: not connected",l.guid);return}let n=l.guid;if(!n&&i.uuid&&(n=i.uuid),!n){console.warn("Can not send destroy: failed to find guid",l);return}let r=new Go(n);e.send("instance-destroyed",r)}function Ph(l,e){let t=new Go(l);e.send("instance-destroyed",t)}function Oh(l){l.connection.beginListen("instance-destroyed",e=>{zo&&console.log("[Remote] Destroyed",l.scene,e);let t=O.findByGuid(e.guid,l.scene);t&&O.destroy(t)})}var Dl=class{guid;originalGuid;seed;visible;hostData;dontSave;parent;position;rotation;scale;constructor(e,t){this.originalGuid=e,this.guid=t}};function Vo(l,e,t,i){let n=l;if(!n.guid)return console.warn("Can not instantiate: No guid",n),null;if(e.context||(e.context=Z.Current),!e.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;let r=e?{...e}:null,{instance:s,seed:o}=Zf(n,e);if(s){let c=s;if(c.guid){zo&&console.log("[Local] new instance","gameobject:",s?.guid);let d=new Dl(n.guid,c.guid);d.seed=o,r&&(r.position&&(d.position={x:r.position.x,y:r.position.y,z:r.position.z}),r.rotation&&(d.rotation={x:r.rotation.x,y:r.rotation.y,z:r.rotation.z,w:r.rotation.w}),r.scale&&(d.scale={x:r.scale.x,y:r.scale.y,z:r.scale.z})),d.position||(d.position={x:c.position.x,y:c.position.y,z:c.position.z}),d.rotation||(d.rotation={x:c.quaternion.x,y:c.quaternion.y,z:c.quaternion.z,w:c.quaternion.w}),d.scale||(d.scale={x:c.scale.x,y:c.scale.y,z:c.scale.z}),d.visible=n.visible,r?.parent&&(typeof r.parent=="string"?d.parent=r.parent:d.parent=r.parent.guid),d.hostData=t,i===!1&&(d.dontSave=!0),e?.context?.connection.send("new-instance-created",d)}else console.warn("Missing guid, can not send new instance event",c)}return s}function Wo(){return Math.random()*9999999}function Ah(l){l.connection.beginListen("new-instance-created",async e=>{let t=await Jf(e.originalGuid,l.scene);if(!t){console.warn("could not find object that was instantiated: "+e.guid);return}let i=new ye;e.position&&(i.position=new qs.Vector3(e.position.x,e.position.y,e.position.z)),e.rotation&&(i.rotation=new qs.Quaternion(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w)),e.scale&&(i.scale=new qs.Vector3(e.scale.x,e.scale.y,e.scale.z)),i.parent=e.parent,e.seed&&(i.idProvider=new We(e.seed)),i.visible=e.visible,i.context=l,zo&&l.alias&&console.log("[Remote] instantiate in: "+l.alias);let n=O.instantiate(t,i);n&&(e.parent==="scene"&&l.scene.add(n),zo&&console.log("[Remote] new instance","gameobject:",n?.guid,t))})}function Zf(l,e){let t=Wo(),i=e??new ye;i.idProvider=new We(t);let n=O.instantiate(l,i);return{seed:t,instance:n}}var kh={};function Ih(l,e){kh[l]=e}async function Jf(l,e){let t=kh[l];if(t!=null){let i=await t(l);if(i)return i}return Mh(l,e)}function Mh(l,e){if(e===null||!l)return null;if(e.guid===l)return e;if(e.children)for(let t of e.children){let i=Mh(l,t);if(i)return i}return null}var un=N("debugcomponents"),Lh=(d=>(d[d.None=0]="None",d[d.HideInHierarchy=1]="HideInHierarchy",d[d.HideInInspector=2]="HideInInspector",d[d.DontSaveInEditor=4]="DontSaveInEditor",d[d.NotEditable=8]="NotEditable",d[d.DontSaveInBuild=16]="DontSaveInBuild",d[d.DontUnloadUnusedAsset=32]="DontUnloadUnusedAsset",d[d.DontSave=52]="DontSave",d[d.HideAndDontSave=61]="HideAndDontSave",d))(Lh||{}),ye=class{idProvider;parent;keepWorldPosition;position;rotation;scale;visible;context};ae.Object3D.prototype.SetActive=function(l){this.visible=l};var O=class extends ae.Object3D{guid;static setActive(e,t){!e||(e.visible=t)}static isActiveSelf(e){return e.visible||O.isUsingInstancing(e)}static isActiveInHierarchy(e){return e[cn]||O.isUsingInstancing(e)}static markAsInstancedRendered(e,t){e.__isUsingInstancing=t}static isUsingInstancing(e){return e.__isUsingInstancing===!0}static foreachComponent(e,t,i=!0){if(!!e){if(e.userData.components)for(let n=0;n<e.userData.components.length;n++){let r=e.userData.components[n];if(r instanceof M){let s=t(r);if(s!==void 0)return s}}if(i&&e.children)for(let n=0;n<e.children.length;n++){let r=e.children[n];if(!r)continue;let s=O.foreachComponent(r,t,i);if(s!==void 0)return s}}}static instantiateSynced(e,t){return e?Vo(e,t):null}static instantiate(e,t=null){if(e===null)return null;let i=null;t!==null&&(t.x!==void 0?(i=new ye,i.position=t):i=t);let n=Z.Current;i?.context&&(n=i.context),un&&n.alias&&console.log("context",n.alias),i&&!i.idProvider&&(i.idProvider=new We(Date.now()));let r=[],s={},o={},c=this.internalInstantiate(n,e,i,r,s,o);c&&(this.resolveReferences(s),this.resolveAndBindSkinnedMeshBones(o,s)),un&&(Us(e,!0),Us(c,!0));let d={};for(let a in r){let h=r[a],u=h.guid;i&&i.idProvider&&(h.guid=i.idProvider.generateUUID(),d[u]=h.guid,un&&console.log(h.name,h.guid)),Cl(h,n),h.__internalNewInstanceCreated&&h.__internalNewInstanceCreated()}for(let a in r){let h=r[a];h.resolveGuids&&h.resolveGuids(d),h.enabled!==!1&&(h.enabled=!0)}return Ai(n),c}static internalInstantiate(e,t,i,n,r,s){if(!t)return null;let o=t.userData;t.userData={};let c=t.children;t.children=[];let d;if(d=t.clone(!1),t.userData=o,t.children=c,r[t.uuid]={original:t,clone:d},t.type==="SkinnedMesh"&&(s[t.uuid]={original:t,clone:d}),i?.visible!==void 0&&(d.visible=i.visible),i?.idProvider){d.uuid=i.idProvider.generateUUID();let h=d;h&&(h.guid=d.uuid)}t.animations&&t.animations.length>0&&(d.animations=[...t.animations]);let a=t.parent;if(a&&a.add(d),i?.position?ie(d,i.position):d.position.copy(t.position),i?.rotation?Ae(d,i.rotation):d.quaternion.copy(t.quaternion),i?.scale?d.scale.copy(i.scale):d.scale.copy(t.scale),i?.parent&&i.parent!=="scene"){let h=null;if(typeof i.parent=="string"?h=dn(i.parent,e.scene,!0):h=i.parent,h){let u=i.keepWorldPosition===!0?h.attach:h.add;u?u.call(h,d):console.error("Invalid parent object",h,"received when instantiating:",t)}else console.warn("could not find parent:",i.parent)}for(let[h,u]of Object.entries(t.userData))h!=="components"&&(d.userData[h]=u);if(t.userData?.components){let h=t.userData.components,u=[];d.userData.components=u;for(let g=0;g<h.length;g++){let E=h[g],b=Object.create(E);Object.assign(b,E),u.push(b),b.gameObject=d,n.push(b)}}i&&(i.position=void 0,i.rotation=void 0,i.scale=void 0,i.parent=void 0);for(let h in t.children){let u=t.children[h],g=O.internalInstantiate(e,u,i,n,r,s);g&&d.add(g)}return d}static resolveAndBindSkinnedMeshBones(e,t){for(let i in e){let n=e[i],r=n.original,s=r.skeleton,o=n.clone;if(!s){console.warn("Skinned mesh has no skeleton?",n);continue}let c=s.bones,d=o.skeleton.clone();o.skeleton=d,o.bindMatrix.clone().copy(r.bindMatrix),o.bindMatrixInverse.copy(r.bindMatrixInverse);let a=[];d.bones=a;for(let h=0;h<c.length;h++){let u=c[h],E=t[u.uuid].clone;a.push(E)}}for(let i in e){let n=e[i].clone;n.skeleton.update(),n.bind(n.skeleton,n.bindMatrix),n.updateMatrixWorld(!0)}}static resolveReferences(e){for(let t in e){let n=e[t].clone;if(n.userData?.components)for(let r=0;r<n.userData.components.length;r++){let s=n.userData.components[r],o=Object.entries(s);for(let[c,d]of o)if(Array.isArray(d)){let a=[];s[c]=a;for(let h=0;h<d.length;h++){let u=d[h];if(typeof u!="object"){a.push(u);continue}let g=this.postProcessNewInstance(s,c,u,e);g!==void 0?a.push(g):a.push(u)}}else if(typeof d=="object"){let a=this.postProcessNewInstance(s,c,d,e);a!==void 0&&(s[c]=a)}}}}static postProcessNewInstance(e,t,i,n){if(i instanceof st||i instanceof M){let r=i.gameObject;if(r){let s=r.uuid,o=n[s]?.clone;if(!o){un&&console.log("reference did not change",t,e,i);return}let c=r.userData.components.indexOf(i);if(c>=0)return un&&console.log(t,s),o.userData.components[c];console.warn("could not find component",t,i)}}else if(i instanceof ae.Object3D){if(t==="gameObject")return;let r=i;if(r){let s=r.uuid,o=n[s]?.clone;if(o)return un&&console.log(t,"old",i,"new",o),o}}}static destroySynced(e,t,i=!0){if(!e)return;let n=e;t=t??Z.Current,Sr(n,t.connection,i)}static destroy(e,t=!0,i=!0){let n=e;if(n.isComponent){n.destroy();return}let r=e;if(un&&console.log(r),t&&r.children)for(let o of r.children)O.destroy(o,t,!1);let s=r.userData.components;if(s){let o=s.length;for(let c=0;c<s.length;c++){let d=s[c];d.destroy&&(un&&console.log("destroying",d),d.destroy()),s.length<o&&(o=s.length,c--)}}i&&r.removeFromParent()}static add(e,t,i){if(!(!e||!t)){if(e===t){console.warn("Can not add object to self",e);return}i||(i=Z.Current),t.add(e),Wn(e),i?O.foreachComponent(e,n=>{xl(n,i),i.new_script_start.includes(n)===!1&&i.new_script_start.push(n)},!0):console.warn("Missing context")}}static remove(e){!e||(e.parent?.remove(e),O.foreachComponent(e,t=>{lh(t)},!0))}static invokeOnChildren(e,t,...i){this.invoke(e,t,!0,i)}static invoke(e,t,i=!1,...n){!e||this.foreachComponent(e,r=>{let s=r[t];s&&typeof s=="function"&&s.bind(r)(...n)},i)}static addNewComponent(e,t,i=!0){let n=new t;return ko(n,e,i),n}static addComponent(e,t){if(t.gameObject==null)throw new Error("Did you mean to create a new component? Use addNewComponent");ph(t,e)}static removeComponent(e){return uh(e.gameObject,e),e}static getOrAddComponent(e,t){let i=this.getComponent(e,t);return i||this.addNewComponent(e,t)}static getComponent(e,t){return e===null?null:Io(t,e)}static getComponents(e,t,i=null){return e===null?i??[]:Mo(t,e,i)}static findByGuid(e,t){return dn(e,t,!0,!0)}static findObjectOfType(e,t,i=!0){return gh(e,t,i)}static findObjectsOfType(e,t){let i=[];return bh(e,i,t),i}static getComponentInChildren(e,t){return Lo(t,e)}static getComponentsInChildren(e,t,i=null){return Do(t,e,i)}static getComponentInParent(e,t){return Sl(t,e)}static getComponentsInParent(e,t,i=null){return Pl(t,e,i)}static getAllComponents(e){return[...e.userData?.components]}static*iterateComponents(e){let t=e?.userData?.components;if(t&&Array.isArray(t))for(let i=0;i<t.length;i++)yield t[i]}};ae.Object3D.prototype.addNewComponent=function(l){return O.addNewComponent(this,l)};ae.Object3D.prototype.removeComponent=function(l){return O.removeComponent(l)};ae.Object3D.prototype.getOrAddComponent=function(l){return O.getOrAddComponent(this,l)};ae.Object3D.prototype.getComponent=function(l){return O.getComponent(this,l)};ae.Object3D.prototype.getComponents=function(l,e){return O.getComponents(this,l,e)};ae.Object3D.prototype.getComponentInChildren=function(l){return O.getComponentInChildren(this,l)};ae.Object3D.prototype.getComponentsInChildren=function(l,e){return O.getComponentsInChildren(this,l,e)};ae.Object3D.prototype.getComponentInParent=function(l){return O.getComponentInParent(this,l)};ae.Object3D.prototype.getComponentsInParent=function(l,e){return O.getComponentsInParent(this,l,e)};var Gt=class{get isComponent(){return!0}__context;get context(){return this.__context??Z.Current}set context(e){this.__context=e}get scene(){return this.context.scene}get layer(){return this.gameObject?.userData?.layer}get name(){return this.gameObject?.userData.name}__name;set name(e){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=e,this.__name=e):this.__name=e}get tag(){return this.gameObject?.userData.tag}set tag(e){this.gameObject&&(this.gameObject.userData.tag=e)}get static(){return this.gameObject?.userData.static}get hideFlags(){return this.gameObject?.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;let e=this.gameObject[cn];return e===void 0?!0:e}gameObject;guid="invalid";sourceId;awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(e,t=1){return this.context.registerCoroutineUpdate(this,e,t)}stopCoroutine(e,t=1){this.context.unregisterCoroutineUpdate(e,t)}get destroyed(){return this.__destroyed}destroy(){this.destroyed||fh(this)}__didAwake=!1;__didStart=!1;__didEnable=!1;__isEnabled=void 0;__destroyed=!1;__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(){this.__didEnable||(this.__didEnable=!0,this.onEnable())}__internalDisable(){!this.__didEnable||(this.__didEnable=!1,this.onDisable())}constructor(){this.__internalNewInstanceCreated()}_worldPosition=void 0;_worldQuaternion=void 0;_worldEuler=void 0;_worldRotation=void 0;get worldPosition(){return this._worldPosition||(this._worldPosition=new ae.Vector3),q(this.gameObject,this._worldPosition),this._worldPosition}set worldPosition(e){ie(this.gameObject,e)}setWorldPosition(e,t,i){Gt._worldPositionBuffer.set(e,t,i),this.worldPosition=Gt._worldPositionBuffer}get worldQuaternion(){return this._worldQuaternion||(this._worldQuaternion=new ae.Quaternion),ve(this.gameObject,this._worldQuaternion)}set worldQuaternion(e){Ae(this.gameObject,e)}setWorldQuaternion(e,t,i,n){Gt._worldQuaternionBuffer.set(e,t,i,n),this.worldQuaternion=Gt._worldQuaternionBuffer}get worldEuler(){return this._worldEuler||(this._worldEuler=new ae.Euler),this._worldEuler.setFromQuaternion(this.worldQuaternion),this._worldEuler}set worldEuler(e){this._worldQuaternion||(this._worldQuaternion=new ae.Quaternion),this._worldQuaternion?.setFromEuler(e),this.worldQuaternion=this._worldQuaternion}get worldRotation(){let e=this.worldEuler;this._worldRotation||(this._worldRotation=new ae.Vector3);let t=this._worldRotation;return t.set(e.x,e.y,e.z),t.x=Q.toDegrees(t.x),t.y=Q.toDegrees(t.y),t.z=Q.toDegrees(t.z),t}set worldRotation(e){this.setWorldRotation(e.x,e.y,e.z,!0)}setWorldRotation(e,t,i,n=!0){n&&(e=Q.toRadians(e),t=Q.toRadians(t),i=Q.toRadians(i)),Gt._worldEulerBuffer.set(e,t,i),Gt._worldQuaternionBuffer.setFromEuler(Gt._worldEulerBuffer),this.worldQuaternion=Gt._worldQuaternionBuffer}get forward(){return Gt._forward.set(0,0,1).applyQuaternion(this.worldQuaternion)}_eventListeners=new Map;addEventListener(e,t){this._eventListeners[e]=this._eventListeners[e]||[],this._eventListeners[e].push(t)}removeEventListener(e,t){if(!this._eventListeners[e])return;let i=this._eventListeners[e].indexOf(t);i>=0&&this._eventListeners[e].splice(i,1)}dispatchEvent(e){if(!this._eventListeners[e.type])return!1;let t=this._eventListeners[e.type];for(let i=0;i<t.length;i++)t[i](e);return!1}},st=Gt;z(st,"_worldPositionBuffer",new ae.Vector3),z(st,"_worldQuaternionBuffer",new ae.Quaternion),z(st,"_worldEulerBuffer",new ae.Euler),z(st,"_tempQuaternionBuffer2",new ae.Quaternion),z(st,"_forward",new ae.Vector3(0,0,1));var M=class extends st{get enabled(){return this.__isEnabled??!0}set enabled(e){typeof e=="number"&&(e>=.5?e=!0:e=!1),e!==this.__isEnabled&&(this.__isEnabled=e,this.__didAwake&&(e?this.__internalEnable():this.__internalDisable()))}};import*as Vt from"three";var Uo=class extends EventTarget{_doubleClickTimeThreshold=.2;_longPressTimeThreshold=1;get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}_specialCursorTrigger=0;setCursorPointer(){this._specialCursorTrigger+=1,this.context.domElement.style.cursor="pointer"}setCursorNormal(){this._specialCursorTrigger-=1,this._specialCursorTrigger=Math.max(0,this._specialCursorTrigger),this._specialCursorTrigger===0&&(this.context.domElement.style.cursor="default")}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}context;_pointerDown=[!1];_pointerUp=[!1];_pointerClick=[!1];_pointerDoubleClick=[!1];_pointerPressed=[!1];_pointerPositions=[new Vt.Vector2];_pointerPositionsLastFrame=[new Vt.Vector2];_pointerPositionsDelta=[new Vt.Vector2];_pointerPositionsRC=[new Vt.Vector2];_pointerPositionDown=[new Vt.Vector2];_pointerDownTime=[];_pointerUpTime=[];_pointerIds=[];_pointerTypes=[""];_mouseWheelChanged=[!1];_pointerEvent=[];getKeyDown(){for(let e in this.keysPressed){let t=this.keysPressed[e];if(t.startFrame===this.context.time.frameCount)return t.key}return null}getKeyPressed(){for(let e in this.keysPressed){let t=this.keysPressed[e];if(t.pressed)return t.key}return null}isKeyDown(e){return this.context.application.isVisible&&this.context.application.hasFocus&&this.keysPressed[e]?.startFrame===this.context.time.frameCount&&this.keysPressed[e].pressed}isKeyUp(e){return this.context.application.isVisible&&this.context.application.hasFocus&&this.keysPressed[e]?.frame===this.context.time.frameCount&&!this.keysPressed[e].pressed}isKeyPressed(e){return this.context.application.isVisible&&this.context.application.hasFocus&&this.keysPressed[e]?.pressed}createPointerDown(e){this.onDown(e)}createPointerMove(e){this.onMove(e)}createPointerUp(e){this.onUp(e)}constructor(e){super(),this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame.bind(this));let t=this.context.renderer.domElement;t.addEventListener("touchmove",this.onTouchMove.bind(this),{passive:!0}),t.addEventListener("touchend",this.onTouchUp.bind(this),!1),t.addEventListener("pointerdown",this.onPointerDown.bind(this),!1),t.addEventListener("pointermove",this.onPointerMove.bind(this),!1),t.addEventListener("pointerup",this.onPointerUp.bind(this),!1),t.addEventListener("wheel",this.onMouseWheel.bind(this),{passive:!0}),window.addEventListener("keydown",this.onKeyDown.bind(this),!1),window.addEventListener("keypress",this.onKeyPressed.bind(this),!1),window.addEventListener("keyup",this.onKeyUp.bind(this),!1),window.addEventListener("blur",this.onLostFocus.bind(this))}onLostFocus(){for(let e in this.keysPressed)this.keysPressed[e].pressed=!1}onEndOfFrame(){for(let e=0;e<this._pointerUp.length;e++)this._pointerUp[e]=!1;for(let e=0;e<this._pointerDown.length;e++)this._pointerDown[e]=!1;for(let e=0;e<this._pointerClick.length;e++)this._pointerClick[e]=!1;for(let e=0;e<this._pointerDoubleClick.length;e++)this._pointerDoubleClick[e]=!1;for(let e of this._pointerPositionsDelta)e.set(0,0);for(let e=0;e<this._mouseWheelChanged.length;e++)this._mouseWheelChanged[e]=!1}keysPressed={};onKeyDown(e){if(!this.context.application.hasFocus)return;let t=this.keysPressed[e.keyCode];t&&t.pressed||(this.keysPressed[e.keyCode]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:e.key})}onKeyPressed(e){if(!this.context.application.hasFocus)return;let t=this.keysPressed[e.keyCode];!t||(t.pressed=!0,t.frame=this.context.time.frameCount+1)}onKeyUp(e){if(!this.context.application.hasFocus)return;let t=this.keysPressed[e.keyCode];!t||(t.pressed=!1,t.frame=this.context.time.frameCount+1)}onMouseWheel(e){this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0}onTouchMove(e){}onTouchUp(e){}onPointerDown(e){if(e.defaultPrevented||e.pointerType===void 0&&e.pointerId===void 0)return;e.preventDefault&&e.preventDefault();let t=e.pointerType==="mouse"?e.button:this.getPointerIndex(e.pointerId);e.pointerId===void 0&&e.button!==void 0&&(t=e.button),this.onDown({button:t,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,source:e})}onPointerMove(e,t=void 0){if(e.defaultPrevented||e.pointerType===void 0&&e.pointerId===void 0)return;t!==!0&&e.preventDefault();let i=e.pointerType==="mouse"?e.button:this.getPointerIndex(e.pointerId);e.pointerId===void 0&&e.button!==void 0&&(i=e.button),i<0&&(i=0);let n={button:i,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,source:e};this.onMove(n)}onPointerUp(e,t=void 0){if(e.defaultPrevented||e.pointerType===void 0&&e.pointerId===void 0)return;t!==!0&&e.preventDefault();let i=e.pointerType==="mouse"?e.button:this.getPointerIndex(e.pointerId);e.pointerId===void 0&&e.button!==void 0&&(i=e.button),this._pointerIds[i]=-1,this.onUp({button:i,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,source:e})}isInRect(e){return!0}onDown(e){if(!!this.isInRect(e)){for(this.setPointerState(e.button,this._pointerPressed,!0),this.setPointerState(e.button,this._pointerDown,!0),this.setPointerStateT(e.button,this._pointerEvent,e.source);e.button>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[e.button]=e.pointerType===void 0?"mouse":e.pointerType;e.button>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new Vt.Vector2);this._pointerPositionDown[e.button].set(e.clientX,e.clientY),e.button>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[e.button]=this.context.time.time,this.updatePointerPosition(e),Z.Current=this.context,this.dispatchEvent(new Event("pointerDown"))}}onMove(e){!this.isInRect(e)||(this.updatePointerPosition(e),this.setPointerStateT(e.button,this._pointerEvent,e.source))}onUp(e){if(this.setPointerState(e.button,this._pointerPressed,!1),this.setPointerStateT(e.button,this._pointerEvent,e.source),!this.isInRect(e))return;if(this.setPointerState(e.button,this._pointerUp,!0),this.updatePointerPosition(e),!this._pointerPositionDown[e.button]){console.warn("Received pointer up event without matching down event for button: "+e.button);return}let t=e.clientX-this._pointerPositionDown[e.button].x,i=e.clientY-this._pointerPositionDown[e.button].y;if(e.button>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),Math.abs(t)<5&&Math.abs(i)<5){this.setPointerState(e.button,this._pointerClick,!0);let n=this._pointerUpTime[e.button],r=this.context.time.time-n;r<this._doubleClickTimeThreshold&&r>0&&this.setPointerState(e.button,this._pointerDoubleClick,!0)}this._pointerUpTime[e.button]=this.context.time.time}updatePointerPosition(e){for(;e.button>=this._pointerPositions.length;)this._pointerPositions.push(new Vt.Vector2);for(;e.button>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new Vt.Vector2);for(;e.button>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new Vt.Vector2);let t=this._pointerPositionsLastFrame[e.button];t.copy(this._pointerPositions[e.button]),this._pointerPositionsDelta[e.button].set(e.clientX-t.x,e.clientY-t.y),this._pointerPositions[e.button].x=e.clientX,this._pointerPositions[e.button].y=e.clientY;let i=e.clientX+window.scrollX,n=e.clientY+window.scrollY;for(;e.button>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new Vt.Vector2);this._pointerPositionsRC[e.button].x=(i-this.context.domX)/this.context.domWidth*2-1,this._pointerPositionsRC[e.button].y=-((n-this.context.domY)/this.context.domHeight)*2+1}getPointerIndex(e){for(let t=0;t<this._pointerIds.length;t++)if(this._pointerIds[t]===e)return t;for(let t=0;t<this._pointerIds.length;t++)if(this._pointerIds[t]===-1&&(this._pointerIds[t]=e),this._pointerIds[t]===e)return t;return this._pointerIds.push(e),this._pointerIds.length-1}setPointerState(e,t,i){for(;t.length<=e;)t.push(!1);t[e]=i}setPointerStateT(e,t,i){for(;t.length<=e;)t.push(null);t[e]=i}};var Ot=class{constructor(e=[0,0,0,0,0,0,0,0,0]){this.elements=void 0,this.elements=e}identity(){let e=this.elements;e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1}setZero(){let e=this.elements;e[0]=0,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=0,e[6]=0,e[7]=0,e[8]=0}setTrace(e){let t=this.elements;t[0]=e.x,t[4]=e.y,t[8]=e.z}getTrace(e=new _){let t=this.elements;return e.x=t[0],e.y=t[4],e.z=t[8],e}vmult(e,t=new _){let i=this.elements,n=e.x,r=e.y,s=e.z;return t.x=i[0]*n+i[1]*r+i[2]*s,t.y=i[3]*n+i[4]*r+i[5]*s,t.z=i[6]*n+i[7]*r+i[8]*s,t}smult(e){for(let t=0;t<this.elements.length;t++)this.elements[t]*=e}mmult(e,t=new Ot){let i=this.elements,n=e.elements,r=t.elements,s=i[0],o=i[1],c=i[2],d=i[3],a=i[4],h=i[5],u=i[6],g=i[7],E=i[8],b=n[0],y=n[1],m=n[2],p=n[3],f=n[4],v=n[5],w=n[6],x=n[7],T=n[8];return r[0]=s*b+o*p+c*w,r[1]=s*y+o*f+c*x,r[2]=s*m+o*v+c*T,r[3]=d*b+a*p+h*w,r[4]=d*y+a*f+h*x,r[5]=d*m+a*v+h*T,r[6]=u*b+g*p+E*w,r[7]=u*y+g*f+E*x,r[8]=u*m+g*v+E*T,t}scale(e,t=new Ot){let i=this.elements,n=t.elements;for(let r=0;r!==3;r++)n[3*r+0]=e.x*i[3*r+0],n[3*r+1]=e.y*i[3*r+1],n[3*r+2]=e.z*i[3*r+2];return t}solve(e,t=new _){let r=[],s,o;for(s=0;s<3*4;s++)r.push(0);for(s=0;s<3;s++)for(o=0;o<3;o++)r[s+4*o]=this.elements[s+3*o];r[3+4*0]=e.x,r[3+4*1]=e.y,r[3+4*2]=e.z;let c=3,d=c,a,h=4,u;do{if(s=d-c,r[s+4*s]===0){for(o=s+1;o<d;o++)if(r[s+4*o]!==0){a=h;do u=h-a,r[u+4*s]+=r[u+4*o];while(--a);break}}if(r[s+4*s]!==0)for(o=s+1;o<d;o++){let g=r[s+4*o]/r[s+4*s];a=h;do u=h-a,r[u+4*o]=u<=s?0:r[u+4*o]-r[u+4*s]*g;while(--a)}}while(--c);if(t.z=r[2*4+3]/r[2*4+2],t.y=(r[1*4+3]-r[1*4+2]*t.z)/r[1*4+1],t.x=(r[0*4+3]-r[0*4+2]*t.z-r[0*4+1]*t.y)/r[0*4+0],isNaN(t.x)||isNaN(t.y)||isNaN(t.z)||t.x===1/0||t.y===1/0||t.z===1/0)throw"Could not solve equation! Got x=["+t.toString()+"], b=["+e.toString()+"], A=["+this.toString()+"]";return t}e(e,t,i){if(i===void 0)return this.elements[t+3*e];this.elements[t+3*e]=i}copy(e){for(let t=0;t<e.elements.length;t++)this.elements[t]=e.elements[t];return this}toString(){let e="",t=",";for(let i=0;i<9;i++)e+=this.elements[i]+t;return e}reverse(e=new Ot){let n=$f,r,s;for(r=0;r<3;r++)for(s=0;s<3;s++)n[r+6*s]=this.elements[r+3*s];n[3+6*0]=1,n[3+6*1]=0,n[3+6*2]=0,n[4+6*0]=0,n[4+6*1]=1,n[4+6*2]=0,n[5+6*0]=0,n[5+6*1]=0,n[5+6*2]=1;let o=3,c=o,d,a=6,h;do{if(r=c-o,n[r+6*r]===0){for(s=r+1;s<c;s++)if(n[r+6*s]!==0){d=a;do h=a-d,n[h+6*r]+=n[h+6*s];while(--d);break}}if(n[r+6*r]!==0)for(s=r+1;s<c;s++){let u=n[r+6*s]/n[r+6*r];d=a;do h=a-d,n[h+6*s]=h<=r?0:n[h+6*s]-n[h+6*r]*u;while(--d)}}while(--o);r=2;do{s=r-1;do{let u=n[r+6*s]/n[r+6*r];d=6;do h=6-d,n[h+6*s]=n[h+6*s]-n[h+6*r]*u;while(--d)}while(s--)}while(--r);r=2;do{let u=1/n[r+6*r];d=6;do h=6-d,n[h+6*r]=n[h+6*r]*u;while(--d)}while(r--);r=2;do{s=2;do{if(h=n[3+s+6*r],isNaN(h)||h===1/0)throw"Could not reverse! A=["+this.toString()+"]";e.e(r,s,h)}while(s--)}while(r--);return e}setRotationFromQuaternion(e){let t=e.x,i=e.y,n=e.z,r=e.w,s=t+t,o=i+i,c=n+n,d=t*s,a=t*o,h=t*c,u=i*o,g=i*c,E=n*c,b=r*s,y=r*o,m=r*c,p=this.elements;return p[3*0+0]=1-(u+E),p[3*0+1]=a-m,p[3*0+2]=h+y,p[3*1+0]=a+m,p[3*1+1]=1-(d+E),p[3*1+2]=g-b,p[3*2+0]=h-y,p[3*2+1]=g+b,p[3*2+2]=1-(d+u),this}transpose(e=new Ot){let t=this.elements,i=e.elements,n;return i[0]=t[0],i[4]=t[4],i[8]=t[8],n=t[1],i[1]=t[3],i[3]=n,n=t[2],i[2]=t[6],i[6]=n,n=t[5],i[5]=t[7],i[7]=n,e}},$f=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],_=class{constructor(e=0,t=0,i=0){this.x=void 0,this.y=void 0,this.z=void 0,this.x=e,this.y=t,this.z=i}cross(e,t=new _){let i=e.x,n=e.y,r=e.z,s=this.x,o=this.y,c=this.z;return t.x=o*r-c*n,t.y=c*i-s*r,t.z=s*n-o*i,t}set(e,t,i){return this.x=e,this.y=t,this.z=i,this}setZero(){this.x=this.y=this.z=0}vadd(e,t){if(t)t.x=e.x+this.x,t.y=e.y+this.y,t.z=e.z+this.z;else return new _(this.x+e.x,this.y+e.y,this.z+e.z)}vsub(e,t){if(t)t.x=this.x-e.x,t.y=this.y-e.y,t.z=this.z-e.z;else return new _(this.x-e.x,this.y-e.y,this.z-e.z)}crossmat(){return new Ot([0,-this.z,this.y,this.z,0,-this.x,-this.y,this.x,0])}normalize(){let e=this.x,t=this.y,i=this.z,n=Math.sqrt(e*e+t*t+i*i);if(n>0){let r=1/n;this.x*=r,this.y*=r,this.z*=r}else this.x=0,this.y=0,this.z=0;return n}unit(e=new _){let t=this.x,i=this.y,n=this.z,r=Math.sqrt(t*t+i*i+n*n);return r>0?(r=1/r,e.x=t*r,e.y=i*r,e.z=n*r):(e.x=1,e.y=0,e.z=0),e}length(){let e=this.x,t=this.y,i=this.z;return Math.sqrt(e*e+t*t+i*i)}lengthSquared(){return this.dot(this)}distanceTo(e){let t=this.x,i=this.y,n=this.z,r=e.x,s=e.y,o=e.z;return Math.sqrt((r-t)*(r-t)+(s-i)*(s-i)+(o-n)*(o-n))}distanceSquared(e){let t=this.x,i=this.y,n=this.z,r=e.x,s=e.y,o=e.z;return(r-t)*(r-t)+(s-i)*(s-i)+(o-n)*(o-n)}scale(e,t=new _){let i=this.x,n=this.y,r=this.z;return t.x=e*i,t.y=e*n,t.z=e*r,t}vmul(e,t=new _){return t.x=e.x*this.x,t.y=e.y*this.y,t.z=e.z*this.z,t}addScaledVector(e,t,i=new _){return i.x=this.x+e*t.x,i.y=this.y+e*t.y,i.z=this.z+e*t.z,i}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}isZero(){return this.x===0&&this.y===0&&this.z===0}negate(e=new _){return e.x=-this.x,e.y=-this.y,e.z=-this.z,e}tangents(e,t){let i=this.length();if(i>0){let n=Kf,r=1/i;n.set(this.x*r,this.y*r,this.z*r);let s=em;Math.abs(n.x)<.9?(s.set(1,0,0),n.cross(s,e)):(s.set(0,1,0),n.cross(s,e)),n.cross(e,t)}else e.set(1,0,0),t.set(0,1,0)}toString(){return this.x+","+this.y+","+this.z}toArray(){return[this.x,this.y,this.z]}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}lerp(e,t,i){let n=this.x,r=this.y,s=this.z;i.x=n+(e.x-n)*t,i.y=r+(e.y-r)*t,i.z=s+(e.z-s)*t}almostEquals(e,t=1e-6){return!(Math.abs(this.x-e.x)>t||Math.abs(this.y-e.y)>t||Math.abs(this.z-e.z)>t)}almostZero(e=1e-6){return!(Math.abs(this.x)>e||Math.abs(this.y)>e||Math.abs(this.z)>e)}isAntiparallelTo(e,t){return this.negate(Dh),Dh.almostEquals(e,t)}clone(){return new _(this.x,this.y,this.z)}};_.ZERO=void 0;_.UNIT_X=void 0;_.UNIT_Y=void 0;_.UNIT_Z=void 0;_.ZERO=new _(0,0,0);_.UNIT_X=new _(1,0,0);_.UNIT_Y=new _(0,1,0);_.UNIT_Z=new _(0,0,1);var Kf=new _,em=new _,Dh=new _,$e=class{constructor(e={}){this.lowerBound=void 0,this.upperBound=void 0,this.lowerBound=new _,this.upperBound=new _,e.lowerBound&&this.lowerBound.copy(e.lowerBound),e.upperBound&&this.upperBound.copy(e.upperBound)}setFromPoints(e,t,i,n){let r=this.lowerBound,s=this.upperBound,o=i;r.copy(e[0]),o&&o.vmult(r,r),s.copy(r);for(let c=1;c<e.length;c++){let d=e[c];o&&(o.vmult(d,Hh),d=Hh),d.x>s.x&&(s.x=d.x),d.x<r.x&&(r.x=d.x),d.y>s.y&&(s.y=d.y),d.y<r.y&&(r.y=d.y),d.z>s.z&&(s.z=d.z),d.z<r.z&&(r.z=d.z)}return t&&(t.vadd(r,r),t.vadd(s,s)),n&&(r.x-=n,r.y-=n,r.z-=n,s.x+=n,s.y+=n,s.z+=n),this}copy(e){return this.lowerBound.copy(e.lowerBound),this.upperBound.copy(e.upperBound),this}clone(){return new $e().copy(this)}extend(e){this.lowerBound.x=Math.min(this.lowerBound.x,e.lowerBound.x),this.upperBound.x=Math.max(this.upperBound.x,e.upperBound.x),this.lowerBound.y=Math.min(this.lowerBound.y,e.lowerBound.y),this.upperBound.y=Math.max(this.upperBound.y,e.upperBound.y),this.lowerBound.z=Math.min(this.lowerBound.z,e.lowerBound.z),this.upperBound.z=Math.max(this.upperBound.z,e.upperBound.z)}overlaps(e){let t=this.lowerBound,i=this.upperBound,n=e.lowerBound,r=e.upperBound,s=n.x<=i.x&&i.x<=r.x||t.x<=r.x&&r.x<=i.x,o=n.y<=i.y&&i.y<=r.y||t.y<=r.y&&r.y<=i.y,c=n.z<=i.z&&i.z<=r.z||t.z<=r.z&&r.z<=i.z;return s&&o&&c}volume(){let e=this.lowerBound,t=this.upperBound;return(t.x-e.x)*(t.y-e.y)*(t.z-e.z)}contains(e){let t=this.lowerBound,i=this.upperBound,n=e.lowerBound,r=e.upperBound;return t.x<=n.x&&i.x>=r.x&&t.y<=n.y&&i.y>=r.y&&t.z<=n.z&&i.z>=r.z}getCorners(e,t,i,n,r,s,o,c){let d=this.lowerBound,a=this.upperBound;e.copy(d),t.set(a.x,d.y,d.z),i.set(a.x,a.y,d.z),n.set(d.x,a.y,a.z),r.set(a.x,d.y,a.z),s.set(d.x,a.y,d.z),o.set(d.x,d.y,a.z),c.copy(a)}toLocalFrame(e,t){let i=jh,n=i[0],r=i[1],s=i[2],o=i[3],c=i[4],d=i[5],a=i[6],h=i[7];this.getCorners(n,r,s,o,c,d,a,h);for(let u=0;u!==8;u++){let g=i[u];e.pointToLocal(g,g)}return t.setFromPoints(i)}toWorldFrame(e,t){let i=jh,n=i[0],r=i[1],s=i[2],o=i[3],c=i[4],d=i[5],a=i[6],h=i[7];this.getCorners(n,r,s,o,c,d,a,h);for(let u=0;u!==8;u++){let g=i[u];e.pointToWorld(g,g)}return t.setFromPoints(i)}overlapsRay(e){let{direction:t,from:i}=e,n=1/t.x,r=1/t.y,s=1/t.z,o=(this.lowerBound.x-i.x)*n,c=(this.upperBound.x-i.x)*n,d=(this.lowerBound.y-i.y)*r,a=(this.upperBound.y-i.y)*r,h=(this.lowerBound.z-i.z)*s,u=(this.upperBound.z-i.z)*s,g=Math.max(Math.max(Math.min(o,c),Math.min(d,a)),Math.min(h,u)),E=Math.min(Math.min(Math.max(o,c),Math.max(d,a)),Math.max(h,u));return!(E<0||g>E)}},Hh=new _,jh=[new _,new _,new _,new _,new _,new _,new _,new _],Jo=class{constructor(){this.matrix=void 0,this.matrix=[]}get(e,t){let{index:i}=e,{index:n}=t;if(n>i){let r=n;n=i,i=r}return this.matrix[(i*(i+1)>>1)+n-1]}set(e,t,i){let{index:n}=e,{index:r}=t;if(r>n){let s=r;r=n,n=s}this.matrix[(n*(n+1)>>1)+r-1]=i?1:0}reset(){for(let e=0,t=this.matrix.length;e!==t;e++)this.matrix[e]=0}setNumObjects(e){this.matrix.length=e*(e-1)>>1}},$o=class{constructor(){this._listeners=void 0}addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let i=this._listeners;return i[e]===void 0&&(i[e]=[]),i[e].includes(t)||i[e].push(t),this}hasEventListener(e,t){if(this._listeners===void 0)return!1;let i=this._listeners;return!!(i[e]!==void 0&&i[e].includes(t))}hasAnyEventListener(e){return this._listeners===void 0?!1:this._listeners[e]!==void 0}removeEventListener(e,t){if(this._listeners===void 0)return this;let i=this._listeners;if(i[e]===void 0)return this;let n=i[e].indexOf(t);return n!==-1&&i[e].splice(n,1),this}dispatchEvent(e){if(this._listeners===void 0)return this;let i=this._listeners[e.type];if(i!==void 0){e.target=this;for(let n=0,r=i.length;n<r;n++)i[n].call(this,e)}return this}},le=class{constructor(e=0,t=0,i=0,n=1){this.x=void 0,this.y=void 0,this.z=void 0,this.w=void 0,this.x=e,this.y=t,this.z=i,this.w=n}set(e,t,i,n){return this.x=e,this.y=t,this.z=i,this.w=n,this}toString(){return this.x+","+this.y+","+this.z+","+this.w}toArray(){return[this.x,this.y,this.z,this.w]}setFromAxisAngle(e,t){let i=Math.sin(t*.5);return this.x=e.x*i,this.y=e.y*i,this.z=e.z*i,this.w=Math.cos(t*.5),this}toAxisAngle(e=new _){this.normalize();let t=2*Math.acos(this.w),i=Math.sqrt(1-this.w*this.w);return i<.001?(e.x=this.x,e.y=this.y,e.z=this.z):(e.x=this.x/i,e.y=this.y/i,e.z=this.z/i),[e,t]}setFromVectors(e,t){if(e.isAntiparallelTo(t)){let i=tm,n=im;e.tangents(i,n),this.setFromAxisAngle(i,Math.PI)}else{let i=e.cross(t);this.x=i.x,this.y=i.y,this.z=i.z,this.w=Math.sqrt(e.length()**2*t.length()**2)+e.dot(t),this.normalize()}return this}mult(e,t=new le){let i=this.x,n=this.y,r=this.z,s=this.w,o=e.x,c=e.y,d=e.z,a=e.w;return t.x=i*a+s*o+n*d-r*c,t.y=n*a+s*c+r*o-i*d,t.z=r*a+s*d+i*c-n*o,t.w=s*a-i*o-n*c-r*d,t}inverse(e=new le){let t=this.x,i=this.y,n=this.z,r=this.w;this.conjugate(e);let s=1/(t*t+i*i+n*n+r*r);return e.x*=s,e.y*=s,e.z*=s,e.w*=s,e}conjugate(e=new le){return e.x=-this.x,e.y=-this.y,e.z=-this.z,e.w=this.w,e}normalize(){let e=Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w);return e===0?(this.x=0,this.y=0,this.z=0,this.w=0):(e=1/e,this.x*=e,this.y*=e,this.z*=e,this.w*=e),this}normalizeFast(){let e=(3-(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w))/2;return e===0?(this.x=0,this.y=0,this.z=0,this.w=0):(this.x*=e,this.y*=e,this.z*=e,this.w*=e),this}vmult(e,t=new _){let i=e.x,n=e.y,r=e.z,s=this.x,o=this.y,c=this.z,d=this.w,a=d*i+o*r-c*n,h=d*n+c*i-s*r,u=d*r+s*n-o*i,g=-s*i-o*n-c*r;return t.x=a*d+g*-s+h*-c-u*-o,t.y=h*d+g*-o+u*-s-a*-c,t.z=u*d+g*-c+a*-o-h*-s,t}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}toEuler(e,t="YZX"){let i,n,r,s=this.x,o=this.y,c=this.z,d=this.w;switch(t){case"YZX":let a=s*o+c*d;if(a>.499&&(i=2*Math.atan2(s,d),n=Math.PI/2,r=0),a<-.499&&(i=-2*Math.atan2(s,d),n=-Math.PI/2,r=0),i===void 0){let h=s*s,u=o*o,g=c*c;i=Math.atan2(2*o*d-2*s*c,1-2*u-2*g),n=Math.asin(2*a),r=Math.atan2(2*s*d-2*o*c,1-2*h-2*g)}break;default:throw new Error("Euler order "+t+" not supported yet.")}e.y=i,e.z=n,e.x=r}setFromEuler(e,t,i,n="XYZ"){let r=Math.cos(e/2),s=Math.cos(t/2),o=Math.cos(i/2),c=Math.sin(e/2),d=Math.sin(t/2),a=Math.sin(i/2);return n==="XYZ"?(this.x=c*s*o+r*d*a,this.y=r*d*o-c*s*a,this.z=r*s*a+c*d*o,this.w=r*s*o-c*d*a):n==="YXZ"?(this.x=c*s*o+r*d*a,this.y=r*d*o-c*s*a,this.z=r*s*a-c*d*o,this.w=r*s*o+c*d*a):n==="ZXY"?(this.x=c*s*o-r*d*a,this.y=r*d*o+c*s*a,this.z=r*s*a+c*d*o,this.w=r*s*o-c*d*a):n==="ZYX"?(this.x=c*s*o-r*d*a,this.y=r*d*o+c*s*a,this.z=r*s*a-c*d*o,this.w=r*s*o+c*d*a):n==="YZX"?(this.x=c*s*o+r*d*a,this.y=r*d*o+c*s*a,this.z=r*s*a-c*d*o,this.w=r*s*o-c*d*a):n==="XZY"&&(this.x=c*s*o-r*d*a,this.y=r*d*o-c*s*a,this.z=r*s*a+c*d*o,this.w=r*s*o+c*d*a),this}clone(){return new le(this.x,this.y,this.z,this.w)}slerp(e,t,i=new le){let n=this.x,r=this.y,s=this.z,o=this.w,c=e.x,d=e.y,a=e.z,h=e.w,u,g,E,b,y;return g=n*c+r*d+s*a+o*h,g<0&&(g=-g,c=-c,d=-d,a=-a,h=-h),1-g>1e-6?(u=Math.acos(g),E=Math.sin(u),b=Math.sin((1-t)*u)/E,y=Math.sin(t*u)/E):(b=1-t,y=t),i.x=b*n+y*c,i.y=b*r+y*d,i.z=b*s+y*a,i.w=b*o+y*h,i}integrate(e,t,i,n=new le){let r=e.x*i.x,s=e.y*i.y,o=e.z*i.z,c=this.x,d=this.y,a=this.z,h=this.w,u=t*.5;return n.x+=u*(r*h+s*a-o*d),n.y+=u*(s*h+o*c-r*a),n.z+=u*(o*h+r*d-s*c),n.w+=u*(-r*c-s*d-o*a),n}},tm=new _,im=new _,nm={SPHERE:1,PLANE:2,BOX:4,COMPOUND:8,CONVEXPOLYHEDRON:16,HEIGHTFIELD:32,PARTICLE:64,CYLINDER:128,TRIMESH:256},V=class{constructor(e={}){this.id=void 0,this.type=void 0,this.boundingSphereRadius=void 0,this.collisionResponse=void 0,this.collisionFilterGroup=void 0,this.collisionFilterMask=void 0,this.material=void 0,this.body=void 0,this.id=V.idCounter++,this.type=e.type||0,this.boundingSphereRadius=0,this.collisionResponse=e.collisionResponse?e.collisionResponse:!0,this.collisionFilterGroup=e.collisionFilterGroup!==void 0?e.collisionFilterGroup:1,this.collisionFilterMask=e.collisionFilterMask!==void 0?e.collisionFilterMask:-1,this.material=e.material?e.material:null,this.body=null}updateBoundingSphereRadius(){throw"computeBoundingSphereRadius() not implemented for shape type "+this.type}volume(){throw"volume() not implemented for shape type "+this.type}calculateLocalInertia(e,t){throw"calculateLocalInertia() not implemented for shape type "+this.type}calculateWorldAABB(e,t,i,n){throw"calculateWorldAABB() not implemented for shape type "+this.type}};V.idCounter=0;V.types=nm;var te=class{constructor(e={}){this.position=void 0,this.quaternion=void 0,this.position=new _,this.quaternion=new le,e.position&&this.position.copy(e.position),e.quaternion&&this.quaternion.copy(e.quaternion)}pointToLocal(e,t){return te.pointToLocalFrame(this.position,this.quaternion,e,t)}pointToWorld(e,t){return te.pointToWorldFrame(this.position,this.quaternion,e,t)}vectorToWorldFrame(e,t=new _){return this.quaternion.vmult(e,t),t}static pointToLocalFrame(e,t,i,n=new _){return i.vsub(e,n),t.conjugate(Bh),Bh.vmult(n,n),n}static pointToWorldFrame(e,t,i,n=new _){return t.vmult(i,n),n.vadd(e,n),n}static vectorToWorldFrame(e,t,i=new _){return e.vmult(t,i),i}static vectorToLocalFrame(e,t,i,n=new _){return t.w*=-1,t.vmult(i,n),t.w*=-1,n}},Bh=new le,Qn=class extends V{constructor(e={}){let{vertices:t=[],faces:i=[],normals:n=[],axes:r,boundingSphereRadius:s}=e;super({type:V.types.CONVEXPOLYHEDRON}),this.vertices=void 0,this.faces=void 0,this.faceNormals=void 0,this.worldVertices=void 0,this.worldVerticesNeedsUpdate=void 0,this.worldFaceNormals=void 0,this.worldFaceNormalsNeedsUpdate=void 0,this.uniqueAxes=void 0,this.uniqueEdges=void 0,this.vertices=t,this.faces=i,this.faceNormals=n,this.faceNormals.length===0&&this.computeNormals(),s?this.boundingSphereRadius=s:this.updateBoundingSphereRadius(),this.worldVertices=[],this.worldVerticesNeedsUpdate=!0,this.worldFaceNormals=[],this.worldFaceNormalsNeedsUpdate=!0,this.uniqueAxes=r?r.slice():null,this.uniqueEdges=[],this.computeEdges()}computeEdges(){let e=this.faces,t=this.vertices,i=this.uniqueEdges;i.length=0;let n=new _;for(let r=0;r!==e.length;r++){let s=e[r],o=s.length;for(let c=0;c!==o;c++){let d=(c+1)%o;t[s[c]].vsub(t[s[d]],n),n.normalize();let a=!1;for(let h=0;h!==i.length;h++)if(i[h].almostEquals(n)||i[h].almostEquals(n)){a=!0;break}a||i.push(n.clone())}}}computeNormals(){this.faceNormals.length=this.faces.length;for(let e=0;e<this.faces.length;e++){for(let n=0;n<this.faces[e].length;n++)if(!this.vertices[this.faces[e][n]])throw new Error("Vertex "+this.faces[e][n]+" not found!");let t=this.faceNormals[e]||new _;this.getFaceNormal(e,t),t.negate(t),this.faceNormals[e]=t;let i=this.vertices[this.faces[e][0]];if(t.dot(i)<0){console.error(".faceNormals["+e+"] = Vec3("+t.toString()+") looks like it points into the shape? The vertices follow. Make sure they are ordered CCW around the normal, using the right hand rule.");for(let n=0;n<this.faces[e].length;n++)console.warn(".vertices["+this.faces[e][n]+"] = Vec3("+this.vertices[this.faces[e][n]].toString()+")")}}}getFaceNormal(e,t){let i=this.faces[e],n=this.vertices[i[0]],r=this.vertices[i[1]],s=this.vertices[i[2]];Qn.computeNormal(n,r,s,t)}static computeNormal(e,t,i,n){let r=new _,s=new _;t.vsub(e,s),i.vsub(t,r),r.cross(s,n),n.isZero()||n.normalize()}clipAgainstHull(e,t,i,n,r,s,o,c,d){let a=new _,h=-1,u=-Number.MAX_VALUE;for(let E=0;E<i.faces.length;E++){a.copy(i.faceNormals[E]),r.vmult(a,a);let b=a.dot(s);b>u&&(u=b,h=E)}let g=[];for(let E=0;E<i.faces[h].length;E++){let b=i.vertices[i.faces[h][E]],y=new _;y.copy(b),r.vmult(y,y),n.vadd(y,y),g.push(y)}h>=0&&this.clipFaceAgainstHull(s,e,t,g,o,c,d)}findSeparatingAxis(e,t,i,n,r,s,o,c){let d=new _,a=new _,h=new _,u=new _,g=new _,E=new _,b=Number.MAX_VALUE,y=this;if(y.uniqueAxes)for(let m=0;m!==y.uniqueAxes.length;m++){i.vmult(y.uniqueAxes[m],d);let p=y.testSepAxis(d,e,t,i,n,r);if(p===!1)return!1;p<b&&(b=p,s.copy(d))}else{let m=o?o.length:y.faces.length;for(let p=0;p<m;p++){let f=o?o[p]:p;d.copy(y.faceNormals[f]),i.vmult(d,d);let v=y.testSepAxis(d,e,t,i,n,r);if(v===!1)return!1;v<b&&(b=v,s.copy(d))}}if(e.uniqueAxes)for(let m=0;m!==e.uniqueAxes.length;m++){r.vmult(e.uniqueAxes[m],a);let p=y.testSepAxis(a,e,t,i,n,r);if(p===!1)return!1;p<b&&(b=p,s.copy(a))}else{let m=c?c.length:e.faces.length;for(let p=0;p<m;p++){let f=c?c[p]:p;a.copy(e.faceNormals[f]),r.vmult(a,a);let v=y.testSepAxis(a,e,t,i,n,r);if(v===!1)return!1;v<b&&(b=v,s.copy(a))}}for(let m=0;m!==y.uniqueEdges.length;m++){i.vmult(y.uniqueEdges[m],u);for(let p=0;p!==e.uniqueEdges.length;p++)if(r.vmult(e.uniqueEdges[p],g),u.cross(g,E),!E.almostZero()){E.normalize();let f=y.testSepAxis(E,e,t,i,n,r);if(f===!1)return!1;f<b&&(b=f,s.copy(E))}}return n.vsub(t,h),h.dot(s)>0&&s.negate(s),!0}testSepAxis(e,t,i,n,r,s){let o=this;Qn.project(o,e,i,n,jl),Qn.project(t,e,r,s,Bl);let c=jl[0],d=jl[1],a=Bl[0],h=Bl[1];if(c<h||a<d)return!1;let u=c-h,g=a-d;return u<g?u:g}calculateLocalInertia(e,t){let i=new _,n=new _;this.computeLocalAABB(n,i);let r=i.x-n.x,s=i.y-n.y,o=i.z-n.z;t.x=1/12*e*(2*s*2*s+2*o*2*o),t.y=1/12*e*(2*r*2*r+2*o*2*o),t.z=1/12*e*(2*s*2*s+2*r*2*r)}getPlaneConstantOfFace(e){let t=this.faces[e],i=this.faceNormals[e],n=this.vertices[t[0]];return-i.dot(n)}clipFaceAgainstHull(e,t,i,n,r,s,o){let c=new _,d=new _,a=new _,h=new _,u=new _,g=new _,E=new _,b=new _,y=this,m=[],p=n,f=m,v=-1,w=Number.MAX_VALUE;for(let P=0;P<y.faces.length;P++){c.copy(y.faceNormals[P]),i.vmult(c,c);let S=c.dot(e);S<w&&(w=S,v=P)}if(v<0)return;let x=y.faces[v];x.connectedFaces=[];for(let P=0;P<y.faces.length;P++)for(let S=0;S<y.faces[P].length;S++)x.indexOf(y.faces[P][S])!==-1&&P!==v&&x.connectedFaces.indexOf(P)===-1&&x.connectedFaces.push(P);let T=x.length;for(let P=0;P<T;P++){let S=y.vertices[x[P]],L=y.vertices[x[(P+1)%T]];S.vsub(L,d),a.copy(d),i.vmult(a,a),t.vadd(a,a),h.copy(this.faceNormals[v]),i.vmult(h,h),t.vadd(h,h),a.cross(h,u),u.negate(u),g.copy(S),i.vmult(g,g),t.vadd(g,g);let I=x.connectedFaces[P];E.copy(this.faceNormals[I]);let j=this.getPlaneConstantOfFace(I);b.copy(E),i.vmult(b,b);let H=j-b.dot(t);for(this.clipFaceAgainstPlane(p,f,b,H);p.length;)p.shift();for(;f.length;)p.push(f.shift())}E.copy(this.faceNormals[v]);let R=this.getPlaneConstantOfFace(v);b.copy(E),i.vmult(b,b);let C=R-b.dot(t);for(let P=0;P<p.length;P++){let S=b.dot(p[P])+C;if(S<=r&&(console.log("clamped: depth="+S+" to minDist="+r),S=r),S<=s){let L=p[P];if(S<=1e-6){let I={point:L,normal:b,depth:S};o.push(I)}}}}clipFaceAgainstPlane(e,t,i,n){let r,s,o=e.length;if(o<2)return t;let c=e[e.length-1],d=e[0];r=i.dot(c)+n;for(let a=0;a<o;a++){if(d=e[a],s=i.dot(d)+n,r<0)if(s<0){let h=new _;h.copy(d),t.push(h)}else{let h=new _;c.lerp(d,r/(r-s),h),t.push(h)}else if(s<0){let h=new _;c.lerp(d,r/(r-s),h),t.push(h),t.push(d)}c=d,r=s}return t}computeWorldVertices(e,t){for(;this.worldVertices.length<this.vertices.length;)this.worldVertices.push(new _);let i=this.vertices,n=this.worldVertices;for(let r=0;r!==this.vertices.length;r++)t.vmult(i[r],n[r]),e.vadd(n[r],n[r]);this.worldVerticesNeedsUpdate=!1}computeLocalAABB(e,t){let i=this.vertices;e.set(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),t.set(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let n=0;n<this.vertices.length;n++){let r=i[n];r.x<e.x?e.x=r.x:r.x>t.x&&(t.x=r.x),r.y<e.y?e.y=r.y:r.y>t.y&&(t.y=r.y),r.z<e.z?e.z=r.z:r.z>t.z&&(t.z=r.z)}}computeWorldFaceNormals(e){let t=this.faceNormals.length;for(;this.worldFaceNormals.length<t;)this.worldFaceNormals.push(new _);let i=this.faceNormals,n=this.worldFaceNormals;for(let r=0;r!==t;r++)e.vmult(i[r],n[r]);this.worldFaceNormalsNeedsUpdate=!1}updateBoundingSphereRadius(){let e=0,t=this.vertices;for(let i=0;i!==t.length;i++){let n=t[i].lengthSquared();n>e&&(e=n)}this.boundingSphereRadius=Math.sqrt(e)}calculateWorldAABB(e,t,i,n){let r=this.vertices,s,o,c,d,a,h,u=new _;for(let g=0;g<r.length;g++){u.copy(r[g]),t.vmult(u,u),e.vadd(u,u);let E=u;(s===void 0||E.x<s)&&(s=E.x),(d===void 0||E.x>d)&&(d=E.x),(o===void 0||E.y<o)&&(o=E.y),(a===void 0||E.y>a)&&(a=E.y),(c===void 0||E.z<c)&&(c=E.z),(h===void 0||E.z>h)&&(h=E.z)}i.set(s,o,c),n.set(d,a,h)}volume(){return 4*Math.PI*this.boundingSphereRadius/3}getAveragePointLocal(e=new _){let t=this.vertices;for(let i=0;i<t.length;i++)e.vadd(t[i],e);return e.scale(1/t.length,e),e}transformAllPoints(e,t){let i=this.vertices.length,n=this.vertices;if(t){for(let r=0;r<i;r++){let s=n[r];t.vmult(s,s)}for(let r=0;r<this.faceNormals.length;r++){let s=this.faceNormals[r];t.vmult(s,s)}}if(e)for(let r=0;r<i;r++){let s=n[r];s.vadd(e,s)}}pointIsInside(e){let t=this.vertices,i=this.faces,n=this.faceNormals,r=new _;this.getAveragePointLocal(r);for(let s=0;s<this.faces.length;s++){let o=n[s],c=t[i[s][0]],d=new _;e.vsub(c,d);let a=o.dot(d),h=new _;r.vsub(c,h);let u=o.dot(h);if(a<0&&u>0||a>0&&u<0)return!1}return-1}static project(e,t,i,n,r){let s=e.vertices.length,o=rm,c=0,d=0,a=sm,h=e.vertices;a.setZero(),te.vectorToLocalFrame(i,n,t,o),te.pointToLocalFrame(i,n,a,a);let u=a.dot(o);d=c=h[0].dot(o);for(let g=1;g<s;g++){let E=h[g].dot(o);E>c&&(c=E),E<d&&(d=E)}if(d-=u,c-=u,d>c){let g=d;d=c,c=g}r[0]=c,r[1]=d}},jl=[],Bl=[],rm=new _,sm=new _,Yn=class extends V{constructor(e){super({type:V.types.BOX}),this.halfExtents=void 0,this.convexPolyhedronRepresentation=void 0,this.halfExtents=e,this.convexPolyhedronRepresentation=null,this.updateConvexPolyhedronRepresentation(),this.updateBoundingSphereRadius()}updateConvexPolyhedronRepresentation(){let e=this.halfExtents.x,t=this.halfExtents.y,i=this.halfExtents.z,n=_,r=[new n(-e,-t,-i),new n(e,-t,-i),new n(e,t,-i),new n(-e,t,-i),new n(-e,-t,i),new n(e,-t,i),new n(e,t,i),new n(-e,t,i)],s=[[3,2,1,0],[4,5,6,7],[5,4,0,1],[2,3,7,6],[0,4,7,3],[1,2,6,5]],o=[new n(0,0,1),new n(0,1,0),new n(1,0,0)],c=new Qn({vertices:r,faces:s,axes:o});this.convexPolyhedronRepresentation=c,c.material=this.material}calculateLocalInertia(e,t=new _){return Yn.calculateInertia(this.halfExtents,e,t),t}static calculateInertia(e,t,i){let n=e;i.x=1/12*t*(2*n.y*2*n.y+2*n.z*2*n.z),i.y=1/12*t*(2*n.x*2*n.x+2*n.z*2*n.z),i.z=1/12*t*(2*n.y*2*n.y+2*n.x*2*n.x)}getSideNormals(e,t){let i=e,n=this.halfExtents;if(i[0].set(n.x,0,0),i[1].set(0,n.y,0),i[2].set(0,0,n.z),i[3].set(-n.x,0,0),i[4].set(0,-n.y,0),i[5].set(0,0,-n.z),t!==void 0)for(let r=0;r!==i.length;r++)t.vmult(i[r],i[r]);return i}volume(){return 8*this.halfExtents.x*this.halfExtents.y*this.halfExtents.z}updateBoundingSphereRadius(){this.boundingSphereRadius=this.halfExtents.length()}forEachWorldCorner(e,t,i){let n=this.halfExtents,r=[[n.x,n.y,n.z],[-n.x,n.y,n.z],[-n.x,-n.y,n.z],[-n.x,-n.y,-n.z],[n.x,-n.y,-n.z],[n.x,n.y,-n.z],[-n.x,n.y,-n.z],[n.x,-n.y,n.z]];for(let s=0;s<r.length;s++)fn.set(r[s][0],r[s][1],r[s][2]),t.vmult(fn,fn),e.vadd(fn,fn),i(fn.x,fn.y,fn.z)}calculateWorldAABB(e,t,i,n){let r=this.halfExtents;ri[0].set(r.x,r.y,r.z),ri[1].set(-r.x,r.y,r.z),ri[2].set(-r.x,-r.y,r.z),ri[3].set(-r.x,-r.y,-r.z),ri[4].set(r.x,-r.y,-r.z),ri[5].set(r.x,r.y,-r.z),ri[6].set(-r.x,r.y,-r.z),ri[7].set(r.x,-r.y,r.z);let s=ri[0];t.vmult(s,s),e.vadd(s,s),n.copy(s),i.copy(s);for(let o=1;o<8;o++){let c=ri[o];t.vmult(c,c),e.vadd(c,c);let d=c.x,a=c.y,h=c.z;d>n.x&&(n.x=d),a>n.y&&(n.y=a),h>n.z&&(n.z=h),d<i.x&&(i.x=d),a<i.y&&(i.y=a),h<i.z&&(i.z=h)}}},fn=new _,ri=[new _,new _,new _,new _,new _,new _,new _,new _],Jl={DYNAMIC:1,STATIC:2,KINEMATIC:4},$l={AWAKE:0,SLEEPY:1,SLEEPING:2},G=class extends $o{constructor(e={}){super(),this.id=void 0,this.index=void 0,this.world=void 0,this.preStep=void 0,this.postStep=void 0,this.vlambda=void 0,this.collisionFilterGroup=void 0,this.collisionFilterMask=void 0,this.collisionResponse=void 0,this.position=void 0,this.previousPosition=void 0,this.interpolatedPosition=void 0,this.initPosition=void 0,this.velocity=void 0,this.initVelocity=void 0,this.force=void 0,this.mass=void 0,this.invMass=void 0,this.material=void 0,this.linearDamping=void 0,this.type=void 0,this.allowSleep=void 0,this.sleepState=void 0,this.sleepSpeedLimit=void 0,this.sleepTimeLimit=void 0,this.timeLastSleepy=void 0,this.wakeUpAfterNarrowphase=void 0,this.torque=void 0,this.quaternion=void 0,this.initQuaternion=void 0,this.previousQuaternion=void 0,this.interpolatedQuaternion=void 0,this.angularVelocity=void 0,this.initAngularVelocity=void 0,this.shapes=void 0,this.shapeOffsets=void 0,this.shapeOrientations=void 0,this.inertia=void 0,this.invInertia=void 0,this.invInertiaWorld=void 0,this.invMassSolve=void 0,this.invInertiaSolve=void 0,this.invInertiaWorldSolve=void 0,this.fixedRotation=void 0,this.angularDamping=void 0,this.linearFactor=void 0,this.angularFactor=void 0,this.aabb=void 0,this.aabbNeedsUpdate=void 0,this.boundingRadius=void 0,this.wlambda=void 0,this.isTrigger=void 0,this.id=G.idCounter++,this.index=-1,this.world=null,this.preStep=null,this.postStep=null,this.vlambda=new _,this.collisionFilterGroup=typeof e.collisionFilterGroup=="number"?e.collisionFilterGroup:1,this.collisionFilterMask=typeof e.collisionFilterMask=="number"?e.collisionFilterMask:-1,this.collisionResponse=typeof e.collisionResponse=="boolean"?e.collisionResponse:!0,this.position=new _,this.previousPosition=new _,this.interpolatedPosition=new _,this.initPosition=new _,e.position&&(this.position.copy(e.position),this.previousPosition.copy(e.position),this.interpolatedPosition.copy(e.position),this.initPosition.copy(e.position)),this.velocity=new _,e.velocity&&this.velocity.copy(e.velocity),this.initVelocity=new _,this.force=new _;let t=typeof e.mass=="number"?e.mass:0;this.mass=t,this.invMass=t>0?1/t:0,this.material=e.material||null,this.linearDamping=typeof e.linearDamping=="number"?e.linearDamping:.01,this.type=t<=0?G.STATIC:G.DYNAMIC,typeof e.type==typeof G.STATIC&&(this.type=e.type),this.allowSleep=typeof e.allowSleep<"u"?e.allowSleep:!0,this.sleepState=G.AWAKE,this.sleepSpeedLimit=typeof e.sleepSpeedLimit<"u"?e.sleepSpeedLimit:.1,this.sleepTimeLimit=typeof e.sleepTimeLimit<"u"?e.sleepTimeLimit:1,this.timeLastSleepy=0,this.wakeUpAfterNarrowphase=!1,this.torque=new _,this.quaternion=new le,this.initQuaternion=new le,this.previousQuaternion=new le,this.interpolatedQuaternion=new le,e.quaternion&&(this.quaternion.copy(e.quaternion),this.initQuaternion.copy(e.quaternion),this.previousQuaternion.copy(e.quaternion),this.interpolatedQuaternion.copy(e.quaternion)),this.angularVelocity=new _,e.angularVelocity&&this.angularVelocity.copy(e.angularVelocity),this.initAngularVelocity=new _,this.shapes=[],this.shapeOffsets=[],this.shapeOrientations=[],this.inertia=new _,this.invInertia=new _,this.invInertiaWorld=new Ot,this.invMassSolve=0,this.invInertiaSolve=new _,this.invInertiaWorldSolve=new Ot,this.fixedRotation=typeof e.fixedRotation<"u"?e.fixedRotation:!1,this.angularDamping=typeof e.angularDamping<"u"?e.angularDamping:.01,this.linearFactor=new _(1,1,1),e.linearFactor&&this.linearFactor.copy(e.linearFactor),this.angularFactor=new _(1,1,1),e.angularFactor&&this.angularFactor.copy(e.angularFactor),this.aabb=new $e,this.aabbNeedsUpdate=!0,this.boundingRadius=0,this.wlambda=new _,this.isTrigger=Boolean(e.isTrigger),e.shape&&this.addShape(e.shape),this.updateMassProperties()}wakeUp(){let e=this.sleepState;this.sleepState=G.AWAKE,this.wakeUpAfterNarrowphase=!1,e===G.SLEEPING&&this.dispatchEvent(G.wakeupEvent)}sleep(){this.sleepState=G.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0),this.wakeUpAfterNarrowphase=!1}sleepTick(e){if(this.allowSleep){let t=this.sleepState,i=this.velocity.lengthSquared()+this.angularVelocity.lengthSquared(),n=this.sleepSpeedLimit**2;t===G.AWAKE&&i<n?(this.sleepState=G.SLEEPY,this.timeLastSleepy=e,this.dispatchEvent(G.sleepyEvent)):t===G.SLEEPY&&i>n?this.wakeUp():t===G.SLEEPY&&e-this.timeLastSleepy>this.sleepTimeLimit&&(this.sleep(),this.dispatchEvent(G.sleepEvent))}}updateSolveMassProperties(){this.sleepState===G.SLEEPING||this.type===G.KINEMATIC?(this.invMassSolve=0,this.invInertiaSolve.setZero(),this.invInertiaWorldSolve.setZero()):(this.invMassSolve=this.invMass,this.invInertiaSolve.copy(this.invInertia),this.invInertiaWorldSolve.copy(this.invInertiaWorld))}pointToLocalFrame(e,t=new _){return e.vsub(this.position,t),this.quaternion.conjugate().vmult(t,t),t}vectorToLocalFrame(e,t=new _){return this.quaternion.conjugate().vmult(e,t),t}pointToWorldFrame(e,t=new _){return this.quaternion.vmult(e,t),t.vadd(this.position,t),t}vectorToWorldFrame(e,t=new _){return this.quaternion.vmult(e,t),t}addShape(e,t,i){let n=new _,r=new le;return t&&n.copy(t),i&&r.copy(i),this.shapes.push(e),this.shapeOffsets.push(n),this.shapeOrientations.push(r),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0,e.body=this,this}removeShape(e){let t=this.shapes.indexOf(e);return t===-1?(console.warn("Shape does not belong to the body"),this):(this.shapes.splice(t,1),this.shapeOffsets.splice(t,1),this.shapeOrientations.splice(t,1),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0,e.body=null,this)}updateBoundingRadius(){let e=this.shapes,t=this.shapeOffsets,i=e.length,n=0;for(let r=0;r!==i;r++){let s=e[r];s.updateBoundingSphereRadius();let o=t[r].length(),c=s.boundingSphereRadius;o+c>n&&(n=o+c)}this.boundingRadius=n}updateAABB(){let e=this.shapes,t=this.shapeOffsets,i=this.shapeOrientations,n=e.length,r=om,s=am,o=this.quaternion,c=this.aabb,d=lm;for(let a=0;a!==n;a++){let h=e[a];o.vmult(t[a],r),r.vadd(this.position,r),o.mult(i[a],s),h.calculateWorldAABB(r,s,d.lowerBound,d.upperBound),a===0?c.copy(d):c.extend(d)}this.aabbNeedsUpdate=!1}updateInertiaWorld(e){let t=this.invInertia;if(!(t.x===t.y&&t.y===t.z&&!e)){let i=cm,n=dm;i.setRotationFromQuaternion(this.quaternion),i.transpose(n),i.scale(t,i),i.mmult(n,this.invInertiaWorld)}}applyForce(e,t=new _){if(this.type!==G.DYNAMIC)return;this.sleepState===G.SLEEPING&&this.wakeUp();let i=hm;t.cross(e,i),this.force.vadd(e,this.force),this.torque.vadd(i,this.torque)}applyLocalForce(e,t=new _){if(this.type!==G.DYNAMIC)return;let i=um,n=pm;this.vectorToWorldFrame(e,i),this.vectorToWorldFrame(t,n),this.applyForce(i,n)}applyTorque(e){this.type===G.DYNAMIC&&(this.sleepState===G.SLEEPING&&this.wakeUp(),this.torque.vadd(e,this.torque))}applyImpulse(e,t=new _){if(this.type!==G.DYNAMIC)return;this.sleepState===G.SLEEPING&&this.wakeUp();let i=t,n=fm;n.copy(e),n.scale(this.invMass,n),this.velocity.vadd(n,this.velocity);let r=mm;i.cross(e,r),this.invInertiaWorld.vmult(r,r),this.angularVelocity.vadd(r,this.angularVelocity)}applyLocalImpulse(e,t=new _){if(this.type!==G.DYNAMIC)return;let i=gm,n=bm;this.vectorToWorldFrame(e,i),this.vectorToWorldFrame(t,n),this.applyImpulse(i,n)}updateMassProperties(){let e=vm;this.invMass=this.mass>0?1/this.mass:0;let t=this.inertia,i=this.fixedRotation;this.updateAABB(),e.set((this.aabb.upperBound.x-this.aabb.lowerBound.x)/2,(this.aabb.upperBound.y-this.aabb.lowerBound.y)/2,(this.aabb.upperBound.z-this.aabb.lowerBound.z)/2),Yn.calculateInertia(e,this.mass,t),this.invInertia.set(t.x>0&&!i?1/t.x:0,t.y>0&&!i?1/t.y:0,t.z>0&&!i?1/t.z:0),this.updateInertiaWorld(!0)}getVelocityAtWorldPoint(e,t){let i=new _;return e.vsub(this.position,i),this.angularVelocity.cross(i,t),this.velocity.vadd(t,t),t}integrate(e,t,i){if(this.previousPosition.copy(this.position),this.previousQuaternion.copy(this.quaternion),!(this.type===G.DYNAMIC||this.type===G.KINEMATIC)||this.sleepState===G.SLEEPING)return;let n=this.velocity,r=this.angularVelocity,s=this.position,o=this.force,c=this.torque,d=this.quaternion,a=this.invMass,h=this.invInertiaWorld,u=this.linearFactor,g=a*e;n.x+=o.x*g*u.x,n.y+=o.y*g*u.y,n.z+=o.z*g*u.z;let E=h.elements,b=this.angularFactor,y=c.x*b.x,m=c.y*b.y,p=c.z*b.z;r.x+=e*(E[0]*y+E[1]*m+E[2]*p),r.y+=e*(E[3]*y+E[4]*m+E[5]*p),r.z+=e*(E[6]*y+E[7]*m+E[8]*p),s.x+=n.x*e,s.y+=n.y*e,s.z+=n.z*e,d.integrate(this.angularVelocity,e,this.angularFactor,d),t&&(i?d.normalizeFast():d.normalize()),this.aabbNeedsUpdate=!0,this.updateInertiaWorld()}};G.idCounter=0;G.COLLIDE_EVENT_NAME="collide";G.DYNAMIC=Jl.DYNAMIC;G.STATIC=Jl.STATIC;G.KINEMATIC=Jl.KINEMATIC;G.AWAKE=$l.AWAKE;G.SLEEPY=$l.SLEEPY;G.SLEEPING=$l.SLEEPING;G.wakeupEvent={type:"wakeup"};G.sleepyEvent={type:"sleepy"};G.sleepEvent={type:"sleep"};var om=new _,am=new le,lm=new $e,cm=new Ot,dm=new Ot,hm=new _,um=new _,pm=new _,fm=new _,mm=new _,gm=new _,bm=new _,vm=new _,Gl=class{constructor(){this.world=void 0,this.useBoundingBoxes=void 0,this.dirty=void 0,this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}collisionPairs(e,t,i){throw new Error("collisionPairs not implemented for this BroadPhase class!")}needBroadphaseCollision(e,t){return!((e.collisionFilterGroup&t.collisionFilterMask)===0||(t.collisionFilterGroup&e.collisionFilterMask)===0||((e.type&G.STATIC)!==0||e.sleepState===G.SLEEPING)&&((t.type&G.STATIC)!==0||t.sleepState===G.SLEEPING))}intersectionTest(e,t,i,n){this.useBoundingBoxes?this.doBoundingBoxBroadphase(e,t,i,n):this.doBoundingSphereBroadphase(e,t,i,n)}doBoundingSphereBroadphase(e,t,i,n){let r=ym;t.position.vsub(e.position,r);let s=(e.boundingRadius+t.boundingRadius)**2;r.lengthSquared()<s&&(i.push(e),n.push(t))}doBoundingBoxBroadphase(e,t,i,n){e.aabbNeedsUpdate&&e.updateAABB(),t.aabbNeedsUpdate&&t.updateAABB(),e.aabb.overlaps(t.aabb)&&(i.push(e),n.push(t))}makePairsUnique(e,t){let i=Em,n=wm,r=_m,s=e.length;for(let o=0;o!==s;o++)n[o]=e[o],r[o]=t[o];e.length=0,t.length=0;for(let o=0;o!==s;o++){let c=n[o].id,d=r[o].id,a=c<d?c+","+d:d+","+c;i[a]=o,i.keys.push(a)}for(let o=0;o!==i.keys.length;o++){let c=i.keys.pop(),d=i[c];e.push(n[d]),t.push(r[d]),delete i[c]}}setWorld(e){}static boundingSphereCheck(e,t){let i=new _;e.position.vsub(t.position,i);let n=e.shapes[0],r=t.shapes[0];return Math.pow(n.boundingSphereRadius+r.boundingSphereRadius,2)>i.lengthSquared()}aabbQuery(e,t,i){return console.warn(".aabbQuery is not implemented in this Broadphase subclass."),[]}},ym=new _,Em={keys:[]},wm=[],_m=[];var M0=new _,Vl=class extends Gl{constructor(){super()}collisionPairs(e,t,i){let n=e.bodies,r=n.length,s,o;for(let c=0;c!==r;c++)for(let d=0;d!==c;d++)s=n[c],o=n[d],this.needBroadphaseCollision(s,o)&&this.intersectionTest(s,o,t,i)}aabbQuery(e,t,i=[]){for(let n=0;n<e.bodies.length;n++){let r=e.bodies[n];r.aabbNeedsUpdate&&r.updateAABB(),r.aabb.overlaps(t)&&i.push(r)}return i}},Js=class{constructor(){this.rayFromWorld=void 0,this.rayToWorld=void 0,this.hitNormalWorld=void 0,this.hitPointWorld=void 0,this.hasHit=void 0,this.shape=void 0,this.body=void 0,this.hitFaceIndex=void 0,this.distance=void 0,this.shouldStop=void 0,this.rayFromWorld=new _,this.rayToWorld=new _,this.hitNormalWorld=new _,this.hitPointWorld=new _,this.hasHit=!1,this.shape=null,this.body=null,this.hitFaceIndex=-1,this.distance=-1,this.shouldStop=!1}reset(){this.rayFromWorld.setZero(),this.rayToWorld.setZero(),this.hitNormalWorld.setZero(),this.hitPointWorld.setZero(),this.hasHit=!1,this.shape=null,this.body=null,this.hitFaceIndex=-1,this.distance=-1,this.shouldStop=!1}abort(){this.shouldStop=!0}set(e,t,i,n,r,s,o){this.rayFromWorld.copy(e),this.rayToWorld.copy(t),this.hitNormalWorld.copy(i),this.hitPointWorld.copy(n),this.shape=r,this.body=s,this.distance=o}},Zh,Jh,$h,Kh,eu,tu,iu,Kl={CLOSEST:1,ANY:2,ALL:4};Zh=V.types.SPHERE;Jh=V.types.PLANE;$h=V.types.BOX;Kh=V.types.CYLINDER;eu=V.types.CONVEXPOLYHEDRON;tu=V.types.HEIGHTFIELD;iu=V.types.TRIMESH;var Ee=class{get[Zh](){return this._intersectSphere}get[Jh](){return this._intersectPlane}get[$h](){return this._intersectBox}get[Kh](){return this._intersectConvex}get[eu](){return this._intersectConvex}get[tu](){return this._intersectHeightfield}get[iu](){return this._intersectTrimesh}constructor(e=new _,t=new _){this.from=void 0,this.to=void 0,this.direction=void 0,this.precision=void 0,this.checkCollisionResponse=void 0,this.skipBackfaces=void 0,this.collisionFilterMask=void 0,this.collisionFilterGroup=void 0,this.mode=void 0,this.result=void 0,this.hasHit=void 0,this.callback=void 0,this.from=e.clone(),this.to=t.clone(),this.direction=new _,this.precision=1e-4,this.checkCollisionResponse=!0,this.skipBackfaces=!1,this.collisionFilterMask=-1,this.collisionFilterGroup=-1,this.mode=Ee.ANY,this.result=new Js,this.hasHit=!1,this.callback=i=>{}}intersectWorld(e,t){return this.mode=t.mode||Ee.ANY,this.result=t.result||new Js,this.skipBackfaces=!!t.skipBackfaces,this.collisionFilterMask=typeof t.collisionFilterMask<"u"?t.collisionFilterMask:-1,this.collisionFilterGroup=typeof t.collisionFilterGroup<"u"?t.collisionFilterGroup:-1,this.checkCollisionResponse=typeof t.checkCollisionResponse<"u"?t.checkCollisionResponse:!0,t.from&&this.from.copy(t.from),t.to&&this.to.copy(t.to),this.callback=t.callback||(()=>{}),this.hasHit=!1,this.result.reset(),this.updateDirection(),this.getAABB(Fh),Fl.length=0,e.broadphase.aabbQuery(e,Fh,Fl),this.intersectBodies(Fl),this.hasHit}intersectBody(e,t){t&&(this.result=t,this.updateDirection());let i=this.checkCollisionResponse;if(i&&!e.collisionResponse||(this.collisionFilterGroup&e.collisionFilterMask)===0||(e.collisionFilterGroup&this.collisionFilterMask)===0)return;let n=xm,r=Tm;for(let s=0,o=e.shapes.length;s<o;s++){let c=e.shapes[s];if(!(i&&!c.collisionResponse)&&(e.quaternion.mult(e.shapeOrientations[s],r),e.quaternion.vmult(e.shapeOffsets[s],n),n.vadd(e.position,n),this.intersectShape(c,r,n,e),this.result.shouldStop))break}}intersectBodies(e,t){t&&(this.result=t,this.updateDirection());for(let i=0,n=e.length;!this.result.shouldStop&&i<n;i++)this.intersectBody(e[i])}updateDirection(){this.to.vsub(this.from,this.direction),this.direction.normalize()}intersectShape(e,t,i,n){let r=this.from;if(Bm(r,this.direction,i)>e.boundingSphereRadius)return;let o=this[e.type];o&&o.call(this,e,t,i,n,e)}_intersectBox(e,t,i,n,r){return this._intersectConvex(e.convexPolyhedronRepresentation,t,i,n,r)}_intersectPlane(e,t,i,n,r){let s=this.from,o=this.to,c=this.direction,d=new _(0,0,1);t.vmult(d,d);let a=new _;s.vsub(i,a);let h=a.dot(d);o.vsub(i,a);let u=a.dot(d);if(h*u>0||s.distanceTo(o)<h)return;let g=d.dot(c);if(Math.abs(g)<this.precision)return;let E=new _,b=new _,y=new _;s.vsub(i,E);let m=-d.dot(E)/g;c.scale(m,b),s.vadd(b,y),this.reportIntersection(d,y,r,n,-1)}getAABB(e){let{lowerBound:t,upperBound:i}=e,n=this.to,r=this.from;t.x=Math.min(n.x,r.x),t.y=Math.min(n.y,r.y),t.z=Math.min(n.z,r.z),i.x=Math.max(n.x,r.x),i.y=Math.max(n.y,r.y),i.z=Math.max(n.z,r.z)}_intersectHeightfield(e,t,i,n,r){e.data,e.elementSize;let s=Rm;s.from.copy(this.from),s.to.copy(this.to),te.pointToLocalFrame(i,t,s.from,s.from),te.pointToLocalFrame(i,t,s.to,s.to),s.updateDirection();let o=Cm,c,d,a,h;c=d=0,a=h=e.data.length-1;let u=new $e;s.getAABB(u),e.getIndexOfPosition(u.lowerBound.x,u.lowerBound.y,o,!0),c=Math.max(c,o[0]),d=Math.max(d,o[1]),e.getIndexOfPosition(u.upperBound.x,u.upperBound.y,o,!0),a=Math.min(a,o[0]+1),h=Math.min(h,o[1]+1);for(let g=c;g<a;g++)for(let E=d;E<h;E++){if(this.result.shouldStop)return;if(e.getAabbAtIndex(g,E,u),!!u.overlapsRay(s)){if(e.getConvexTrianglePillar(g,E,!1),te.pointToWorldFrame(i,t,e.pillarOffset,qo),this._intersectConvex(e.pillarConvex,t,qo,n,r,Nh),this.result.shouldStop)return;e.getConvexTrianglePillar(g,E,!0),te.pointToWorldFrame(i,t,e.pillarOffset,qo),this._intersectConvex(e.pillarConvex,t,qo,n,r,Nh)}}}_intersectSphere(e,t,i,n,r){let s=this.from,o=this.to,c=e.radius,d=(o.x-s.x)**2+(o.y-s.y)**2+(o.z-s.z)**2,a=2*((o.x-s.x)*(s.x-i.x)+(o.y-s.y)*(s.y-i.y)+(o.z-s.z)*(s.z-i.z)),h=(s.x-i.x)**2+(s.y-i.y)**2+(s.z-i.z)**2-c**2,u=a**2-4*d*h,g=Sm,E=Pm;if(!(u<0))if(u===0)s.lerp(o,u,g),g.vsub(i,E),E.normalize(),this.reportIntersection(E,g,r,n,-1);else{let b=(-a-Math.sqrt(u))/(2*d),y=(-a+Math.sqrt(u))/(2*d);if(b>=0&&b<=1&&(s.lerp(o,b,g),g.vsub(i,E),E.normalize(),this.reportIntersection(E,g,r,n,-1)),this.result.shouldStop)return;y>=0&&y<=1&&(s.lerp(o,y,g),g.vsub(i,E),E.normalize(),this.reportIntersection(E,g,r,n,-1))}}_intersectConvex(e,t,i,n,r,s){let o=Om,c=zh,d=s&&s.faceList||null,a=e.faces,h=e.vertices,u=e.faceNormals,g=this.direction,E=this.from,b=this.to,y=E.distanceTo(b),m=d?d.length:a.length,p=this.result;for(let f=0;!p.shouldStop&&f<m;f++){let v=d?d[f]:f,w=a[v],x=u[v],T=t,R=i;c.copy(h[w[0]]),T.vmult(c,c),c.vadd(R,c),c.vsub(E,c),T.vmult(x,o);let C=g.dot(o);if(Math.abs(C)<this.precision)continue;let P=o.dot(c)/C;if(!(P<0)){g.scale(P,ot),ot.vadd(E,ot),Wt.copy(h[w[0]]),T.vmult(Wt,Wt),R.vadd(Wt,Wt);for(let S=1;!p.shouldStop&&S<w.length-1;S++){si.copy(h[w[S]]),oi.copy(h[w[S+1]]),T.vmult(si,si),T.vmult(oi,oi),R.vadd(si,si),R.vadd(oi,oi);let L=ot.distanceTo(E);!(Ee.pointInTriangle(ot,Wt,si,oi)||Ee.pointInTriangle(ot,si,Wt,oi))||L>y||this.reportIntersection(o,ot,r,n,v)}}}}_intersectTrimesh(e,t,i,n,r,s){let o=Am,c=Hm,d=jm,a=zh,h=km,u=Im,g=Mm,E=Dm,b=Lm,y=e.indices;e.vertices;let m=this.from,p=this.to,f=this.direction;d.position.copy(i),d.quaternion.copy(t),te.vectorToLocalFrame(i,t,f,h),te.pointToLocalFrame(i,t,m,u),te.pointToLocalFrame(i,t,p,g),g.x*=e.scale.x,g.y*=e.scale.y,g.z*=e.scale.z,u.x*=e.scale.x,u.y*=e.scale.y,u.z*=e.scale.z,g.vsub(u,h),h.normalize();let v=u.distanceSquared(g);e.tree.rayQuery(this,d,c);for(let w=0,x=c.length;!this.result.shouldStop&&w!==x;w++){let T=c[w];e.getNormal(T,o),e.getVertex(y[T*3],Wt),Wt.vsub(u,a);let R=h.dot(o),C=o.dot(a)/R;if(C<0)continue;h.scale(C,ot),ot.vadd(u,ot),e.getVertex(y[T*3+1],si),e.getVertex(y[T*3+2],oi);let P=ot.distanceSquared(u);!(Ee.pointInTriangle(ot,si,Wt,oi)||Ee.pointInTriangle(ot,Wt,si,oi))||P>v||(te.vectorToWorldFrame(t,o,b),te.pointToWorldFrame(i,t,ot,E),this.reportIntersection(b,E,r,n,T))}c.length=0}reportIntersection(e,t,i,n,r){let s=this.from,o=this.to,c=s.distanceTo(t),d=this.result;if(!(this.skipBackfaces&&e.dot(this.direction)>0))switch(d.hitFaceIndex=typeof r<"u"?r:-1,this.mode){case Ee.ALL:this.hasHit=!0,d.set(s,o,e,t,i,n,c),d.hasHit=!0,this.callback(d);break;case Ee.CLOSEST:(c<d.distance||!d.hasHit)&&(this.hasHit=!0,d.hasHit=!0,d.set(s,o,e,t,i,n,c));break;case Ee.ANY:this.hasHit=!0,d.hasHit=!0,d.set(s,o,e,t,i,n,c),d.shouldStop=!0;break}}static pointInTriangle(e,t,i,n){n.vsub(t,Xn),i.vsub(t,Xs),e.vsub(t,Nl);let r=Xn.dot(Xn),s=Xn.dot(Xs),o=Xn.dot(Nl),c=Xs.dot(Xs),d=Xs.dot(Nl),a,h;return(a=c*o-s*d)>=0&&(h=r*d-s*o)>=0&&a+h<r*c-s*s}};Ee.CLOSEST=Kl.CLOSEST;Ee.ANY=Kl.ANY;Ee.ALL=Kl.ALL;var Fh=new $e,Fl=[],Xs=new _,Nl=new _,xm=new _,Tm=new le,ot=new _,Wt=new _,si=new _,oi=new _,Nh={faceList:[0]},qo=new _,Rm=new Ee,Cm=[],Sm=new _,Pm=new _,Om=new _,zh=new _,Am=new _,km=new _,Im=new _,Mm=new _,Lm=new _,Dm=new _;new $e;var Hm=[],jm=new te,Xn=new _,Xo=new _;function Bm(l,e,t){t.vsub(l,Xn);let i=Xn.dot(e);return e.scale(i,Xo),Xo.vadd(l,Xo),t.distanceTo(Xo)}var Ko=class{static defaults(e={},t){for(let i in t)i in e||(e[i]=t[i]);return e}},$s=class{constructor(e,t,i={}){this.equations=void 0,this.bodyA=void 0,this.bodyB=void 0,this.id=void 0,this.collideConnected=void 0,i=Ko.defaults(i,{collideConnected:!0,wakeUpBodies:!0}),this.equations=[],this.bodyA=e,this.bodyB=t,this.id=$s.idCounter++,this.collideConnected=i.collideConnected,i.wakeUpBodies&&(e&&e.wakeUp(),t&&t.wakeUp())}update(){throw new Error("method update() not implmemented in this Constraint subclass!")}enable(){let e=this.equations;for(let t=0;t<e.length;t++)e[t].enabled=!0}disable(){let e=this.equations;for(let t=0;t<e.length;t++)e[t].enabled=!1}};$s.idCounter=0;var ea=class{constructor(){this.spatial=void 0,this.rotational=void 0,this.spatial=new _,this.rotational=new _}multiplyElement(e){return e.spatial.dot(this.spatial)+e.rotational.dot(this.rotational)}multiplyVectors(e,t){return e.dot(this.spatial)+t.dot(this.rotational)}},Zn=class{constructor(e,t,i=-1e6,n=1e6){this.id=void 0,this.minForce=void 0,this.maxForce=void 0,this.bi=void 0,this.bj=void 0,this.si=void 0,this.sj=void 0,this.a=void 0,this.b=void 0,this.eps=void 0,this.jacobianElementA=void 0,this.jacobianElementB=void 0,this.enabled=void 0,this.multiplier=void 0,this.id=Zn.idCounter++,this.minForce=i,this.maxForce=n,this.bi=e,this.bj=t,this.a=0,this.b=0,this.eps=0,this.jacobianElementA=new ea,this.jacobianElementB=new ea,this.enabled=!0,this.multiplier=0,this.setSpookParams(1e7,4,1/60)}setSpookParams(e,t,i){let n=t,r=e,s=i;this.a=4/(s*(1+4*n)),this.b=4*n/(1+4*n),this.eps=4/(s*s*r*(1+4*n))}computeB(e,t,i){let n=this.computeGW(),r=this.computeGq(),s=this.computeGiMf();return-r*e-n*t-s*i}computeGq(){let e=this.jacobianElementA,t=this.jacobianElementB,i=this.bi,n=this.bj,r=i.position,s=n.position;return e.spatial.dot(r)+t.spatial.dot(s)}computeGW(){let e=this.jacobianElementA,t=this.jacobianElementB,i=this.bi,n=this.bj,r=i.velocity,s=n.velocity,o=i.angularVelocity,c=n.angularVelocity;return e.multiplyVectors(r,o)+t.multiplyVectors(s,c)}computeGWlambda(){let e=this.jacobianElementA,t=this.jacobianElementB,i=this.bi,n=this.bj,r=i.vlambda,s=n.vlambda,o=i.wlambda,c=n.wlambda;return e.multiplyVectors(r,o)+t.multiplyVectors(s,c)}computeGiMf(){let e=this.jacobianElementA,t=this.jacobianElementB,i=this.bi,n=this.bj,r=i.force,s=i.torque,o=n.force,c=n.torque,d=i.invMassSolve,a=n.invMassSolve;return r.scale(d,Gh),o.scale(a,Vh),i.invInertiaWorldSolve.vmult(s,Wh),n.invInertiaWorldSolve.vmult(c,Uh),e.multiplyVectors(Gh,Wh)+t.multiplyVectors(Vh,Uh)}computeGiMGt(){let e=this.jacobianElementA,t=this.jacobianElementB,i=this.bi,n=this.bj,r=i.invMassSolve,s=n.invMassSolve,o=i.invInertiaWorldSolve,c=n.invInertiaWorldSolve,d=r+s;return o.vmult(e.rotational,Qo),d+=Qo.dot(e.rotational),c.vmult(t.rotational,Qo),d+=Qo.dot(t.rotational),d}addToWlambda(e){let t=this.jacobianElementA,i=this.jacobianElementB,n=this.bi,r=this.bj,s=Fm;n.vlambda.addScaledVector(n.invMassSolve*e,t.spatial,n.vlambda),r.vlambda.addScaledVector(r.invMassSolve*e,i.spatial,r.vlambda),n.invInertiaWorldSolve.vmult(t.rotational,s),n.wlambda.addScaledVector(e,s,n.wlambda),r.invInertiaWorldSolve.vmult(i.rotational,s),r.wlambda.addScaledVector(e,s,r.wlambda)}computeC(){return this.computeGiMGt()+this.eps}};Zn.idCounter=0;var Gh=new _,Vh=new _,Wh=new _,Uh=new _,Qo=new _,Fm=new _,Wl=class extends Zn{constructor(e,t,i=1e6){super(e,t,0,i),this.restitution=void 0,this.ri=void 0,this.rj=void 0,this.ni=void 0,this.restitution=0,this.ri=new _,this.rj=new _,this.ni=new _}computeB(e){let t=this.a,i=this.b,n=this.bi,r=this.bj,s=this.ri,o=this.rj,c=Nm,d=zm,a=n.velocity,h=n.angularVelocity;n.force,n.torque;let u=r.velocity,g=r.angularVelocity;r.force,r.torque;let E=Gm,b=this.jacobianElementA,y=this.jacobianElementB,m=this.ni;s.cross(m,c),o.cross(m,d),m.negate(b.spatial),c.negate(b.rotational),y.spatial.copy(m),y.rotational.copy(d),E.copy(r.position),E.vadd(o,E),E.vsub(n.position,E),E.vsub(s,E);let p=m.dot(E),f=this.restitution+1,v=f*u.dot(m)-f*a.dot(m)+g.dot(d)-h.dot(c),w=this.computeGiMf();return-p*t-v*i-e*w}getImpactVelocityAlongNormal(){let e=Vm,t=Wm,i=Um,n=qm,r=Xm;return this.bi.position.vadd(this.ri,i),this.bj.position.vadd(this.rj,n),this.bi.getVelocityAtWorldPoint(i,e),this.bj.getVelocityAtWorldPoint(n,t),e.vsub(t,r),this.ni.dot(r)}},Nm=new _,zm=new _,Gm=new _,Vm=new _,Wm=new _,Um=new _,qm=new _,Xm=new _;var L0=new _,D0=new _;var H0=new _,j0=new _;var B0=new _,F0=new _,ta=class extends Zn{constructor(e,t,i){super(e,t,-i,i),this.ri=void 0,this.rj=void 0,this.t=void 0,this.ri=new _,this.rj=new _,this.t=new _}computeB(e){this.a;let t=this.b;this.bi,this.bj;let i=this.ri,n=this.rj,r=Qm,s=Ym,o=this.t;i.cross(o,r),n.cross(o,s);let c=this.jacobianElementA,d=this.jacobianElementB;o.negate(c.spatial),r.negate(c.rotational),d.spatial.copy(o),d.rotational.copy(s);let a=this.computeGW(),h=this.computeGiMf();return-a*t-e*h}},Qm=new _,Ym=new _,Ar=class{constructor(e,t,i){this.id=void 0,this.materials=void 0,this.friction=void 0,this.restitution=void 0,this.contactEquationStiffness=void 0,this.contactEquationRelaxation=void 0,this.frictionEquationStiffness=void 0,this.frictionEquationRelaxation=void 0,i=Ko.defaults(i,{friction:.3,restitution:.3,contactEquationStiffness:1e7,contactEquationRelaxation:3,frictionEquationStiffness:1e7,frictionEquationRelaxation:3}),this.id=Ar.idCounter++,this.materials=[e,t],this.friction=i.friction,this.restitution=i.restitution,this.contactEquationStiffness=i.contactEquationStiffness,this.contactEquationRelaxation=i.contactEquationRelaxation,this.frictionEquationStiffness=i.frictionEquationStiffness,this.frictionEquationRelaxation=i.frictionEquationRelaxation}};Ar.idCounter=0;var kr=class{constructor(e={}){this.name=void 0,this.id=void 0,this.friction=void 0,this.restitution=void 0;let t="";typeof e=="string"&&(t=e,e={}),this.name=t,this.id=kr.idCounter++,this.friction=typeof e.friction<"u"?e.friction:-1,this.restitution=typeof e.restitution<"u"?e.restitution:-1}};kr.idCounter=0;var ia=class{constructor(e,t,i={}){this.restLength=void 0,this.stiffness=void 0,this.damping=void 0,this.bodyA=void 0,this.bodyB=void 0,this.localAnchorA=void 0,this.localAnchorB=void 0,this.restLength=typeof i.restLength=="number"?i.restLength:1,this.stiffness=i.stiffness||100,this.damping=i.damping||1,this.bodyA=e,this.bodyB=t,this.localAnchorA=new _,this.localAnchorB=new _,i.localAnchorA&&this.localAnchorA.copy(i.localAnchorA),i.localAnchorB&&this.localAnchorB.copy(i.localAnchorB),i.worldAnchorA&&this.setWorldAnchorA(i.worldAnchorA),i.worldAnchorB&&this.setWorldAnchorB(i.worldAnchorB)}setWorldAnchorA(e){this.bodyA.pointToLocalFrame(e,this.localAnchorA)}setWorldAnchorB(e){this.bodyB.pointToLocalFrame(e,this.localAnchorB)}getWorldAnchorA(e){this.bodyA.pointToWorldFrame(this.localAnchorA,e)}getWorldAnchorB(e){this.bodyB.pointToWorldFrame(this.localAnchorB,e)}applyForce(){let e=this.stiffness,t=this.damping,i=this.restLength,n=this.bodyA,r=this.bodyB,s=Zm,o=Jm,c=$m,d=Km,a=og,h=eg,u=tg,g=ig,E=ng,b=rg,y=sg;this.getWorldAnchorA(h),this.getWorldAnchorB(u),h.vsub(n.position,g),u.vsub(r.position,E),u.vsub(h,s);let m=s.length();o.copy(s),o.normalize(),r.velocity.vsub(n.velocity,c),r.angularVelocity.cross(E,a),c.vadd(a,c),n.angularVelocity.cross(g,a),c.vsub(a,c),o.scale(-e*(m-i)-t*c.dot(o),d),n.force.vsub(d,n.force),r.force.vadd(d,r.force),g.cross(d,b),E.cross(d,y),n.torque.vsub(b,n.torque),r.torque.vadd(y,r.torque)}},Zm=new _,Jm=new _,$m=new _,Km=new _,eg=new _,tg=new _,ig=new _,ng=new _,rg=new _,sg=new _,og=new _;var N0=new _,z0=new _;var G0=new _,V0=new _,W0=new _;new Ee;var U0=new _,q0=new _,X0=[new _(1,0,0),new _(0,1,0),new _(0,0,1)],Q0=new _;var Y0=new _,Z0=new _,J0=new _;var $0=new _,K0=new _,ew=new _,tw=new _;var iw=new _,nw=new _,rw=new _;var na=class extends V{constructor(e){if(super({type:V.types.SPHERE}),this.radius=void 0,this.radius=e!==void 0?e:1,this.radius<0)throw new Error("The sphere radius cannot be negative.");this.updateBoundingSphereRadius()}calculateLocalInertia(e,t=new _){let i=2*e*this.radius*this.radius/5;return t.x=i,t.y=i,t.z=i,t}volume(){return 4*Math.PI*Math.pow(this.radius,3)/3}updateBoundingSphereRadius(){this.boundingSphereRadius=this.radius}calculateWorldAABB(e,t,i,n){let r=this.radius,s=["x","y","z"];for(let o=0;o<s.length;o++){let c=s[o];i[c]=e[c]-r,n[c]=e[c]+r}}};var sw=new _,ow=new _;var aw=new _,lw=new _,cw=new _,dw=new _,hw=new _,uw=new _,pw=new _;var fw=new _;var mw=new _,gw=new _,bw=new _,vw=new _,yw=new _,Ew=new _,ww=new _,_w=new _,xw=new _;var Tw=new _,Rw=new $e;var Cw=new _,Sw=new $e,Pw=new _,Ow=new _,Aw=new _,kw=new _,Iw=new _,Mw=new _,Lw=new _,Dw=new $e,Hw=new _,jw=new te,Bw=new $e,Ul=class{constructor(){this.equations=void 0,this.equations=[]}solve(e,t){return 0}addEquation(e){e.enabled&&!e.bi.isTrigger&&!e.bj.isTrigger&&this.equations.push(e)}removeEquation(e){let t=this.equations,i=t.indexOf(e);i!==-1&&t.splice(i,1)}removeAllEquations(){this.equations.length=0}},ql=class extends Ul{constructor(){super(),this.iterations=void 0,this.tolerance=void 0,this.iterations=10,this.tolerance=1e-7}solve(e,t){let i=0,n=this.iterations,r=this.tolerance*this.tolerance,s=this.equations,o=s.length,c=t.bodies,d=c.length,a=e,h,u,g,E,b,y;if(o!==0)for(let v=0;v!==d;v++)c[v].updateSolveMassProperties();let m=lg,p=cg,f=ag;m.length=o,p.length=o,f.length=o;for(let v=0;v!==o;v++){let w=s[v];f[v]=0,p[v]=w.computeB(a),m[v]=1/w.computeC()}if(o!==0){for(let x=0;x!==d;x++){let T=c[x],R=T.vlambda,C=T.wlambda;R.set(0,0,0),C.set(0,0,0)}for(i=0;i!==n;i++){E=0;for(let x=0;x!==o;x++){let T=s[x];h=p[x],u=m[x],y=f[x],b=T.computeGWlambda(),g=u*(h-b-T.eps*y),y+g<T.minForce?g=T.minForce-y:y+g>T.maxForce&&(g=T.maxForce-y),f[x]+=g,E+=g>0?g:-g,T.addToWlambda(g)}if(E*E<r)break}for(let x=0;x!==d;x++){let T=c[x],R=T.velocity,C=T.angularVelocity;T.vlambda.vmul(T.linearFactor,T.vlambda),R.vadd(T.vlambda,R),T.wlambda.vmul(T.angularFactor,T.wlambda),C.vadd(T.wlambda,C)}let v=s.length,w=1/a;for(;v--;)s[v].multiplier=f[v]*w}return i}},ag=[],lg=[],cg=[];var Fw=G.STATIC;var Xl=class{constructor(){this.objects=[],this.type=Object}release(...e){let t=e.length;for(let i=0;i!==t;i++)this.objects.push(e[i]);return this}get(){return this.objects.length===0?this.constructObject():this.objects.pop()}constructObject(){throw new Error("constructObject() not implemented in this Pool subclass yet!")}resize(e){let t=this.objects;for(;t.length>e;)t.pop();for(;t.length<e;)t.push(this.constructObject());return this}},Ql=class extends Xl{constructor(...e){super(...e),this.type=_}constructObject(){return new _}},nu,ru,su,ou,au,lu,cu,du,hu,uu,pu,fu,mu,gu,bu,vu,yu,Eu,wu,_u,xu,Tu,Ru,Cu,Su,de={sphereSphere:V.types.SPHERE,spherePlane:V.types.SPHERE|V.types.PLANE,boxBox:V.types.BOX|V.types.BOX,sphereBox:V.types.SPHERE|V.types.BOX,planeBox:V.types.PLANE|V.types.BOX,convexConvex:V.types.CONVEXPOLYHEDRON,sphereConvex:V.types.SPHERE|V.types.CONVEXPOLYHEDRON,planeConvex:V.types.PLANE|V.types.CONVEXPOLYHEDRON,boxConvex:V.types.BOX|V.types.CONVEXPOLYHEDRON,sphereHeightfield:V.types.SPHERE|V.types.HEIGHTFIELD,boxHeightfield:V.types.BOX|V.types.HEIGHTFIELD,convexHeightfield:V.types.CONVEXPOLYHEDRON|V.types.HEIGHTFIELD,sphereParticle:V.types.PARTICLE|V.types.SPHERE,planeParticle:V.types.PLANE|V.types.PARTICLE,boxParticle:V.types.BOX|V.types.PARTICLE,convexParticle:V.types.PARTICLE|V.types.CONVEXPOLYHEDRON,cylinderCylinder:V.types.CYLINDER,sphereCylinder:V.types.SPHERE|V.types.CYLINDER,planeCylinder:V.types.PLANE|V.types.CYLINDER,boxCylinder:V.types.BOX|V.types.CYLINDER,convexCylinder:V.types.CONVEXPOLYHEDRON|V.types.CYLINDER,heightfieldCylinder:V.types.HEIGHTFIELD|V.types.CYLINDER,particleCylinder:V.types.PARTICLE|V.types.CYLINDER,sphereTrimesh:V.types.SPHERE|V.types.TRIMESH,planeTrimesh:V.types.PLANE|V.types.TRIMESH};nu=de.sphereSphere;ru=de.spherePlane;su=de.boxBox;ou=de.sphereBox;au=de.planeBox;lu=de.convexConvex;cu=de.sphereConvex;du=de.planeConvex;hu=de.boxConvex;uu=de.sphereHeightfield;pu=de.boxHeightfield;fu=de.convexHeightfield;mu=de.sphereParticle;gu=de.planeParticle;bu=de.boxParticle;vu=de.convexParticle;yu=de.cylinderCylinder;Eu=de.sphereCylinder;wu=de.planeCylinder;_u=de.boxCylinder;xu=de.convexCylinder;Tu=de.heightfieldCylinder;Ru=de.particleCylinder;Cu=de.sphereTrimesh;Su=de.planeTrimesh;var Yl=class{get[nu](){return this.sphereSphere}get[ru](){return this.spherePlane}get[su](){return this.boxBox}get[ou](){return this.sphereBox}get[au](){return this.planeBox}get[lu](){return this.convexConvex}get[cu](){return this.sphereConvex}get[du](){return this.planeConvex}get[hu](){return this.boxConvex}get[uu](){return this.sphereHeightfield}get[pu](){return this.boxHeightfield}get[fu](){return this.convexHeightfield}get[mu](){return this.sphereParticle}get[gu](){return this.planeParticle}get[bu](){return this.boxParticle}get[vu](){return this.convexParticle}get[yu](){return this.convexConvex}get[Eu](){return this.sphereConvex}get[wu](){return this.planeConvex}get[_u](){return this.boxConvex}get[xu](){return this.convexConvex}get[Tu](){return this.heightfieldCylinder}get[Ru](){return this.particleCylinder}get[Cu](){return this.sphereTrimesh}get[Su](){return this.planeTrimesh}constructor(e){this.contactPointPool=void 0,this.frictionEquationPool=void 0,this.result=void 0,this.frictionResult=void 0,this.v3pool=void 0,this.world=void 0,this.currentContactMaterial=void 0,this.enableFrictionReduction=void 0,this.contactPointPool=[],this.frictionEquationPool=[],this.result=[],this.frictionResult=[],this.v3pool=new Ql,this.world=e,this.currentContactMaterial=e.defaultContactMaterial,this.enableFrictionReduction=!1}createContactEquation(e,t,i,n,r,s){let o;this.contactPointPool.length?(o=this.contactPointPool.pop(),o.bi=e,o.bj=t):o=new Wl(e,t),o.enabled=e.collisionResponse&&t.collisionResponse&&i.collisionResponse&&n.collisionResponse;let c=this.currentContactMaterial;o.restitution=c.restitution,o.setSpookParams(c.contactEquationStiffness,c.contactEquationRelaxation,this.world.dt);let d=i.material||e.material,a=n.material||t.material;return d&&a&&d.restitution>=0&&a.restitution>=0&&(o.restitution=d.restitution*a.restitution),o.si=r||i,o.sj=s||n,o}createFrictionEquationsFromContact(e,t){let i=e.bi,n=e.bj,r=e.si,s=e.sj,o=this.world,c=this.currentContactMaterial,d=c.friction,a=r.material||i.material,h=s.material||n.material;if(a&&h&&a.friction>=0&&h.friction>=0&&(d=a.friction*h.friction),d>0){let u=d*o.gravity.length(),g=i.invMass+n.invMass;g>0&&(g=1/g);let E=this.frictionEquationPool,b=E.length?E.pop():new ta(i,n,u*g),y=E.length?E.pop():new ta(i,n,u*g);return b.bi=y.bi=i,b.bj=y.bj=n,b.minForce=y.minForce=-u*g,b.maxForce=y.maxForce=u*g,b.ri.copy(e.ri),b.rj.copy(e.rj),y.ri.copy(e.ri),y.rj.copy(e.rj),e.ni.tangents(b.t,y.t),b.setSpookParams(c.frictionEquationStiffness,c.frictionEquationRelaxation,o.dt),y.setSpookParams(c.frictionEquationStiffness,c.frictionEquationRelaxation,o.dt),b.enabled=y.enabled=e.enabled,t.push(b,y),!0}return!1}createFrictionFromAverage(e){let t=this.result[this.result.length-1];if(!this.createFrictionEquationsFromContact(t,this.frictionResult)||e===1)return;let i=this.frictionResult[this.frictionResult.length-2],n=this.frictionResult[this.frictionResult.length-1];qn.setZero(),Pr.setZero(),Or.setZero();let r=t.bi;t.bj;for(let o=0;o!==e;o++)t=this.result[this.result.length-1-o],t.bi!==r?(qn.vadd(t.ni,qn),Pr.vadd(t.ri,Pr),Or.vadd(t.rj,Or)):(qn.vsub(t.ni,qn),Pr.vadd(t.rj,Pr),Or.vadd(t.ri,Or));let s=1/e;Pr.scale(s,i.ri),Or.scale(s,i.rj),n.ri.copy(i.ri),n.rj.copy(i.rj),qn.normalize(),qn.tangents(i.t,n.t)}getContacts(e,t,i,n,r,s,o){this.contactPointPool=r,this.frictionEquationPool=o,this.result=n,this.frictionResult=s;let c=ug,d=pg,a=dg,h=hg;for(let u=0,g=e.length;u!==g;u++){let E=e[u],b=t[u],y=null;E.material&&b.material&&(y=i.getContactMaterial(E.material,b.material)||null);let m=E.type&G.KINEMATIC&&b.type&G.STATIC||E.type&G.STATIC&&b.type&G.KINEMATIC||E.type&G.KINEMATIC&&b.type&G.KINEMATIC;for(let p=0;p<E.shapes.length;p++){E.quaternion.mult(E.shapeOrientations[p],c),E.quaternion.vmult(E.shapeOffsets[p],a),a.vadd(E.position,a);let f=E.shapes[p];for(let v=0;v<b.shapes.length;v++){b.quaternion.mult(b.shapeOrientations[v],d),b.quaternion.vmult(b.shapeOffsets[v],h),h.vadd(b.position,h);let w=b.shapes[v];if(!(f.collisionFilterMask&w.collisionFilterGroup&&w.collisionFilterMask&f.collisionFilterGroup)||a.distanceTo(h)>f.boundingSphereRadius+w.boundingSphereRadius)continue;let x=null;f.material&&w.material&&(x=i.getContactMaterial(f.material,w.material)||null),this.currentContactMaterial=x||y||i.defaultContactMaterial;let T=f.type|w.type,R=this[T];if(R){let C=!1;f.type<w.type?C=R.call(this,f,w,a,h,c,d,E,b,f,w,m):C=R.call(this,w,f,h,a,d,c,b,E,f,w,m),C&&m&&(i.shapeOverlapKeeper.set(f.id,w.id),i.bodyOverlapKeeper.set(E.id,b.id))}}}}}sphereSphere(e,t,i,n,r,s,o,c,d,a,h){if(h)return i.distanceSquared(n)<(e.radius+t.radius)**2;let u=this.createContactEquation(o,c,e,t,d,a);n.vsub(i,u.ni),u.ni.normalize(),u.ri.copy(u.ni),u.rj.copy(u.ni),u.ri.scale(e.radius,u.ri),u.rj.scale(-t.radius,u.rj),u.ri.vadd(i,u.ri),u.ri.vsub(o.position,u.ri),u.rj.vadd(n,u.rj),u.rj.vsub(c.position,u.rj),this.result.push(u),this.createFrictionEquationsFromContact(u,this.frictionResult)}spherePlane(e,t,i,n,r,s,o,c,d,a,h){let u=this.createContactEquation(o,c,e,t,d,a);if(u.ni.set(0,0,1),s.vmult(u.ni,u.ni),u.ni.negate(u.ni),u.ni.normalize(),u.ni.scale(e.radius,u.ri),i.vsub(n,Yo),u.ni.scale(u.ni.dot(Yo),qh),Yo.vsub(qh,u.rj),-Yo.dot(u.ni)<=e.radius){if(h)return!0;let g=u.ri,E=u.rj;g.vadd(i,g),g.vsub(o.position,g),E.vadd(n,E),E.vsub(c.position,E),this.result.push(u),this.createFrictionEquationsFromContact(u,this.frictionResult)}}boxBox(e,t,i,n,r,s,o,c,d,a,h){return e.convexPolyhedronRepresentation.material=e.material,t.convexPolyhedronRepresentation.material=t.material,e.convexPolyhedronRepresentation.collisionResponse=e.collisionResponse,t.convexPolyhedronRepresentation.collisionResponse=t.collisionResponse,this.convexConvex(e.convexPolyhedronRepresentation,t.convexPolyhedronRepresentation,i,n,r,s,o,c,e,t,h)}sphereBox(e,t,i,n,r,s,o,c,d,a,h){let u=this.v3pool,g=Fg;i.vsub(n,Zo),t.getSideNormals(g,s);let E=e.radius,b=!1,y=zg,m=Gg,p=Vg,f=null,v=0,w=0,x=0,T=null;for(let F=0,U=g.length;F!==U&&b===!1;F++){let J=Hg;J.copy(g[F]);let W=J.length();J.normalize();let ze=Zo.dot(J);if(ze<W+E&&ze>0){let ge=jg,X=Bg;ge.copy(g[(F+1)%3]),X.copy(g[(F+2)%3]);let qe=ge.length(),ln=X.length();ge.normalize(),X.normalize();let zn=Zo.dot(ge),Pi=Zo.dot(X);if(zn<qe&&zn>-qe&&Pi<ln&&Pi>-ln){let Pt=Math.abs(ze-W-E);if((T===null||Pt<T)&&(T=Pt,w=zn,x=Pi,f=W,y.copy(J),m.copy(ge),p.copy(X),v++,h))return!0}}}if(v){b=!0;let F=this.createContactEquation(o,c,e,t,d,a);y.scale(-E,F.ri),F.ni.copy(y),F.ni.negate(F.ni),y.scale(f,y),m.scale(w,m),y.vadd(m,y),p.scale(x,p),y.vadd(p,F.rj),F.ri.vadd(i,F.ri),F.ri.vsub(o.position,F.ri),F.rj.vadd(n,F.rj),F.rj.vsub(c.position,F.rj),this.result.push(F),this.createFrictionEquationsFromContact(F,this.frictionResult)}let R=u.get(),C=Ng;for(let F=0;F!==2&&!b;F++)for(let U=0;U!==2&&!b;U++)for(let J=0;J!==2&&!b;J++)if(R.set(0,0,0),F?R.vadd(g[0],R):R.vsub(g[0],R),U?R.vadd(g[1],R):R.vsub(g[1],R),J?R.vadd(g[2],R):R.vsub(g[2],R),n.vadd(R,C),C.vsub(i,C),C.lengthSquared()<E*E){if(h)return!0;b=!0;let W=this.createContactEquation(o,c,e,t,d,a);W.ri.copy(C),W.ri.normalize(),W.ni.copy(W.ri),W.ri.scale(E,W.ri),W.rj.copy(R),W.ri.vadd(i,W.ri),W.ri.vsub(o.position,W.ri),W.rj.vadd(n,W.rj),W.rj.vsub(c.position,W.rj),this.result.push(W),this.createFrictionEquationsFromContact(W,this.frictionResult)}u.release(R),R=null;let P=u.get(),S=u.get(),L=u.get(),I=u.get(),j=u.get(),H=g.length;for(let F=0;F!==H&&!b;F++)for(let U=0;U!==H&&!b;U++)if(F%3!==U%3){g[U].cross(g[F],P),P.normalize(),g[F].vadd(g[U],S),L.copy(i),L.vsub(S,L),L.vsub(n,L);let J=L.dot(P);P.scale(J,I);let W=0;for(;W===F%3||W===U%3;)W++;j.copy(i),j.vsub(I,j),j.vsub(S,j),j.vsub(n,j);let ze=Math.abs(J),ge=j.length();if(ze<g[W].length()&&ge<E){if(h)return!0;b=!0;let X=this.createContactEquation(o,c,e,t,d,a);S.vadd(I,X.rj),X.rj.copy(X.rj),j.negate(X.ni),X.ni.normalize(),X.ri.copy(X.rj),X.ri.vadd(n,X.ri),X.ri.vsub(i,X.ri),X.ri.normalize(),X.ri.scale(E,X.ri),X.ri.vadd(i,X.ri),X.ri.vsub(o.position,X.ri),X.rj.vadd(n,X.rj),X.rj.vsub(c.position,X.rj),this.result.push(X),this.createFrictionEquationsFromContact(X,this.frictionResult)}}u.release(P,S,L,I,j)}planeBox(e,t,i,n,r,s,o,c,d,a,h){return t.convexPolyhedronRepresentation.material=t.material,t.convexPolyhedronRepresentation.collisionResponse=t.collisionResponse,t.convexPolyhedronRepresentation.id=t.id,this.planeConvex(e,t.convexPolyhedronRepresentation,i,n,r,s,o,c,e,t,h)}convexConvex(e,t,i,n,r,s,o,c,d,a,h,u,g){let E=rb;if(!(i.distanceTo(n)>e.boundingSphereRadius+t.boundingSphereRadius)&&e.findSeparatingAxis(t,i,r,n,s,E,u,g)){let b=[],y=sb;e.clipAgainstHull(i,r,t,n,s,E,-100,100,b);let m=0;for(let p=0;p!==b.length;p++){if(h)return!0;let f=this.createContactEquation(o,c,e,t,d,a),v=f.ri,w=f.rj;E.negate(f.ni),b[p].normal.negate(y),y.scale(b[p].depth,y),b[p].point.vadd(y,v),w.copy(b[p].point),v.vsub(i,v),w.vsub(n,w),v.vadd(i,v),v.vsub(o.position,v),w.vadd(n,w),w.vsub(c.position,w),this.result.push(f),m++,this.enableFrictionReduction||this.createFrictionEquationsFromContact(f,this.frictionResult)}this.enableFrictionReduction&&m&&this.createFrictionFromAverage(m)}}sphereConvex(e,t,i,n,r,s,o,c,d,a,h){let u=this.v3pool;i.vsub(n,Wg);let g=t.faceNormals,E=t.faces,b=t.vertices,y=e.radius,m=!1;for(let p=0;p!==b.length;p++){let f=b[p],v=Qg;s.vmult(f,v),n.vadd(v,v);let w=Xg;if(v.vsub(i,w),w.lengthSquared()<y*y){if(h)return!0;m=!0;let x=this.createContactEquation(o,c,e,t,d,a);x.ri.copy(w),x.ri.normalize(),x.ni.copy(x.ri),x.ri.scale(y,x.ri),v.vsub(n,x.rj),x.ri.vadd(i,x.ri),x.ri.vsub(o.position,x.ri),x.rj.vadd(n,x.rj),x.rj.vsub(c.position,x.rj),this.result.push(x),this.createFrictionEquationsFromContact(x,this.frictionResult);return}}for(let p=0,f=E.length;p!==f&&m===!1;p++){let v=g[p],w=E[p],x=Yg;s.vmult(v,x);let T=Zg;s.vmult(b[w[0]],T),T.vadd(n,T);let R=Jg;x.scale(-y,R),i.vadd(R,R);let C=$g;R.vsub(T,C);let P=C.dot(x),S=Kg;if(i.vsub(T,S),P<0&&S.dot(x)>0){let L=[];for(let I=0,j=w.length;I!==j;I++){let H=u.get();s.vmult(b[w[I]],H),n.vadd(H,H),L.push(H)}if(Dg(L,x,i)){if(h)return!0;m=!0;let I=this.createContactEquation(o,c,e,t,d,a);x.scale(-y,I.ri),x.negate(I.ni);let j=u.get();x.scale(-P,j);let H=u.get();x.scale(-y,H),i.vsub(n,I.rj),I.rj.vadd(H,I.rj),I.rj.vadd(j,I.rj),I.rj.vadd(n,I.rj),I.rj.vsub(c.position,I.rj),I.ri.vadd(i,I.ri),I.ri.vsub(o.position,I.ri),u.release(j),u.release(H),this.result.push(I),this.createFrictionEquationsFromContact(I,this.frictionResult);for(let F=0,U=L.length;F!==U;F++)u.release(L[F]);return}else for(let I=0;I!==w.length;I++){let j=u.get(),H=u.get();s.vmult(b[w[(I+1)%w.length]],j),s.vmult(b[w[(I+2)%w.length]],H),n.vadd(j,j),n.vadd(H,H);let F=Ug;H.vsub(j,F);let U=qg;F.unit(U);let J=u.get(),W=u.get();i.vsub(j,W);let ze=W.dot(U);U.scale(ze,J),J.vadd(j,J);let ge=u.get();if(J.vsub(i,ge),ze>0&&ze*ze<F.lengthSquared()&&ge.lengthSquared()<y*y){if(h)return!0;let X=this.createContactEquation(o,c,e,t,d,a);J.vsub(n,X.rj),J.vsub(i,X.ni),X.ni.normalize(),X.ni.scale(y,X.ri),X.rj.vadd(n,X.rj),X.rj.vsub(c.position,X.rj),X.ri.vadd(i,X.ri),X.ri.vsub(o.position,X.ri),this.result.push(X),this.createFrictionEquationsFromContact(X,this.frictionResult);for(let qe=0,ln=L.length;qe!==ln;qe++)u.release(L[qe]);u.release(j),u.release(H),u.release(J),u.release(ge),u.release(W);return}u.release(j),u.release(H),u.release(J),u.release(ge),u.release(W)}for(let I=0,j=L.length;I!==j;I++)u.release(L[I])}}}planeConvex(e,t,i,n,r,s,o,c,d,a,h){let u=eb,g=tb;g.set(0,0,1),r.vmult(g,g);let E=0,b=ib;for(let y=0;y!==t.vertices.length;y++)if(u.copy(t.vertices[y]),s.vmult(u,u),n.vadd(u,u),u.vsub(i,b),g.dot(b)<=0){if(h)return!0;let p=this.createContactEquation(o,c,e,t,d,a),f=nb;g.scale(g.dot(b),f),u.vsub(f,f),f.vsub(i,p.ri),p.ni.copy(g),u.vsub(n,p.rj),p.ri.vadd(i,p.ri),p.ri.vsub(o.position,p.ri),p.rj.vadd(n,p.rj),p.rj.vsub(c.position,p.rj),this.result.push(p),E++,this.enableFrictionReduction||this.createFrictionEquationsFromContact(p,this.frictionResult)}this.enableFrictionReduction&&E&&this.createFrictionFromAverage(E)}boxConvex(e,t,i,n,r,s,o,c,d,a,h){return e.convexPolyhedronRepresentation.material=e.material,e.convexPolyhedronRepresentation.collisionResponse=e.collisionResponse,this.convexConvex(e.convexPolyhedronRepresentation,t,i,n,r,s,o,c,e,t,h)}sphereHeightfield(e,t,i,n,r,s,o,c,d,a,h){let u=t.data,g=e.radius,E=t.elementSize,b=bb,y=gb;te.pointToLocalFrame(n,s,i,y);let m=Math.floor((y.x-g)/E)-1,p=Math.ceil((y.x+g)/E)+1,f=Math.floor((y.y-g)/E)-1,v=Math.ceil((y.y+g)/E)+1;if(p<0||v<0||m>u.length||f>u[0].length)return;m<0&&(m=0),p<0&&(p=0),f<0&&(f=0),v<0&&(v=0),m>=u.length&&(m=u.length-1),p>=u.length&&(p=u.length-1),v>=u[0].length&&(v=u[0].length-1),f>=u[0].length&&(f=u[0].length-1);let w=[];t.getRectMinMax(m,f,p,v,w);let x=w[0],T=w[1];if(y.z-g>T||y.z+g<x)return;let R=this.result;for(let C=m;C<p;C++)for(let P=f;P<v;P++){let S=R.length,L=!1;if(t.getConvexTrianglePillar(C,P,!1),te.pointToWorldFrame(n,s,t.pillarOffset,b),i.distanceTo(b)<t.pillarConvex.boundingSphereRadius+e.boundingSphereRadius&&(L=this.sphereConvex(e,t.pillarConvex,i,b,r,s,o,c,e,t,h)),h&&L||(t.getConvexTrianglePillar(C,P,!0),te.pointToWorldFrame(n,s,t.pillarOffset,b),i.distanceTo(b)<t.pillarConvex.boundingSphereRadius+e.boundingSphereRadius&&(L=this.sphereConvex(e,t.pillarConvex,i,b,r,s,o,c,e,t,h)),h&&L))return!0;if(R.length-S>2)return}}boxHeightfield(e,t,i,n,r,s,o,c,d,a,h){return e.convexPolyhedronRepresentation.material=e.material,e.convexPolyhedronRepresentation.collisionResponse=e.collisionResponse,this.convexHeightfield(e.convexPolyhedronRepresentation,t,i,n,r,s,o,c,e,t,h)}convexHeightfield(e,t,i,n,r,s,o,c,d,a,h){let u=t.data,g=t.elementSize,E=e.boundingSphereRadius,b=fb,y=mb,m=pb;te.pointToLocalFrame(n,s,i,m);let p=Math.floor((m.x-E)/g)-1,f=Math.ceil((m.x+E)/g)+1,v=Math.floor((m.y-E)/g)-1,w=Math.ceil((m.y+E)/g)+1;if(f<0||w<0||p>u.length||v>u[0].length)return;p<0&&(p=0),f<0&&(f=0),v<0&&(v=0),w<0&&(w=0),p>=u.length&&(p=u.length-1),f>=u.length&&(f=u.length-1),w>=u[0].length&&(w=u[0].length-1),v>=u[0].length&&(v=u[0].length-1);let x=[];t.getRectMinMax(p,v,f,w,x);let T=x[0],R=x[1];if(!(m.z-E>R||m.z+E<T))for(let C=p;C<f;C++)for(let P=v;P<w;P++){let S=!1;if(t.getConvexTrianglePillar(C,P,!1),te.pointToWorldFrame(n,s,t.pillarOffset,b),i.distanceTo(b)<t.pillarConvex.boundingSphereRadius+e.boundingSphereRadius&&(S=this.convexConvex(e,t.pillarConvex,i,b,r,s,o,c,null,null,h,y,null)),h&&S||(t.getConvexTrianglePillar(C,P,!0),te.pointToWorldFrame(n,s,t.pillarOffset,b),i.distanceTo(b)<t.pillarConvex.boundingSphereRadius+e.boundingSphereRadius&&(S=this.convexConvex(e,t.pillarConvex,i,b,r,s,o,c,null,null,h,y,null)),h&&S))return!0}}sphereParticle(e,t,i,n,r,s,o,c,d,a,h){let u=cb;if(u.set(0,0,1),n.vsub(i,u),u.lengthSquared()<=e.radius*e.radius){if(h)return!0;let E=this.createContactEquation(c,o,t,e,d,a);u.normalize(),E.rj.copy(u),E.rj.scale(e.radius,E.rj),E.ni.copy(u),E.ni.negate(E.ni),E.ri.set(0,0,0),this.result.push(E),this.createFrictionEquationsFromContact(E,this.frictionResult)}}planeParticle(e,t,i,n,r,s,o,c,d,a,h){let u=ob;u.set(0,0,1),o.quaternion.vmult(u,u);let g=ab;if(n.vsub(o.position,g),u.dot(g)<=0){if(h)return!0;let b=this.createContactEquation(c,o,t,e,d,a);b.ni.copy(u),b.ni.negate(b.ni),b.ri.set(0,0,0);let y=lb;u.scale(u.dot(n),y),n.vsub(y,y),b.rj.copy(y),this.result.push(b),this.createFrictionEquationsFromContact(b,this.frictionResult)}}boxParticle(e,t,i,n,r,s,o,c,d,a,h){return e.convexPolyhedronRepresentation.material=e.material,e.convexPolyhedronRepresentation.collisionResponse=e.collisionResponse,this.convexParticle(e.convexPolyhedronRepresentation,t,i,n,r,s,o,c,e,t,h)}convexParticle(e,t,i,n,r,s,o,c,d,a,h){let u=-1,g=hb,E=ub,b=null,y=db;if(y.copy(n),y.vsub(i,y),r.conjugate(Xh),Xh.vmult(y,y),e.pointIsInside(y)){e.worldVerticesNeedsUpdate&&e.computeWorldVertices(i,r),e.worldFaceNormalsNeedsUpdate&&e.computeWorldFaceNormals(r);for(let m=0,p=e.faces.length;m!==p;m++){let f=[e.worldVertices[e.faces[m][0]]],v=e.worldFaceNormals[m];n.vsub(f[0],Qh);let w=-v.dot(Qh);if(b===null||Math.abs(w)<Math.abs(b)){if(h)return!0;b=w,u=m,g.copy(v)}}if(u!==-1){let m=this.createContactEquation(c,o,t,e,d,a);g.scale(b,E),E.vadd(n,E),E.vsub(i,E),m.rj.copy(E),g.negate(m.ni),m.ri.set(0,0,0);let p=m.ri,f=m.rj;p.vadd(n,p),p.vsub(c.position,p),f.vadd(i,f),f.vsub(o.position,f),this.result.push(m),this.createFrictionEquationsFromContact(m,this.frictionResult)}else console.warn("Point found inside convex, but did not find penetrating face!")}}heightfieldCylinder(e,t,i,n,r,s,o,c,d,a,h){return this.convexHeightfield(t,e,n,i,s,r,c,o,d,a,h)}particleCylinder(e,t,i,n,r,s,o,c,d,a,h){return this.convexParticle(t,e,n,i,s,r,c,o,d,a,h)}sphereTrimesh(e,t,i,n,r,s,o,c,d,a,h){let u=wg,g=_g,E=xg,b=Tg,y=Rg,m=Cg,p=Ag,f=Eg,v=vg,w=kg;te.pointToLocalFrame(n,s,i,y);let x=e.radius;p.lowerBound.set(y.x-x,y.y-x,y.z-x),p.upperBound.set(y.x+x,y.y+x,y.z+x),t.getTrianglesInAABB(p,w);let T=yg,R=e.radius*e.radius;for(let I=0;I<w.length;I++)for(let j=0;j<3;j++)if(t.getVertex(t.indices[w[I]*3+j],T),T.vsub(y,v),v.lengthSquared()<=R){if(f.copy(T),te.pointToWorldFrame(n,s,f,T),T.vsub(i,v),h)return!0;let H=this.createContactEquation(o,c,e,t,d,a);H.ni.copy(v),H.ni.normalize(),H.ri.copy(H.ni),H.ri.scale(e.radius,H.ri),H.ri.vadd(i,H.ri),H.ri.vsub(o.position,H.ri),H.rj.copy(T),H.rj.vsub(c.position,H.rj),this.result.push(H),this.createFrictionEquationsFromContact(H,this.frictionResult)}for(let I=0;I<w.length;I++)for(let j=0;j<3;j++){t.getVertex(t.indices[w[I]*3+j],u),t.getVertex(t.indices[w[I]*3+(j+1)%3],g),g.vsub(u,E),y.vsub(g,m);let H=m.dot(E);y.vsub(u,m);let F=m.dot(E);if(F>0&&H<0&&(y.vsub(u,m),b.copy(E),b.normalize(),F=m.dot(b),b.scale(F,m),m.vadd(u,m),m.distanceTo(y)<e.radius)){if(h)return!0;let J=this.createContactEquation(o,c,e,t,d,a);m.vsub(y,J.ni),J.ni.normalize(),J.ni.scale(e.radius,J.ri),J.ri.vadd(i,J.ri),J.ri.vsub(o.position,J.ri),te.pointToWorldFrame(n,s,m,m),m.vsub(c.position,J.rj),te.vectorToWorldFrame(s,J.ni,J.ni),te.vectorToWorldFrame(s,J.ri,J.ri),this.result.push(J),this.createFrictionEquationsFromContact(J,this.frictionResult)}}let C=Sg,P=Pg,S=Og,L=bg;for(let I=0,j=w.length;I!==j;I++){t.getTriangleVertices(w[I],C,P,S),t.getNormal(w[I],L),y.vsub(C,m);let H=m.dot(L);if(L.scale(H,m),y.vsub(m,m),H=m.distanceTo(y),Ee.pointInTriangle(m,C,P,S)&&H<e.radius){if(h)return!0;let F=this.createContactEquation(o,c,e,t,d,a);m.vsub(y,F.ni),F.ni.normalize(),F.ni.scale(e.radius,F.ri),F.ri.vadd(i,F.ri),F.ri.vsub(o.position,F.ri),te.pointToWorldFrame(n,s,m,m),m.vsub(c.position,F.rj),te.vectorToWorldFrame(s,F.ni,F.ni),te.vectorToWorldFrame(s,F.ri,F.ri),this.result.push(F),this.createFrictionEquationsFromContact(F,this.frictionResult)}}w.length=0}planeTrimesh(e,t,i,n,r,s,o,c,d,a,h){let u=new _,g=fg;g.set(0,0,1),r.vmult(g,g);for(let E=0;E<t.vertices.length/3;E++){t.getVertex(E,u);let b=new _;b.copy(u),te.pointToWorldFrame(n,s,b,u);let y=mg;if(u.vsub(i,y),g.dot(y)<=0){if(h)return!0;let p=this.createContactEquation(o,c,e,t,d,a);p.ni.copy(g);let f=gg;g.scale(y.dot(g),f),u.vsub(f,f),p.ri.copy(f),p.ri.vsub(o.position,p.ri),p.rj.copy(u),p.rj.vsub(c.position,p.rj),this.result.push(p),this.createFrictionEquationsFromContact(p,this.frictionResult)}}}},qn=new _,Pr=new _,Or=new _,dg=new _,hg=new _,ug=new le,pg=new le,fg=new _,mg=new _,gg=new _,bg=new _,vg=new _,yg=new _,Eg=new _,wg=new _,_g=new _,xg=new _,Tg=new _,Rg=new _,Cg=new _,Sg=new _,Pg=new _,Og=new _,Ag=new $e,kg=[],Yo=new _,qh=new _,Ig=new _,Mg=new _,Lg=new _;function Dg(l,e,t){let i=null,n=l.length;for(let r=0;r!==n;r++){let s=l[r],o=Ig;l[(r+1)%n].vsub(s,o);let c=Mg;o.cross(e,c);let d=Lg;t.vsub(s,d);let a=c.dot(d);if(i===null||a>0&&i===!0||a<=0&&i===!1){i===null&&(i=a>0);continue}else return!1}return!0}var Zo=new _,Hg=new _,jg=new _,Bg=new _,Fg=[new _,new _,new _,new _,new _,new _],Ng=new _,zg=new _,Gg=new _,Vg=new _,Wg=new _,Ug=new _,qg=new _,Xg=new _,Qg=new _,Yg=new _,Zg=new _,Jg=new _,$g=new _,Kg=new _,eb=new _,tb=new _,ib=new _,nb=new _,rb=new _,sb=new _,ob=new _,ab=new _,lb=new _,cb=new _,Xh=new le,db=new _,hb=new _,Qh=new _,ub=new _,pb=new _,fb=new _,mb=[0],gb=new _,bb=new _,ra=class{constructor(){this.current=void 0,this.previous=void 0,this.current=[],this.previous=[]}getKey(e,t){if(t<e){let i=t;t=e,e=i}return e<<16|t}set(e,t){let i=this.getKey(e,t),n=this.current,r=0;for(;i>n[r];)r++;if(i!==n[r]){for(let s=n.length-1;s>=r;s--)n[s+1]=n[s];n[r]=i}}tick(){let e=this.current;this.current=this.previous,this.previous=e,this.current.length=0}getDiff(e,t){let i=this.current,n=this.previous,r=i.length,s=n.length,o=0;for(let c=0;c<r;c++){let d=!1,a=i[c];for(;a>n[o];)o++;d=a===n[o],d||Yh(e,a)}o=0;for(let c=0;c<s;c++){let d=!1,a=n[c];for(;a>i[o];)o++;d=i[o]===a,d||Yh(t,a)}}};function Yh(l,e){l.push((e&4294901760)>>16,e&65535)}var Zl=class{constructor(){this.data={keys:[]}}get(e,t){if(e>t){let i=t;t=e,e=i}return this.data[e+"-"+t]}set(e,t,i){if(e>t){let r=t;t=e,e=r}let n=e+"-"+t;this.get(e,t)||this.data.keys.push(n),this.data[n]=i}reset(){let e=this.data,t=e.keys;for(;t.length>0;){let i=t.pop();delete e[i]}}},sa=class extends $o{constructor(e={}){super(),this.dt=void 0,this.allowSleep=void 0,this.contacts=void 0,this.frictionEquations=void 0,this.quatNormalizeSkip=void 0,this.quatNormalizeFast=void 0,this.time=void 0,this.stepnumber=void 0,this.default_dt=void 0,this.nextId=void 0,this.gravity=void 0,this.broadphase=void 0,this.bodies=void 0,this.hasActiveBodies=void 0,this.solver=void 0,this.constraints=void 0,this.narrowphase=void 0,this.collisionMatrix=void 0,this.collisionMatrixPrevious=void 0,this.bodyOverlapKeeper=void 0,this.shapeOverlapKeeper=void 0,this.materials=void 0,this.contactmaterials=void 0,this.contactMaterialTable=void 0,this.defaultMaterial=void 0,this.defaultContactMaterial=void 0,this.doProfiling=void 0,this.profile=void 0,this.accumulator=void 0,this.subsystems=void 0,this.addBodyEvent=void 0,this.removeBodyEvent=void 0,this.idToBodyMap=void 0,this.dt=-1,this.allowSleep=!!e.allowSleep,this.contacts=[],this.frictionEquations=[],this.quatNormalizeSkip=e.quatNormalizeSkip!==void 0?e.quatNormalizeSkip:0,this.quatNormalizeFast=e.quatNormalizeFast!==void 0?e.quatNormalizeFast:!1,this.time=0,this.stepnumber=0,this.default_dt=1/60,this.nextId=0,this.gravity=new _,e.gravity&&this.gravity.copy(e.gravity),this.broadphase=e.broadphase!==void 0?e.broadphase:new Vl,this.bodies=[],this.hasActiveBodies=!1,this.solver=e.solver!==void 0?e.solver:new ql,this.constraints=[],this.narrowphase=new Yl(this),this.collisionMatrix=new Jo,this.collisionMatrixPrevious=new Jo,this.bodyOverlapKeeper=new ra,this.shapeOverlapKeeper=new ra,this.materials=[],this.contactmaterials=[],this.contactMaterialTable=new Zl,this.defaultMaterial=new kr("default"),this.defaultContactMaterial=new Ar(this.defaultMaterial,this.defaultMaterial,{friction:.3,restitution:0}),this.doProfiling=!1,this.profile={solve:0,makeContactConstraints:0,broadphase:0,integrate:0,narrowphase:0},this.accumulator=0,this.subsystems=[],this.addBodyEvent={type:"addBody",body:null},this.removeBodyEvent={type:"removeBody",body:null},this.idToBodyMap={},this.broadphase.setWorld(this)}getContactMaterial(e,t){return this.contactMaterialTable.get(e.id,t.id)}numObjects(){return this.bodies.length}collisionMatrixTick(){let e=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=e,this.collisionMatrix.reset(),this.bodyOverlapKeeper.tick(),this.shapeOverlapKeeper.tick()}addConstraint(e){this.constraints.push(e)}removeConstraint(e){let t=this.constraints.indexOf(e);t!==-1&&this.constraints.splice(t,1)}rayTest(e,t,i){i instanceof Js?this.raycastClosest(e,t,{skipBackfaces:!0},i):this.raycastAll(e,t,{skipBackfaces:!0},i)}raycastAll(e,t,i={},n){return i.mode=Ee.ALL,i.from=e,i.to=t,i.callback=n,zl.intersectWorld(this,i)}raycastAny(e,t,i={},n){return i.mode=Ee.ANY,i.from=e,i.to=t,i.result=n,zl.intersectWorld(this,i)}raycastClosest(e,t,i={},n){return i.mode=Ee.CLOSEST,i.from=e,i.to=t,i.result=n,zl.intersectWorld(this,i)}addBody(e){this.bodies.includes(e)||(e.index=this.bodies.length,this.bodies.push(e),e.world=this,e.initPosition.copy(e.position),e.initVelocity.copy(e.velocity),e.timeLastSleepy=this.time,e instanceof G&&(e.initAngularVelocity.copy(e.angularVelocity),e.initQuaternion.copy(e.quaternion)),this.collisionMatrix.setNumObjects(this.bodies.length),this.addBodyEvent.body=e,this.idToBodyMap[e.id]=e,this.dispatchEvent(this.addBodyEvent))}removeBody(e){e.world=null;let t=this.bodies.length-1,i=this.bodies,n=i.indexOf(e);if(n!==-1){i.splice(n,1);for(let r=0;r!==i.length;r++)i[r].index=r;this.collisionMatrix.setNumObjects(t),this.removeBodyEvent.body=e,delete this.idToBodyMap[e.id],this.dispatchEvent(this.removeBodyEvent)}}getBodyById(e){return this.idToBodyMap[e]}getShapeById(e){let t=this.bodies;for(let i=0;i<t.length;i++){let n=t[i].shapes;for(let r=0;r<n.length;r++){let s=n[r];if(s.id===e)return s}}return null}addMaterial(e){this.materials.push(e)}addContactMaterial(e){this.contactmaterials.push(e),this.contactMaterialTable.set(e.materials[0].id,e.materials[1].id,e)}step(e,t,i=10){if(t===void 0)this.internalStep(e),this.time+=e;else{this.accumulator+=t;let n=He.now(),r=0;for(;this.accumulator>=e&&r<i&&(this.internalStep(e),this.accumulator-=e,r++,!(He.now()-n>e*1e3)););this.accumulator=this.accumulator%e;let s=this.accumulator/e;for(let o=0;o!==this.bodies.length;o++){let c=this.bodies[o];c.previousPosition.lerp(c.position,s,c.interpolatedPosition),c.previousQuaternion.slerp(c.quaternion,s,c.interpolatedQuaternion),c.previousQuaternion.normalize()}this.time+=t}}internalStep(e){this.dt=e;let t=this.contacts,i=_b,n=xb,r=this.numObjects(),s=this.bodies,o=this.solver,c=this.gravity,d=this.doProfiling,a=this.profile,h=G.DYNAMIC,u=-1/0,g=this.constraints,E=wb;c.length();let b=c.x,y=c.y,m=c.z,p=0;for(d&&(u=He.now()),p=0;p!==r;p++){let I=s[p];if(I.type===h){let j=I.force,H=I.mass;j.x+=H*b,j.y+=H*y,j.z+=H*m}}for(let I=0,j=this.subsystems.length;I!==j;I++)this.subsystems[I].update();d&&(u=He.now()),i.length=0,n.length=0,this.broadphase.collisionPairs(this,i,n),d&&(a.broadphase=He.now()-u);let f=g.length;for(p=0;p!==f;p++){let I=g[p];if(!I.collideConnected)for(let j=i.length-1;j>=0;j-=1)(I.bodyA===i[j]&&I.bodyB===n[j]||I.bodyB===i[j]&&I.bodyA===n[j])&&(i.splice(j,1),n.splice(j,1))}this.collisionMatrixTick(),d&&(u=He.now());let v=Eb,w=t.length;for(p=0;p!==w;p++)v.push(t[p]);t.length=0;let x=this.frictionEquations.length;for(p=0;p!==x;p++)E.push(this.frictionEquations[p]);for(this.frictionEquations.length=0,this.narrowphase.getContacts(i,n,this,t,v,this.frictionEquations,E),d&&(a.narrowphase=He.now()-u),d&&(u=He.now()),p=0;p<this.frictionEquations.length;p++)o.addEquation(this.frictionEquations[p]);let T=t.length;for(let I=0;I!==T;I++){let j=t[I],H=j.bi,F=j.bj,U=j.si,J=j.sj,W;if(H.material&&F.material?W=this.getContactMaterial(H.material,F.material)||this.defaultContactMaterial:W=this.defaultContactMaterial,W.friction,H.material&&F.material&&(H.material.friction>=0&&F.material.friction>=0&&H.material.friction*F.material.friction,H.material.restitution>=0&&F.material.restitution>=0&&(j.restitution=H.material.restitution*F.material.restitution)),o.addEquation(j),H.allowSleep&&H.type===G.DYNAMIC&&H.sleepState===G.SLEEPING&&F.sleepState===G.AWAKE&&F.type!==G.STATIC){let ze=F.velocity.lengthSquared()+F.angularVelocity.lengthSquared(),ge=F.sleepSpeedLimit**2;ze>=ge*2&&(H.wakeUpAfterNarrowphase=!0)}if(F.allowSleep&&F.type===G.DYNAMIC&&F.sleepState===G.SLEEPING&&H.sleepState===G.AWAKE&&H.type!==G.STATIC){let ze=H.velocity.lengthSquared()+H.angularVelocity.lengthSquared(),ge=H.sleepSpeedLimit**2;ze>=ge*2&&(F.wakeUpAfterNarrowphase=!0)}this.collisionMatrix.set(H,F,!0),this.collisionMatrixPrevious.get(H,F)||(Qs.body=F,Qs.contact=j,H.dispatchEvent(Qs),Qs.body=H,F.dispatchEvent(Qs)),this.bodyOverlapKeeper.set(H.id,F.id),this.shapeOverlapKeeper.set(U.id,J.id)}for(this.emitContactEvents(),d&&(a.makeContactConstraints=He.now()-u,u=He.now()),p=0;p!==r;p++){let I=s[p];I.wakeUpAfterNarrowphase&&(I.wakeUp(),I.wakeUpAfterNarrowphase=!1)}for(f=g.length,p=0;p!==f;p++){let I=g[p];I.update();for(let j=0,H=I.equations.length;j!==H;j++){let F=I.equations[j];o.addEquation(F)}}o.solve(e,this),d&&(a.solve=He.now()-u),o.removeAllEquations();let R=Math.pow;for(p=0;p!==r;p++){let I=s[p];if(I.type&h){let j=R(1-I.linearDamping,e),H=I.velocity;H.scale(j,H);let F=I.angularVelocity;if(F){let U=R(1-I.angularDamping,e);F.scale(U,F)}}}for(this.dispatchEvent(yb),p=0;p!==r;p++){let I=s[p];I.preStep&&I.preStep.call(I)}d&&(u=He.now());let P=this.stepnumber%(this.quatNormalizeSkip+1)===0,S=this.quatNormalizeFast;for(p=0;p!==r;p++)s[p].integrate(e,P,S);for(this.clearForces(),this.broadphase.dirty=!0,d&&(a.integrate=He.now()-u),this.stepnumber+=1,this.dispatchEvent(vb),p=0;p!==r;p++){let I=s[p],j=I.postStep;j&&j.call(I)}let L=!0;if(this.allowSleep)for(L=!1,p=0;p!==r;p++){let I=s[p];I.sleepTick(this.time),I.sleepState!==G.SLEEPING&&(L=!0)}this.hasActiveBodies=L}emitContactEvents(){let e=this.hasAnyEventListener("beginContact"),t=this.hasAnyEventListener("endContact");if((e||t)&&this.bodyOverlapKeeper.getDiff(ki,Ii),e){for(let r=0,s=ki.length;r<s;r+=2)Ys.bodyA=this.getBodyById(ki[r]),Ys.bodyB=this.getBodyById(ki[r+1]),this.dispatchEvent(Ys);Ys.bodyA=Ys.bodyB=null}if(t){for(let r=0,s=Ii.length;r<s;r+=2)Zs.bodyA=this.getBodyById(Ii[r]),Zs.bodyB=this.getBodyById(Ii[r+1]),this.dispatchEvent(Zs);Zs.bodyA=Zs.bodyB=null}ki.length=Ii.length=0;let i=this.hasAnyEventListener("beginShapeContact"),n=this.hasAnyEventListener("endShapeContact");if((i||n)&&this.shapeOverlapKeeper.getDiff(ki,Ii),i){for(let r=0,s=ki.length;r<s;r+=2){let o=this.getShapeById(ki[r]),c=this.getShapeById(ki[r+1]);Mi.shapeA=o,Mi.shapeB=c,o&&(Mi.bodyA=o.body),c&&(Mi.bodyB=c.body),this.dispatchEvent(Mi)}Mi.bodyA=Mi.bodyB=Mi.shapeA=Mi.shapeB=null}if(n){for(let r=0,s=Ii.length;r<s;r+=2){let o=this.getShapeById(Ii[r]),c=this.getShapeById(Ii[r+1]);Li.shapeA=o,Li.shapeB=c,o&&(Li.bodyA=o.body),c&&(Li.bodyB=c.body),this.dispatchEvent(Li)}Li.bodyA=Li.bodyB=Li.shapeA=Li.shapeB=null}}clearForces(){let e=this.bodies,t=e.length;for(let i=0;i!==t;i++){let n=e[i];n.force,n.torque,n.force.set(0,0,0),n.torque.set(0,0,0)}}};new $e;var zl=new Ee,He=globalThis.performance||{};if(!He.now){let l=Date.now();He.timing&&He.timing.navigationStart&&(l=He.timing.navigationStart),He.now=()=>Date.now()-l}var vb={type:"postStep"},yb={type:"preStep"},Qs={type:G.COLLIDE_EVENT_NAME,body:null,contact:null},Eb=[],wb=[],_b=[],xb=[],ki=[],Ii=[],Ys={type:"beginContact",bodyA:null,bodyB:null},Zs={type:"endContact",bodyA:null,bodyB:null},Mi={type:"beginShapeContact",bodyA:null,bodyB:null,shapeA:null,shapeB:null},Li={type:"endShapeContact",bodyA:null,bodyB:null,shapeA:null,shapeB:null};import*as ke from"three";import{MeshBasicMaterial as Tb,SphereGeometry as Pu,BoxGeometry as Ou,PlaneGeometry as Au,Mesh as mn,CylinderGeometry as Rb,BufferGeometry as tc,Float32BufferAttribute as ic}from"three";function Cb(l,e,{color:t=65280,scale:i=1,onInit:n,onUpdate:r,autoUpdate:s}={}){let o=[],c=new Tb({color:t??65280,wireframe:!0}),d=new _,a=new _,h=new _,u=new le,g=new Pu(1),E=new Ou(1,1,1),b=new Au(10,10,10,10);function y(R){let C=new tc,P=[];for(let L=0;L<R.vertices.length;L++){let I=R.vertices[L];P.push(I.x,I.y,I.z)}C.setAttribute("position",new ic(P,3));let S=[];for(let L=0;L<R.faces.length;L++){let I=R.faces[L],j=I[0];for(let H=1;H<I.length-1;H++){let F=I[H],U=I[H+1];S.push(j,F,U)}}return C.setIndex(S),C.computeBoundingSphere(),C.computeVertexNormals(),C}function m(R){let C=new tc,P=[],S=d,L=a,I=h;for(let j=0;j<R.indices.length/3;j++)R.getTriangleVertices(j,S,L,I),P.push(S.x,S.y,S.z),P.push(L.x,L.y,L.z),P.push(I.x,I.y,I.z);return C.setAttribute("position",new ic(P,3)),C.computeBoundingSphere(),C.computeVertexNormals(),C}function p(R){let C=new tc,P=R.elementSize||1,S=R.data.flatMap((I,j)=>I.flatMap((H,F)=>[j*P,F*P,H])),L=[];for(let I=0;I<R.data.length-1;I++)for(let j=0;j<R.data[I].length-1;j++){let H=R.data[I].length,F=I*H+j;L.push(F+1,F+H,F+H+1),L.push(F+H,F+1,F)}return C.setIndex(L),C.setAttribute("position",new ic(S,3)),C.computeBoundingSphere(),C.computeVertexNormals(),C}function f(R){let C=new mn,{SPHERE:P,BOX:S,PLANE:L,CYLINDER:I,CONVEXPOLYHEDRON:j,TRIMESH:H,HEIGHTFIELD:F}=V.types;switch(R.type){case P:{C=new mn(g,c);break}case S:{C=new mn(E,c);break}case L:{C=new mn(b,c);break}case I:{let U=new Rb(R.radiusTop,R.radiusBottom,R.height,R.numSegments);C=new mn(U,c),R.geometryId=U.id;break}case j:{let U=y(R);C=new mn(U,c),R.geometryId=U.id;break}case H:{let U=m(R);C=new mn(U,c),R.geometryId=U.id;break}case F:{let U=p(R);C=new mn(U,c),R.geometryId=U.id;break}}return l.add(C),C}function v(R,C){let{SPHERE:P,BOX:S,PLANE:L,CYLINDER:I,CONVEXPOLYHEDRON:j,TRIMESH:H,HEIGHTFIELD:F}=V.types;switch(C.type){case P:{let{radius:U}=C;R.scale.set(U*i,U*i,U*i);break}case S:{R.scale.copy(C.halfExtents),R.scale.multiplyScalar(2*i);break}case L:break;case I:{R.scale.set(1*i,1*i,1*i);break}case j:{R.scale.set(1*i,1*i,1*i);break}case H:{R.scale.copy(C.scale).multiplyScalar(i);break}case F:{R.scale.set(1*i,1*i,1*i);break}}}function w(R,C){if(!R)return!1;let{geometry:P}=R;return P instanceof Pu&&C.type===V.types.SPHERE||P instanceof Ou&&C.type===V.types.BOX||P instanceof Au&&C.type===V.types.PLANE||P.id===C.geometryId&&C.type===V.types.CYLINDER||P.id===C.geometryId&&C.type===V.types.CONVEXPOLYHEDRON||P.id===C.geometryId&&C.type===V.types.TRIMESH||P.id===C.geometryId&&C.type===V.types.HEIGHTFIELD}function x(R,C){let P=o[R],S=!1;return w(P,C)||(P&&l.remove(P),o[R]=P=f(C),S=!0),v(P,C),S}function T(){let R=o,C=d,P=u,S=0;for(let L of e)for(let I=0;I!==L.shapes.length;I++){let j=L.shapes[I],H=x(S,j),F=R[S];F&&(L.quaternion.vmult(L.shapeOffsets[I],C),L.position.vadd(C,C),L.quaternion.mult(L.shapeOrientations[I],P),F.position.copy(C),F.quaternion.copy(P),H&&n instanceof Function&&n(L,F,j),!H&&r instanceof Function&&r(L,F,j)),S++}for(let L=S;L<R.length;L++){let I=R[L];I&&l.remove(I)}R.length=S,s!==!1&&requestAnimationFrame(T)}return s!==!1&&requestAnimationFrame(T),{update:T}}var ku=Cb;import*as ai from"three";import*as Ks from"three";var Di=class{get lightmap(){return this.lightmapTexture}set lightmap(e){e!==this.lightmapTexture&&(this.lightmapTexture=e,this.setupLightmap())}lightmapIndex=-1;lightmapScaleOffset=new Ks.Vector4(1,1,0,0);context;gameObject;lightmapTexture=null;lightmapScaleOffsetUniform={value:new Ks.Vector4(1,1,0,0)};lightmapUniform={value:null};beforeRenderCallback;constructor(e,t){this.gameObject=e,this.context=t}init(e,t,i,n=!1){if(console.assert(this.gameObject!==void 0&&this.gameObject!==null,"Missing gameobject",this),this.lightmapIndex=e,this.lightmapIndex<0)return;this.lightmapScaleOffset=t,this.lightmapTexture=i,n&&this.setLightmapDebugMaterial(),this.setupLightmap()}bindOnBeforeRender(){this.beforeRenderCallback=this.onBeforeRenderThreeComplete.bind(this),this.context.addBeforeRenderListener(this.gameObject,this.beforeRenderCallback)}onBeforeRenderThreeComplete(e,t,i,n,r,s){this.onBeforeRenderThree(r)}setupLightmap(){if(this.gameObject.type==="Object3D")return;if(this.gameObject.type==="Group"){console.warn("Lightmap on multimaterial object is not supported yet... please ask kindly for implementation.");return}console.assert(this.gameObject.type==="Mesh","Lightmap only works on meshes",this);let e=this.gameObject;e.geometry.getAttribute("uv2")||e.geometry.setAttribute("uv2",e.geometry.getAttribute("uv"));let t=this.gameObject.material.clone();if(this.gameObject.material=t,this.gameObject.material.onBeforeCompile=(i,n)=>{i.uniforms.lightmap=this.lightmapUniform,i.uniforms.lightmapScaleOffset=this.lightmapScaleOffsetUniform},this.lightmapIndex>=0){let i=this.lightmapTexture,n=this.gameObject.material;n&&i&&(n.uniforms||(n.uniforms={}),n.lightMap=i,n.uniforms.lightmap={value:i})}}onBeforeRenderThree(e){let t=e.uniforms;t&&t.lightmap&&(this.lightmapScaleOffsetUniform.value=this.lightmapScaleOffset,this.lightmapUniform.value=this.lightmapTexture,t.lightmap=this.lightmapUniform,t.lightmapScaleOffset=this.lightmapScaleOffsetUniform)}setLightmapDebugMaterial(){this.gameObject.material=new Ks.ShaderMaterial({vertexShader:`
91
+ }`});import*as Jo from"three";var Oh=/^(?:[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 qf(l){return typeof l=="string"&&Oh.test(l)}var Ah=qf;var Ve=[];for(let l=0;l<256;++l)Ve.push((l+256).toString(16).slice(1));function kh(l,e=0){return(Ve[l[e+0]]+Ve[l[e+1]]+Ve[l[e+2]]+Ve[l[e+3]]+"-"+Ve[l[e+4]]+Ve[l[e+5]]+"-"+Ve[l[e+6]]+Ve[l[e+7]]+"-"+Ve[l[e+8]]+Ve[l[e+9]]+"-"+Ve[l[e+10]]+Ve[l[e+11]]+Ve[l[e+12]]+Ve[l[e+13]]+Ve[l[e+14]]+Ve[l[e+15]]).toLowerCase()}function Xf(l){if(!Ah(l))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(l.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(l.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(l.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(l.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(l.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}var Ih=Xf;function Qf(l){l=unescape(encodeURIComponent(l));let e=[];for(let t=0;t<l.length;++t)e.push(l.charCodeAt(t));return e}var Yf="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Zf="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Ml(l,e,t){function i(n,r,o,s){var c;if(typeof n=="string"&&(n=Qf(n)),typeof r=="string"&&(r=Ih(r)),((c=r)===null||c===void 0?void 0:c.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let d=new Uint8Array(16+n.length);if(d.set(r),d.set(n,r.length),d=t(d),d[6]=d[6]&15|e,d[8]=d[8]&63|128,o){s=s||0;for(let a=0;a<16;++a)o[s+a]=d[a];return o}return kh(d)}try{i.name=l}catch{}return i.DNS=Yf,i.URL=Zf,i}function Jf(l,e,t,i){switch(l){case 0:return e&t^~e&i;case 1:return e^t^i;case 2:return e&t^e&i^t&i;case 3:return e^t^i}}function Ll(l,e){return l<<e|l>>>32-e}function $f(l){let e=[1518500249,1859775393,2400959708,3395469782],t=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof l=="string"){let o=unescape(encodeURIComponent(l));l=[];for(let s=0;s<o.length;++s)l.push(o.charCodeAt(s))}else Array.isArray(l)||(l=Array.prototype.slice.call(l));l.push(128);let i=l.length/4+2,n=Math.ceil(i/16),r=new Array(n);for(let o=0;o<n;++o){let s=new Uint32Array(16);for(let c=0;c<16;++c)s[c]=l[o*64+c*4]<<24|l[o*64+c*4+1]<<16|l[o*64+c*4+2]<<8|l[o*64+c*4+3];r[o]=s}r[n-1][14]=(l.length-1)*8/Math.pow(2,32),r[n-1][14]=Math.floor(r[n-1][14]),r[n-1][15]=(l.length-1)*8&4294967295;for(let o=0;o<n;++o){let s=new Uint32Array(80);for(let f=0;f<16;++f)s[f]=r[o][f];for(let f=16;f<80;++f)s[f]=Ll(s[f-3]^s[f-8]^s[f-14]^s[f-16],1);let c=t[0],d=t[1],a=t[2],h=t[3],u=t[4];for(let f=0;f<80;++f){let E=Math.floor(f/20),b=Ll(c,5)+Jf(E,d,a,h)+u+e[E]+s[f]>>>0;u=h,h=a,a=Ll(d,30)>>>0,d=c,c=b}t[0]=t[0]+c>>>0,t[1]=t[1]+d>>>0,t[2]=t[2]+a>>>0,t[3]=t[3]+h>>>0,t[4]=t[4]+u>>>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]}var Mh=$f;var Kf=Ml("v5",80,Mh),Dl=Kf;var Gs=N("debugcomponents"),em="eff8ba80-635d-11ec-90d6-0242ac120003",We=class{get seed(){return this._seed}_originalSeed;_seed;constructor(e){this._originalSeed=e,this._seed=e}generateUUID(){let e=this._seed;return this._seed-=1,Dl(e.toString(),em)}static createFromString(e){return new We(this.hash(e))}static hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}};var Vs=class{guid;constructor(e){this.guid=e}};function kr(l,e,t=!0){if(!l)return;let i=l;if(O.destroy(l,t),!e){console.warn("Can not send destroy: No networking connection provided",l.guid);return}if(!e.isConnected){console.warn("Can not send destroy: not connected",l.guid);return}let n=l.guid;if(!n&&i.uuid&&(n=i.uuid),!n){console.warn("Can not send destroy: failed to find guid",l);return}let r=new Vs(n);e.send("instance-destroyed",r)}function Lh(l,e){let t=new Vs(l);e.send("instance-destroyed",t)}function Dh(l){l.connection.beginListen("instance-destroyed",e=>{Gs&&console.log("[Remote] Destroyed",l.scene,e);let t=O.findByGuid(e.guid,l.scene);t&&O.destroy(t)})}var Hl=class{guid;originalGuid;seed;visible;hostData;dontSave;parent;position;rotation;scale;constructor(e,t){this.originalGuid=e,this.guid=t}};function Ws(l,e,t,i){let n=l;if(!n.guid)return console.warn("Can not instantiate: No guid",n),null;if(e.context||(e.context=Z.Current),!e.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;let r=e?{...e}:null,{instance:o,seed:s}=tm(n,e);if(o){let c=o;if(c.guid){Gs&&console.log("[Local] new instance","gameobject:",o?.guid);let d=new Hl(n.guid,c.guid);d.seed=s,r&&(r.position&&(d.position={x:r.position.x,y:r.position.y,z:r.position.z}),r.rotation&&(d.rotation={x:r.rotation.x,y:r.rotation.y,z:r.rotation.z,w:r.rotation.w}),r.scale&&(d.scale={x:r.scale.x,y:r.scale.y,z:r.scale.z})),d.position||(d.position={x:c.position.x,y:c.position.y,z:c.position.z}),d.rotation||(d.rotation={x:c.quaternion.x,y:c.quaternion.y,z:c.quaternion.z,w:c.quaternion.w}),d.scale||(d.scale={x:c.scale.x,y:c.scale.y,z:c.scale.z}),d.visible=n.visible,r?.parent&&(typeof r.parent=="string"?d.parent=r.parent:d.parent=r.parent.guid),d.hostData=t,i===!1&&(d.dontSave=!0),e?.context?.connection.send("new-instance-created",d)}else console.warn("Missing guid, can not send new instance event",c)}return o}function Us(){return Math.random()*9999999}function Hh(l){l.connection.beginListen("new-instance-created",async e=>{let t=await im(e.originalGuid,l.scene);if(!t){console.warn("could not find object that was instantiated: "+e.guid);return}let i=new ye;e.position&&(i.position=new Jo.Vector3(e.position.x,e.position.y,e.position.z)),e.rotation&&(i.rotation=new Jo.Quaternion(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w)),e.scale&&(i.scale=new Jo.Vector3(e.scale.x,e.scale.y,e.scale.z)),i.parent=e.parent,e.seed&&(i.idProvider=new We(e.seed)),i.visible=e.visible,i.context=l,Gs&&l.alias&&console.log("[Remote] instantiate in: "+l.alias);let n=O.instantiate(t,i);n&&(e.parent==="scene"&&l.scene.add(n),Gs&&console.log("[Remote] new instance","gameobject:",n?.guid,t))})}function tm(l,e){let t=Us(),i=e??new ye;i.idProvider=new We(t);let n=O.instantiate(l,i);return{seed:t,instance:n}}var jh={};function Bh(l,e){jh[l]=e}async function im(l,e){let t=jh[l];if(t!=null){let i=await t(l);if(i)return i}return Fh(l,e)}function Fh(l,e){if(e===null||!l)return null;if(e.guid===l)return e;if(e.children)for(let t of e.children){let i=Fh(l,t);if(i)return i}return null}var pn=N("debugcomponents"),Nh=(d=>(d[d.None=0]="None",d[d.HideInHierarchy=1]="HideInHierarchy",d[d.HideInInspector=2]="HideInInspector",d[d.DontSaveInEditor=4]="DontSaveInEditor",d[d.NotEditable=8]="NotEditable",d[d.DontSaveInBuild=16]="DontSaveInBuild",d[d.DontUnloadUnusedAsset=32]="DontUnloadUnusedAsset",d[d.DontSave=52]="DontSave",d[d.HideAndDontSave=61]="HideAndDontSave",d))(Nh||{}),ye=class{idProvider;parent;keepWorldPosition;position;rotation;scale;visible;context};ae.Object3D.prototype.SetActive=function(l){this.visible=l};var O=class extends ae.Object3D{guid;static setActive(e,t){!e||(e.visible=t)}static isActiveSelf(e){return e.visible||O.isUsingInstancing(e)}static isActiveInHierarchy(e){return e[dn]||O.isUsingInstancing(e)}static markAsInstancedRendered(e,t){e.__isUsingInstancing=t}static isUsingInstancing(e){return e.__isUsingInstancing===!0}static foreachComponent(e,t,i=!0){if(!!e){if(e.userData.components)for(let n=0;n<e.userData.components.length;n++){let r=e.userData.components[n];if(r instanceof M){let o=t(r);if(o!==void 0)return o}}if(i&&e.children)for(let n=0;n<e.children.length;n++){let r=e.children[n];if(!r)continue;let o=O.foreachComponent(r,t,i);if(o!==void 0)return o}}}static instantiateSynced(e,t){return e?Ws(e,t):null}static instantiate(e,t=null){if(e===null)return null;let i=null;t!==null&&(t.x!==void 0?(i=new ye,i.position=t):i=t);let n=Z.Current;i?.context&&(n=i.context),pn&&n.alias&&console.log("context",n.alias),i&&!i.idProvider&&(i.idProvider=new We(Date.now()));let r=[],o={},s={},c=this.internalInstantiate(n,e,i,r,o,s);c&&(this.resolveReferences(o),this.resolveAndBindSkinnedMeshBones(s,o)),pn&&(Zo(e,!0),Zo(c,!0));let d={};for(let a in r){let h=r[a],u=h.guid;i&&i.idProvider&&(h.guid=i.idProvider.generateUUID(),d[u]=h.guid,pn&&console.log(h.name,h.guid)),Cl(h,n),h.__internalNewInstanceCreated&&h.__internalNewInstanceCreated()}for(let a in r){let h=r[a];h.resolveGuids&&h.resolveGuids(d),h.enabled!==!1&&(h.enabled=!0)}return ki(n),c}static internalInstantiate(e,t,i,n,r,o){if(!t)return null;let s=t.userData;t.userData={};let c=t.children;t.children=[];let d;if(d=t.clone(!1),t.userData=s,t.children=c,r[t.uuid]={original:t,clone:d},t.type==="SkinnedMesh"&&(o[t.uuid]={original:t,clone:d}),i?.visible!==void 0&&(d.visible=i.visible),i?.idProvider){d.uuid=i.idProvider.generateUUID();let h=d;h&&(h.guid=d.uuid)}t.animations&&t.animations.length>0&&(d.animations=[...t.animations]);let a=t.parent;if(a&&a.add(d),i?.position?ie(d,i.position):d.position.copy(t.position),i?.rotation?Ae(d,i.rotation):d.quaternion.copy(t.quaternion),i?.scale?d.scale.copy(i.scale):d.scale.copy(t.scale),i?.parent&&i.parent!=="scene"){let h=null;if(typeof i.parent=="string"?h=hn(i.parent,e.scene,!0):h=i.parent,h){let u=i.keepWorldPosition===!0?h.attach:h.add;u?u.call(h,d):console.error("Invalid parent object",h,"received when instantiating:",t)}else console.warn("could not find parent:",i.parent)}for(let[h,u]of Object.entries(t.userData))h!=="components"&&(d.userData[h]=u);if(t.userData?.components){let h=t.userData.components,u=[];d.userData.components=u;for(let f=0;f<h.length;f++){let E=h[f],b=Object.create(E);Object.assign(b,E),u.push(b),b.gameObject=d,n.push(b)}}i&&(i.position=void 0,i.rotation=void 0,i.scale=void 0,i.parent=void 0);for(let h in t.children){let u=t.children[h],f=O.internalInstantiate(e,u,i,n,r,o);f&&d.add(f)}return d}static resolveAndBindSkinnedMeshBones(e,t){for(let i in e){let n=e[i],r=n.original,o=r.skeleton,s=n.clone;if(!o){console.warn("Skinned mesh has no skeleton?",n);continue}let c=o.bones,d=s.skeleton.clone();s.skeleton=d,s.bindMatrix.clone().copy(r.bindMatrix),s.bindMatrixInverse.copy(r.bindMatrixInverse);let a=[];d.bones=a;for(let h=0;h<c.length;h++){let u=c[h],E=t[u.uuid].clone;a.push(E)}}for(let i in e){let n=e[i].clone;n.skeleton.update(),n.bind(n.skeleton,n.bindMatrix),n.updateMatrixWorld(!0)}}static resolveReferences(e){for(let t in e){let n=e[t].clone;if(n.userData?.components)for(let r=0;r<n.userData.components.length;r++){let o=n.userData.components[r],s=Object.entries(o);for(let[c,d]of s)if(Array.isArray(d)){let a=[];o[c]=a;for(let h=0;h<d.length;h++){let u=d[h];if(typeof u!="object"){a.push(u);continue}let f=this.postProcessNewInstance(o,c,u,e);f!==void 0?a.push(f):a.push(u)}}else if(typeof d=="object"){let a=this.postProcessNewInstance(o,c,d,e);a!==void 0&&(o[c]=a)}}}}static postProcessNewInstance(e,t,i,n){if(i instanceof ot||i instanceof M){let r=i.gameObject;if(r){let o=r.uuid,s=n[o]?.clone;if(!s){pn&&console.log("reference did not change",t,e,i);return}let c=r.userData.components.indexOf(i);if(c>=0)return pn&&console.log(t,o),s.userData.components[c];console.warn("could not find component",t,i)}}else if(i instanceof ae.Object3D){if(t==="gameObject")return;let r=i;if(r){let o=r.uuid,s=n[o]?.clone;if(s)return pn&&console.log(t,"old",i,"new",s),s}}}static destroySynced(e,t,i=!0){if(!e)return;let n=e;t=t??Z.Current,kr(n,t.connection,i)}static destroy(e,t=!0,i=!0){let n=e;if(n.isComponent){n.destroy();return}let r=e;if(pn&&console.log(r),t&&r.children)for(let s of r.children)O.destroy(s,t,!1);let o=r.userData.components;if(o){let s=o.length;for(let c=0;c<o.length;c++){let d=o[c];d.destroy&&(pn&&console.log("destroying",d),d.destroy()),o.length<s&&(s=o.length,c--)}}i&&r.removeFromParent()}static add(e,t,i){if(!(!e||!t)){if(e===t){console.warn("Can not add object to self",e);return}i||(i=Z.Current),t.add(e),qn(e),i?O.foreachComponent(e,n=>{xl(n,i),i.new_script_start.includes(n)===!1&&i.new_script_start.push(n)},!0):console.warn("Missing context")}}static remove(e){!e||(e.parent?.remove(e),O.foreachComponent(e,t=>{fh(t)},!0))}static invokeOnChildren(e,t,...i){this.invoke(e,t,!0,i)}static invoke(e,t,i=!1,...n){!e||this.foreachComponent(e,r=>{let o=r[t];o&&typeof o=="function"&&o.bind(r)(...n)},i)}static addNewComponent(e,t,i=!0){let n=new t;return Ls(n,e,i),n}static addComponent(e,t){if(t.gameObject==null)throw new Error("Did you mean to create a new component? Use addNewComponent");yh(t,e)}static removeComponent(e){return vh(e.gameObject,e),e}static getOrAddComponent(e,t){let i=this.getComponent(e,t);return i||this.addNewComponent(e,t)}static getComponent(e,t){return e===null?null:Ds(t,e)}static getComponents(e,t,i=null){return e===null?i??[]:Hs(t,e,i)}static findByGuid(e,t){return hn(e,t,!0,!0)}static findObjectOfType(e,t,i=!0){return _h(e,t,i)}static findObjectsOfType(e,t){let i=[];return xh(e,i,t),i}static getComponentInChildren(e,t){return js(t,e)}static getComponentsInChildren(e,t,i=null){return Bs(t,e,i)}static getComponentInParent(e,t){return Sl(t,e)}static getComponentsInParent(e,t,i=null){return Pl(t,e,i)}static getAllComponents(e){return[...e.userData?.components]}static*iterateComponents(e){let t=e?.userData?.components;if(t&&Array.isArray(t))for(let i=0;i<t.length;i++)yield t[i]}};ae.Object3D.prototype.addNewComponent=function(l){return O.addNewComponent(this,l)};ae.Object3D.prototype.removeComponent=function(l){return O.removeComponent(l)};ae.Object3D.prototype.getOrAddComponent=function(l){return O.getOrAddComponent(this,l)};ae.Object3D.prototype.getComponent=function(l){return O.getComponent(this,l)};ae.Object3D.prototype.getComponents=function(l,e){return O.getComponents(this,l,e)};ae.Object3D.prototype.getComponentInChildren=function(l){return O.getComponentInChildren(this,l)};ae.Object3D.prototype.getComponentsInChildren=function(l,e){return O.getComponentsInChildren(this,l,e)};ae.Object3D.prototype.getComponentInParent=function(l){return O.getComponentInParent(this,l)};ae.Object3D.prototype.getComponentsInParent=function(l,e){return O.getComponentsInParent(this,l,e)};var Gt=class{get isComponent(){return!0}__context;get context(){return this.__context??Z.Current}set context(e){this.__context=e}get scene(){return this.context.scene}get layer(){return this.gameObject?.userData?.layer}get name(){return this.gameObject?.userData.name}__name;set name(e){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=e,this.__name=e):this.__name=e}get tag(){return this.gameObject?.userData.tag}set tag(e){this.gameObject&&(this.gameObject.userData.tag=e)}get static(){return this.gameObject?.userData.static}get hideFlags(){return this.gameObject?.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;let e=this.gameObject[dn];return e===void 0?!0:e}gameObject;guid="invalid";sourceId;awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(e,t=1){return this.context.registerCoroutineUpdate(this,e,t)}stopCoroutine(e,t=1){this.context.unregisterCoroutineUpdate(e,t)}get destroyed(){return this.__destroyed}destroy(){this.destroyed||Eh(this)}__didAwake=!1;__didStart=!1;__didEnable=!1;__isEnabled=void 0;__destroyed=!1;__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(){this.__didEnable||(this.__didEnable=!0,this.onEnable())}__internalDisable(){!this.__didEnable||(this.__didEnable=!1,this.onDisable())}constructor(){this.__internalNewInstanceCreated()}_worldPosition=void 0;_worldQuaternion=void 0;_worldEuler=void 0;_worldRotation=void 0;get worldPosition(){return this._worldPosition||(this._worldPosition=new ae.Vector3),q(this.gameObject,this._worldPosition),this._worldPosition}set worldPosition(e){ie(this.gameObject,e)}setWorldPosition(e,t,i){Gt._worldPositionBuffer.set(e,t,i),this.worldPosition=Gt._worldPositionBuffer}get worldQuaternion(){return this._worldQuaternion||(this._worldQuaternion=new ae.Quaternion),ve(this.gameObject,this._worldQuaternion)}set worldQuaternion(e){Ae(this.gameObject,e)}setWorldQuaternion(e,t,i,n){Gt._worldQuaternionBuffer.set(e,t,i,n),this.worldQuaternion=Gt._worldQuaternionBuffer}get worldEuler(){return this._worldEuler||(this._worldEuler=new ae.Euler),this._worldEuler.setFromQuaternion(this.worldQuaternion),this._worldEuler}set worldEuler(e){this._worldQuaternion||(this._worldQuaternion=new ae.Quaternion),this._worldQuaternion?.setFromEuler(e),this.worldQuaternion=this._worldQuaternion}get worldRotation(){let e=this.worldEuler;this._worldRotation||(this._worldRotation=new ae.Vector3);let t=this._worldRotation;return t.set(e.x,e.y,e.z),t.x=Q.toDegrees(t.x),t.y=Q.toDegrees(t.y),t.z=Q.toDegrees(t.z),t}set worldRotation(e){this.setWorldRotation(e.x,e.y,e.z,!0)}setWorldRotation(e,t,i,n=!0){n&&(e=Q.toRadians(e),t=Q.toRadians(t),i=Q.toRadians(i)),Gt._worldEulerBuffer.set(e,t,i),Gt._worldQuaternionBuffer.setFromEuler(Gt._worldEulerBuffer),this.worldQuaternion=Gt._worldQuaternionBuffer}get forward(){return Gt._forward.set(0,0,1).applyQuaternion(this.worldQuaternion)}_eventListeners=new Map;addEventListener(e,t){this._eventListeners[e]=this._eventListeners[e]||[],this._eventListeners[e].push(t)}removeEventListener(e,t){if(!this._eventListeners[e])return;let i=this._eventListeners[e].indexOf(t);i>=0&&this._eventListeners[e].splice(i,1)}dispatchEvent(e){if(!this._eventListeners[e.type])return!1;let t=this._eventListeners[e.type];for(let i=0;i<t.length;i++)t[i](e);return!1}},ot=Gt;z(ot,"_worldPositionBuffer",new ae.Vector3),z(ot,"_worldQuaternionBuffer",new ae.Quaternion),z(ot,"_worldEulerBuffer",new ae.Euler),z(ot,"_tempQuaternionBuffer2",new ae.Quaternion),z(ot,"_forward",new ae.Vector3(0,0,1));var M=class extends ot{get enabled(){return this.__isEnabled??!0}set enabled(e){typeof e=="number"&&(e>=.5?e=!0:e=!1),e!==this.__isEnabled&&(this.__isEnabled=e,this.__didAwake&&(e?this.__internalEnable():this.__internalDisable()))}};import*as Vt from"three";var qs=class extends EventTarget{_doubleClickTimeThreshold=.2;_longPressTimeThreshold=1;get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}_specialCursorTrigger=0;setCursorPointer(){this._specialCursorTrigger+=1,this.context.domElement.style.cursor="pointer"}setCursorNormal(){this._specialCursorTrigger-=1,this._specialCursorTrigger=Math.max(0,this._specialCursorTrigger),this._specialCursorTrigger===0&&(this.context.domElement.style.cursor="default")}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}context;_pointerDown=[!1];_pointerUp=[!1];_pointerClick=[!1];_pointerDoubleClick=[!1];_pointerPressed=[!1];_pointerPositions=[new Vt.Vector2];_pointerPositionsLastFrame=[new Vt.Vector2];_pointerPositionsDelta=[new Vt.Vector2];_pointerPositionsRC=[new Vt.Vector2];_pointerPositionDown=[new Vt.Vector2];_pointerDownTime=[];_pointerUpTime=[];_pointerIds=[];_pointerTypes=[""];_mouseWheelChanged=[!1];_pointerEvent=[];getKeyDown(){for(let e in this.keysPressed){let t=this.keysPressed[e];if(t.startFrame===this.context.time.frameCount)return t.key}return null}getKeyPressed(){for(let e in this.keysPressed){let t=this.keysPressed[e];if(t.pressed)return t.key}return null}isKeyDown(e){return this.context.application.isVisible&&this.context.application.hasFocus&&this.keysPressed[e]?.startFrame===this.context.time.frameCount&&this.keysPressed[e].pressed}isKeyUp(e){return this.context.application.isVisible&&this.context.application.hasFocus&&this.keysPressed[e]?.frame===this.context.time.frameCount&&!this.keysPressed[e].pressed}isKeyPressed(e){return this.context.application.isVisible&&this.context.application.hasFocus&&this.keysPressed[e]?.pressed}createPointerDown(e){this.onDown(e)}createPointerMove(e){this.onMove(e)}createPointerUp(e){this.onUp(e)}constructor(e){super(),this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame.bind(this));let t=this.context.renderer.domElement;t.addEventListener("touchmove",this.onTouchMove.bind(this),{passive:!0}),t.addEventListener("touchend",this.onTouchUp.bind(this),!1),t.addEventListener("pointerdown",this.onPointerDown.bind(this),!1),t.addEventListener("pointermove",this.onPointerMove.bind(this),!1),t.addEventListener("pointerup",this.onPointerUp.bind(this),!1),t.addEventListener("wheel",this.onMouseWheel.bind(this),{passive:!0}),window.addEventListener("keydown",this.onKeyDown.bind(this),!1),window.addEventListener("keypress",this.onKeyPressed.bind(this),!1),window.addEventListener("keyup",this.onKeyUp.bind(this),!1),window.addEventListener("blur",this.onLostFocus.bind(this))}onLostFocus(){for(let e in this.keysPressed)this.keysPressed[e].pressed=!1}onEndOfFrame(){for(let e=0;e<this._pointerUp.length;e++)this._pointerUp[e]=!1;for(let e=0;e<this._pointerDown.length;e++)this._pointerDown[e]=!1;for(let e=0;e<this._pointerClick.length;e++)this._pointerClick[e]=!1;for(let e=0;e<this._pointerDoubleClick.length;e++)this._pointerDoubleClick[e]=!1;for(let e of this._pointerPositionsDelta)e.set(0,0);for(let e=0;e<this._mouseWheelChanged.length;e++)this._mouseWheelChanged[e]=!1}keysPressed={};onKeyDown(e){if(!this.context.application.hasFocus)return;let t=this.keysPressed[e.keyCode];t&&t.pressed||(this.keysPressed[e.keyCode]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:e.key})}onKeyPressed(e){if(!this.context.application.hasFocus)return;let t=this.keysPressed[e.keyCode];!t||(t.pressed=!0,t.frame=this.context.time.frameCount+1)}onKeyUp(e){if(!this.context.application.hasFocus)return;let t=this.keysPressed[e.keyCode];!t||(t.pressed=!1,t.frame=this.context.time.frameCount+1)}onMouseWheel(e){this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0}onTouchMove(e){}onTouchUp(e){}onPointerDown(e){if(e.defaultPrevented||e.pointerType===void 0&&e.pointerId===void 0)return;e.preventDefault&&e.preventDefault();let t=e.pointerType==="mouse"?e.button:this.getPointerIndex(e.pointerId);e.pointerId===void 0&&e.button!==void 0&&(t=e.button),this.onDown({button:t,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,source:e})}onPointerMove(e,t=void 0){if(e.defaultPrevented||e.pointerType===void 0&&e.pointerId===void 0)return;t!==!0&&e.preventDefault();let i=e.pointerType==="mouse"?e.button:this.getPointerIndex(e.pointerId);e.pointerId===void 0&&e.button!==void 0&&(i=e.button),i<0&&(i=0);let n={button:i,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,source:e};this.onMove(n)}onPointerUp(e,t=void 0){if(e.defaultPrevented||e.pointerType===void 0&&e.pointerId===void 0)return;t!==!0&&e.preventDefault();let i=e.pointerType==="mouse"?e.button:this.getPointerIndex(e.pointerId);e.pointerId===void 0&&e.button!==void 0&&(i=e.button),this._pointerIds[i]=-1,this.onUp({button:i,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,source:e})}isInRect(e){return!0}onDown(e){if(!!this.isInRect(e)){for(this.setPointerState(e.button,this._pointerPressed,!0),this.setPointerState(e.button,this._pointerDown,!0),this.setPointerStateT(e.button,this._pointerEvent,e.source);e.button>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[e.button]=e.pointerType===void 0?"mouse":e.pointerType;e.button>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new Vt.Vector2);this._pointerPositionDown[e.button].set(e.clientX,e.clientY),e.button>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[e.button]=this.context.time.time,this.updatePointerPosition(e),Z.Current=this.context,this.dispatchEvent(new Event("pointerDown"))}}onMove(e){!this.isInRect(e)||(this.updatePointerPosition(e),this.setPointerStateT(e.button,this._pointerEvent,e.source))}onUp(e){if(this.setPointerState(e.button,this._pointerPressed,!1),this.setPointerStateT(e.button,this._pointerEvent,e.source),!this.isInRect(e))return;if(this.setPointerState(e.button,this._pointerUp,!0),this.updatePointerPosition(e),!this._pointerPositionDown[e.button]){console.warn("Received pointer up event without matching down event for button: "+e.button);return}let t=e.clientX-this._pointerPositionDown[e.button].x,i=e.clientY-this._pointerPositionDown[e.button].y;if(e.button>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),Math.abs(t)<5&&Math.abs(i)<5){this.setPointerState(e.button,this._pointerClick,!0);let n=this._pointerUpTime[e.button],r=this.context.time.time-n;r<this._doubleClickTimeThreshold&&r>0&&this.setPointerState(e.button,this._pointerDoubleClick,!0)}this._pointerUpTime[e.button]=this.context.time.time}updatePointerPosition(e){for(;e.button>=this._pointerPositions.length;)this._pointerPositions.push(new Vt.Vector2);for(;e.button>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new Vt.Vector2);for(;e.button>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new Vt.Vector2);let t=this._pointerPositionsLastFrame[e.button];t.copy(this._pointerPositions[e.button]),this._pointerPositionsDelta[e.button].set(e.clientX-t.x,e.clientY-t.y),this._pointerPositions[e.button].x=e.clientX,this._pointerPositions[e.button].y=e.clientY;let i=e.clientX+window.scrollX,n=e.clientY+window.scrollY;for(;e.button>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new Vt.Vector2);this._pointerPositionsRC[e.button].x=(i-this.context.domX)/this.context.domWidth*2-1,this._pointerPositionsRC[e.button].y=-((n-this.context.domY)/this.context.domHeight)*2+1}getPointerIndex(e){for(let t=0;t<this._pointerIds.length;t++)if(this._pointerIds[t]===e)return t;for(let t=0;t<this._pointerIds.length;t++)if(this._pointerIds[t]===-1&&(this._pointerIds[t]=e),this._pointerIds[t]===e)return t;return this._pointerIds.push(e),this._pointerIds.length-1}setPointerState(e,t,i){for(;t.length<=e;)t.push(!1);t[e]=i}setPointerStateT(e,t,i){for(;t.length<=e;)t.push(null);t[e]=i}};var Ot=class{constructor(e=[0,0,0,0,0,0,0,0,0]){this.elements=void 0,this.elements=e}identity(){let e=this.elements;e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1}setZero(){let e=this.elements;e[0]=0,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=0,e[6]=0,e[7]=0,e[8]=0}setTrace(e){let t=this.elements;t[0]=e.x,t[4]=e.y,t[8]=e.z}getTrace(e=new _){let t=this.elements;return e.x=t[0],e.y=t[4],e.z=t[8],e}vmult(e,t=new _){let i=this.elements,n=e.x,r=e.y,o=e.z;return t.x=i[0]*n+i[1]*r+i[2]*o,t.y=i[3]*n+i[4]*r+i[5]*o,t.z=i[6]*n+i[7]*r+i[8]*o,t}smult(e){for(let t=0;t<this.elements.length;t++)this.elements[t]*=e}mmult(e,t=new Ot){let i=this.elements,n=e.elements,r=t.elements,o=i[0],s=i[1],c=i[2],d=i[3],a=i[4],h=i[5],u=i[6],f=i[7],E=i[8],b=n[0],y=n[1],g=n[2],p=n[3],m=n[4],v=n[5],w=n[6],x=n[7],T=n[8];return r[0]=o*b+s*p+c*w,r[1]=o*y+s*m+c*x,r[2]=o*g+s*v+c*T,r[3]=d*b+a*p+h*w,r[4]=d*y+a*m+h*x,r[5]=d*g+a*v+h*T,r[6]=u*b+f*p+E*w,r[7]=u*y+f*m+E*x,r[8]=u*g+f*v+E*T,t}scale(e,t=new Ot){let i=this.elements,n=t.elements;for(let r=0;r!==3;r++)n[3*r+0]=e.x*i[3*r+0],n[3*r+1]=e.y*i[3*r+1],n[3*r+2]=e.z*i[3*r+2];return t}solve(e,t=new _){let r=[],o,s;for(o=0;o<3*4;o++)r.push(0);for(o=0;o<3;o++)for(s=0;s<3;s++)r[o+4*s]=this.elements[o+3*s];r[3+4*0]=e.x,r[3+4*1]=e.y,r[3+4*2]=e.z;let c=3,d=c,a,h=4,u;do{if(o=d-c,r[o+4*o]===0){for(s=o+1;s<d;s++)if(r[o+4*s]!==0){a=h;do u=h-a,r[u+4*o]+=r[u+4*s];while(--a);break}}if(r[o+4*o]!==0)for(s=o+1;s<d;s++){let f=r[o+4*s]/r[o+4*o];a=h;do u=h-a,r[u+4*s]=u<=o?0:r[u+4*s]-r[u+4*o]*f;while(--a)}}while(--c);if(t.z=r[2*4+3]/r[2*4+2],t.y=(r[1*4+3]-r[1*4+2]*t.z)/r[1*4+1],t.x=(r[0*4+3]-r[0*4+2]*t.z-r[0*4+1]*t.y)/r[0*4+0],isNaN(t.x)||isNaN(t.y)||isNaN(t.z)||t.x===1/0||t.y===1/0||t.z===1/0)throw"Could not solve equation! Got x=["+t.toString()+"], b=["+e.toString()+"], A=["+this.toString()+"]";return t}e(e,t,i){if(i===void 0)return this.elements[t+3*e];this.elements[t+3*e]=i}copy(e){for(let t=0;t<e.elements.length;t++)this.elements[t]=e.elements[t];return this}toString(){let e="",t=",";for(let i=0;i<9;i++)e+=this.elements[i]+t;return e}reverse(e=new Ot){let n=nm,r,o;for(r=0;r<3;r++)for(o=0;o<3;o++)n[r+6*o]=this.elements[r+3*o];n[3+6*0]=1,n[3+6*1]=0,n[3+6*2]=0,n[4+6*0]=0,n[4+6*1]=1,n[4+6*2]=0,n[5+6*0]=0,n[5+6*1]=0,n[5+6*2]=1;let s=3,c=s,d,a=6,h;do{if(r=c-s,n[r+6*r]===0){for(o=r+1;o<c;o++)if(n[r+6*o]!==0){d=a;do h=a-d,n[h+6*r]+=n[h+6*o];while(--d);break}}if(n[r+6*r]!==0)for(o=r+1;o<c;o++){let u=n[r+6*o]/n[r+6*r];d=a;do h=a-d,n[h+6*o]=h<=r?0:n[h+6*o]-n[h+6*r]*u;while(--d)}}while(--s);r=2;do{o=r-1;do{let u=n[r+6*o]/n[r+6*r];d=6;do h=6-d,n[h+6*o]=n[h+6*o]-n[h+6*r]*u;while(--d)}while(o--)}while(--r);r=2;do{let u=1/n[r+6*r];d=6;do h=6-d,n[h+6*r]=n[h+6*r]*u;while(--d)}while(r--);r=2;do{o=2;do{if(h=n[3+o+6*r],isNaN(h)||h===1/0)throw"Could not reverse! A=["+this.toString()+"]";e.e(r,o,h)}while(o--)}while(r--);return e}setRotationFromQuaternion(e){let t=e.x,i=e.y,n=e.z,r=e.w,o=t+t,s=i+i,c=n+n,d=t*o,a=t*s,h=t*c,u=i*s,f=i*c,E=n*c,b=r*o,y=r*s,g=r*c,p=this.elements;return p[3*0+0]=1-(u+E),p[3*0+1]=a-g,p[3*0+2]=h+y,p[3*1+0]=a+g,p[3*1+1]=1-(d+E),p[3*1+2]=f-b,p[3*2+0]=h-y,p[3*2+1]=f+b,p[3*2+2]=1-(d+u),this}transpose(e=new Ot){let t=this.elements,i=e.elements,n;return i[0]=t[0],i[4]=t[4],i[8]=t[8],n=t[1],i[1]=t[3],i[3]=n,n=t[2],i[2]=t[6],i[6]=n,n=t[5],i[5]=t[7],i[7]=n,e}},nm=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],_=class{constructor(e=0,t=0,i=0){this.x=void 0,this.y=void 0,this.z=void 0,this.x=e,this.y=t,this.z=i}cross(e,t=new _){let i=e.x,n=e.y,r=e.z,o=this.x,s=this.y,c=this.z;return t.x=s*r-c*n,t.y=c*i-o*r,t.z=o*n-s*i,t}set(e,t,i){return this.x=e,this.y=t,this.z=i,this}setZero(){this.x=this.y=this.z=0}vadd(e,t){if(t)t.x=e.x+this.x,t.y=e.y+this.y,t.z=e.z+this.z;else return new _(this.x+e.x,this.y+e.y,this.z+e.z)}vsub(e,t){if(t)t.x=this.x-e.x,t.y=this.y-e.y,t.z=this.z-e.z;else return new _(this.x-e.x,this.y-e.y,this.z-e.z)}crossmat(){return new Ot([0,-this.z,this.y,this.z,0,-this.x,-this.y,this.x,0])}normalize(){let e=this.x,t=this.y,i=this.z,n=Math.sqrt(e*e+t*t+i*i);if(n>0){let r=1/n;this.x*=r,this.y*=r,this.z*=r}else this.x=0,this.y=0,this.z=0;return n}unit(e=new _){let t=this.x,i=this.y,n=this.z,r=Math.sqrt(t*t+i*i+n*n);return r>0?(r=1/r,e.x=t*r,e.y=i*r,e.z=n*r):(e.x=1,e.y=0,e.z=0),e}length(){let e=this.x,t=this.y,i=this.z;return Math.sqrt(e*e+t*t+i*i)}lengthSquared(){return this.dot(this)}distanceTo(e){let t=this.x,i=this.y,n=this.z,r=e.x,o=e.y,s=e.z;return Math.sqrt((r-t)*(r-t)+(o-i)*(o-i)+(s-n)*(s-n))}distanceSquared(e){let t=this.x,i=this.y,n=this.z,r=e.x,o=e.y,s=e.z;return(r-t)*(r-t)+(o-i)*(o-i)+(s-n)*(s-n)}scale(e,t=new _){let i=this.x,n=this.y,r=this.z;return t.x=e*i,t.y=e*n,t.z=e*r,t}vmul(e,t=new _){return t.x=e.x*this.x,t.y=e.y*this.y,t.z=e.z*this.z,t}addScaledVector(e,t,i=new _){return i.x=this.x+e*t.x,i.y=this.y+e*t.y,i.z=this.z+e*t.z,i}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}isZero(){return this.x===0&&this.y===0&&this.z===0}negate(e=new _){return e.x=-this.x,e.y=-this.y,e.z=-this.z,e}tangents(e,t){let i=this.length();if(i>0){let n=rm,r=1/i;n.set(this.x*r,this.y*r,this.z*r);let o=om;Math.abs(n.x)<.9?(o.set(1,0,0),n.cross(o,e)):(o.set(0,1,0),n.cross(o,e)),n.cross(e,t)}else e.set(1,0,0),t.set(0,1,0)}toString(){return this.x+","+this.y+","+this.z}toArray(){return[this.x,this.y,this.z]}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}lerp(e,t,i){let n=this.x,r=this.y,o=this.z;i.x=n+(e.x-n)*t,i.y=r+(e.y-r)*t,i.z=o+(e.z-o)*t}almostEquals(e,t=1e-6){return!(Math.abs(this.x-e.x)>t||Math.abs(this.y-e.y)>t||Math.abs(this.z-e.z)>t)}almostZero(e=1e-6){return!(Math.abs(this.x)>e||Math.abs(this.y)>e||Math.abs(this.z)>e)}isAntiparallelTo(e,t){return this.negate(zh),zh.almostEquals(e,t)}clone(){return new _(this.x,this.y,this.z)}};_.ZERO=void 0;_.UNIT_X=void 0;_.UNIT_Y=void 0;_.UNIT_Z=void 0;_.ZERO=new _(0,0,0);_.UNIT_X=new _(1,0,0);_.UNIT_Y=new _(0,1,0);_.UNIT_Z=new _(0,0,1);var rm=new _,om=new _,zh=new _,$e=class{constructor(e={}){this.lowerBound=void 0,this.upperBound=void 0,this.lowerBound=new _,this.upperBound=new _,e.lowerBound&&this.lowerBound.copy(e.lowerBound),e.upperBound&&this.upperBound.copy(e.upperBound)}setFromPoints(e,t,i,n){let r=this.lowerBound,o=this.upperBound,s=i;r.copy(e[0]),s&&s.vmult(r,r),o.copy(r);for(let c=1;c<e.length;c++){let d=e[c];s&&(s.vmult(d,Gh),d=Gh),d.x>o.x&&(o.x=d.x),d.x<r.x&&(r.x=d.x),d.y>o.y&&(o.y=d.y),d.y<r.y&&(r.y=d.y),d.z>o.z&&(o.z=d.z),d.z<r.z&&(r.z=d.z)}return t&&(t.vadd(r,r),t.vadd(o,o)),n&&(r.x-=n,r.y-=n,r.z-=n,o.x+=n,o.y+=n,o.z+=n),this}copy(e){return this.lowerBound.copy(e.lowerBound),this.upperBound.copy(e.upperBound),this}clone(){return new $e().copy(this)}extend(e){this.lowerBound.x=Math.min(this.lowerBound.x,e.lowerBound.x),this.upperBound.x=Math.max(this.upperBound.x,e.upperBound.x),this.lowerBound.y=Math.min(this.lowerBound.y,e.lowerBound.y),this.upperBound.y=Math.max(this.upperBound.y,e.upperBound.y),this.lowerBound.z=Math.min(this.lowerBound.z,e.lowerBound.z),this.upperBound.z=Math.max(this.upperBound.z,e.upperBound.z)}overlaps(e){let t=this.lowerBound,i=this.upperBound,n=e.lowerBound,r=e.upperBound,o=n.x<=i.x&&i.x<=r.x||t.x<=r.x&&r.x<=i.x,s=n.y<=i.y&&i.y<=r.y||t.y<=r.y&&r.y<=i.y,c=n.z<=i.z&&i.z<=r.z||t.z<=r.z&&r.z<=i.z;return o&&s&&c}volume(){let e=this.lowerBound,t=this.upperBound;return(t.x-e.x)*(t.y-e.y)*(t.z-e.z)}contains(e){let t=this.lowerBound,i=this.upperBound,n=e.lowerBound,r=e.upperBound;return t.x<=n.x&&i.x>=r.x&&t.y<=n.y&&i.y>=r.y&&t.z<=n.z&&i.z>=r.z}getCorners(e,t,i,n,r,o,s,c){let d=this.lowerBound,a=this.upperBound;e.copy(d),t.set(a.x,d.y,d.z),i.set(a.x,a.y,d.z),n.set(d.x,a.y,a.z),r.set(a.x,d.y,a.z),o.set(d.x,a.y,d.z),s.set(d.x,d.y,a.z),c.copy(a)}toLocalFrame(e,t){let i=Vh,n=i[0],r=i[1],o=i[2],s=i[3],c=i[4],d=i[5],a=i[6],h=i[7];this.getCorners(n,r,o,s,c,d,a,h);for(let u=0;u!==8;u++){let f=i[u];e.pointToLocal(f,f)}return t.setFromPoints(i)}toWorldFrame(e,t){let i=Vh,n=i[0],r=i[1],o=i[2],s=i[3],c=i[4],d=i[5],a=i[6],h=i[7];this.getCorners(n,r,o,s,c,d,a,h);for(let u=0;u!==8;u++){let f=i[u];e.pointToWorld(f,f)}return t.setFromPoints(i)}overlapsRay(e){let{direction:t,from:i}=e,n=1/t.x,r=1/t.y,o=1/t.z,s=(this.lowerBound.x-i.x)*n,c=(this.upperBound.x-i.x)*n,d=(this.lowerBound.y-i.y)*r,a=(this.upperBound.y-i.y)*r,h=(this.lowerBound.z-i.z)*o,u=(this.upperBound.z-i.z)*o,f=Math.max(Math.max(Math.min(s,c),Math.min(d,a)),Math.min(h,u)),E=Math.min(Math.min(Math.max(s,c),Math.max(d,a)),Math.max(h,u));return!(E<0||f>E)}},Gh=new _,Vh=[new _,new _,new _,new _,new _,new _,new _,new _],$s=class{constructor(){this.matrix=void 0,this.matrix=[]}get(e,t){let{index:i}=e,{index:n}=t;if(n>i){let r=n;n=i,i=r}return this.matrix[(i*(i+1)>>1)+n-1]}set(e,t,i){let{index:n}=e,{index:r}=t;if(r>n){let o=r;r=n,n=o}this.matrix[(n*(n+1)>>1)+r-1]=i?1:0}reset(){for(let e=0,t=this.matrix.length;e!==t;e++)this.matrix[e]=0}setNumObjects(e){this.matrix.length=e*(e-1)>>1}},Ks=class{constructor(){this._listeners=void 0}addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let i=this._listeners;return i[e]===void 0&&(i[e]=[]),i[e].includes(t)||i[e].push(t),this}hasEventListener(e,t){if(this._listeners===void 0)return!1;let i=this._listeners;return!!(i[e]!==void 0&&i[e].includes(t))}hasAnyEventListener(e){return this._listeners===void 0?!1:this._listeners[e]!==void 0}removeEventListener(e,t){if(this._listeners===void 0)return this;let i=this._listeners;if(i[e]===void 0)return this;let n=i[e].indexOf(t);return n!==-1&&i[e].splice(n,1),this}dispatchEvent(e){if(this._listeners===void 0)return this;let i=this._listeners[e.type];if(i!==void 0){e.target=this;for(let n=0,r=i.length;n<r;n++)i[n].call(this,e)}return this}},le=class{constructor(e=0,t=0,i=0,n=1){this.x=void 0,this.y=void 0,this.z=void 0,this.w=void 0,this.x=e,this.y=t,this.z=i,this.w=n}set(e,t,i,n){return this.x=e,this.y=t,this.z=i,this.w=n,this}toString(){return this.x+","+this.y+","+this.z+","+this.w}toArray(){return[this.x,this.y,this.z,this.w]}setFromAxisAngle(e,t){let i=Math.sin(t*.5);return this.x=e.x*i,this.y=e.y*i,this.z=e.z*i,this.w=Math.cos(t*.5),this}toAxisAngle(e=new _){this.normalize();let t=2*Math.acos(this.w),i=Math.sqrt(1-this.w*this.w);return i<.001?(e.x=this.x,e.y=this.y,e.z=this.z):(e.x=this.x/i,e.y=this.y/i,e.z=this.z/i),[e,t]}setFromVectors(e,t){if(e.isAntiparallelTo(t)){let i=sm,n=am;e.tangents(i,n),this.setFromAxisAngle(i,Math.PI)}else{let i=e.cross(t);this.x=i.x,this.y=i.y,this.z=i.z,this.w=Math.sqrt(e.length()**2*t.length()**2)+e.dot(t),this.normalize()}return this}mult(e,t=new le){let i=this.x,n=this.y,r=this.z,o=this.w,s=e.x,c=e.y,d=e.z,a=e.w;return t.x=i*a+o*s+n*d-r*c,t.y=n*a+o*c+r*s-i*d,t.z=r*a+o*d+i*c-n*s,t.w=o*a-i*s-n*c-r*d,t}inverse(e=new le){let t=this.x,i=this.y,n=this.z,r=this.w;this.conjugate(e);let o=1/(t*t+i*i+n*n+r*r);return e.x*=o,e.y*=o,e.z*=o,e.w*=o,e}conjugate(e=new le){return e.x=-this.x,e.y=-this.y,e.z=-this.z,e.w=this.w,e}normalize(){let e=Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w);return e===0?(this.x=0,this.y=0,this.z=0,this.w=0):(e=1/e,this.x*=e,this.y*=e,this.z*=e,this.w*=e),this}normalizeFast(){let e=(3-(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w))/2;return e===0?(this.x=0,this.y=0,this.z=0,this.w=0):(this.x*=e,this.y*=e,this.z*=e,this.w*=e),this}vmult(e,t=new _){let i=e.x,n=e.y,r=e.z,o=this.x,s=this.y,c=this.z,d=this.w,a=d*i+s*r-c*n,h=d*n+c*i-o*r,u=d*r+o*n-s*i,f=-o*i-s*n-c*r;return t.x=a*d+f*-o+h*-c-u*-s,t.y=h*d+f*-s+u*-o-a*-c,t.z=u*d+f*-c+a*-s-h*-o,t}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}toEuler(e,t="YZX"){let i,n,r,o=this.x,s=this.y,c=this.z,d=this.w;switch(t){case"YZX":let a=o*s+c*d;if(a>.499&&(i=2*Math.atan2(o,d),n=Math.PI/2,r=0),a<-.499&&(i=-2*Math.atan2(o,d),n=-Math.PI/2,r=0),i===void 0){let h=o*o,u=s*s,f=c*c;i=Math.atan2(2*s*d-2*o*c,1-2*u-2*f),n=Math.asin(2*a),r=Math.atan2(2*o*d-2*s*c,1-2*h-2*f)}break;default:throw new Error("Euler order "+t+" not supported yet.")}e.y=i,e.z=n,e.x=r}setFromEuler(e,t,i,n="XYZ"){let r=Math.cos(e/2),o=Math.cos(t/2),s=Math.cos(i/2),c=Math.sin(e/2),d=Math.sin(t/2),a=Math.sin(i/2);return n==="XYZ"?(this.x=c*o*s+r*d*a,this.y=r*d*s-c*o*a,this.z=r*o*a+c*d*s,this.w=r*o*s-c*d*a):n==="YXZ"?(this.x=c*o*s+r*d*a,this.y=r*d*s-c*o*a,this.z=r*o*a-c*d*s,this.w=r*o*s+c*d*a):n==="ZXY"?(this.x=c*o*s-r*d*a,this.y=r*d*s+c*o*a,this.z=r*o*a+c*d*s,this.w=r*o*s-c*d*a):n==="ZYX"?(this.x=c*o*s-r*d*a,this.y=r*d*s+c*o*a,this.z=r*o*a-c*d*s,this.w=r*o*s+c*d*a):n==="YZX"?(this.x=c*o*s+r*d*a,this.y=r*d*s+c*o*a,this.z=r*o*a-c*d*s,this.w=r*o*s-c*d*a):n==="XZY"&&(this.x=c*o*s-r*d*a,this.y=r*d*s-c*o*a,this.z=r*o*a+c*d*s,this.w=r*o*s+c*d*a),this}clone(){return new le(this.x,this.y,this.z,this.w)}slerp(e,t,i=new le){let n=this.x,r=this.y,o=this.z,s=this.w,c=e.x,d=e.y,a=e.z,h=e.w,u,f,E,b,y;return f=n*c+r*d+o*a+s*h,f<0&&(f=-f,c=-c,d=-d,a=-a,h=-h),1-f>1e-6?(u=Math.acos(f),E=Math.sin(u),b=Math.sin((1-t)*u)/E,y=Math.sin(t*u)/E):(b=1-t,y=t),i.x=b*n+y*c,i.y=b*r+y*d,i.z=b*o+y*a,i.w=b*s+y*h,i}integrate(e,t,i,n=new le){let r=e.x*i.x,o=e.y*i.y,s=e.z*i.z,c=this.x,d=this.y,a=this.z,h=this.w,u=t*.5;return n.x+=u*(r*h+o*a-s*d),n.y+=u*(o*h+s*c-r*a),n.z+=u*(s*h+r*d-o*c),n.w+=u*(-r*c-o*d-s*a),n}},sm=new _,am=new _,lm={SPHERE:1,PLANE:2,BOX:4,COMPOUND:8,CONVEXPOLYHEDRON:16,HEIGHTFIELD:32,PARTICLE:64,CYLINDER:128,TRIMESH:256},V=class{constructor(e={}){this.id=void 0,this.type=void 0,this.boundingSphereRadius=void 0,this.collisionResponse=void 0,this.collisionFilterGroup=void 0,this.collisionFilterMask=void 0,this.material=void 0,this.body=void 0,this.id=V.idCounter++,this.type=e.type||0,this.boundingSphereRadius=0,this.collisionResponse=e.collisionResponse?e.collisionResponse:!0,this.collisionFilterGroup=e.collisionFilterGroup!==void 0?e.collisionFilterGroup:1,this.collisionFilterMask=e.collisionFilterMask!==void 0?e.collisionFilterMask:-1,this.material=e.material?e.material:null,this.body=null}updateBoundingSphereRadius(){throw"computeBoundingSphereRadius() not implemented for shape type "+this.type}volume(){throw"volume() not implemented for shape type "+this.type}calculateLocalInertia(e,t){throw"calculateLocalInertia() not implemented for shape type "+this.type}calculateWorldAABB(e,t,i,n){throw"calculateWorldAABB() not implemented for shape type "+this.type}};V.idCounter=0;V.types=lm;var te=class{constructor(e={}){this.position=void 0,this.quaternion=void 0,this.position=new _,this.quaternion=new le,e.position&&this.position.copy(e.position),e.quaternion&&this.quaternion.copy(e.quaternion)}pointToLocal(e,t){return te.pointToLocalFrame(this.position,this.quaternion,e,t)}pointToWorld(e,t){return te.pointToWorldFrame(this.position,this.quaternion,e,t)}vectorToWorldFrame(e,t=new _){return this.quaternion.vmult(e,t),t}static pointToLocalFrame(e,t,i,n=new _){return i.vsub(e,n),t.conjugate(Wh),Wh.vmult(n,n),n}static pointToWorldFrame(e,t,i,n=new _){return t.vmult(i,n),n.vadd(e,n),n}static vectorToWorldFrame(e,t,i=new _){return e.vmult(t,i),i}static vectorToLocalFrame(e,t,i,n=new _){return t.w*=-1,t.vmult(i,n),t.w*=-1,n}},Wh=new le,Zn=class extends V{constructor(e={}){let{vertices:t=[],faces:i=[],normals:n=[],axes:r,boundingSphereRadius:o}=e;super({type:V.types.CONVEXPOLYHEDRON}),this.vertices=void 0,this.faces=void 0,this.faceNormals=void 0,this.worldVertices=void 0,this.worldVerticesNeedsUpdate=void 0,this.worldFaceNormals=void 0,this.worldFaceNormalsNeedsUpdate=void 0,this.uniqueAxes=void 0,this.uniqueEdges=void 0,this.vertices=t,this.faces=i,this.faceNormals=n,this.faceNormals.length===0&&this.computeNormals(),o?this.boundingSphereRadius=o:this.updateBoundingSphereRadius(),this.worldVertices=[],this.worldVerticesNeedsUpdate=!0,this.worldFaceNormals=[],this.worldFaceNormalsNeedsUpdate=!0,this.uniqueAxes=r?r.slice():null,this.uniqueEdges=[],this.computeEdges()}computeEdges(){let e=this.faces,t=this.vertices,i=this.uniqueEdges;i.length=0;let n=new _;for(let r=0;r!==e.length;r++){let o=e[r],s=o.length;for(let c=0;c!==s;c++){let d=(c+1)%s;t[o[c]].vsub(t[o[d]],n),n.normalize();let a=!1;for(let h=0;h!==i.length;h++)if(i[h].almostEquals(n)||i[h].almostEquals(n)){a=!0;break}a||i.push(n.clone())}}}computeNormals(){this.faceNormals.length=this.faces.length;for(let e=0;e<this.faces.length;e++){for(let n=0;n<this.faces[e].length;n++)if(!this.vertices[this.faces[e][n]])throw new Error("Vertex "+this.faces[e][n]+" not found!");let t=this.faceNormals[e]||new _;this.getFaceNormal(e,t),t.negate(t),this.faceNormals[e]=t;let i=this.vertices[this.faces[e][0]];if(t.dot(i)<0){console.error(".faceNormals["+e+"] = Vec3("+t.toString()+") looks like it points into the shape? The vertices follow. Make sure they are ordered CCW around the normal, using the right hand rule.");for(let n=0;n<this.faces[e].length;n++)console.warn(".vertices["+this.faces[e][n]+"] = Vec3("+this.vertices[this.faces[e][n]].toString()+")")}}}getFaceNormal(e,t){let i=this.faces[e],n=this.vertices[i[0]],r=this.vertices[i[1]],o=this.vertices[i[2]];Zn.computeNormal(n,r,o,t)}static computeNormal(e,t,i,n){let r=new _,o=new _;t.vsub(e,o),i.vsub(t,r),r.cross(o,n),n.isZero()||n.normalize()}clipAgainstHull(e,t,i,n,r,o,s,c,d){let a=new _,h=-1,u=-Number.MAX_VALUE;for(let E=0;E<i.faces.length;E++){a.copy(i.faceNormals[E]),r.vmult(a,a);let b=a.dot(o);b>u&&(u=b,h=E)}let f=[];for(let E=0;E<i.faces[h].length;E++){let b=i.vertices[i.faces[h][E]],y=new _;y.copy(b),r.vmult(y,y),n.vadd(y,y),f.push(y)}h>=0&&this.clipFaceAgainstHull(o,e,t,f,s,c,d)}findSeparatingAxis(e,t,i,n,r,o,s,c){let d=new _,a=new _,h=new _,u=new _,f=new _,E=new _,b=Number.MAX_VALUE,y=this;if(y.uniqueAxes)for(let g=0;g!==y.uniqueAxes.length;g++){i.vmult(y.uniqueAxes[g],d);let p=y.testSepAxis(d,e,t,i,n,r);if(p===!1)return!1;p<b&&(b=p,o.copy(d))}else{let g=s?s.length:y.faces.length;for(let p=0;p<g;p++){let m=s?s[p]:p;d.copy(y.faceNormals[m]),i.vmult(d,d);let v=y.testSepAxis(d,e,t,i,n,r);if(v===!1)return!1;v<b&&(b=v,o.copy(d))}}if(e.uniqueAxes)for(let g=0;g!==e.uniqueAxes.length;g++){r.vmult(e.uniqueAxes[g],a);let p=y.testSepAxis(a,e,t,i,n,r);if(p===!1)return!1;p<b&&(b=p,o.copy(a))}else{let g=c?c.length:e.faces.length;for(let p=0;p<g;p++){let m=c?c[p]:p;a.copy(e.faceNormals[m]),r.vmult(a,a);let v=y.testSepAxis(a,e,t,i,n,r);if(v===!1)return!1;v<b&&(b=v,o.copy(a))}}for(let g=0;g!==y.uniqueEdges.length;g++){i.vmult(y.uniqueEdges[g],u);for(let p=0;p!==e.uniqueEdges.length;p++)if(r.vmult(e.uniqueEdges[p],f),u.cross(f,E),!E.almostZero()){E.normalize();let m=y.testSepAxis(E,e,t,i,n,r);if(m===!1)return!1;m<b&&(b=m,o.copy(E))}}return n.vsub(t,h),h.dot(o)>0&&o.negate(o),!0}testSepAxis(e,t,i,n,r,o){let s=this;Zn.project(s,e,i,n,Bl),Zn.project(t,e,r,o,Fl);let c=Bl[0],d=Bl[1],a=Fl[0],h=Fl[1];if(c<h||a<d)return!1;let u=c-h,f=a-d;return u<f?u:f}calculateLocalInertia(e,t){let i=new _,n=new _;this.computeLocalAABB(n,i);let r=i.x-n.x,o=i.y-n.y,s=i.z-n.z;t.x=1/12*e*(2*o*2*o+2*s*2*s),t.y=1/12*e*(2*r*2*r+2*s*2*s),t.z=1/12*e*(2*o*2*o+2*r*2*r)}getPlaneConstantOfFace(e){let t=this.faces[e],i=this.faceNormals[e],n=this.vertices[t[0]];return-i.dot(n)}clipFaceAgainstHull(e,t,i,n,r,o,s){let c=new _,d=new _,a=new _,h=new _,u=new _,f=new _,E=new _,b=new _,y=this,g=[],p=n,m=g,v=-1,w=Number.MAX_VALUE;for(let P=0;P<y.faces.length;P++){c.copy(y.faceNormals[P]),i.vmult(c,c);let S=c.dot(e);S<w&&(w=S,v=P)}if(v<0)return;let x=y.faces[v];x.connectedFaces=[];for(let P=0;P<y.faces.length;P++)for(let S=0;S<y.faces[P].length;S++)x.indexOf(y.faces[P][S])!==-1&&P!==v&&x.connectedFaces.indexOf(P)===-1&&x.connectedFaces.push(P);let T=x.length;for(let P=0;P<T;P++){let S=y.vertices[x[P]],L=y.vertices[x[(P+1)%T]];S.vsub(L,d),a.copy(d),i.vmult(a,a),t.vadd(a,a),h.copy(this.faceNormals[v]),i.vmult(h,h),t.vadd(h,h),a.cross(h,u),u.negate(u),f.copy(S),i.vmult(f,f),t.vadd(f,f);let I=x.connectedFaces[P];E.copy(this.faceNormals[I]);let j=this.getPlaneConstantOfFace(I);b.copy(E),i.vmult(b,b);let H=j-b.dot(t);for(this.clipFaceAgainstPlane(p,m,b,H);p.length;)p.shift();for(;m.length;)p.push(m.shift())}E.copy(this.faceNormals[v]);let R=this.getPlaneConstantOfFace(v);b.copy(E),i.vmult(b,b);let C=R-b.dot(t);for(let P=0;P<p.length;P++){let S=b.dot(p[P])+C;if(S<=r&&(console.log("clamped: depth="+S+" to minDist="+r),S=r),S<=o){let L=p[P];if(S<=1e-6){let I={point:L,normal:b,depth:S};s.push(I)}}}}clipFaceAgainstPlane(e,t,i,n){let r,o,s=e.length;if(s<2)return t;let c=e[e.length-1],d=e[0];r=i.dot(c)+n;for(let a=0;a<s;a++){if(d=e[a],o=i.dot(d)+n,r<0)if(o<0){let h=new _;h.copy(d),t.push(h)}else{let h=new _;c.lerp(d,r/(r-o),h),t.push(h)}else if(o<0){let h=new _;c.lerp(d,r/(r-o),h),t.push(h),t.push(d)}c=d,r=o}return t}computeWorldVertices(e,t){for(;this.worldVertices.length<this.vertices.length;)this.worldVertices.push(new _);let i=this.vertices,n=this.worldVertices;for(let r=0;r!==this.vertices.length;r++)t.vmult(i[r],n[r]),e.vadd(n[r],n[r]);this.worldVerticesNeedsUpdate=!1}computeLocalAABB(e,t){let i=this.vertices;e.set(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),t.set(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let n=0;n<this.vertices.length;n++){let r=i[n];r.x<e.x?e.x=r.x:r.x>t.x&&(t.x=r.x),r.y<e.y?e.y=r.y:r.y>t.y&&(t.y=r.y),r.z<e.z?e.z=r.z:r.z>t.z&&(t.z=r.z)}}computeWorldFaceNormals(e){let t=this.faceNormals.length;for(;this.worldFaceNormals.length<t;)this.worldFaceNormals.push(new _);let i=this.faceNormals,n=this.worldFaceNormals;for(let r=0;r!==t;r++)e.vmult(i[r],n[r]);this.worldFaceNormalsNeedsUpdate=!1}updateBoundingSphereRadius(){let e=0,t=this.vertices;for(let i=0;i!==t.length;i++){let n=t[i].lengthSquared();n>e&&(e=n)}this.boundingSphereRadius=Math.sqrt(e)}calculateWorldAABB(e,t,i,n){let r=this.vertices,o,s,c,d,a,h,u=new _;for(let f=0;f<r.length;f++){u.copy(r[f]),t.vmult(u,u),e.vadd(u,u);let E=u;(o===void 0||E.x<o)&&(o=E.x),(d===void 0||E.x>d)&&(d=E.x),(s===void 0||E.y<s)&&(s=E.y),(a===void 0||E.y>a)&&(a=E.y),(c===void 0||E.z<c)&&(c=E.z),(h===void 0||E.z>h)&&(h=E.z)}i.set(o,s,c),n.set(d,a,h)}volume(){return 4*Math.PI*this.boundingSphereRadius/3}getAveragePointLocal(e=new _){let t=this.vertices;for(let i=0;i<t.length;i++)e.vadd(t[i],e);return e.scale(1/t.length,e),e}transformAllPoints(e,t){let i=this.vertices.length,n=this.vertices;if(t){for(let r=0;r<i;r++){let o=n[r];t.vmult(o,o)}for(let r=0;r<this.faceNormals.length;r++){let o=this.faceNormals[r];t.vmult(o,o)}}if(e)for(let r=0;r<i;r++){let o=n[r];o.vadd(e,o)}}pointIsInside(e){let t=this.vertices,i=this.faces,n=this.faceNormals,r=new _;this.getAveragePointLocal(r);for(let o=0;o<this.faces.length;o++){let s=n[o],c=t[i[o][0]],d=new _;e.vsub(c,d);let a=s.dot(d),h=new _;r.vsub(c,h);let u=s.dot(h);if(a<0&&u>0||a>0&&u<0)return!1}return-1}static project(e,t,i,n,r){let o=e.vertices.length,s=cm,c=0,d=0,a=dm,h=e.vertices;a.setZero(),te.vectorToLocalFrame(i,n,t,s),te.pointToLocalFrame(i,n,a,a);let u=a.dot(s);d=c=h[0].dot(s);for(let f=1;f<o;f++){let E=h[f].dot(s);E>c&&(c=E),E<d&&(d=E)}if(d-=u,c-=u,d>c){let f=d;d=c,c=f}r[0]=c,r[1]=d}},Bl=[],Fl=[],cm=new _,dm=new _,Jn=class extends V{constructor(e){super({type:V.types.BOX}),this.halfExtents=void 0,this.convexPolyhedronRepresentation=void 0,this.halfExtents=e,this.convexPolyhedronRepresentation=null,this.updateConvexPolyhedronRepresentation(),this.updateBoundingSphereRadius()}updateConvexPolyhedronRepresentation(){let e=this.halfExtents.x,t=this.halfExtents.y,i=this.halfExtents.z,n=_,r=[new n(-e,-t,-i),new n(e,-t,-i),new n(e,t,-i),new n(-e,t,-i),new n(-e,-t,i),new n(e,-t,i),new n(e,t,i),new n(-e,t,i)],o=[[3,2,1,0],[4,5,6,7],[5,4,0,1],[2,3,7,6],[0,4,7,3],[1,2,6,5]],s=[new n(0,0,1),new n(0,1,0),new n(1,0,0)],c=new Zn({vertices:r,faces:o,axes:s});this.convexPolyhedronRepresentation=c,c.material=this.material}calculateLocalInertia(e,t=new _){return Jn.calculateInertia(this.halfExtents,e,t),t}static calculateInertia(e,t,i){let n=e;i.x=1/12*t*(2*n.y*2*n.y+2*n.z*2*n.z),i.y=1/12*t*(2*n.x*2*n.x+2*n.z*2*n.z),i.z=1/12*t*(2*n.y*2*n.y+2*n.x*2*n.x)}getSideNormals(e,t){let i=e,n=this.halfExtents;if(i[0].set(n.x,0,0),i[1].set(0,n.y,0),i[2].set(0,0,n.z),i[3].set(-n.x,0,0),i[4].set(0,-n.y,0),i[5].set(0,0,-n.z),t!==void 0)for(let r=0;r!==i.length;r++)t.vmult(i[r],i[r]);return i}volume(){return 8*this.halfExtents.x*this.halfExtents.y*this.halfExtents.z}updateBoundingSphereRadius(){this.boundingSphereRadius=this.halfExtents.length()}forEachWorldCorner(e,t,i){let n=this.halfExtents,r=[[n.x,n.y,n.z],[-n.x,n.y,n.z],[-n.x,-n.y,n.z],[-n.x,-n.y,-n.z],[n.x,-n.y,-n.z],[n.x,n.y,-n.z],[-n.x,n.y,-n.z],[n.x,-n.y,n.z]];for(let o=0;o<r.length;o++)mn.set(r[o][0],r[o][1],r[o][2]),t.vmult(mn,mn),e.vadd(mn,mn),i(mn.x,mn.y,mn.z)}calculateWorldAABB(e,t,i,n){let r=this.halfExtents;oi[0].set(r.x,r.y,r.z),oi[1].set(-r.x,r.y,r.z),oi[2].set(-r.x,-r.y,r.z),oi[3].set(-r.x,-r.y,-r.z),oi[4].set(r.x,-r.y,-r.z),oi[5].set(r.x,r.y,-r.z),oi[6].set(-r.x,r.y,-r.z),oi[7].set(r.x,-r.y,r.z);let o=oi[0];t.vmult(o,o),e.vadd(o,o),n.copy(o),i.copy(o);for(let s=1;s<8;s++){let c=oi[s];t.vmult(c,c),e.vadd(c,c);let d=c.x,a=c.y,h=c.z;d>n.x&&(n.x=d),a>n.y&&(n.y=a),h>n.z&&(n.z=h),d<i.x&&(i.x=d),a<i.y&&(i.y=a),h<i.z&&(i.z=h)}}},mn=new _,oi=[new _,new _,new _,new _,new _,new _,new _,new _],$l={DYNAMIC:1,STATIC:2,KINEMATIC:4},Kl={AWAKE:0,SLEEPY:1,SLEEPING:2},G=class extends Ks{constructor(e={}){super(),this.id=void 0,this.index=void 0,this.world=void 0,this.preStep=void 0,this.postStep=void 0,this.vlambda=void 0,this.collisionFilterGroup=void 0,this.collisionFilterMask=void 0,this.collisionResponse=void 0,this.position=void 0,this.previousPosition=void 0,this.interpolatedPosition=void 0,this.initPosition=void 0,this.velocity=void 0,this.initVelocity=void 0,this.force=void 0,this.mass=void 0,this.invMass=void 0,this.material=void 0,this.linearDamping=void 0,this.type=void 0,this.allowSleep=void 0,this.sleepState=void 0,this.sleepSpeedLimit=void 0,this.sleepTimeLimit=void 0,this.timeLastSleepy=void 0,this.wakeUpAfterNarrowphase=void 0,this.torque=void 0,this.quaternion=void 0,this.initQuaternion=void 0,this.previousQuaternion=void 0,this.interpolatedQuaternion=void 0,this.angularVelocity=void 0,this.initAngularVelocity=void 0,this.shapes=void 0,this.shapeOffsets=void 0,this.shapeOrientations=void 0,this.inertia=void 0,this.invInertia=void 0,this.invInertiaWorld=void 0,this.invMassSolve=void 0,this.invInertiaSolve=void 0,this.invInertiaWorldSolve=void 0,this.fixedRotation=void 0,this.angularDamping=void 0,this.linearFactor=void 0,this.angularFactor=void 0,this.aabb=void 0,this.aabbNeedsUpdate=void 0,this.boundingRadius=void 0,this.wlambda=void 0,this.isTrigger=void 0,this.id=G.idCounter++,this.index=-1,this.world=null,this.preStep=null,this.postStep=null,this.vlambda=new _,this.collisionFilterGroup=typeof e.collisionFilterGroup=="number"?e.collisionFilterGroup:1,this.collisionFilterMask=typeof e.collisionFilterMask=="number"?e.collisionFilterMask:-1,this.collisionResponse=typeof e.collisionResponse=="boolean"?e.collisionResponse:!0,this.position=new _,this.previousPosition=new _,this.interpolatedPosition=new _,this.initPosition=new _,e.position&&(this.position.copy(e.position),this.previousPosition.copy(e.position),this.interpolatedPosition.copy(e.position),this.initPosition.copy(e.position)),this.velocity=new _,e.velocity&&this.velocity.copy(e.velocity),this.initVelocity=new _,this.force=new _;let t=typeof e.mass=="number"?e.mass:0;this.mass=t,this.invMass=t>0?1/t:0,this.material=e.material||null,this.linearDamping=typeof e.linearDamping=="number"?e.linearDamping:.01,this.type=t<=0?G.STATIC:G.DYNAMIC,typeof e.type==typeof G.STATIC&&(this.type=e.type),this.allowSleep=typeof e.allowSleep<"u"?e.allowSleep:!0,this.sleepState=G.AWAKE,this.sleepSpeedLimit=typeof e.sleepSpeedLimit<"u"?e.sleepSpeedLimit:.1,this.sleepTimeLimit=typeof e.sleepTimeLimit<"u"?e.sleepTimeLimit:1,this.timeLastSleepy=0,this.wakeUpAfterNarrowphase=!1,this.torque=new _,this.quaternion=new le,this.initQuaternion=new le,this.previousQuaternion=new le,this.interpolatedQuaternion=new le,e.quaternion&&(this.quaternion.copy(e.quaternion),this.initQuaternion.copy(e.quaternion),this.previousQuaternion.copy(e.quaternion),this.interpolatedQuaternion.copy(e.quaternion)),this.angularVelocity=new _,e.angularVelocity&&this.angularVelocity.copy(e.angularVelocity),this.initAngularVelocity=new _,this.shapes=[],this.shapeOffsets=[],this.shapeOrientations=[],this.inertia=new _,this.invInertia=new _,this.invInertiaWorld=new Ot,this.invMassSolve=0,this.invInertiaSolve=new _,this.invInertiaWorldSolve=new Ot,this.fixedRotation=typeof e.fixedRotation<"u"?e.fixedRotation:!1,this.angularDamping=typeof e.angularDamping<"u"?e.angularDamping:.01,this.linearFactor=new _(1,1,1),e.linearFactor&&this.linearFactor.copy(e.linearFactor),this.angularFactor=new _(1,1,1),e.angularFactor&&this.angularFactor.copy(e.angularFactor),this.aabb=new $e,this.aabbNeedsUpdate=!0,this.boundingRadius=0,this.wlambda=new _,this.isTrigger=Boolean(e.isTrigger),e.shape&&this.addShape(e.shape),this.updateMassProperties()}wakeUp(){let e=this.sleepState;this.sleepState=G.AWAKE,this.wakeUpAfterNarrowphase=!1,e===G.SLEEPING&&this.dispatchEvent(G.wakeupEvent)}sleep(){this.sleepState=G.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0),this.wakeUpAfterNarrowphase=!1}sleepTick(e){if(this.allowSleep){let t=this.sleepState,i=this.velocity.lengthSquared()+this.angularVelocity.lengthSquared(),n=this.sleepSpeedLimit**2;t===G.AWAKE&&i<n?(this.sleepState=G.SLEEPY,this.timeLastSleepy=e,this.dispatchEvent(G.sleepyEvent)):t===G.SLEEPY&&i>n?this.wakeUp():t===G.SLEEPY&&e-this.timeLastSleepy>this.sleepTimeLimit&&(this.sleep(),this.dispatchEvent(G.sleepEvent))}}updateSolveMassProperties(){this.sleepState===G.SLEEPING||this.type===G.KINEMATIC?(this.invMassSolve=0,this.invInertiaSolve.setZero(),this.invInertiaWorldSolve.setZero()):(this.invMassSolve=this.invMass,this.invInertiaSolve.copy(this.invInertia),this.invInertiaWorldSolve.copy(this.invInertiaWorld))}pointToLocalFrame(e,t=new _){return e.vsub(this.position,t),this.quaternion.conjugate().vmult(t,t),t}vectorToLocalFrame(e,t=new _){return this.quaternion.conjugate().vmult(e,t),t}pointToWorldFrame(e,t=new _){return this.quaternion.vmult(e,t),t.vadd(this.position,t),t}vectorToWorldFrame(e,t=new _){return this.quaternion.vmult(e,t),t}addShape(e,t,i){let n=new _,r=new le;return t&&n.copy(t),i&&r.copy(i),this.shapes.push(e),this.shapeOffsets.push(n),this.shapeOrientations.push(r),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0,e.body=this,this}removeShape(e){let t=this.shapes.indexOf(e);return t===-1?(console.warn("Shape does not belong to the body"),this):(this.shapes.splice(t,1),this.shapeOffsets.splice(t,1),this.shapeOrientations.splice(t,1),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0,e.body=null,this)}updateBoundingRadius(){let e=this.shapes,t=this.shapeOffsets,i=e.length,n=0;for(let r=0;r!==i;r++){let o=e[r];o.updateBoundingSphereRadius();let s=t[r].length(),c=o.boundingSphereRadius;s+c>n&&(n=s+c)}this.boundingRadius=n}updateAABB(){let e=this.shapes,t=this.shapeOffsets,i=this.shapeOrientations,n=e.length,r=hm,o=um,s=this.quaternion,c=this.aabb,d=pm;for(let a=0;a!==n;a++){let h=e[a];s.vmult(t[a],r),r.vadd(this.position,r),s.mult(i[a],o),h.calculateWorldAABB(r,o,d.lowerBound,d.upperBound),a===0?c.copy(d):c.extend(d)}this.aabbNeedsUpdate=!1}updateInertiaWorld(e){let t=this.invInertia;if(!(t.x===t.y&&t.y===t.z&&!e)){let i=fm,n=mm;i.setRotationFromQuaternion(this.quaternion),i.transpose(n),i.scale(t,i),i.mmult(n,this.invInertiaWorld)}}applyForce(e,t=new _){if(this.type!==G.DYNAMIC)return;this.sleepState===G.SLEEPING&&this.wakeUp();let i=gm;t.cross(e,i),this.force.vadd(e,this.force),this.torque.vadd(i,this.torque)}applyLocalForce(e,t=new _){if(this.type!==G.DYNAMIC)return;let i=bm,n=vm;this.vectorToWorldFrame(e,i),this.vectorToWorldFrame(t,n),this.applyForce(i,n)}applyTorque(e){this.type===G.DYNAMIC&&(this.sleepState===G.SLEEPING&&this.wakeUp(),this.torque.vadd(e,this.torque))}applyImpulse(e,t=new _){if(this.type!==G.DYNAMIC)return;this.sleepState===G.SLEEPING&&this.wakeUp();let i=t,n=ym;n.copy(e),n.scale(this.invMass,n),this.velocity.vadd(n,this.velocity);let r=Em;i.cross(e,r),this.invInertiaWorld.vmult(r,r),this.angularVelocity.vadd(r,this.angularVelocity)}applyLocalImpulse(e,t=new _){if(this.type!==G.DYNAMIC)return;let i=wm,n=_m;this.vectorToWorldFrame(e,i),this.vectorToWorldFrame(t,n),this.applyImpulse(i,n)}updateMassProperties(){let e=xm;this.invMass=this.mass>0?1/this.mass:0;let t=this.inertia,i=this.fixedRotation;this.updateAABB(),e.set((this.aabb.upperBound.x-this.aabb.lowerBound.x)/2,(this.aabb.upperBound.y-this.aabb.lowerBound.y)/2,(this.aabb.upperBound.z-this.aabb.lowerBound.z)/2),Jn.calculateInertia(e,this.mass,t),this.invInertia.set(t.x>0&&!i?1/t.x:0,t.y>0&&!i?1/t.y:0,t.z>0&&!i?1/t.z:0),this.updateInertiaWorld(!0)}getVelocityAtWorldPoint(e,t){let i=new _;return e.vsub(this.position,i),this.angularVelocity.cross(i,t),this.velocity.vadd(t,t),t}integrate(e,t,i){if(this.previousPosition.copy(this.position),this.previousQuaternion.copy(this.quaternion),!(this.type===G.DYNAMIC||this.type===G.KINEMATIC)||this.sleepState===G.SLEEPING)return;let n=this.velocity,r=this.angularVelocity,o=this.position,s=this.force,c=this.torque,d=this.quaternion,a=this.invMass,h=this.invInertiaWorld,u=this.linearFactor,f=a*e;n.x+=s.x*f*u.x,n.y+=s.y*f*u.y,n.z+=s.z*f*u.z;let E=h.elements,b=this.angularFactor,y=c.x*b.x,g=c.y*b.y,p=c.z*b.z;r.x+=e*(E[0]*y+E[1]*g+E[2]*p),r.y+=e*(E[3]*y+E[4]*g+E[5]*p),r.z+=e*(E[6]*y+E[7]*g+E[8]*p),o.x+=n.x*e,o.y+=n.y*e,o.z+=n.z*e,d.integrate(this.angularVelocity,e,this.angularFactor,d),t&&(i?d.normalizeFast():d.normalize()),this.aabbNeedsUpdate=!0,this.updateInertiaWorld()}};G.idCounter=0;G.COLLIDE_EVENT_NAME="collide";G.DYNAMIC=$l.DYNAMIC;G.STATIC=$l.STATIC;G.KINEMATIC=$l.KINEMATIC;G.AWAKE=Kl.AWAKE;G.SLEEPY=Kl.SLEEPY;G.SLEEPING=Kl.SLEEPING;G.wakeupEvent={type:"wakeup"};G.sleepyEvent={type:"sleepy"};G.sleepEvent={type:"sleep"};var hm=new _,um=new le,pm=new $e,fm=new Ot,mm=new Ot,gm=new _,bm=new _,vm=new _,ym=new _,Em=new _,wm=new _,_m=new _,xm=new _,Vl=class{constructor(){this.world=void 0,this.useBoundingBoxes=void 0,this.dirty=void 0,this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}collisionPairs(e,t,i){throw new Error("collisionPairs not implemented for this BroadPhase class!")}needBroadphaseCollision(e,t){return!((e.collisionFilterGroup&t.collisionFilterMask)===0||(t.collisionFilterGroup&e.collisionFilterMask)===0||((e.type&G.STATIC)!==0||e.sleepState===G.SLEEPING)&&((t.type&G.STATIC)!==0||t.sleepState===G.SLEEPING))}intersectionTest(e,t,i,n){this.useBoundingBoxes?this.doBoundingBoxBroadphase(e,t,i,n):this.doBoundingSphereBroadphase(e,t,i,n)}doBoundingSphereBroadphase(e,t,i,n){let r=Tm;t.position.vsub(e.position,r);let o=(e.boundingRadius+t.boundingRadius)**2;r.lengthSquared()<o&&(i.push(e),n.push(t))}doBoundingBoxBroadphase(e,t,i,n){e.aabbNeedsUpdate&&e.updateAABB(),t.aabbNeedsUpdate&&t.updateAABB(),e.aabb.overlaps(t.aabb)&&(i.push(e),n.push(t))}makePairsUnique(e,t){let i=Rm,n=Cm,r=Sm,o=e.length;for(let s=0;s!==o;s++)n[s]=e[s],r[s]=t[s];e.length=0,t.length=0;for(let s=0;s!==o;s++){let c=n[s].id,d=r[s].id,a=c<d?c+","+d:d+","+c;i[a]=s,i.keys.push(a)}for(let s=0;s!==i.keys.length;s++){let c=i.keys.pop(),d=i[c];e.push(n[d]),t.push(r[d]),delete i[c]}}setWorld(e){}static boundingSphereCheck(e,t){let i=new _;e.position.vsub(t.position,i);let n=e.shapes[0],r=t.shapes[0];return Math.pow(n.boundingSphereRadius+r.boundingSphereRadius,2)>i.lengthSquared()}aabbQuery(e,t,i){return console.warn(".aabbQuery is not implemented in this Broadphase subclass."),[]}},Tm=new _,Rm={keys:[]},Cm=[],Sm=[];var H0=new _,Wl=class extends Vl{constructor(){super()}collisionPairs(e,t,i){let n=e.bodies,r=n.length,o,s;for(let c=0;c!==r;c++)for(let d=0;d!==c;d++)o=n[c],s=n[d],this.needBroadphaseCollision(o,s)&&this.intersectionTest(o,s,t,i)}aabbQuery(e,t,i=[]){for(let n=0;n<e.bodies.length;n++){let r=e.bodies[n];r.aabbNeedsUpdate&&r.updateAABB(),r.aabb.overlaps(t)&&i.push(r)}return i}},is=class{constructor(){this.rayFromWorld=void 0,this.rayToWorld=void 0,this.hitNormalWorld=void 0,this.hitPointWorld=void 0,this.hasHit=void 0,this.shape=void 0,this.body=void 0,this.hitFaceIndex=void 0,this.distance=void 0,this.shouldStop=void 0,this.rayFromWorld=new _,this.rayToWorld=new _,this.hitNormalWorld=new _,this.hitPointWorld=new _,this.hasHit=!1,this.shape=null,this.body=null,this.hitFaceIndex=-1,this.distance=-1,this.shouldStop=!1}reset(){this.rayFromWorld.setZero(),this.rayToWorld.setZero(),this.hitNormalWorld.setZero(),this.hitPointWorld.setZero(),this.hasHit=!1,this.shape=null,this.body=null,this.hitFaceIndex=-1,this.distance=-1,this.shouldStop=!1}abort(){this.shouldStop=!0}set(e,t,i,n,r,o,s){this.rayFromWorld.copy(e),this.rayToWorld.copy(t),this.hitNormalWorld.copy(i),this.hitPointWorld.copy(n),this.shape=r,this.body=o,this.distance=s}},iu,nu,ru,ou,su,au,lu,ec={CLOSEST:1,ANY:2,ALL:4};iu=V.types.SPHERE;nu=V.types.PLANE;ru=V.types.BOX;ou=V.types.CYLINDER;su=V.types.CONVEXPOLYHEDRON;au=V.types.HEIGHTFIELD;lu=V.types.TRIMESH;var Ee=class{get[iu](){return this._intersectSphere}get[nu](){return this._intersectPlane}get[ru](){return this._intersectBox}get[ou](){return this._intersectConvex}get[su](){return this._intersectConvex}get[au](){return this._intersectHeightfield}get[lu](){return this._intersectTrimesh}constructor(e=new _,t=new _){this.from=void 0,this.to=void 0,this.direction=void 0,this.precision=void 0,this.checkCollisionResponse=void 0,this.skipBackfaces=void 0,this.collisionFilterMask=void 0,this.collisionFilterGroup=void 0,this.mode=void 0,this.result=void 0,this.hasHit=void 0,this.callback=void 0,this.from=e.clone(),this.to=t.clone(),this.direction=new _,this.precision=1e-4,this.checkCollisionResponse=!0,this.skipBackfaces=!1,this.collisionFilterMask=-1,this.collisionFilterGroup=-1,this.mode=Ee.ANY,this.result=new is,this.hasHit=!1,this.callback=i=>{}}intersectWorld(e,t){return this.mode=t.mode||Ee.ANY,this.result=t.result||new is,this.skipBackfaces=!!t.skipBackfaces,this.collisionFilterMask=typeof t.collisionFilterMask<"u"?t.collisionFilterMask:-1,this.collisionFilterGroup=typeof t.collisionFilterGroup<"u"?t.collisionFilterGroup:-1,this.checkCollisionResponse=typeof t.checkCollisionResponse<"u"?t.checkCollisionResponse:!0,t.from&&this.from.copy(t.from),t.to&&this.to.copy(t.to),this.callback=t.callback||(()=>{}),this.hasHit=!1,this.result.reset(),this.updateDirection(),this.getAABB(Uh),Nl.length=0,e.broadphase.aabbQuery(e,Uh,Nl),this.intersectBodies(Nl),this.hasHit}intersectBody(e,t){t&&(this.result=t,this.updateDirection());let i=this.checkCollisionResponse;if(i&&!e.collisionResponse||(this.collisionFilterGroup&e.collisionFilterMask)===0||(e.collisionFilterGroup&this.collisionFilterMask)===0)return;let n=Pm,r=Om;for(let o=0,s=e.shapes.length;o<s;o++){let c=e.shapes[o];if(!(i&&!c.collisionResponse)&&(e.quaternion.mult(e.shapeOrientations[o],r),e.quaternion.vmult(e.shapeOffsets[o],n),n.vadd(e.position,n),this.intersectShape(c,r,n,e),this.result.shouldStop))break}}intersectBodies(e,t){t&&(this.result=t,this.updateDirection());for(let i=0,n=e.length;!this.result.shouldStop&&i<n;i++)this.intersectBody(e[i])}updateDirection(){this.to.vsub(this.from,this.direction),this.direction.normalize()}intersectShape(e,t,i,n){let r=this.from;if(Vm(r,this.direction,i)>e.boundingSphereRadius)return;let s=this[e.type];s&&s.call(this,e,t,i,n,e)}_intersectBox(e,t,i,n,r){return this._intersectConvex(e.convexPolyhedronRepresentation,t,i,n,r)}_intersectPlane(e,t,i,n,r){let o=this.from,s=this.to,c=this.direction,d=new _(0,0,1);t.vmult(d,d);let a=new _;o.vsub(i,a);let h=a.dot(d);s.vsub(i,a);let u=a.dot(d);if(h*u>0||o.distanceTo(s)<h)return;let f=d.dot(c);if(Math.abs(f)<this.precision)return;let E=new _,b=new _,y=new _;o.vsub(i,E);let g=-d.dot(E)/f;c.scale(g,b),o.vadd(b,y),this.reportIntersection(d,y,r,n,-1)}getAABB(e){let{lowerBound:t,upperBound:i}=e,n=this.to,r=this.from;t.x=Math.min(n.x,r.x),t.y=Math.min(n.y,r.y),t.z=Math.min(n.z,r.z),i.x=Math.max(n.x,r.x),i.y=Math.max(n.y,r.y),i.z=Math.max(n.z,r.z)}_intersectHeightfield(e,t,i,n,r){e.data,e.elementSize;let o=Am;o.from.copy(this.from),o.to.copy(this.to),te.pointToLocalFrame(i,t,o.from,o.from),te.pointToLocalFrame(i,t,o.to,o.to),o.updateDirection();let s=km,c,d,a,h;c=d=0,a=h=e.data.length-1;let u=new $e;o.getAABB(u),e.getIndexOfPosition(u.lowerBound.x,u.lowerBound.y,s,!0),c=Math.max(c,s[0]),d=Math.max(d,s[1]),e.getIndexOfPosition(u.upperBound.x,u.upperBound.y,s,!0),a=Math.min(a,s[0]+1),h=Math.min(h,s[1]+1);for(let f=c;f<a;f++)for(let E=d;E<h;E++){if(this.result.shouldStop)return;if(e.getAabbAtIndex(f,E,u),!!u.overlapsRay(o)){if(e.getConvexTrianglePillar(f,E,!1),te.pointToWorldFrame(i,t,e.pillarOffset,Xs),this._intersectConvex(e.pillarConvex,t,Xs,n,r,qh),this.result.shouldStop)return;e.getConvexTrianglePillar(f,E,!0),te.pointToWorldFrame(i,t,e.pillarOffset,Xs),this._intersectConvex(e.pillarConvex,t,Xs,n,r,qh)}}}_intersectSphere(e,t,i,n,r){let o=this.from,s=this.to,c=e.radius,d=(s.x-o.x)**2+(s.y-o.y)**2+(s.z-o.z)**2,a=2*((s.x-o.x)*(o.x-i.x)+(s.y-o.y)*(o.y-i.y)+(s.z-o.z)*(o.z-i.z)),h=(o.x-i.x)**2+(o.y-i.y)**2+(o.z-i.z)**2-c**2,u=a**2-4*d*h,f=Im,E=Mm;if(!(u<0))if(u===0)o.lerp(s,u,f),f.vsub(i,E),E.normalize(),this.reportIntersection(E,f,r,n,-1);else{let b=(-a-Math.sqrt(u))/(2*d),y=(-a+Math.sqrt(u))/(2*d);if(b>=0&&b<=1&&(o.lerp(s,b,f),f.vsub(i,E),E.normalize(),this.reportIntersection(E,f,r,n,-1)),this.result.shouldStop)return;y>=0&&y<=1&&(o.lerp(s,y,f),f.vsub(i,E),E.normalize(),this.reportIntersection(E,f,r,n,-1))}}_intersectConvex(e,t,i,n,r,o){let s=Lm,c=Xh,d=o&&o.faceList||null,a=e.faces,h=e.vertices,u=e.faceNormals,f=this.direction,E=this.from,b=this.to,y=E.distanceTo(b),g=d?d.length:a.length,p=this.result;for(let m=0;!p.shouldStop&&m<g;m++){let v=d?d[m]:m,w=a[v],x=u[v],T=t,R=i;c.copy(h[w[0]]),T.vmult(c,c),c.vadd(R,c),c.vsub(E,c),T.vmult(x,s);let C=f.dot(s);if(Math.abs(C)<this.precision)continue;let P=s.dot(c)/C;if(!(P<0)){f.scale(P,st),st.vadd(E,st),Wt.copy(h[w[0]]),T.vmult(Wt,Wt),R.vadd(Wt,Wt);for(let S=1;!p.shouldStop&&S<w.length-1;S++){si.copy(h[w[S]]),ai.copy(h[w[S+1]]),T.vmult(si,si),T.vmult(ai,ai),R.vadd(si,si),R.vadd(ai,ai);let L=st.distanceTo(E);!(Ee.pointInTriangle(st,Wt,si,ai)||Ee.pointInTriangle(st,si,Wt,ai))||L>y||this.reportIntersection(s,st,r,n,v)}}}}_intersectTrimesh(e,t,i,n,r,o){let s=Dm,c=zm,d=Gm,a=Xh,h=Hm,u=jm,f=Bm,E=Nm,b=Fm,y=e.indices;e.vertices;let g=this.from,p=this.to,m=this.direction;d.position.copy(i),d.quaternion.copy(t),te.vectorToLocalFrame(i,t,m,h),te.pointToLocalFrame(i,t,g,u),te.pointToLocalFrame(i,t,p,f),f.x*=e.scale.x,f.y*=e.scale.y,f.z*=e.scale.z,u.x*=e.scale.x,u.y*=e.scale.y,u.z*=e.scale.z,f.vsub(u,h),h.normalize();let v=u.distanceSquared(f);e.tree.rayQuery(this,d,c);for(let w=0,x=c.length;!this.result.shouldStop&&w!==x;w++){let T=c[w];e.getNormal(T,s),e.getVertex(y[T*3],Wt),Wt.vsub(u,a);let R=h.dot(s),C=s.dot(a)/R;if(C<0)continue;h.scale(C,st),st.vadd(u,st),e.getVertex(y[T*3+1],si),e.getVertex(y[T*3+2],ai);let P=st.distanceSquared(u);!(Ee.pointInTriangle(st,si,Wt,ai)||Ee.pointInTriangle(st,Wt,si,ai))||P>v||(te.vectorToWorldFrame(t,s,b),te.pointToWorldFrame(i,t,st,E),this.reportIntersection(b,E,r,n,T))}c.length=0}reportIntersection(e,t,i,n,r){let o=this.from,s=this.to,c=o.distanceTo(t),d=this.result;if(!(this.skipBackfaces&&e.dot(this.direction)>0))switch(d.hitFaceIndex=typeof r<"u"?r:-1,this.mode){case Ee.ALL:this.hasHit=!0,d.set(o,s,e,t,i,n,c),d.hasHit=!0,this.callback(d);break;case Ee.CLOSEST:(c<d.distance||!d.hasHit)&&(this.hasHit=!0,d.hasHit=!0,d.set(o,s,e,t,i,n,c));break;case Ee.ANY:this.hasHit=!0,d.hasHit=!0,d.set(o,s,e,t,i,n,c),d.shouldStop=!0;break}}static pointInTriangle(e,t,i,n){n.vsub(t,Yn),i.vsub(t,$o),e.vsub(t,zl);let r=Yn.dot(Yn),o=Yn.dot($o),s=Yn.dot(zl),c=$o.dot($o),d=$o.dot(zl),a,h;return(a=c*s-o*d)>=0&&(h=r*d-o*s)>=0&&a+h<r*c-o*o}};Ee.CLOSEST=ec.CLOSEST;Ee.ANY=ec.ANY;Ee.ALL=ec.ALL;var Uh=new $e,Nl=[],$o=new _,zl=new _,Pm=new _,Om=new le,st=new _,Wt=new _,si=new _,ai=new _,qh={faceList:[0]},Xs=new _,Am=new Ee,km=[],Im=new _,Mm=new _,Lm=new _,Xh=new _,Dm=new _,Hm=new _,jm=new _,Bm=new _,Fm=new _,Nm=new _;new $e;var zm=[],Gm=new te,Yn=new _,Qs=new _;function Vm(l,e,t){t.vsub(l,Yn);let i=Yn.dot(e);return e.scale(i,Qs),Qs.vadd(l,Qs),t.distanceTo(Qs)}var ea=class{static defaults(e={},t){for(let i in t)i in e||(e[i]=t[i]);return e}},ns=class{constructor(e,t,i={}){this.equations=void 0,this.bodyA=void 0,this.bodyB=void 0,this.id=void 0,this.collideConnected=void 0,i=ea.defaults(i,{collideConnected:!0,wakeUpBodies:!0}),this.equations=[],this.bodyA=e,this.bodyB=t,this.id=ns.idCounter++,this.collideConnected=i.collideConnected,i.wakeUpBodies&&(e&&e.wakeUp(),t&&t.wakeUp())}update(){throw new Error("method update() not implmemented in this Constraint subclass!")}enable(){let e=this.equations;for(let t=0;t<e.length;t++)e[t].enabled=!0}disable(){let e=this.equations;for(let t=0;t<e.length;t++)e[t].enabled=!1}};ns.idCounter=0;var ta=class{constructor(){this.spatial=void 0,this.rotational=void 0,this.spatial=new _,this.rotational=new _}multiplyElement(e){return e.spatial.dot(this.spatial)+e.rotational.dot(this.rotational)}multiplyVectors(e,t){return e.dot(this.spatial)+t.dot(this.rotational)}},$n=class{constructor(e,t,i=-1e6,n=1e6){this.id=void 0,this.minForce=void 0,this.maxForce=void 0,this.bi=void 0,this.bj=void 0,this.si=void 0,this.sj=void 0,this.a=void 0,this.b=void 0,this.eps=void 0,this.jacobianElementA=void 0,this.jacobianElementB=void 0,this.enabled=void 0,this.multiplier=void 0,this.id=$n.idCounter++,this.minForce=i,this.maxForce=n,this.bi=e,this.bj=t,this.a=0,this.b=0,this.eps=0,this.jacobianElementA=new ta,this.jacobianElementB=new ta,this.enabled=!0,this.multiplier=0,this.setSpookParams(1e7,4,1/60)}setSpookParams(e,t,i){let n=t,r=e,o=i;this.a=4/(o*(1+4*n)),this.b=4*n/(1+4*n),this.eps=4/(o*o*r*(1+4*n))}computeB(e,t,i){let n=this.computeGW(),r=this.computeGq(),o=this.computeGiMf();return-r*e-n*t-o*i}computeGq(){let e=this.jacobianElementA,t=this.jacobianElementB,i=this.bi,n=this.bj,r=i.position,o=n.position;return e.spatial.dot(r)+t.spatial.dot(o)}computeGW(){let e=this.jacobianElementA,t=this.jacobianElementB,i=this.bi,n=this.bj,r=i.velocity,o=n.velocity,s=i.angularVelocity,c=n.angularVelocity;return e.multiplyVectors(r,s)+t.multiplyVectors(o,c)}computeGWlambda(){let e=this.jacobianElementA,t=this.jacobianElementB,i=this.bi,n=this.bj,r=i.vlambda,o=n.vlambda,s=i.wlambda,c=n.wlambda;return e.multiplyVectors(r,s)+t.multiplyVectors(o,c)}computeGiMf(){let e=this.jacobianElementA,t=this.jacobianElementB,i=this.bi,n=this.bj,r=i.force,o=i.torque,s=n.force,c=n.torque,d=i.invMassSolve,a=n.invMassSolve;return r.scale(d,Qh),s.scale(a,Yh),i.invInertiaWorldSolve.vmult(o,Zh),n.invInertiaWorldSolve.vmult(c,Jh),e.multiplyVectors(Qh,Zh)+t.multiplyVectors(Yh,Jh)}computeGiMGt(){let e=this.jacobianElementA,t=this.jacobianElementB,i=this.bi,n=this.bj,r=i.invMassSolve,o=n.invMassSolve,s=i.invInertiaWorldSolve,c=n.invInertiaWorldSolve,d=r+o;return s.vmult(e.rotational,Ys),d+=Ys.dot(e.rotational),c.vmult(t.rotational,Ys),d+=Ys.dot(t.rotational),d}addToWlambda(e){let t=this.jacobianElementA,i=this.jacobianElementB,n=this.bi,r=this.bj,o=Wm;n.vlambda.addScaledVector(n.invMassSolve*e,t.spatial,n.vlambda),r.vlambda.addScaledVector(r.invMassSolve*e,i.spatial,r.vlambda),n.invInertiaWorldSolve.vmult(t.rotational,o),n.wlambda.addScaledVector(e,o,n.wlambda),r.invInertiaWorldSolve.vmult(i.rotational,o),r.wlambda.addScaledVector(e,o,r.wlambda)}computeC(){return this.computeGiMGt()+this.eps}};$n.idCounter=0;var Qh=new _,Yh=new _,Zh=new _,Jh=new _,Ys=new _,Wm=new _,Ul=class extends $n{constructor(e,t,i=1e6){super(e,t,0,i),this.restitution=void 0,this.ri=void 0,this.rj=void 0,this.ni=void 0,this.restitution=0,this.ri=new _,this.rj=new _,this.ni=new _}computeB(e){let t=this.a,i=this.b,n=this.bi,r=this.bj,o=this.ri,s=this.rj,c=Um,d=qm,a=n.velocity,h=n.angularVelocity;n.force,n.torque;let u=r.velocity,f=r.angularVelocity;r.force,r.torque;let E=Xm,b=this.jacobianElementA,y=this.jacobianElementB,g=this.ni;o.cross(g,c),s.cross(g,d),g.negate(b.spatial),c.negate(b.rotational),y.spatial.copy(g),y.rotational.copy(d),E.copy(r.position),E.vadd(s,E),E.vsub(n.position,E),E.vsub(o,E);let p=g.dot(E),m=this.restitution+1,v=m*u.dot(g)-m*a.dot(g)+f.dot(d)-h.dot(c),w=this.computeGiMf();return-p*t-v*i-e*w}getImpactVelocityAlongNormal(){let e=Qm,t=Ym,i=Zm,n=Jm,r=$m;return this.bi.position.vadd(this.ri,i),this.bj.position.vadd(this.rj,n),this.bi.getVelocityAtWorldPoint(i,e),this.bj.getVelocityAtWorldPoint(n,t),e.vsub(t,r),this.ni.dot(r)}},Um=new _,qm=new _,Xm=new _,Qm=new _,Ym=new _,Zm=new _,Jm=new _,$m=new _;var j0=new _,B0=new _;var F0=new _,N0=new _;var z0=new _,G0=new _,ia=class extends $n{constructor(e,t,i){super(e,t,-i,i),this.ri=void 0,this.rj=void 0,this.t=void 0,this.ri=new _,this.rj=new _,this.t=new _}computeB(e){this.a;let t=this.b;this.bi,this.bj;let i=this.ri,n=this.rj,r=Km,o=eg,s=this.t;i.cross(s,r),n.cross(s,o);let c=this.jacobianElementA,d=this.jacobianElementB;s.negate(c.spatial),r.negate(c.rotational),d.spatial.copy(s),d.rotational.copy(o);let a=this.computeGW(),h=this.computeGiMf();return-a*t-e*h}},Km=new _,eg=new _,Lr=class{constructor(e,t,i){this.id=void 0,this.materials=void 0,this.friction=void 0,this.restitution=void 0,this.contactEquationStiffness=void 0,this.contactEquationRelaxation=void 0,this.frictionEquationStiffness=void 0,this.frictionEquationRelaxation=void 0,i=ea.defaults(i,{friction:.3,restitution:.3,contactEquationStiffness:1e7,contactEquationRelaxation:3,frictionEquationStiffness:1e7,frictionEquationRelaxation:3}),this.id=Lr.idCounter++,this.materials=[e,t],this.friction=i.friction,this.restitution=i.restitution,this.contactEquationStiffness=i.contactEquationStiffness,this.contactEquationRelaxation=i.contactEquationRelaxation,this.frictionEquationStiffness=i.frictionEquationStiffness,this.frictionEquationRelaxation=i.frictionEquationRelaxation}};Lr.idCounter=0;var Dr=class{constructor(e={}){this.name=void 0,this.id=void 0,this.friction=void 0,this.restitution=void 0;let t="";typeof e=="string"&&(t=e,e={}),this.name=t,this.id=Dr.idCounter++,this.friction=typeof e.friction<"u"?e.friction:-1,this.restitution=typeof e.restitution<"u"?e.restitution:-1}};Dr.idCounter=0;var na=class{constructor(e,t,i={}){this.restLength=void 0,this.stiffness=void 0,this.damping=void 0,this.bodyA=void 0,this.bodyB=void 0,this.localAnchorA=void 0,this.localAnchorB=void 0,this.restLength=typeof i.restLength=="number"?i.restLength:1,this.stiffness=i.stiffness||100,this.damping=i.damping||1,this.bodyA=e,this.bodyB=t,this.localAnchorA=new _,this.localAnchorB=new _,i.localAnchorA&&this.localAnchorA.copy(i.localAnchorA),i.localAnchorB&&this.localAnchorB.copy(i.localAnchorB),i.worldAnchorA&&this.setWorldAnchorA(i.worldAnchorA),i.worldAnchorB&&this.setWorldAnchorB(i.worldAnchorB)}setWorldAnchorA(e){this.bodyA.pointToLocalFrame(e,this.localAnchorA)}setWorldAnchorB(e){this.bodyB.pointToLocalFrame(e,this.localAnchorB)}getWorldAnchorA(e){this.bodyA.pointToWorldFrame(this.localAnchorA,e)}getWorldAnchorB(e){this.bodyB.pointToWorldFrame(this.localAnchorB,e)}applyForce(){let e=this.stiffness,t=this.damping,i=this.restLength,n=this.bodyA,r=this.bodyB,o=tg,s=ig,c=ng,d=rg,a=hg,h=og,u=sg,f=ag,E=lg,b=cg,y=dg;this.getWorldAnchorA(h),this.getWorldAnchorB(u),h.vsub(n.position,f),u.vsub(r.position,E),u.vsub(h,o);let g=o.length();s.copy(o),s.normalize(),r.velocity.vsub(n.velocity,c),r.angularVelocity.cross(E,a),c.vadd(a,c),n.angularVelocity.cross(f,a),c.vsub(a,c),s.scale(-e*(g-i)-t*c.dot(s),d),n.force.vsub(d,n.force),r.force.vadd(d,r.force),f.cross(d,b),E.cross(d,y),n.torque.vsub(b,n.torque),r.torque.vadd(y,r.torque)}},tg=new _,ig=new _,ng=new _,rg=new _,og=new _,sg=new _,ag=new _,lg=new _,cg=new _,dg=new _,hg=new _;var V0=new _,W0=new _;var U0=new _,q0=new _,X0=new _;new Ee;var Q0=new _,Y0=new _,Z0=[new _(1,0,0),new _(0,1,0),new _(0,0,1)],J0=new _;var $0=new _,K0=new _,ew=new _;var tw=new _,iw=new _,nw=new _,rw=new _;var ow=new _,sw=new _,aw=new _;var ra=class extends V{constructor(e){if(super({type:V.types.SPHERE}),this.radius=void 0,this.radius=e!==void 0?e:1,this.radius<0)throw new Error("The sphere radius cannot be negative.");this.updateBoundingSphereRadius()}calculateLocalInertia(e,t=new _){let i=2*e*this.radius*this.radius/5;return t.x=i,t.y=i,t.z=i,t}volume(){return 4*Math.PI*Math.pow(this.radius,3)/3}updateBoundingSphereRadius(){this.boundingSphereRadius=this.radius}calculateWorldAABB(e,t,i,n){let r=this.radius,o=["x","y","z"];for(let s=0;s<o.length;s++){let c=o[s];i[c]=e[c]-r,n[c]=e[c]+r}}};var lw=new _,cw=new _;var dw=new _,hw=new _,uw=new _,pw=new _,fw=new _,mw=new _,gw=new _;var bw=new _;var vw=new _,yw=new _,Ew=new _,ww=new _,_w=new _,xw=new _,Tw=new _,Rw=new _,Cw=new _;var Sw=new _,Pw=new $e;var Ow=new _,Aw=new $e,kw=new _,Iw=new _,Mw=new _,Lw=new _,Dw=new _,Hw=new _,jw=new _,Bw=new $e,Fw=new _,Nw=new te,zw=new $e,ql=class{constructor(){this.equations=void 0,this.equations=[]}solve(e,t){return 0}addEquation(e){e.enabled&&!e.bi.isTrigger&&!e.bj.isTrigger&&this.equations.push(e)}removeEquation(e){let t=this.equations,i=t.indexOf(e);i!==-1&&t.splice(i,1)}removeAllEquations(){this.equations.length=0}},Xl=class extends ql{constructor(){super(),this.iterations=void 0,this.tolerance=void 0,this.iterations=10,this.tolerance=1e-7}solve(e,t){let i=0,n=this.iterations,r=this.tolerance*this.tolerance,o=this.equations,s=o.length,c=t.bodies,d=c.length,a=e,h,u,f,E,b,y;if(s!==0)for(let v=0;v!==d;v++)c[v].updateSolveMassProperties();let g=pg,p=fg,m=ug;g.length=s,p.length=s,m.length=s;for(let v=0;v!==s;v++){let w=o[v];m[v]=0,p[v]=w.computeB(a),g[v]=1/w.computeC()}if(s!==0){for(let x=0;x!==d;x++){let T=c[x],R=T.vlambda,C=T.wlambda;R.set(0,0,0),C.set(0,0,0)}for(i=0;i!==n;i++){E=0;for(let x=0;x!==s;x++){let T=o[x];h=p[x],u=g[x],y=m[x],b=T.computeGWlambda(),f=u*(h-b-T.eps*y),y+f<T.minForce?f=T.minForce-y:y+f>T.maxForce&&(f=T.maxForce-y),m[x]+=f,E+=f>0?f:-f,T.addToWlambda(f)}if(E*E<r)break}for(let x=0;x!==d;x++){let T=c[x],R=T.velocity,C=T.angularVelocity;T.vlambda.vmul(T.linearFactor,T.vlambda),R.vadd(T.vlambda,R),T.wlambda.vmul(T.angularFactor,T.wlambda),C.vadd(T.wlambda,C)}let v=o.length,w=1/a;for(;v--;)o[v].multiplier=m[v]*w}return i}},ug=[],pg=[],fg=[];var Gw=G.STATIC;var Ql=class{constructor(){this.objects=[],this.type=Object}release(...e){let t=e.length;for(let i=0;i!==t;i++)this.objects.push(e[i]);return this}get(){return this.objects.length===0?this.constructObject():this.objects.pop()}constructObject(){throw new Error("constructObject() not implemented in this Pool subclass yet!")}resize(e){let t=this.objects;for(;t.length>e;)t.pop();for(;t.length<e;)t.push(this.constructObject());return this}},Yl=class extends Ql{constructor(...e){super(...e),this.type=_}constructObject(){return new _}},cu,du,hu,uu,pu,fu,mu,gu,bu,vu,yu,Eu,wu,_u,xu,Tu,Ru,Cu,Su,Pu,Ou,Au,ku,Iu,Mu,de={sphereSphere:V.types.SPHERE,spherePlane:V.types.SPHERE|V.types.PLANE,boxBox:V.types.BOX|V.types.BOX,sphereBox:V.types.SPHERE|V.types.BOX,planeBox:V.types.PLANE|V.types.BOX,convexConvex:V.types.CONVEXPOLYHEDRON,sphereConvex:V.types.SPHERE|V.types.CONVEXPOLYHEDRON,planeConvex:V.types.PLANE|V.types.CONVEXPOLYHEDRON,boxConvex:V.types.BOX|V.types.CONVEXPOLYHEDRON,sphereHeightfield:V.types.SPHERE|V.types.HEIGHTFIELD,boxHeightfield:V.types.BOX|V.types.HEIGHTFIELD,convexHeightfield:V.types.CONVEXPOLYHEDRON|V.types.HEIGHTFIELD,sphereParticle:V.types.PARTICLE|V.types.SPHERE,planeParticle:V.types.PLANE|V.types.PARTICLE,boxParticle:V.types.BOX|V.types.PARTICLE,convexParticle:V.types.PARTICLE|V.types.CONVEXPOLYHEDRON,cylinderCylinder:V.types.CYLINDER,sphereCylinder:V.types.SPHERE|V.types.CYLINDER,planeCylinder:V.types.PLANE|V.types.CYLINDER,boxCylinder:V.types.BOX|V.types.CYLINDER,convexCylinder:V.types.CONVEXPOLYHEDRON|V.types.CYLINDER,heightfieldCylinder:V.types.HEIGHTFIELD|V.types.CYLINDER,particleCylinder:V.types.PARTICLE|V.types.CYLINDER,sphereTrimesh:V.types.SPHERE|V.types.TRIMESH,planeTrimesh:V.types.PLANE|V.types.TRIMESH};cu=de.sphereSphere;du=de.spherePlane;hu=de.boxBox;uu=de.sphereBox;pu=de.planeBox;fu=de.convexConvex;mu=de.sphereConvex;gu=de.planeConvex;bu=de.boxConvex;vu=de.sphereHeightfield;yu=de.boxHeightfield;Eu=de.convexHeightfield;wu=de.sphereParticle;_u=de.planeParticle;xu=de.boxParticle;Tu=de.convexParticle;Ru=de.cylinderCylinder;Cu=de.sphereCylinder;Su=de.planeCylinder;Pu=de.boxCylinder;Ou=de.convexCylinder;Au=de.heightfieldCylinder;ku=de.particleCylinder;Iu=de.sphereTrimesh;Mu=de.planeTrimesh;var Zl=class{get[cu](){return this.sphereSphere}get[du](){return this.spherePlane}get[hu](){return this.boxBox}get[uu](){return this.sphereBox}get[pu](){return this.planeBox}get[fu](){return this.convexConvex}get[mu](){return this.sphereConvex}get[gu](){return this.planeConvex}get[bu](){return this.boxConvex}get[vu](){return this.sphereHeightfield}get[yu](){return this.boxHeightfield}get[Eu](){return this.convexHeightfield}get[wu](){return this.sphereParticle}get[_u](){return this.planeParticle}get[xu](){return this.boxParticle}get[Tu](){return this.convexParticle}get[Ru](){return this.convexConvex}get[Cu](){return this.sphereConvex}get[Su](){return this.planeConvex}get[Pu](){return this.boxConvex}get[Ou](){return this.convexConvex}get[Au](){return this.heightfieldCylinder}get[ku](){return this.particleCylinder}get[Iu](){return this.sphereTrimesh}get[Mu](){return this.planeTrimesh}constructor(e){this.contactPointPool=void 0,this.frictionEquationPool=void 0,this.result=void 0,this.frictionResult=void 0,this.v3pool=void 0,this.world=void 0,this.currentContactMaterial=void 0,this.enableFrictionReduction=void 0,this.contactPointPool=[],this.frictionEquationPool=[],this.result=[],this.frictionResult=[],this.v3pool=new Yl,this.world=e,this.currentContactMaterial=e.defaultContactMaterial,this.enableFrictionReduction=!1}createContactEquation(e,t,i,n,r,o){let s;this.contactPointPool.length?(s=this.contactPointPool.pop(),s.bi=e,s.bj=t):s=new Ul(e,t),s.enabled=e.collisionResponse&&t.collisionResponse&&i.collisionResponse&&n.collisionResponse;let c=this.currentContactMaterial;s.restitution=c.restitution,s.setSpookParams(c.contactEquationStiffness,c.contactEquationRelaxation,this.world.dt);let d=i.material||e.material,a=n.material||t.material;return d&&a&&d.restitution>=0&&a.restitution>=0&&(s.restitution=d.restitution*a.restitution),s.si=r||i,s.sj=o||n,s}createFrictionEquationsFromContact(e,t){let i=e.bi,n=e.bj,r=e.si,o=e.sj,s=this.world,c=this.currentContactMaterial,d=c.friction,a=r.material||i.material,h=o.material||n.material;if(a&&h&&a.friction>=0&&h.friction>=0&&(d=a.friction*h.friction),d>0){let u=d*s.gravity.length(),f=i.invMass+n.invMass;f>0&&(f=1/f);let E=this.frictionEquationPool,b=E.length?E.pop():new ia(i,n,u*f),y=E.length?E.pop():new ia(i,n,u*f);return b.bi=y.bi=i,b.bj=y.bj=n,b.minForce=y.minForce=-u*f,b.maxForce=y.maxForce=u*f,b.ri.copy(e.ri),b.rj.copy(e.rj),y.ri.copy(e.ri),y.rj.copy(e.rj),e.ni.tangents(b.t,y.t),b.setSpookParams(c.frictionEquationStiffness,c.frictionEquationRelaxation,s.dt),y.setSpookParams(c.frictionEquationStiffness,c.frictionEquationRelaxation,s.dt),b.enabled=y.enabled=e.enabled,t.push(b,y),!0}return!1}createFrictionFromAverage(e){let t=this.result[this.result.length-1];if(!this.createFrictionEquationsFromContact(t,this.frictionResult)||e===1)return;let i=this.frictionResult[this.frictionResult.length-2],n=this.frictionResult[this.frictionResult.length-1];Qn.setZero(),Ir.setZero(),Mr.setZero();let r=t.bi;t.bj;for(let s=0;s!==e;s++)t=this.result[this.result.length-1-s],t.bi!==r?(Qn.vadd(t.ni,Qn),Ir.vadd(t.ri,Ir),Mr.vadd(t.rj,Mr)):(Qn.vsub(t.ni,Qn),Ir.vadd(t.rj,Ir),Mr.vadd(t.ri,Mr));let o=1/e;Ir.scale(o,i.ri),Mr.scale(o,i.rj),n.ri.copy(i.ri),n.rj.copy(i.rj),Qn.normalize(),Qn.tangents(i.t,n.t)}getContacts(e,t,i,n,r,o,s){this.contactPointPool=r,this.frictionEquationPool=s,this.result=n,this.frictionResult=o;let c=bg,d=vg,a=mg,h=gg;for(let u=0,f=e.length;u!==f;u++){let E=e[u],b=t[u],y=null;E.material&&b.material&&(y=i.getContactMaterial(E.material,b.material)||null);let g=E.type&G.KINEMATIC&&b.type&G.STATIC||E.type&G.STATIC&&b.type&G.KINEMATIC||E.type&G.KINEMATIC&&b.type&G.KINEMATIC;for(let p=0;p<E.shapes.length;p++){E.quaternion.mult(E.shapeOrientations[p],c),E.quaternion.vmult(E.shapeOffsets[p],a),a.vadd(E.position,a);let m=E.shapes[p];for(let v=0;v<b.shapes.length;v++){b.quaternion.mult(b.shapeOrientations[v],d),b.quaternion.vmult(b.shapeOffsets[v],h),h.vadd(b.position,h);let w=b.shapes[v];if(!(m.collisionFilterMask&w.collisionFilterGroup&&w.collisionFilterMask&m.collisionFilterGroup)||a.distanceTo(h)>m.boundingSphereRadius+w.boundingSphereRadius)continue;let x=null;m.material&&w.material&&(x=i.getContactMaterial(m.material,w.material)||null),this.currentContactMaterial=x||y||i.defaultContactMaterial;let T=m.type|w.type,R=this[T];if(R){let C=!1;m.type<w.type?C=R.call(this,m,w,a,h,c,d,E,b,m,w,g):C=R.call(this,w,m,h,a,d,c,b,E,m,w,g),C&&g&&(i.shapeOverlapKeeper.set(m.id,w.id),i.bodyOverlapKeeper.set(E.id,b.id))}}}}}sphereSphere(e,t,i,n,r,o,s,c,d,a,h){if(h)return i.distanceSquared(n)<(e.radius+t.radius)**2;let u=this.createContactEquation(s,c,e,t,d,a);n.vsub(i,u.ni),u.ni.normalize(),u.ri.copy(u.ni),u.rj.copy(u.ni),u.ri.scale(e.radius,u.ri),u.rj.scale(-t.radius,u.rj),u.ri.vadd(i,u.ri),u.ri.vsub(s.position,u.ri),u.rj.vadd(n,u.rj),u.rj.vsub(c.position,u.rj),this.result.push(u),this.createFrictionEquationsFromContact(u,this.frictionResult)}spherePlane(e,t,i,n,r,o,s,c,d,a,h){let u=this.createContactEquation(s,c,e,t,d,a);if(u.ni.set(0,0,1),o.vmult(u.ni,u.ni),u.ni.negate(u.ni),u.ni.normalize(),u.ni.scale(e.radius,u.ri),i.vsub(n,Zs),u.ni.scale(u.ni.dot(Zs),$h),Zs.vsub($h,u.rj),-Zs.dot(u.ni)<=e.radius){if(h)return!0;let f=u.ri,E=u.rj;f.vadd(i,f),f.vsub(s.position,f),E.vadd(n,E),E.vsub(c.position,E),this.result.push(u),this.createFrictionEquationsFromContact(u,this.frictionResult)}}boxBox(e,t,i,n,r,o,s,c,d,a,h){return e.convexPolyhedronRepresentation.material=e.material,t.convexPolyhedronRepresentation.material=t.material,e.convexPolyhedronRepresentation.collisionResponse=e.collisionResponse,t.convexPolyhedronRepresentation.collisionResponse=t.collisionResponse,this.convexConvex(e.convexPolyhedronRepresentation,t.convexPolyhedronRepresentation,i,n,r,o,s,c,e,t,h)}sphereBox(e,t,i,n,r,o,s,c,d,a,h){let u=this.v3pool,f=Wg;i.vsub(n,Js),t.getSideNormals(f,o);let E=e.radius,b=!1,y=qg,g=Xg,p=Qg,m=null,v=0,w=0,x=0,T=null;for(let F=0,U=f.length;F!==U&&b===!1;F++){let J=zg;J.copy(f[F]);let W=J.length();J.normalize();let ze=Js.dot(J);if(ze<W+E&&ze>0){let ge=Gg,X=Vg;ge.copy(f[(F+1)%3]),X.copy(f[(F+2)%3]);let qe=ge.length(),cn=X.length();ge.normalize(),X.normalize();let Vn=Js.dot(ge),Oi=Js.dot(X);if(Vn<qe&&Vn>-qe&&Oi<cn&&Oi>-cn){let Pt=Math.abs(ze-W-E);if((T===null||Pt<T)&&(T=Pt,w=Vn,x=Oi,m=W,y.copy(J),g.copy(ge),p.copy(X),v++,h))return!0}}}if(v){b=!0;let F=this.createContactEquation(s,c,e,t,d,a);y.scale(-E,F.ri),F.ni.copy(y),F.ni.negate(F.ni),y.scale(m,y),g.scale(w,g),y.vadd(g,y),p.scale(x,p),y.vadd(p,F.rj),F.ri.vadd(i,F.ri),F.ri.vsub(s.position,F.ri),F.rj.vadd(n,F.rj),F.rj.vsub(c.position,F.rj),this.result.push(F),this.createFrictionEquationsFromContact(F,this.frictionResult)}let R=u.get(),C=Ug;for(let F=0;F!==2&&!b;F++)for(let U=0;U!==2&&!b;U++)for(let J=0;J!==2&&!b;J++)if(R.set(0,0,0),F?R.vadd(f[0],R):R.vsub(f[0],R),U?R.vadd(f[1],R):R.vsub(f[1],R),J?R.vadd(f[2],R):R.vsub(f[2],R),n.vadd(R,C),C.vsub(i,C),C.lengthSquared()<E*E){if(h)return!0;b=!0;let W=this.createContactEquation(s,c,e,t,d,a);W.ri.copy(C),W.ri.normalize(),W.ni.copy(W.ri),W.ri.scale(E,W.ri),W.rj.copy(R),W.ri.vadd(i,W.ri),W.ri.vsub(s.position,W.ri),W.rj.vadd(n,W.rj),W.rj.vsub(c.position,W.rj),this.result.push(W),this.createFrictionEquationsFromContact(W,this.frictionResult)}u.release(R),R=null;let P=u.get(),S=u.get(),L=u.get(),I=u.get(),j=u.get(),H=f.length;for(let F=0;F!==H&&!b;F++)for(let U=0;U!==H&&!b;U++)if(F%3!==U%3){f[U].cross(f[F],P),P.normalize(),f[F].vadd(f[U],S),L.copy(i),L.vsub(S,L),L.vsub(n,L);let J=L.dot(P);P.scale(J,I);let W=0;for(;W===F%3||W===U%3;)W++;j.copy(i),j.vsub(I,j),j.vsub(S,j),j.vsub(n,j);let ze=Math.abs(J),ge=j.length();if(ze<f[W].length()&&ge<E){if(h)return!0;b=!0;let X=this.createContactEquation(s,c,e,t,d,a);S.vadd(I,X.rj),X.rj.copy(X.rj),j.negate(X.ni),X.ni.normalize(),X.ri.copy(X.rj),X.ri.vadd(n,X.ri),X.ri.vsub(i,X.ri),X.ri.normalize(),X.ri.scale(E,X.ri),X.ri.vadd(i,X.ri),X.ri.vsub(s.position,X.ri),X.rj.vadd(n,X.rj),X.rj.vsub(c.position,X.rj),this.result.push(X),this.createFrictionEquationsFromContact(X,this.frictionResult)}}u.release(P,S,L,I,j)}planeBox(e,t,i,n,r,o,s,c,d,a,h){return t.convexPolyhedronRepresentation.material=t.material,t.convexPolyhedronRepresentation.collisionResponse=t.collisionResponse,t.convexPolyhedronRepresentation.id=t.id,this.planeConvex(e,t.convexPolyhedronRepresentation,i,n,r,o,s,c,e,t,h)}convexConvex(e,t,i,n,r,o,s,c,d,a,h,u,f){let E=cb;if(!(i.distanceTo(n)>e.boundingSphereRadius+t.boundingSphereRadius)&&e.findSeparatingAxis(t,i,r,n,o,E,u,f)){let b=[],y=db;e.clipAgainstHull(i,r,t,n,o,E,-100,100,b);let g=0;for(let p=0;p!==b.length;p++){if(h)return!0;let m=this.createContactEquation(s,c,e,t,d,a),v=m.ri,w=m.rj;E.negate(m.ni),b[p].normal.negate(y),y.scale(b[p].depth,y),b[p].point.vadd(y,v),w.copy(b[p].point),v.vsub(i,v),w.vsub(n,w),v.vadd(i,v),v.vsub(s.position,v),w.vadd(n,w),w.vsub(c.position,w),this.result.push(m),g++,this.enableFrictionReduction||this.createFrictionEquationsFromContact(m,this.frictionResult)}this.enableFrictionReduction&&g&&this.createFrictionFromAverage(g)}}sphereConvex(e,t,i,n,r,o,s,c,d,a,h){let u=this.v3pool;i.vsub(n,Yg);let f=t.faceNormals,E=t.faces,b=t.vertices,y=e.radius,g=!1;for(let p=0;p!==b.length;p++){let m=b[p],v=Kg;o.vmult(m,v),n.vadd(v,v);let w=$g;if(v.vsub(i,w),w.lengthSquared()<y*y){if(h)return!0;g=!0;let x=this.createContactEquation(s,c,e,t,d,a);x.ri.copy(w),x.ri.normalize(),x.ni.copy(x.ri),x.ri.scale(y,x.ri),v.vsub(n,x.rj),x.ri.vadd(i,x.ri),x.ri.vsub(s.position,x.ri),x.rj.vadd(n,x.rj),x.rj.vsub(c.position,x.rj),this.result.push(x),this.createFrictionEquationsFromContact(x,this.frictionResult);return}}for(let p=0,m=E.length;p!==m&&g===!1;p++){let v=f[p],w=E[p],x=eb;o.vmult(v,x);let T=tb;o.vmult(b[w[0]],T),T.vadd(n,T);let R=ib;x.scale(-y,R),i.vadd(R,R);let C=nb;R.vsub(T,C);let P=C.dot(x),S=rb;if(i.vsub(T,S),P<0&&S.dot(x)>0){let L=[];for(let I=0,j=w.length;I!==j;I++){let H=u.get();o.vmult(b[w[I]],H),n.vadd(H,H),L.push(H)}if(Ng(L,x,i)){if(h)return!0;g=!0;let I=this.createContactEquation(s,c,e,t,d,a);x.scale(-y,I.ri),x.negate(I.ni);let j=u.get();x.scale(-P,j);let H=u.get();x.scale(-y,H),i.vsub(n,I.rj),I.rj.vadd(H,I.rj),I.rj.vadd(j,I.rj),I.rj.vadd(n,I.rj),I.rj.vsub(c.position,I.rj),I.ri.vadd(i,I.ri),I.ri.vsub(s.position,I.ri),u.release(j),u.release(H),this.result.push(I),this.createFrictionEquationsFromContact(I,this.frictionResult);for(let F=0,U=L.length;F!==U;F++)u.release(L[F]);return}else for(let I=0;I!==w.length;I++){let j=u.get(),H=u.get();o.vmult(b[w[(I+1)%w.length]],j),o.vmult(b[w[(I+2)%w.length]],H),n.vadd(j,j),n.vadd(H,H);let F=Zg;H.vsub(j,F);let U=Jg;F.unit(U);let J=u.get(),W=u.get();i.vsub(j,W);let ze=W.dot(U);U.scale(ze,J),J.vadd(j,J);let ge=u.get();if(J.vsub(i,ge),ze>0&&ze*ze<F.lengthSquared()&&ge.lengthSquared()<y*y){if(h)return!0;let X=this.createContactEquation(s,c,e,t,d,a);J.vsub(n,X.rj),J.vsub(i,X.ni),X.ni.normalize(),X.ni.scale(y,X.ri),X.rj.vadd(n,X.rj),X.rj.vsub(c.position,X.rj),X.ri.vadd(i,X.ri),X.ri.vsub(s.position,X.ri),this.result.push(X),this.createFrictionEquationsFromContact(X,this.frictionResult);for(let qe=0,cn=L.length;qe!==cn;qe++)u.release(L[qe]);u.release(j),u.release(H),u.release(J),u.release(ge),u.release(W);return}u.release(j),u.release(H),u.release(J),u.release(ge),u.release(W)}for(let I=0,j=L.length;I!==j;I++)u.release(L[I])}}}planeConvex(e,t,i,n,r,o,s,c,d,a,h){let u=ob,f=sb;f.set(0,0,1),r.vmult(f,f);let E=0,b=ab;for(let y=0;y!==t.vertices.length;y++)if(u.copy(t.vertices[y]),o.vmult(u,u),n.vadd(u,u),u.vsub(i,b),f.dot(b)<=0){if(h)return!0;let p=this.createContactEquation(s,c,e,t,d,a),m=lb;f.scale(f.dot(b),m),u.vsub(m,m),m.vsub(i,p.ri),p.ni.copy(f),u.vsub(n,p.rj),p.ri.vadd(i,p.ri),p.ri.vsub(s.position,p.ri),p.rj.vadd(n,p.rj),p.rj.vsub(c.position,p.rj),this.result.push(p),E++,this.enableFrictionReduction||this.createFrictionEquationsFromContact(p,this.frictionResult)}this.enableFrictionReduction&&E&&this.createFrictionFromAverage(E)}boxConvex(e,t,i,n,r,o,s,c,d,a,h){return e.convexPolyhedronRepresentation.material=e.material,e.convexPolyhedronRepresentation.collisionResponse=e.collisionResponse,this.convexConvex(e.convexPolyhedronRepresentation,t,i,n,r,o,s,c,e,t,h)}sphereHeightfield(e,t,i,n,r,o,s,c,d,a,h){let u=t.data,f=e.radius,E=t.elementSize,b=_b,y=wb;te.pointToLocalFrame(n,o,i,y);let g=Math.floor((y.x-f)/E)-1,p=Math.ceil((y.x+f)/E)+1,m=Math.floor((y.y-f)/E)-1,v=Math.ceil((y.y+f)/E)+1;if(p<0||v<0||g>u.length||m>u[0].length)return;g<0&&(g=0),p<0&&(p=0),m<0&&(m=0),v<0&&(v=0),g>=u.length&&(g=u.length-1),p>=u.length&&(p=u.length-1),v>=u[0].length&&(v=u[0].length-1),m>=u[0].length&&(m=u[0].length-1);let w=[];t.getRectMinMax(g,m,p,v,w);let x=w[0],T=w[1];if(y.z-f>T||y.z+f<x)return;let R=this.result;for(let C=g;C<p;C++)for(let P=m;P<v;P++){let S=R.length,L=!1;if(t.getConvexTrianglePillar(C,P,!1),te.pointToWorldFrame(n,o,t.pillarOffset,b),i.distanceTo(b)<t.pillarConvex.boundingSphereRadius+e.boundingSphereRadius&&(L=this.sphereConvex(e,t.pillarConvex,i,b,r,o,s,c,e,t,h)),h&&L||(t.getConvexTrianglePillar(C,P,!0),te.pointToWorldFrame(n,o,t.pillarOffset,b),i.distanceTo(b)<t.pillarConvex.boundingSphereRadius+e.boundingSphereRadius&&(L=this.sphereConvex(e,t.pillarConvex,i,b,r,o,s,c,e,t,h)),h&&L))return!0;if(R.length-S>2)return}}boxHeightfield(e,t,i,n,r,o,s,c,d,a,h){return e.convexPolyhedronRepresentation.material=e.material,e.convexPolyhedronRepresentation.collisionResponse=e.collisionResponse,this.convexHeightfield(e.convexPolyhedronRepresentation,t,i,n,r,o,s,c,e,t,h)}convexHeightfield(e,t,i,n,r,o,s,c,d,a,h){let u=t.data,f=t.elementSize,E=e.boundingSphereRadius,b=yb,y=Eb,g=vb;te.pointToLocalFrame(n,o,i,g);let p=Math.floor((g.x-E)/f)-1,m=Math.ceil((g.x+E)/f)+1,v=Math.floor((g.y-E)/f)-1,w=Math.ceil((g.y+E)/f)+1;if(m<0||w<0||p>u.length||v>u[0].length)return;p<0&&(p=0),m<0&&(m=0),v<0&&(v=0),w<0&&(w=0),p>=u.length&&(p=u.length-1),m>=u.length&&(m=u.length-1),w>=u[0].length&&(w=u[0].length-1),v>=u[0].length&&(v=u[0].length-1);let x=[];t.getRectMinMax(p,v,m,w,x);let T=x[0],R=x[1];if(!(g.z-E>R||g.z+E<T))for(let C=p;C<m;C++)for(let P=v;P<w;P++){let S=!1;if(t.getConvexTrianglePillar(C,P,!1),te.pointToWorldFrame(n,o,t.pillarOffset,b),i.distanceTo(b)<t.pillarConvex.boundingSphereRadius+e.boundingSphereRadius&&(S=this.convexConvex(e,t.pillarConvex,i,b,r,o,s,c,null,null,h,y,null)),h&&S||(t.getConvexTrianglePillar(C,P,!0),te.pointToWorldFrame(n,o,t.pillarOffset,b),i.distanceTo(b)<t.pillarConvex.boundingSphereRadius+e.boundingSphereRadius&&(S=this.convexConvex(e,t.pillarConvex,i,b,r,o,s,c,null,null,h,y,null)),h&&S))return!0}}sphereParticle(e,t,i,n,r,o,s,c,d,a,h){let u=fb;if(u.set(0,0,1),n.vsub(i,u),u.lengthSquared()<=e.radius*e.radius){if(h)return!0;let E=this.createContactEquation(c,s,t,e,d,a);u.normalize(),E.rj.copy(u),E.rj.scale(e.radius,E.rj),E.ni.copy(u),E.ni.negate(E.ni),E.ri.set(0,0,0),this.result.push(E),this.createFrictionEquationsFromContact(E,this.frictionResult)}}planeParticle(e,t,i,n,r,o,s,c,d,a,h){let u=hb;u.set(0,0,1),s.quaternion.vmult(u,u);let f=ub;if(n.vsub(s.position,f),u.dot(f)<=0){if(h)return!0;let b=this.createContactEquation(c,s,t,e,d,a);b.ni.copy(u),b.ni.negate(b.ni),b.ri.set(0,0,0);let y=pb;u.scale(u.dot(n),y),n.vsub(y,y),b.rj.copy(y),this.result.push(b),this.createFrictionEquationsFromContact(b,this.frictionResult)}}boxParticle(e,t,i,n,r,o,s,c,d,a,h){return e.convexPolyhedronRepresentation.material=e.material,e.convexPolyhedronRepresentation.collisionResponse=e.collisionResponse,this.convexParticle(e.convexPolyhedronRepresentation,t,i,n,r,o,s,c,e,t,h)}convexParticle(e,t,i,n,r,o,s,c,d,a,h){let u=-1,f=gb,E=bb,b=null,y=mb;if(y.copy(n),y.vsub(i,y),r.conjugate(Kh),Kh.vmult(y,y),e.pointIsInside(y)){e.worldVerticesNeedsUpdate&&e.computeWorldVertices(i,r),e.worldFaceNormalsNeedsUpdate&&e.computeWorldFaceNormals(r);for(let g=0,p=e.faces.length;g!==p;g++){let m=[e.worldVertices[e.faces[g][0]]],v=e.worldFaceNormals[g];n.vsub(m[0],eu);let w=-v.dot(eu);if(b===null||Math.abs(w)<Math.abs(b)){if(h)return!0;b=w,u=g,f.copy(v)}}if(u!==-1){let g=this.createContactEquation(c,s,t,e,d,a);f.scale(b,E),E.vadd(n,E),E.vsub(i,E),g.rj.copy(E),f.negate(g.ni),g.ri.set(0,0,0);let p=g.ri,m=g.rj;p.vadd(n,p),p.vsub(c.position,p),m.vadd(i,m),m.vsub(s.position,m),this.result.push(g),this.createFrictionEquationsFromContact(g,this.frictionResult)}else console.warn("Point found inside convex, but did not find penetrating face!")}}heightfieldCylinder(e,t,i,n,r,o,s,c,d,a,h){return this.convexHeightfield(t,e,n,i,o,r,c,s,d,a,h)}particleCylinder(e,t,i,n,r,o,s,c,d,a,h){return this.convexParticle(t,e,n,i,o,r,c,s,d,a,h)}sphereTrimesh(e,t,i,n,r,o,s,c,d,a,h){let u=Cg,f=Sg,E=Pg,b=Og,y=Ag,g=kg,p=Dg,m=Rg,v=xg,w=Hg;te.pointToLocalFrame(n,o,i,y);let x=e.radius;p.lowerBound.set(y.x-x,y.y-x,y.z-x),p.upperBound.set(y.x+x,y.y+x,y.z+x),t.getTrianglesInAABB(p,w);let T=Tg,R=e.radius*e.radius;for(let I=0;I<w.length;I++)for(let j=0;j<3;j++)if(t.getVertex(t.indices[w[I]*3+j],T),T.vsub(y,v),v.lengthSquared()<=R){if(m.copy(T),te.pointToWorldFrame(n,o,m,T),T.vsub(i,v),h)return!0;let H=this.createContactEquation(s,c,e,t,d,a);H.ni.copy(v),H.ni.normalize(),H.ri.copy(H.ni),H.ri.scale(e.radius,H.ri),H.ri.vadd(i,H.ri),H.ri.vsub(s.position,H.ri),H.rj.copy(T),H.rj.vsub(c.position,H.rj),this.result.push(H),this.createFrictionEquationsFromContact(H,this.frictionResult)}for(let I=0;I<w.length;I++)for(let j=0;j<3;j++){t.getVertex(t.indices[w[I]*3+j],u),t.getVertex(t.indices[w[I]*3+(j+1)%3],f),f.vsub(u,E),y.vsub(f,g);let H=g.dot(E);y.vsub(u,g);let F=g.dot(E);if(F>0&&H<0&&(y.vsub(u,g),b.copy(E),b.normalize(),F=g.dot(b),b.scale(F,g),g.vadd(u,g),g.distanceTo(y)<e.radius)){if(h)return!0;let J=this.createContactEquation(s,c,e,t,d,a);g.vsub(y,J.ni),J.ni.normalize(),J.ni.scale(e.radius,J.ri),J.ri.vadd(i,J.ri),J.ri.vsub(s.position,J.ri),te.pointToWorldFrame(n,o,g,g),g.vsub(c.position,J.rj),te.vectorToWorldFrame(o,J.ni,J.ni),te.vectorToWorldFrame(o,J.ri,J.ri),this.result.push(J),this.createFrictionEquationsFromContact(J,this.frictionResult)}}let C=Ig,P=Mg,S=Lg,L=_g;for(let I=0,j=w.length;I!==j;I++){t.getTriangleVertices(w[I],C,P,S),t.getNormal(w[I],L),y.vsub(C,g);let H=g.dot(L);if(L.scale(H,g),y.vsub(g,g),H=g.distanceTo(y),Ee.pointInTriangle(g,C,P,S)&&H<e.radius){if(h)return!0;let F=this.createContactEquation(s,c,e,t,d,a);g.vsub(y,F.ni),F.ni.normalize(),F.ni.scale(e.radius,F.ri),F.ri.vadd(i,F.ri),F.ri.vsub(s.position,F.ri),te.pointToWorldFrame(n,o,g,g),g.vsub(c.position,F.rj),te.vectorToWorldFrame(o,F.ni,F.ni),te.vectorToWorldFrame(o,F.ri,F.ri),this.result.push(F),this.createFrictionEquationsFromContact(F,this.frictionResult)}}w.length=0}planeTrimesh(e,t,i,n,r,o,s,c,d,a,h){let u=new _,f=yg;f.set(0,0,1),r.vmult(f,f);for(let E=0;E<t.vertices.length/3;E++){t.getVertex(E,u);let b=new _;b.copy(u),te.pointToWorldFrame(n,o,b,u);let y=Eg;if(u.vsub(i,y),f.dot(y)<=0){if(h)return!0;let p=this.createContactEquation(s,c,e,t,d,a);p.ni.copy(f);let m=wg;f.scale(y.dot(f),m),u.vsub(m,m),p.ri.copy(m),p.ri.vsub(s.position,p.ri),p.rj.copy(u),p.rj.vsub(c.position,p.rj),this.result.push(p),this.createFrictionEquationsFromContact(p,this.frictionResult)}}}},Qn=new _,Ir=new _,Mr=new _,mg=new _,gg=new _,bg=new le,vg=new le,yg=new _,Eg=new _,wg=new _,_g=new _,xg=new _,Tg=new _,Rg=new _,Cg=new _,Sg=new _,Pg=new _,Og=new _,Ag=new _,kg=new _,Ig=new _,Mg=new _,Lg=new _,Dg=new $e,Hg=[],Zs=new _,$h=new _,jg=new _,Bg=new _,Fg=new _;function Ng(l,e,t){let i=null,n=l.length;for(let r=0;r!==n;r++){let o=l[r],s=jg;l[(r+1)%n].vsub(o,s);let c=Bg;s.cross(e,c);let d=Fg;t.vsub(o,d);let a=c.dot(d);if(i===null||a>0&&i===!0||a<=0&&i===!1){i===null&&(i=a>0);continue}else return!1}return!0}var Js=new _,zg=new _,Gg=new _,Vg=new _,Wg=[new _,new _,new _,new _,new _,new _],Ug=new _,qg=new _,Xg=new _,Qg=new _,Yg=new _,Zg=new _,Jg=new _,$g=new _,Kg=new _,eb=new _,tb=new _,ib=new _,nb=new _,rb=new _,ob=new _,sb=new _,ab=new _,lb=new _,cb=new _,db=new _,hb=new _,ub=new _,pb=new _,fb=new _,Kh=new le,mb=new _,gb=new _,eu=new _,bb=new _,vb=new _,yb=new _,Eb=[0],wb=new _,_b=new _,oa=class{constructor(){this.current=void 0,this.previous=void 0,this.current=[],this.previous=[]}getKey(e,t){if(t<e){let i=t;t=e,e=i}return e<<16|t}set(e,t){let i=this.getKey(e,t),n=this.current,r=0;for(;i>n[r];)r++;if(i!==n[r]){for(let o=n.length-1;o>=r;o--)n[o+1]=n[o];n[r]=i}}tick(){let e=this.current;this.current=this.previous,this.previous=e,this.current.length=0}getDiff(e,t){let i=this.current,n=this.previous,r=i.length,o=n.length,s=0;for(let c=0;c<r;c++){let d=!1,a=i[c];for(;a>n[s];)s++;d=a===n[s],d||tu(e,a)}s=0;for(let c=0;c<o;c++){let d=!1,a=n[c];for(;a>i[s];)s++;d=i[s]===a,d||tu(t,a)}}};function tu(l,e){l.push((e&4294901760)>>16,e&65535)}var Jl=class{constructor(){this.data={keys:[]}}get(e,t){if(e>t){let i=t;t=e,e=i}return this.data[e+"-"+t]}set(e,t,i){if(e>t){let r=t;t=e,e=r}let n=e+"-"+t;this.get(e,t)||this.data.keys.push(n),this.data[n]=i}reset(){let e=this.data,t=e.keys;for(;t.length>0;){let i=t.pop();delete e[i]}}},sa=class extends Ks{constructor(e={}){super(),this.dt=void 0,this.allowSleep=void 0,this.contacts=void 0,this.frictionEquations=void 0,this.quatNormalizeSkip=void 0,this.quatNormalizeFast=void 0,this.time=void 0,this.stepnumber=void 0,this.default_dt=void 0,this.nextId=void 0,this.gravity=void 0,this.broadphase=void 0,this.bodies=void 0,this.hasActiveBodies=void 0,this.solver=void 0,this.constraints=void 0,this.narrowphase=void 0,this.collisionMatrix=void 0,this.collisionMatrixPrevious=void 0,this.bodyOverlapKeeper=void 0,this.shapeOverlapKeeper=void 0,this.materials=void 0,this.contactmaterials=void 0,this.contactMaterialTable=void 0,this.defaultMaterial=void 0,this.defaultContactMaterial=void 0,this.doProfiling=void 0,this.profile=void 0,this.accumulator=void 0,this.subsystems=void 0,this.addBodyEvent=void 0,this.removeBodyEvent=void 0,this.idToBodyMap=void 0,this.dt=-1,this.allowSleep=!!e.allowSleep,this.contacts=[],this.frictionEquations=[],this.quatNormalizeSkip=e.quatNormalizeSkip!==void 0?e.quatNormalizeSkip:0,this.quatNormalizeFast=e.quatNormalizeFast!==void 0?e.quatNormalizeFast:!1,this.time=0,this.stepnumber=0,this.default_dt=1/60,this.nextId=0,this.gravity=new _,e.gravity&&this.gravity.copy(e.gravity),this.broadphase=e.broadphase!==void 0?e.broadphase:new Wl,this.bodies=[],this.hasActiveBodies=!1,this.solver=e.solver!==void 0?e.solver:new Xl,this.constraints=[],this.narrowphase=new Zl(this),this.collisionMatrix=new $s,this.collisionMatrixPrevious=new $s,this.bodyOverlapKeeper=new oa,this.shapeOverlapKeeper=new oa,this.materials=[],this.contactmaterials=[],this.contactMaterialTable=new Jl,this.defaultMaterial=new Dr("default"),this.defaultContactMaterial=new Lr(this.defaultMaterial,this.defaultMaterial,{friction:.3,restitution:0}),this.doProfiling=!1,this.profile={solve:0,makeContactConstraints:0,broadphase:0,integrate:0,narrowphase:0},this.accumulator=0,this.subsystems=[],this.addBodyEvent={type:"addBody",body:null},this.removeBodyEvent={type:"removeBody",body:null},this.idToBodyMap={},this.broadphase.setWorld(this)}getContactMaterial(e,t){return this.contactMaterialTable.get(e.id,t.id)}numObjects(){return this.bodies.length}collisionMatrixTick(){let e=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=e,this.collisionMatrix.reset(),this.bodyOverlapKeeper.tick(),this.shapeOverlapKeeper.tick()}addConstraint(e){this.constraints.push(e)}removeConstraint(e){let t=this.constraints.indexOf(e);t!==-1&&this.constraints.splice(t,1)}rayTest(e,t,i){i instanceof is?this.raycastClosest(e,t,{skipBackfaces:!0},i):this.raycastAll(e,t,{skipBackfaces:!0},i)}raycastAll(e,t,i={},n){return i.mode=Ee.ALL,i.from=e,i.to=t,i.callback=n,Gl.intersectWorld(this,i)}raycastAny(e,t,i={},n){return i.mode=Ee.ANY,i.from=e,i.to=t,i.result=n,Gl.intersectWorld(this,i)}raycastClosest(e,t,i={},n){return i.mode=Ee.CLOSEST,i.from=e,i.to=t,i.result=n,Gl.intersectWorld(this,i)}addBody(e){this.bodies.includes(e)||(e.index=this.bodies.length,this.bodies.push(e),e.world=this,e.initPosition.copy(e.position),e.initVelocity.copy(e.velocity),e.timeLastSleepy=this.time,e instanceof G&&(e.initAngularVelocity.copy(e.angularVelocity),e.initQuaternion.copy(e.quaternion)),this.collisionMatrix.setNumObjects(this.bodies.length),this.addBodyEvent.body=e,this.idToBodyMap[e.id]=e,this.dispatchEvent(this.addBodyEvent))}removeBody(e){e.world=null;let t=this.bodies.length-1,i=this.bodies,n=i.indexOf(e);if(n!==-1){i.splice(n,1);for(let r=0;r!==i.length;r++)i[r].index=r;this.collisionMatrix.setNumObjects(t),this.removeBodyEvent.body=e,delete this.idToBodyMap[e.id],this.dispatchEvent(this.removeBodyEvent)}}getBodyById(e){return this.idToBodyMap[e]}getShapeById(e){let t=this.bodies;for(let i=0;i<t.length;i++){let n=t[i].shapes;for(let r=0;r<n.length;r++){let o=n[r];if(o.id===e)return o}}return null}addMaterial(e){this.materials.push(e)}addContactMaterial(e){this.contactmaterials.push(e),this.contactMaterialTable.set(e.materials[0].id,e.materials[1].id,e)}step(e,t,i=10){if(t===void 0)this.internalStep(e),this.time+=e;else{this.accumulator+=t;let n=He.now(),r=0;for(;this.accumulator>=e&&r<i&&(this.internalStep(e),this.accumulator-=e,r++,!(He.now()-n>e*1e3)););this.accumulator=this.accumulator%e;let o=this.accumulator/e;for(let s=0;s!==this.bodies.length;s++){let c=this.bodies[s];c.previousPosition.lerp(c.position,o,c.interpolatedPosition),c.previousQuaternion.slerp(c.quaternion,o,c.interpolatedQuaternion),c.previousQuaternion.normalize()}this.time+=t}}internalStep(e){this.dt=e;let t=this.contacts,i=Sb,n=Pb,r=this.numObjects(),o=this.bodies,s=this.solver,c=this.gravity,d=this.doProfiling,a=this.profile,h=G.DYNAMIC,u=-1/0,f=this.constraints,E=Cb;c.length();let b=c.x,y=c.y,g=c.z,p=0;for(d&&(u=He.now()),p=0;p!==r;p++){let I=o[p];if(I.type===h){let j=I.force,H=I.mass;j.x+=H*b,j.y+=H*y,j.z+=H*g}}for(let I=0,j=this.subsystems.length;I!==j;I++)this.subsystems[I].update();d&&(u=He.now()),i.length=0,n.length=0,this.broadphase.collisionPairs(this,i,n),d&&(a.broadphase=He.now()-u);let m=f.length;for(p=0;p!==m;p++){let I=f[p];if(!I.collideConnected)for(let j=i.length-1;j>=0;j-=1)(I.bodyA===i[j]&&I.bodyB===n[j]||I.bodyB===i[j]&&I.bodyA===n[j])&&(i.splice(j,1),n.splice(j,1))}this.collisionMatrixTick(),d&&(u=He.now());let v=Rb,w=t.length;for(p=0;p!==w;p++)v.push(t[p]);t.length=0;let x=this.frictionEquations.length;for(p=0;p!==x;p++)E.push(this.frictionEquations[p]);for(this.frictionEquations.length=0,this.narrowphase.getContacts(i,n,this,t,v,this.frictionEquations,E),d&&(a.narrowphase=He.now()-u),d&&(u=He.now()),p=0;p<this.frictionEquations.length;p++)s.addEquation(this.frictionEquations[p]);let T=t.length;for(let I=0;I!==T;I++){let j=t[I],H=j.bi,F=j.bj,U=j.si,J=j.sj,W;if(H.material&&F.material?W=this.getContactMaterial(H.material,F.material)||this.defaultContactMaterial:W=this.defaultContactMaterial,W.friction,H.material&&F.material&&(H.material.friction>=0&&F.material.friction>=0&&H.material.friction*F.material.friction,H.material.restitution>=0&&F.material.restitution>=0&&(j.restitution=H.material.restitution*F.material.restitution)),s.addEquation(j),H.allowSleep&&H.type===G.DYNAMIC&&H.sleepState===G.SLEEPING&&F.sleepState===G.AWAKE&&F.type!==G.STATIC){let ze=F.velocity.lengthSquared()+F.angularVelocity.lengthSquared(),ge=F.sleepSpeedLimit**2;ze>=ge*2&&(H.wakeUpAfterNarrowphase=!0)}if(F.allowSleep&&F.type===G.DYNAMIC&&F.sleepState===G.SLEEPING&&H.sleepState===G.AWAKE&&H.type!==G.STATIC){let ze=H.velocity.lengthSquared()+H.angularVelocity.lengthSquared(),ge=H.sleepSpeedLimit**2;ze>=ge*2&&(F.wakeUpAfterNarrowphase=!0)}this.collisionMatrix.set(H,F,!0),this.collisionMatrixPrevious.get(H,F)||(Ko.body=F,Ko.contact=j,H.dispatchEvent(Ko),Ko.body=H,F.dispatchEvent(Ko)),this.bodyOverlapKeeper.set(H.id,F.id),this.shapeOverlapKeeper.set(U.id,J.id)}for(this.emitContactEvents(),d&&(a.makeContactConstraints=He.now()-u,u=He.now()),p=0;p!==r;p++){let I=o[p];I.wakeUpAfterNarrowphase&&(I.wakeUp(),I.wakeUpAfterNarrowphase=!1)}for(m=f.length,p=0;p!==m;p++){let I=f[p];I.update();for(let j=0,H=I.equations.length;j!==H;j++){let F=I.equations[j];s.addEquation(F)}}s.solve(e,this),d&&(a.solve=He.now()-u),s.removeAllEquations();let R=Math.pow;for(p=0;p!==r;p++){let I=o[p];if(I.type&h){let j=R(1-I.linearDamping,e),H=I.velocity;H.scale(j,H);let F=I.angularVelocity;if(F){let U=R(1-I.angularDamping,e);F.scale(U,F)}}}for(this.dispatchEvent(Tb),p=0;p!==r;p++){let I=o[p];I.preStep&&I.preStep.call(I)}d&&(u=He.now());let P=this.stepnumber%(this.quatNormalizeSkip+1)===0,S=this.quatNormalizeFast;for(p=0;p!==r;p++)o[p].integrate(e,P,S);for(this.clearForces(),this.broadphase.dirty=!0,d&&(a.integrate=He.now()-u),this.stepnumber+=1,this.dispatchEvent(xb),p=0;p!==r;p++){let I=o[p],j=I.postStep;j&&j.call(I)}let L=!0;if(this.allowSleep)for(L=!1,p=0;p!==r;p++){let I=o[p];I.sleepTick(this.time),I.sleepState!==G.SLEEPING&&(L=!0)}this.hasActiveBodies=L}emitContactEvents(){let e=this.hasAnyEventListener("beginContact"),t=this.hasAnyEventListener("endContact");if((e||t)&&this.bodyOverlapKeeper.getDiff(Ii,Mi),e){for(let r=0,o=Ii.length;r<o;r+=2)es.bodyA=this.getBodyById(Ii[r]),es.bodyB=this.getBodyById(Ii[r+1]),this.dispatchEvent(es);es.bodyA=es.bodyB=null}if(t){for(let r=0,o=Mi.length;r<o;r+=2)ts.bodyA=this.getBodyById(Mi[r]),ts.bodyB=this.getBodyById(Mi[r+1]),this.dispatchEvent(ts);ts.bodyA=ts.bodyB=null}Ii.length=Mi.length=0;let i=this.hasAnyEventListener("beginShapeContact"),n=this.hasAnyEventListener("endShapeContact");if((i||n)&&this.shapeOverlapKeeper.getDiff(Ii,Mi),i){for(let r=0,o=Ii.length;r<o;r+=2){let s=this.getShapeById(Ii[r]),c=this.getShapeById(Ii[r+1]);Li.shapeA=s,Li.shapeB=c,s&&(Li.bodyA=s.body),c&&(Li.bodyB=c.body),this.dispatchEvent(Li)}Li.bodyA=Li.bodyB=Li.shapeA=Li.shapeB=null}if(n){for(let r=0,o=Mi.length;r<o;r+=2){let s=this.getShapeById(Mi[r]),c=this.getShapeById(Mi[r+1]);Di.shapeA=s,Di.shapeB=c,s&&(Di.bodyA=s.body),c&&(Di.bodyB=c.body),this.dispatchEvent(Di)}Di.bodyA=Di.bodyB=Di.shapeA=Di.shapeB=null}}clearForces(){let e=this.bodies,t=e.length;for(let i=0;i!==t;i++){let n=e[i];n.force,n.torque,n.force.set(0,0,0),n.torque.set(0,0,0)}}};new $e;var Gl=new Ee,He=globalThis.performance||{};if(!He.now){let l=Date.now();He.timing&&He.timing.navigationStart&&(l=He.timing.navigationStart),He.now=()=>Date.now()-l}var xb={type:"postStep"},Tb={type:"preStep"},Ko={type:G.COLLIDE_EVENT_NAME,body:null,contact:null},Rb=[],Cb=[],Sb=[],Pb=[],Ii=[],Mi=[],es={type:"beginContact",bodyA:null,bodyB:null},ts={type:"endContact",bodyA:null,bodyB:null},Li={type:"beginShapeContact",bodyA:null,bodyB:null,shapeA:null,shapeB:null},Di={type:"endShapeContact",bodyA:null,bodyB:null,shapeA:null,shapeB:null};import*as ke from"three";import{MeshBasicMaterial as Ob,SphereGeometry as Lu,BoxGeometry as Du,PlaneGeometry as Hu,Mesh as gn,CylinderGeometry as Ab,BufferGeometry as ic,Float32BufferAttribute as nc}from"three";function kb(l,e,{color:t=65280,scale:i=1,onInit:n,onUpdate:r,autoUpdate:o}={}){let s=[],c=new Ob({color:t??65280,wireframe:!0}),d=new _,a=new _,h=new _,u=new le,f=new Lu(1),E=new Du(1,1,1),b=new Hu(10,10,10,10);function y(R){let C=new ic,P=[];for(let L=0;L<R.vertices.length;L++){let I=R.vertices[L];P.push(I.x,I.y,I.z)}C.setAttribute("position",new nc(P,3));let S=[];for(let L=0;L<R.faces.length;L++){let I=R.faces[L],j=I[0];for(let H=1;H<I.length-1;H++){let F=I[H],U=I[H+1];S.push(j,F,U)}}return C.setIndex(S),C.computeBoundingSphere(),C.computeVertexNormals(),C}function g(R){let C=new ic,P=[],S=d,L=a,I=h;for(let j=0;j<R.indices.length/3;j++)R.getTriangleVertices(j,S,L,I),P.push(S.x,S.y,S.z),P.push(L.x,L.y,L.z),P.push(I.x,I.y,I.z);return C.setAttribute("position",new nc(P,3)),C.computeBoundingSphere(),C.computeVertexNormals(),C}function p(R){let C=new ic,P=R.elementSize||1,S=R.data.flatMap((I,j)=>I.flatMap((H,F)=>[j*P,F*P,H])),L=[];for(let I=0;I<R.data.length-1;I++)for(let j=0;j<R.data[I].length-1;j++){let H=R.data[I].length,F=I*H+j;L.push(F+1,F+H,F+H+1),L.push(F+H,F+1,F)}return C.setIndex(L),C.setAttribute("position",new nc(S,3)),C.computeBoundingSphere(),C.computeVertexNormals(),C}function m(R){let C=new gn,{SPHERE:P,BOX:S,PLANE:L,CYLINDER:I,CONVEXPOLYHEDRON:j,TRIMESH:H,HEIGHTFIELD:F}=V.types;switch(R.type){case P:{C=new gn(f,c);break}case S:{C=new gn(E,c);break}case L:{C=new gn(b,c);break}case I:{let U=new Ab(R.radiusTop,R.radiusBottom,R.height,R.numSegments);C=new gn(U,c),R.geometryId=U.id;break}case j:{let U=y(R);C=new gn(U,c),R.geometryId=U.id;break}case H:{let U=g(R);C=new gn(U,c),R.geometryId=U.id;break}case F:{let U=p(R);C=new gn(U,c),R.geometryId=U.id;break}}return l.add(C),C}function v(R,C){let{SPHERE:P,BOX:S,PLANE:L,CYLINDER:I,CONVEXPOLYHEDRON:j,TRIMESH:H,HEIGHTFIELD:F}=V.types;switch(C.type){case P:{let{radius:U}=C;R.scale.set(U*i,U*i,U*i);break}case S:{R.scale.copy(C.halfExtents),R.scale.multiplyScalar(2*i);break}case L:break;case I:{R.scale.set(1*i,1*i,1*i);break}case j:{R.scale.set(1*i,1*i,1*i);break}case H:{R.scale.copy(C.scale).multiplyScalar(i);break}case F:{R.scale.set(1*i,1*i,1*i);break}}}function w(R,C){if(!R)return!1;let{geometry:P}=R;return P instanceof Lu&&C.type===V.types.SPHERE||P instanceof Du&&C.type===V.types.BOX||P instanceof Hu&&C.type===V.types.PLANE||P.id===C.geometryId&&C.type===V.types.CYLINDER||P.id===C.geometryId&&C.type===V.types.CONVEXPOLYHEDRON||P.id===C.geometryId&&C.type===V.types.TRIMESH||P.id===C.geometryId&&C.type===V.types.HEIGHTFIELD}function x(R,C){let P=s[R],S=!1;return w(P,C)||(P&&l.remove(P),s[R]=P=m(C),S=!0),v(P,C),S}function T(){let R=s,C=d,P=u,S=0;for(let L of e)for(let I=0;I!==L.shapes.length;I++){let j=L.shapes[I],H=x(S,j),F=R[S];F&&(L.quaternion.vmult(L.shapeOffsets[I],C),L.position.vadd(C,C),L.quaternion.mult(L.shapeOrientations[I],P),F.position.copy(C),F.quaternion.copy(P),H&&n instanceof Function&&n(L,F,j),!H&&r instanceof Function&&r(L,F,j)),S++}for(let L=S;L<R.length;L++){let I=R[L];I&&l.remove(I)}R.length=S,o!==!1&&requestAnimationFrame(T)}return o!==!1&&requestAnimationFrame(T),{update:T}}var ju=kb;import*as li from"three";import*as rs from"three";var Hi=class{get lightmap(){return this.lightmapTexture}set lightmap(e){e!==this.lightmapTexture&&(this.lightmapTexture=e,this.setupLightmap())}lightmapIndex=-1;lightmapScaleOffset=new rs.Vector4(1,1,0,0);context;gameObject;lightmapTexture=null;lightmapScaleOffsetUniform={value:new rs.Vector4(1,1,0,0)};lightmapUniform={value:null};beforeRenderCallback;constructor(e,t){this.gameObject=e,this.context=t}init(e,t,i,n=!1){if(console.assert(this.gameObject!==void 0&&this.gameObject!==null,"Missing gameobject",this),this.lightmapIndex=e,this.lightmapIndex<0)return;this.lightmapScaleOffset=t,this.lightmapTexture=i,n&&this.setLightmapDebugMaterial(),this.setupLightmap()}bindOnBeforeRender(){this.beforeRenderCallback=this.onBeforeRenderThreeComplete.bind(this),this.context.addBeforeRenderListener(this.gameObject,this.beforeRenderCallback)}onBeforeRenderThreeComplete(e,t,i,n,r,o){this.onBeforeRenderThree(r)}setupLightmap(){if(this.gameObject.type==="Object3D")return;if(this.gameObject.type==="Group"){console.warn("Lightmap on multimaterial object is not supported yet... please ask kindly for implementation.");return}console.assert(this.gameObject.type==="Mesh","Lightmap only works on meshes",this);let e=this.gameObject;e.geometry.getAttribute("uv2")||e.geometry.setAttribute("uv2",e.geometry.getAttribute("uv"));let t=this.gameObject.material.clone();if(this.gameObject.material=t,this.gameObject.material.onBeforeCompile=(i,n)=>{i.uniforms.lightmap=this.lightmapUniform,i.uniforms.lightmapScaleOffset=this.lightmapScaleOffsetUniform},this.lightmapIndex>=0){let i=this.lightmapTexture,n=this.gameObject.material;n&&i&&(n.uniforms||(n.uniforms={}),n.lightMap=i,n.uniforms.lightmap={value:i})}}onBeforeRenderThree(e){let t=e.uniforms;t&&t.lightmap&&(this.lightmapScaleOffsetUniform.value=this.lightmapScaleOffset,this.lightmapUniform.value=this.lightmapTexture,t.lightmap=this.lightmapUniform,t.lightmapScaleOffset=this.lightmapScaleOffsetUniform)}setLightmapDebugMaterial(){this.gameObject.material=new rs.ShaderMaterial({vertexShader:`
92
92
  attribute vec2 uv2;
93
93
  varying vec2 vUv2;
94
94
  void main()
@@ -120,7 +120,7 @@ a=extmap-allow-mixed`)!==-1){var f=p.sdp.split(`
120
120
  // gl_FragColor = vec4(vUv2.xy, 0, 1);
121
121
  gl_FragColor = lightMapTexel;
122
122
  }
123
- `,defines:{USE_LIGHTMAP:""}})}};var A=function(l){if(l===void 0&&(l=null),!Array.isArray(l))l=Iu(l);else for(let e=0;e<l.length;e++){let t=l[e];l[e]=Iu(t)}return function(e,t){Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});let i=e.$serializedTypes=e.$serializedTypes||{};i[t]=l}};function Iu(l){switch(l?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return l}import{Vector4 as Zb}from"three";import{NeverStencilFunc as Sb,LessStencilFunc as Pb,EqualStencilFunc as Ob,LessEqualStencilFunc as Ab,GreaterStencilFunc as kb,NotEqualStencilFunc as Ib,GreaterEqualStencilFunc as Mb,AlwaysStencilFunc as Lb,ZeroStencilOp as Db,KeepStencilOp as Hb,ReplaceStencilOp as jb,IncrementStencilOp as Bb,DecrementStencilOp as Fb,IncrementWrapStencilOp as Nb,DecrementWrapStencilOp as zb,InvertStencilOp as Gb}from"three";var nc=N("debugstencil");function Vb(l,e){return(l&1<<e.layer)!=0}var Jn=class{static applyStencil(e){if(!e)return;let t=e.sourceId;if(nc&&console.log(t,Jn.stencils),!t)return;let i=Jn.stencils[t];if(!!i)for(let n=i.length-1;n>=0;n--){let r=i[n];if(Vb(r.layer,e)){nc&&console.log(r);let s=e.material?.clone();s&&(e.material=s,e.gameObject.renderOrder=r.event*1e3+r.index*50,s.stencilWrite=!0,s.stencilWriteMask=255,s.stencilFuncMask=255,s.stencilRef=r.value,s.stencilFunc=r.compareFunc,s.stencilZPass=r.passOp,s.stencilFail=r.failOp,s.stencilZFail=r.zFailOp);break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){let t=this.parser.json.extensions;if(t){let i=t[Ub];if(i){nc&&console.log(i);let n=i.stencil;if(n&&Array.isArray(n))for(let r of n){let s={...r};s.compareFunc=Wb(s.compareFunc),s.passOp=rc(s.passOp),s.failOp=rc(s.failOp),s.zFailOp=rc(s.zFailOp),Jn.stencils[this.source]||(Jn.stencils[this.source]=[]),Jn.stencils[this.source].push(s)}}}return null}},$n=Jn;z($n,"stencils",{});function rc(l){switch(l){case 0:return Hb;case 1:return Db;case 2:return jb;case 3:return Bb;case 4:return Fb;case 6:return Nb;case 7:return zb;case 5:return Gb}return 0}function Wb(l){switch(l){case 1:return Sb;case 2:return Pb;case 3:return Ob;case 4:return Ab;case 5:return kb;case 6:return Ib;case 7:return Mb;case 8:return Lb}return 0}var Ub="NEEDLE_render_objects";import{TextureLoader as Qb}from"three";import{GLTFLoader as Yb}from"three/examples/jsm/loaders/GLTFLoader";import{DRACOLoader as qb}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as Xb}from"three/examples/jsm/loaders/KTX2Loader.js";var eo,to;function Kn(l,e){eo||(eo=new qb,eo.setDecoderPath("./include/draco/"),eo.setDecoderConfig({type:"js"})),to||(to=new Xb,to.setTranscoderPath("./include/ktx2/"),e.renderer&&to.detectSupport(e.renderer)),l.setDRACOLoader(eo),l.setKTX2Loader(to)}var sc="NEEDLE_deferred_texture",gn=N("debugdeferredtextures"),io=class{static assignTextureLOD(e,t,i=0){if(!!t)for(let n of Object.keys(t)){let r=t[n];r?.isTexture===!0&&(gn&&console.log("FIND",n,r?.name,r?.userData,r),io.getOrLoadTexture(e,t,n,r,i).then(s=>{s?.isTexture===!0&&(s.needsUpdate=!0,t[n]=s,t.needsUpdate=!0)}))}}get name(){return sc}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}_loading=[];afterRoot(e){return gn&&console.log("AFTER",e),this.parser.json.textures?.forEach((t,i)=>{if(t?.extensions){let n=t?.extensions[sc];if(n){let r=this.parser.getDependency("texture",i);this._loading.splice(this._loading.indexOf(i),1),r.then(s=>{gn&&console.log("register texture",s.name,s.uuid,n),s.userData.deferred=n,io.cache.set(s.uuid,n)})}}}),null}static async getOrLoadTexture(e,t,i,n,r){let s=n.uuid,o=io.cache.get(s)||n.userData.deferred;if(o){gn&&console.log(s,o.uri,o.guid);let c=o.uri;if(c.endsWith(".glb")||c.endsWith(".gltf")){if(!o.guid)return console.warn("missing pointer for glb/gltf texture",o),null;let d=o.uri+"_"+o.guid;if(this.resolved[d])return this.resolved[d];let a=new Yb;Kn(a,e),gn&&console.log("Load "+c,t.name,i);let h=await a.loadAsync(c),u=h.parser,g=-1,E=!1;for(let y of h.parser.json.textures)if(g++,y?.extensions){let m=y?.extensions[sc];if(m?.guid&&m.guid===o.guid){E=!0;break}}if(!E)return null;let b=await u.getDependency("texture",g);return this.resolved[d]=b,gn&&console.log(t.name,i,'change "'+n.name+'" \u2192 "'+b.name+'"',c,g,b,t),b}else{let a=await new Qb().loadAsync(o.uri);return a&&gn?console.log(o,a):console.warn("failed loading",o.uri),a}}else gn&&console.warn("unknown uuid",n.name,n.uuid,n);return null}},Hi=io;z(Hi,"cache",new Map),z(Hi,"resolved",{});var Lu=N("noInstancing"),Du=!!N("debuglightmaps"),Jb=N("debuginstancing"),$b=N("debugprogressiveload"),Ir=class{path=null;asset=null;default};var oc=class{_renderer;_targets=[];is(e){return this._renderer===e}constructor(e){this._renderer=e;let t=this.setMaterial.bind(this),i=this.getMaterial.bind(this),n=e.gameObject;if(this._targets=[],n)switch(n.type){case"Group":this._targets=[...n.children];break;case"Mesh":this._targets.push(n);break}return new Proxy(this,{get(r,s){if(typeof s=="string"){let o=parseInt(s);if(!isNaN(o))return i(o)}return r[s]},set(r,s,o){return typeof s=="string"&&t(o,Number.parseInt(s)),Reflect.set(r,s,o)}})}get length(){return this._targets.length}setMaterial(e,t){if(t<0||t>=this._targets.length)return;let i=this._targets[t];!i||(i.material=e)}getMaterial(e){if(e<0)return null;let t=this._targets;if(e>=t.length)return null;let i=t[e];return i?i.material:null}},hc=class extends M{receiveShadows=!1;shadowCastingMode=ac.Off;lightmapIndex=-1;lightmapScaleOffset=new ai.Vector4(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;_lightmaps;get material(){return this.gameObject.material}set material(e){this.gameObject.material=e}_sharedMaterials;get sharedMaterials(){return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._sharedMaterials=new oc(this)),this._sharedMaterials}static get shouldSuppressInstancing(){return Lu}_lightmapTextureOverride=void 0;get lightmap(){return this._lightmaps?.length?this._lightmaps[0].lightmap:null}set lightmap(e){if(this._lightmapTextureOverride=e,e===void 0&&(e=this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex)),this._lightmaps?.length)for(let t of this._lightmaps)t.lightmap=e}get hasLightmap(){let e=this.lightmap;return e!=null}get activeSelf(){return this.enabled}set activeSelf(e){let t=typeof e=="number"?e>.5:e;this.enabled=t,t&&(this.gameObject.visible=!0)}awake(){let e=this.gameObject.type;if(e==="Group"){for(let t of this.gameObject.children)this.context.addBeforeRenderListener(t,this.onBeforeRenderThree.bind(this)),t.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let t=0;for(let i=0;i<this.gameObject.children.length;i++){let n=this.gameObject.children[i];if(!(n.type!=="Mesh"||O.getComponent(n,hc))){if(this.renderOrder.length<=t){console.error("Incorrect element count",this);break}n.renderOrder=this.renderOrder[t],t+=1}}}}else(e==="Mesh"||e==="SkinnedMesh")&&(this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree.bind(this)),this.renderOrder!==void 0&&this.renderOrder.length>0&&(this.gameObject.renderOrder=this.renderOrder[0]));if(this.lightmapIndex>=0){let t=this._lightmapTextureOverride!==void 0?this._lightmapTextureOverride:this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex);if(t){if(this._lightmaps=[],e==="Mesh"){if(!this.gameObject.material?.isMeshBasicMaterial){let i=new Di(this.gameObject,this.context);this._lightmaps.push(i),i.init(this.lightmapIndex,this.lightmapScaleOffset,t,Du)}}else if(e==="Group"){for(let i of this.gameObject.children)if(!i.material?.isMeshBasicMaterial){let n=new Di(i,this.context);this._lightmaps.push(n),n.init(this.lightmapIndex,this.lightmapScaleOffset,t,Du),n.bindOnBeforeRender()}}}}}_isInstancingEnabled=!1;handles=void 0;prevLayers=void 0;setInstancingEnabled(e){if(this._isInstancingEnabled===e)return e&&(this.handles===void 0||this.handles!=null&&this.handles.length>0);if(this._isInstancingEnabled=e,e){if(this.handles===void 0){if(this.handles=Kb.setup(this.gameObject,this.context,null,{rend:this,foundMeshes:0}),this.handles)return O.markAsInstancedRendered(this.gameObject,!0),!0}else if(this.handles!==null){for(let t of this.handles)t.updateInstanceMatrix(!0),t.add();return O.markAsInstancedRendered(this.gameObject,!0),!0}}else{if(this.handles)for(let t of this.handles)t.remove();return!0}return!1}start(){if(this.enableInstancing&&!Lu&&this.setInstancingEnabled(!0),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.gameObject.type==="Group")for(let e=0;e<this.gameObject.children.length;e++){let t=this.gameObject.children[e];t.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this._isInstancingEnabled?this.setInstancingEnabled(!0):this.enabled&&(this.gameObject.visible=!0,this.applyStencil())}onDisable(){this.handles&&this.handles.length>0?this.setInstancingEnabled(!1):this.enabled||(this.gameObject.visible=!1)}onDestroy(){this.handles=null}applyStencil(){$n.applyStencil(this)}onBeforeRenderThree(e,t,i,n,r,s){if(r._didRequestTextureLOD===void 0&&(r._didRequestTextureLOD=0,$b?(console.log("Load material LOD (with delay)",r.name),setTimeout(()=>{Hi.assignTextureLOD(this.context,r)},2e3)):Hi.assignTextureLOD(this.context,r)),r.envMapIntensity!==void 0){let o=this.hasLightmap?Math.PI:1;r.envMapIntensity=Math.max(0,this.context.rendererData.environmentIntensity/o)}if(this._lightmaps)for(let o of this._lightmaps)o.onBeforeRenderThree(r)}onBeforeRender(){if(!this.gameObject)return;let e=this.gameObject[lc]===!0||this.gameObject.matrixWorldNeedsUpdate;if(this.gameObject.type==="Group"&&this.gameObject.children?.length>0)for(let t of this.gameObject.children)this.applySettings(t);else this.applySettings(this.gameObject);if(e&&(delete this.gameObject[lc],this.handles)){for(let i=this.handles.length-1;i>=0;i--)this.handles[i].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this.handles&&this.handles.length<=0&&O.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this.handles)for(let t=0;t<this.handles.length;t++){let i=this.handles[t];this.prevLayers||(this.prevLayers=[]);let n=i.object.layers.mask;t>=this.prevLayers.length?this.prevLayers.push(n):this.prevLayers[t]=n,i.object.layers.disableAll()}}onAfterRender(){if(this._isInstancingEnabled&&this.handles&&this.prevLayers&&this.prevLayers.length>=this.handles.length)for(let e=0;e<this.handles.length;e++){let t=this.handles[e];t.object.layers.mask=this.prevLayers[e]}}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==ac.On?e.castShadow=!0:e.castShadow=!1}},Te=hc;k([A()],Te.prototype,"receiveShadows",2),k([A()],Te.prototype,"shadowCastingMode",2),k([A()],Te.prototype,"lightmapIndex",2),k([A(Zb)],Te.prototype,"lightmapScaleOffset",2),k([A()],Te.prototype,"enableInstancing",2),k([A()],Te.prototype,"renderOrder",2),k([A()],Te.prototype,"allowOcclusionWhenDynamic",2);var er=class extends Te{},Mr=class extends er{awake(){super.awake(),this.allowOcclusionWhenDynamic=!1}},ac=(n=>(n[n.Off=0]="Off",n[n.On=1]="On",n[n.TwoSided=2]="TwoSided",n[n.ShadowsOnly=3]="ShadowsOnly",n))(ac||{}),lc="NEEDLE_NEED_UPDATE_INSTANCE",he=class{static markDirty(e,t=!0){if(!!e&&(O.isUsingInstancing(e)&&(e[lc]=!0,e.matrixWorldNeedsUpdate=!0),t))for(let i of e.children)he.markDirty(i,!0)}},cc=class{objs=[];setup(e,t,i,n,r=0){let s=this.tryCreateOrAddInstance(e,t,n);if(s)return i===null&&(i=[]),i.push(s),i;if(r<=0&&e.type!=="Mesh"){let o=r+1;for(let c of e.children)i=this.setup(c,t,i,n,o)}return i}tryCreateOrAddInstance(e,t,i){if(e.type==="Mesh"){let n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing||n>=i.rend.enableInstancing.length||!i.rend.enableInstancing[n])return null;let r=e,s=r.geometry,o=r.material;for(let d of this.objs)if(!d.isFull()&&d.geo===s&&d.material===o)return d.addInstance(r);let c=new oa(e.name,s,o,200,t);return this.objs.push(c),c.addInstance(r)}return null}},Kb=new cc,dc=class{get name(){return this.object.name}instanceIndex=-1;object;instancer;constructor(e,t,i){this.instanceIndex=e,this.object=t,this.instancer=i,O.markAsInstancedRendered(t,!0)}updateInstanceMatrix(e=!1){this.instanceIndex<0||(this.object.updateWorldMatrix(!0,e),this.instancer.updateInstance(this.object.matrixWorld,this.instanceIndex))}add(){this.instanceIndex>=0||this.instancer.add(this)}remove(){this.instanceIndex<0||this.instancer.remove(this)}},uc=class{name="";geo;material;get currentCount(){return this.inst.count}context;inst;handles=[];maxCount;isFull(){return this.currentCount>=this.maxCount}constructor(e,t,i,n,r){this.name=e,this.geo=t,this.material=i,this.context=r,this.maxCount=n,Jb&&(i=new ai.MeshBasicMaterial({color:this.randomColor()})),this.inst=new ai.InstancedMesh(t,i,n),this.inst.count=0,this.inst.layers.set(2),this.inst.visible=!0,this.context.scene.add(this.inst)}randomColor(){return new ai.Color(Math.random(),Math.random(),Math.random())}addInstance(e){if(this.currentCount>=this.maxCount)return console.error("TOO MANY INSTANCES - resize is not yet implemented!",this.inst.count),null;let t=new dc(-1,e,this);return this.add(t),t}add(e){e.instanceIndex<0&&(e.instanceIndex=this.currentCount,e.instanceIndex>=this.handles.length?this.handles.push(e):this.handles[e.instanceIndex]=e),e.object.updateWorldMatrix(!0,!0),this.inst.setMatrixAt(e.instanceIndex,e.object.matrixWorld),this.inst.instanceMatrix.needsUpdate=!0,this.inst.count+=1,this.inst.count>0&&(this.inst.visible=!0)}remove(e){if(!e||e.instanceIndex<0||e.instanceIndex>=this.handles.length||this.inst.count<=0)return;if(this.handles[e.instanceIndex]!==e){console.error("instance handle is not part of renderer, was it removed before?",e.instanceIndex,this.name);let i=this.handles.indexOf(e);if(i<0)return;e.instanceIndex=i}if(this.handles[e.instanceIndex]=null,this.inst.setMatrixAt(e.instanceIndex,uc.nullMatrix),!(e.instanceIndex>=this.currentCount-1)&&this.currentCount>0){let i=this.handles[this.currentCount-1];i&&(i.instanceIndex=e.instanceIndex,i.updateInstanceMatrix(),this.handles[e.instanceIndex]=i,this.handles[this.currentCount-1]=null)}this.inst.count>0&&(this.inst.count-=1),e.instanceIndex=-1,this.inst.count<=0&&(this.inst.visible=!1),this.inst.instanceMatrix.needsUpdate=!0}updateInstance(e,t){this.inst.setMatrixAt(t,e),this.inst.instanceMatrix.needsUpdate=!0}},oa=uc;z(oa,"nullMatrix",new ai.Matrix4);var no=N("debugphysics"),ev=N("debugcollisions"),aa=class{mass=1;kinematic=!1;physicsEvents=!1;drag=0;angularDrag=.05;sleepThreshold=.01},ro=class{obj;parent;body;shapes=[];collisonCallback=null;_hasRigidbody=!1;_didSleepLastStep=!1;constructor(e,t){this.obj=e,this.parent=e.parent,this.body=t}},pc=class{obj;contact;target;type;constructor(e,t){this.contact=e,this.type=t,this.obj=null,this.target=null}};var je=class{ray=void 0;screenPoint=void 0;raycaster=void 0;results=void 0;targets=void 0;recursive=!0;minDistance=void 0;maxDistance=void 0;lineThreshold=void 0;layerMask=void 0;ignore=void 0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new ke.Vector2),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setMask(e){this.layerMask||(this.layerMask=new ke.Layers);let t=this.layerMask;t?t.mask=e:this.layerMask=e}};z(je,"AllLayers",4294967295);var fc=class{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}},la=class{raycaster=new ke.Raycaster;defaultRaycastOptions=new je;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:0},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new ke.Layers;sphereOverlap(e,t){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;let i=new ke.Sphere(e,t),n=this.sphereMask;n.enableAll(),n.disable(2);for(let r of this.context.scene.children){let s=this.onSphereOverlap(r,i,n);s&&this.sphereResults.push(s)}return this.sphereResults.sort((r,s)=>r.distance-s.distance)}tempBoundingBox=new ke.Box3;onSphereOverlap(e,t,i){if(e.type==="Mesh"){if(!e.layers.test(i))return null;let n=e,r=n.geometry;if(r.boundingBox||r.computeBoundingBox(),!r.boundingBox)return null;n.matrixWorldNeedsUpdate&&n.updateMatrixWorld();let s=this.tempBoundingBox.copy(r.boundingBox).applyMatrix4(n.matrixWorld);if(t.intersectsBox(s)){let c=q(e).distanceTo(t.center);return new fc(e,c,t.center.clone())}}else if(e.children)for(let n of e.children){let r=this.onSphereOverlap(n,t,i);if(r)return r}return null}raycastFromRay(e,t=null){let i=t??this.defaultRaycastOptions;return i.ray=e,this.raycast(i)}raycast(e=null){e||(e=this.defaultRaycastOptions);let t=e.screenPoint??this.context.input.mousePositionRC,i=e.raycaster??this.raycaster;if(i.near=e.minDistance??0,i.far=e.maxDistance??1/0,i.params=this.defaultThresholds,e.lineThreshold?i.params.Line={threshold:e.lineThreshold}:i.params.Line={threshold:0},e.ray)i.ray.copy(e.ray);else{let o=this.context.mainCamera;if(!o)return console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];i.setFromCamera(t,o)}let n=e.targets;n||(n=this.targetBuffer,n[0]=this.context.scene);let r=e.results;r||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),r=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof ke.Layers?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),r.length=0,i.intersectObjects(n,e.recursive,r);let s=e.ignore;return s!==void 0&&s.length>0&&(r=r.filter(o=>!s.includes(o.object))),r}get isUpdating(){return this._isUpdatingPhysicsWorld}_isUpdatingPhysicsWorld=!1;context;world=new sa;objects=[];tempPosition=new ke.Vector3;tempQuaternion=new ke.Quaternion;constructor(e){if(this.context=e,this.world.gravity.set(0,-9.82,0),no){let t={};t.onInit=(i,n,r)=>{n.layers.set(-1)},ku(e.scene,this.world.bodies,t)}}addPreStepListener(e){this.world.addEventListener("preStep",e)}addPostStepListener(e){this.world.addEventListener("postStep",e)}addConstraint(e){this.world.addConstraint(e)}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}multiplyGravity(e){this.world.gravity.x*=e.x,this.world.gravity.y*=e.y,this.world.gravity.z*=e.z}addBody(e,t){for(let i=0;i<this.objects.length;i++){let n=this.objects[i];if(n.obj===e){n._hasRigidbody=!0;break}}this.world.addBody(t)}removeBody(e,t,i=!0){this.world.removeBody(t);for(let n=0;n<this.objects.length;n++){let r=this.objects[n];if(r.obj===e){r._hasRigidbody=!1,i&&this.objects.splice(n,1);break}}}removeShape(e,t){for(let i of this.objects)if(i.obj===e){i.body&&(i.body.removeShape(t),i.body.updateMassProperties());return}}createBody(e,t){let i=this.internalCreateBody(e,null);t.mass&&(i.mass=t.mass),t.kinematic?i.type=G.KINEMATIC:i.type=G.DYNAMIC,t.drag&&(i.linearDamping=t.drag),t.angularDrag&&(i.angularDamping=t.angularDrag),t.sleepThreshold&&(i.sleepSpeedLimit=t.sleepThreshold),this.world.addBody(i);let n=new ro(e,i);return n._hasRigidbody=!0,this.objects.push(n),no&&console.log("created new body",e.name,i,i.sleepState,this.world.gravity),t.physicsEvents&&this.registerCollisionEvents(n),i}addBoxCollider(e,t,i,n,r){let s=this.tempPosition;e.getWorldScale(s);let o=new _(.5*s.x*n.x,.5*s.y*n.y,.5*s.z*n.z),c=new Yn(o);c.collisionResponse=!t,i=i.clone(),i.multiply(s);let d=this.addShape(e,c,i,r);if(d!==null){if(this.isAlreadyRegistered(d))return c;let a=new ro(e,d);this.objects.push(a)}return c}addSphereCollider(e,t,i,n){let r=this.tempPosition;e.getWorldScale(r);let s=Math.max(r.x,r.y,r.z),o=new na(i*s);t=t.clone(),t.multiply(r);let c=this.addShape(e,o,t,n);if(c!==null){if(this.isAlreadyRegistered(c))return o;let d=new ro(e,c);this.objects.push(d)}return o}addMeshCollider(e){no&&console.warn("TODO mesh collider not yet supported")}isAlreadyRegistered(e){for(let t of this.objects)if(t.body===e)return!0;return!1}addShape(e,t,i,n){let r=null;if(n?(n.initialize(),console.assert(!!n.body,"rigidbody didn't initialize / produce a physics body",n),r=n.body):(r=this.internalCreateBody(e,null),r.type=G.KINEMATIC,this.world.addBody(r)),r){i.x*=-1;let s=ve(e),o=q(e);o.add(i);let c=new ke.Quaternion(r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w);s.multiply(c.invert());let d=r.position,a=new _(o.x-d.x,o.y-d.y,o.z-d.z),h=new le(s.x,s.y,s.z,s.w);r.addShape(t,a,h),r.updateMassProperties()}return r}step(e){this._isUpdatingPhysicsWorld=!0,e=Math.min(e,1/30),this.world.step(e),this._isUpdatingPhysicsWorld=!1,no&&this.context.time.frameCount%60===0&&console.log("physics world has "+this.world.bodies.length+" bodies",this.world)}temp=new ke.Vector3;tempQuat=new ke.Quaternion;postStep(){this._isUpdatingPhysicsWorld=!0;for(let e=0;e<this.objects.length;e++){let t=this.objects[e],i=t.body;if(!i||!i.world)continue;i.sleepTick(this.context.time.time),no&&(!t._didSleepLastStep&&i.sleepState===G.SLEEPING?console.log("BODY SLEEPING",i):t._didSleepLastStep&&i.sleepState!==G.SLEEPING&&console.log("BODY WOKE UP",i)),t._didSleepLastStep=i.sleepState===G.SLEEPING;let n=t.obj;if(i.type===G.KINEMATIC){let r=q(n,this.temp);i.position.set(r.x,r.y,r.z);let s=ve(n,this.tempQuat);i.quaternion.set(s.x,s.y,s.z,s.w);continue}if(t.parent&&n.parent===t.parent){Eh(n,i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w);let r=i.position;Cr(n,r.x,r.y,r.z),i.velocity.length()>i.sleepSpeedLimit&&he.markDirty(n)}}this._isUpdatingPhysicsWorld=!1}internalCreateBody(e,t){let i=new G;i._owner=e,i._name=e.name,e.getWorldPosition(this.tempPosition);let n=this.tempPosition;i.position=new _(n.x,n.y,n.z);let r=this.tempQuaternion;return e.getWorldQuaternion(r),i.quaternion=new le(r.x,r.y,r.z,r.w),i.type=G.KINEMATIC,t&&(i.addShape(t),i.updateMassProperties()),i}registerCollisionEvents(e){if(e.collisonCallback&&this.unregisterCollisionEvents(e),!e.body)return;let t=i=>this.raiseCollisionEvents(e.obj,i);e.collisonCallback=t.bind(this),e.body.addEventListener("collide",e.collisonCallback)}unregisterCollisionEvents(e){!e.collisonCallback||!e.body||e.body.removeEventListener("collide",e.collisonCallback)}raiseCollisionEvents(e,t){let i=new pc(t.contact,t.type),n=0,r=this.objects;function s(){if(!(n>0))for(let o=0;o<r.length;o++){if(n==2)return;let c=r[o];c.body==t.body?(i.obj=c.obj,++n):c.body==t.target&&(i.target=c.obj,++n)}}ev&&console.log("collision between",t.contact.bi,t.contact.bj,e,t);for(let o=0;o<e.userData?.components?.length;o++){let c=e.userData.components[o];c.onCollision&&(s(),c.onCollision(i))}}};import{Clock as tv}from"three";var ca=class{deltaTime=0;time=0;frame=0;get realtimeSinceStartup(){return this.clock.elapsedTime}get frameCount(){return this.frame}get smoothedFps(){return this._smoothedFps}clock=new tv;_smoothedFps=0;_fpsSamples=[];_fpsSampleIndex=0;update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<30?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%30]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedFps=1/(e/this._fpsSamples.length)}};import{WebsocketBuilder as nv}from"websocket-ts";function Hu(l=window.location.hostname){return new RegExp("[0-9]{3}.[0-9]{2,3}.[0-9]{2,3}.[0-9]{2,3}|localhost","gm").test(l)===!0}var pt=class extends M{url=null;urlParameterName=null;localhost=null;getWebsocketUrl(){let e=this.url?pt.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){let r=N(this.urlParameterName);r&&typeof r=="string"&&(e=r)}if(!e)return null;let i=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return i?.groups?i?.groups.socket_prefix?e:"wss://"+i?.groups.url:null}static GetUrl(e,t){let i=e,n=pt.IsLocalNetwork()&&t;return n&&(i=t),e?.startsWith("/")&&(i=(n?i:window.location.origin)+e),i}static IsLocalNetwork(e=window.location.hostname){return Hu(e)}};var li=new Int32Array(2),da=new Float32Array(li.buffer),ha=new Float64Array(li.buffer),Lr=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;var Xe=class{constructor(e,t){this.low=e|0,this.high=t|0}static create(e,t){return e==0&&t==0?Xe.ZERO:new Xe(e,t)}toFloat64(){return(this.low>>>0)+this.high*4294967296}equals(e){return this.low==e.low&&this.high==e.high}};Xe.ZERO=new Xe(0,0);var so;(function(l){l[l.UTF8_BYTES=1]="UTF8_BYTES",l[l.UTF16_STRING=2]="UTF16_STRING"})(so||(so={}));var ci=class{constructor(e){this.bytes_=e,this.position_=0}static allocate(e){return new ci(new Uint8Array(e))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(e){this.position_=e}capacity(){return this.bytes_.length}readInt8(e){return this.readUint8(e)<<24>>24}readUint8(e){return this.bytes_[e]}readInt16(e){return this.readUint16(e)<<16>>16}readUint16(e){return this.bytes_[e]|this.bytes_[e+1]<<8}readInt32(e){return this.bytes_[e]|this.bytes_[e+1]<<8|this.bytes_[e+2]<<16|this.bytes_[e+3]<<24}readUint32(e){return this.readInt32(e)>>>0}readInt64(e){return new Xe(this.readInt32(e),this.readInt32(e+4))}readUint64(e){return new Xe(this.readUint32(e),this.readUint32(e+4))}readFloat32(e){return li[0]=this.readInt32(e),da[0]}readFloat64(e){return li[Lr?0:1]=this.readInt32(e),li[Lr?1:0]=this.readInt32(e+4),ha[0]}writeInt8(e,t){this.bytes_[e]=t}writeUint8(e,t){this.bytes_[e]=t}writeInt16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeUint16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeInt32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeUint32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeInt64(e,t){this.writeInt32(e,t.low),this.writeInt32(e+4,t.high)}writeUint64(e,t){this.writeUint32(e,t.low),this.writeUint32(e+4,t.high)}writeFloat32(e,t){da[0]=t,this.writeInt32(e,li[0])}writeFloat64(e,t){ha[0]=t,this.writeInt32(e,li[Lr?0:1]),this.writeInt32(e+4,li[Lr?1:0])}getBufferIdentifier(){if(this.bytes_.length<this.position_+4+4)throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");let e="";for(let t=0;t<4;t++)e+=String.fromCharCode(this.readInt8(this.position_+4+t));return e}__offset(e,t){let i=e-this.readInt32(e);return t<this.readInt16(i)?this.readInt16(i+t):0}__union(e,t){return e.bb_pos=t+this.readInt32(t),e.bb=this,e}__string(e,t){e+=this.readInt32(e);let i=this.readInt32(e),n="",r=0;if(e+=4,t===so.UTF8_BYTES)return this.bytes_.subarray(e,e+i);for(;r<i;){let s,o=this.readUint8(e+r++);if(o<192)s=o;else{let c=this.readUint8(e+r++);if(o<224)s=(o&31)<<6|c&63;else{let d=this.readUint8(e+r++);if(o<240)s=(o&15)<<12|(c&63)<<6|d&63;else{let a=this.readUint8(e+r++);s=(o&7)<<18|(c&63)<<12|(d&63)<<6|a&63}}}s<65536?n+=String.fromCharCode(s):(s-=65536,n+=String.fromCharCode((s>>10)+55296,(s&(1<<10)-1)+56320))}return n}__union_with_string(e,t){return typeof e=="string"?this.__string(t):this.__union(e,t)}__indirect(e){return e+this.readInt32(e)}__vector(e){return e+this.readInt32(e)+4}__vector_len(e){return this.readInt32(e+this.readInt32(e))}__has_identifier(e){if(e.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let t=0;t<4;t++)if(e.charCodeAt(t)!=this.readInt8(this.position()+4+t))return!1;return!0}createLong(e,t){return Xe.create(e,t)}createScalarList(e,t){let i=[];for(let n=0;n<t;++n)e(n)!==null&&i.push(e(n));return i}createObjList(e,t){let i=[];for(let n=0;n<t;++n){let r=e(n);r!==null&&i.push(r.unpack())}return i}};var ft=class{constructor(e){this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null;let t;e?t=e:t=1024,this.bb=ci.allocate(t),this.space=t}clear(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null}forceDefaults(e){this.force_defaults=e}dataBuffer(){return this.bb}asUint8Array(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())}prep(e,t){e>this.minalign&&(this.minalign=e);let i=~(this.bb.capacity()-this.space+t)+1&e-1;for(;this.space<i+e+t;){let n=this.bb.capacity();this.bb=ft.growByteBuffer(this.bb),this.space+=this.bb.capacity()-n}this.pad(i)}pad(e){for(let t=0;t<e;t++)this.bb.writeInt8(--this.space,0)}writeInt8(e){this.bb.writeInt8(this.space-=1,e)}writeInt16(e){this.bb.writeInt16(this.space-=2,e)}writeInt32(e){this.bb.writeInt32(this.space-=4,e)}writeInt64(e){this.bb.writeInt64(this.space-=8,e)}writeFloat32(e){this.bb.writeFloat32(this.space-=4,e)}writeFloat64(e){this.bb.writeFloat64(this.space-=8,e)}addInt8(e){this.prep(1,0),this.writeInt8(e)}addInt16(e){this.prep(2,0),this.writeInt16(e)}addInt32(e){this.prep(4,0),this.writeInt32(e)}addInt64(e){this.prep(8,0),this.writeInt64(e)}addFloat32(e){this.prep(4,0),this.writeFloat32(e)}addFloat64(e){this.prep(8,0),this.writeFloat64(e)}addFieldInt8(e,t,i){(this.force_defaults||t!=i)&&(this.addInt8(t),this.slot(e))}addFieldInt16(e,t,i){(this.force_defaults||t!=i)&&(this.addInt16(t),this.slot(e))}addFieldInt32(e,t,i){(this.force_defaults||t!=i)&&(this.addInt32(t),this.slot(e))}addFieldInt64(e,t,i){(this.force_defaults||!t.equals(i))&&(this.addInt64(t),this.slot(e))}addFieldFloat32(e,t,i){(this.force_defaults||t!=i)&&(this.addFloat32(t),this.slot(e))}addFieldFloat64(e,t,i){(this.force_defaults||t!=i)&&(this.addFloat64(t),this.slot(e))}addFieldOffset(e,t,i){(this.force_defaults||t!=i)&&(this.addOffset(t),this.slot(e))}addFieldStruct(e,t,i){t!=i&&(this.nested(t),this.slot(e))}nested(e){if(e!=this.offset())throw new Error("FlatBuffers: struct must be serialized inline.")}notNested(){if(this.isNested)throw new Error("FlatBuffers: object serialization must not be nested.")}slot(e){this.vtable!==null&&(this.vtable[e]=this.offset())}offset(){return this.bb.capacity()-this.space}static growByteBuffer(e){let t=e.capacity();if(t&3221225472)throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");let i=t<<1,n=ci.allocate(i);return n.setPosition(i-t),n.bytes().set(e.bytes(),i-t),n}addOffset(e){this.prep(4,0),this.writeInt32(this.offset()-e+4)}startObject(e){this.notNested(),this.vtable==null&&(this.vtable=[]),this.vtable_in_use=e;for(let t=0;t<e;t++)this.vtable[t]=0;this.isNested=!0,this.object_start=this.offset()}endObject(){if(this.vtable==null||!this.isNested)throw new Error("FlatBuffers: endObject called without startObject");this.addInt32(0);let e=this.offset(),t=this.vtable_in_use-1;for(;t>=0&&this.vtable[t]==0;t--);let i=t+1;for(;t>=0;t--)this.addInt16(this.vtable[t]!=0?e-this.vtable[t]:0);let n=2;this.addInt16(e-this.object_start);let r=(i+n)*2;this.addInt16(r);let s=0,o=this.space;e:for(t=0;t<this.vtables.length;t++){let c=this.bb.capacity()-this.vtables[t];if(r==this.bb.readInt16(c)){for(let d=2;d<r;d+=2)if(this.bb.readInt16(o+d)!=this.bb.readInt16(c+d))continue e;s=this.vtables[t];break}}return s?(this.space=this.bb.capacity()-e,this.bb.writeInt32(this.space,s-e)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-e,this.offset()-e)),this.isNested=!1,e}finish(e,t,i){let n=i?4:0;if(t){let r=t;if(this.prep(this.minalign,4+4+n),r.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let s=4-1;s>=0;s--)this.writeInt8(r.charCodeAt(s))}this.prep(this.minalign,4+n),this.addOffset(e),n&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(e,t){this.finish(e,t,!0)}requiredField(e,t){let i=this.bb.capacity()-e,n=i-this.bb.readInt32(i);if(!(this.bb.readInt16(n+t)!=0))throw new Error("FlatBuffers: field "+t+" must be set")}startVector(e,t,i){this.notNested(),this.vector_num_elems=t,this.prep(4,e*t),this.prep(i,e*t)}endVector(){return this.writeInt32(this.vector_num_elems),this.offset()}createSharedString(e){if(!e)return 0;if(this.string_maps||(this.string_maps=new Map),this.string_maps.has(e))return this.string_maps.get(e);let t=this.createString(e);return this.string_maps.set(e,t),t}createString(e){if(!e)return 0;let t;if(e instanceof Uint8Array)t=e;else{t=[];let i=0;for(;i<e.length;){let n,r=e.charCodeAt(i++);if(r<55296||r>=56320)n=r;else{let s=e.charCodeAt(i++);n=(r<<10)+s+(65536-(55296<<10)-56320)}n<128?t.push(n):(n<2048?t.push(n>>6&31|192):(n<65536?t.push(n>>12&15|224):t.push(n>>18&7|240,n>>12&63|128),t.push(n>>6&63|128)),t.push(n&63|128))}}this.addInt8(0),this.startVector(1,t.length,1),this.bb.setPosition(this.space-=t.length);for(let i=0,n=this.space,r=this.bb.bytes();i<t.length;i++)r[n++]=t[i];return this.endVector()}createLong(e,t){return Xe.create(e,t)}createObjectOffset(e){return e===null?0:typeof e=="string"?this.createString(e):e.pack(this)}createObjectOffsetList(e){let t=[];for(let i=0;i<e.length;++i){let n=e[i];if(n!==null)t.push(this.createObjectOffset(n));else throw new Error("FlatBuffers: Argument for createObjectOffsetList cannot contain null.")}return t}createStructOffsetList(e,t){return t(this,e.length),this.createObjectOffsetList(e),this.endVector()}};var ju={};function Hr(l,e){ju[l]=e}function Bu(l){let e=l.getBufferIdentifier(),t=ju[e];return t(l)}function Fu(l){return typeof l.guid=="function"?l.guid():null}var bc=vl(gc(),1);var pa=class{get isHost(){return this._host!==void 0}_host;_client;_clientData;constructor(){this.onEnable()}onEnable(){let e="HOST-5980e65c-8438-453e-8b35-f13c736dcd81";this.trySetupHost(e)}trySetupHost(e){let t=new bc.default(e);t.on("error",i=>{console.error(i),this._host=void 0,this.trySetupClient(e)}),t.on("open",i=>{this._host=new yc(t)})}trySetupClient(e){this._client=new bc.default,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",i=>{console.log("<<",i)})})}},vc=class{_peer;constructor(e){this._peer=e}};var yc=class extends vc{get isHost(){return!0}_connections=[];constructor(e){super(e),console.log("I AM THE HOST"),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){let t=this._connections.map(i=>i.metadata?.id).filter(i=>i!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(let t in this._peer.connections){let i=this._peer.connections[t];if(!!i)if(Array.isArray(i))for(let n of i)!n||n.send(e);else console.warn(i)}}}};var Ec="wss://needle-tiny-starter.glitch.me/socket",mt=!!N("debugnet"),fa=!!(mt||N("debugowner"));var vn=class{guid;connection;get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}_hasOwnership=!1;_isOwned=void 0;_gainSubscription;_lostSubscription;_hasOwnerResponse;constructor(e,t){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)}_isWaitingForOwnershipResponseCallback=null;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.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(fa&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let i=0,n=()=>{if(i++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):n()},100)};n()})}requestOwnership(){return fa&&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.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListening("gained-ownership",this._gainSubscription),this.connection.stopListening("lost-ownership",this._lostSubscription),this.connection.stopListening("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(fa&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(fa&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}};var ma=class{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new pa),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return mt}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}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}_usersInRoomCopy=[];usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(let t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){this.connect(),mt&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},0)}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,i=2){if(t===null&&(t={}),i===2){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,i)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendBinary(e){mt&&console.log("<< bin",e.length),this._ws?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._ws)return;this._defaultMessagesBufferArray.length=0;let e=Object.keys(this._defaultMessagesBuffer).length;for(let i in this._defaultMessagesBuffer){let n=this._defaultMessagesBuffer[i];if(e<=1){this.sendWithWebsocket(n.key,n.value,3);break}let r=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(r)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&mt&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;let t=JSON.stringify(this._defaultMessagesBufferArray);this._ws?.send(t)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){if(!t||!this._listeners[e])return;let i=this._listeners[e].indexOf(t);i>=0&&this._listeners[e].splice(i,1)}beginListenBinrary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;let i=this._listenersBinary[e].indexOf(t);i>=0&&this._listenersBinary[e].splice(i,1)}connect(){if(this.connected)return;mt&&console.log("connecting");let t=O.findObjectOfType(pt,this.context,!1)?.getWebsocketUrl();t&&(Ec=t),this.connectWebsocket()}_listeners={};_listenersBinary={};connected=!1;channelId;_connectionId=null;_isConnectingToWebsocket=!1;_ws;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;connectWebsocket(){if(this._isConnectingToWebsocket)return;this._isConnectingToWebsocket=!0,console.log("Connecting to "+Ec);let e=new nv(Ec).onOpen(()=>{this._ws=e,this._isConnectingToWebsocket=!1,this.connected=!0,console.log("Connected to websocket"),this.onSendQueued(0)}).onClose(t=>{this.connected=!1,this._isInRoom=!1}).onError((t,i)=>{console.error(t,i)}).onMessage(this.onMessage.bind(this)).onRetry(()=>{console.log("websocket connection retry")}).build()}onMessage(e,t){let i=t.data;try{if(typeof i!="string"){i.size&&this.handleIncomingBinaryMessage(i);return}let n=JSON.parse(i);if(Array.isArray(n))for(let r of n)this.handleIncomingStringMessage(r);else this.handleIncomingStringMessage(n);return}catch{mt&&i==="pong"&&console.log("<<",i)}}async handleIncomingBinaryMessage(e){let t=await e.arrayBuffer();var i=new Uint8Array(t);let n=new ci(i),r=n.getBufferIdentifier(),s=this._listenersBinary[r],o=Bu(n),c=Fu(o);if(c&&typeof c=="string"&&(this._state[c]=o),!s)return;let d=o??n;for(let a of s)a(d)}handleIncomingStringMessage(e){if(mt&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){let s=e.data;s&&(console.assert(s.id!==void 0&&s.id!==null&&s.id.length>0,"server did not send connection id",s.id),console.log("Your id is: "+s.id,this.context.alias??""),this._connectionId=s.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(mt&&console.log(e),e){this._isInRoom=!0;let s=e;this._currentRoomName=s.room,this._currentRoomViewId=s.viewId,this._currentRoomAllowEditing=s.allowEditing??!0,console.log("Room view id",this._currentRoomViewId),this._currentInRoom.length=0,this._currentInRoom.push(...s.inRoom),mt&&console.log("joined room with",this._currentInRoom,this.context.alias??"")}this.onSendQueued(1);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){let s=e.data;this._currentInRoom.push(s.userId),mt&&console.log(s.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){let s=e.data,o=this._currentInRoom.indexOf(s.userId);o>=0&&(console.log(s.userId+" left",this.context.alias??""),this._currentInRoom.splice(o,1)),s.userId===this.connectionId&&console.log("you left the room")}break;case"ping":case"pong":let r=e.data?.time;r&&(this._currentDelay=this.context.time.time-r),mt&&console.log("Current latency: "+this._currentDelay.toFixed(1)+" sec","Clients in room: "+this._currentInRoom?.length);break}let t=this._listeners[e.key];if(t)for(let n of t)n(e.data);let i=e.data;i&&(this._state[i.guid]=i)}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=1){if(!this._ws){let r=this._waitingForSocket[i]||[];r.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=r;return}let n=JSON.stringify(this.toMessage(e,t));mt&&console.log(">>",e),this._ws.send(n)}onSendQueued(e){let t=this._waitingForSocket[e];if(t){for(let i of t)i();t.length=0}}};import*as qt from"three";import{OrbitControls as sv}from"three/examples/jsm/controls/OrbitControls";import{Object3D as rv}from"three";var ji=class extends M{constraintActive=!0;locked=!1;sources=[]};k([A(rv)],ji.prototype,"sources",2);import*as oo from"three";var gt=class extends M{get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){this.controls?.addEventListener("start",e)}autoRotate=!1;autoRotateSpeed=1;enableKeys=!0;enableDamping=!0;dampingFactor=.1;enableZoom=!0;minZoom=0;maxZoom=1/0;enablePan=!0;lookAtConstraint=null;lookAtConstraint01=1;middleClickToFocus=!0;doubleClickToFocus=!0;useSlerp=!1;debugLog=!1;targetLerpSpeed=5;_lookTargetPosition;_controls=null;_cameraObject=null;_lerpToTargetPosition=!1;_lerpCameraToTarget=!1;_cameraTargetPosition=null;_inputs=0;_enableTime=0;awake(){this._lookTargetPosition=new oo.Vector3}onEnable(){this._enableTime=this.context.time.time;let t=O.getComponent(this.gameObject,ne)?.cam;this._controls||(console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t),this._controls=new sv(t,this.context.renderer.domElement)),this._controls&&(this._controls.enableDamping=this.enableDamping,this._controls.enableKeys=this.enableKeys,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,t?.type==="PerspectiveCamera"?(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan)}onDisable(){this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1)}start(){if(this._controls){let e=O.getComponent(this.gameObject,ne);if(e&&!this.setFromTargetPosition()){console.log("NO TARGET");let t=new oo.Vector3(0,0,-1).applyMatrix4(e.cam.matrixWorld);this.setTarget(t,!0)}}this.startCoroutine(this.startRaycastDelayed())}*startRaycastDelayed(){if(yield,!this.setFromTargetPosition()){let e=new je;e.screenPoint=new oo.Vector2(0,0),e.lineThreshold=.1;let t=this.context.physics.raycast(e);t.length>0&&this.setTarget(t[0].point,!0)}}onBeforeRender(){if(!this._controls)return;(this.context.input.getPointerDown(0)||this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2))&&(this._inputs+=1),this._inputs>0&&(this._controls.autoRotate=!1,this._lerpCameraToTarget=!1,this._lerpToTargetPosition=!1),this._inputs=0;let e=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(e||=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3,e?this.setTargetFromRaycast():(this.context.input.getPointerDown(0)||this.context.input.mouseWheelChanged)&&(this._lerpToTargetPosition=!1,this._lerpCameraToTarget=!1),this._lerpToTargetPosition||this._lerpCameraToTarget){let t=this.context.time.deltaTime*this.targetLerpSpeed;this._lerpCameraToTarget&&this._cameraTargetPosition&&this._cameraObject&&(this.useSlerp&&typeof this._cameraObject?.position.slerp=="function"?(this._cameraObject?.position).slerp(this._cameraTargetPosition,t):this._cameraObject?.position.lerp(this._cameraTargetPosition,t),this._cameraObject.position.distanceTo(this._cameraTargetPosition)<.01&&(this._lerpCameraToTarget=!1)),this._lerpToTargetPosition&&(this.lerpTarget(this._lookTargetPosition,t),this._lookTargetPosition.distanceTo(this._controls.target)<.005&&(this._lerpToTargetPosition=!1))}this.lookAtConstraint?.locked&&this.setFromTargetPosition(0,this.lookAtConstraint01),this._controls&&(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!0,this._controls.update())}setCameraTarget(e,t=!1){e?(this._lerpCameraToTarget=!0,this._cameraTargetPosition=e.clone(),t&&this._cameraTargetPosition&&this.controllerObject?.position.copy(this._cameraTargetPosition)):this._lerpCameraToTarget=!1}setFromTargetPosition(e=0,t=1){if(!this._controls)return!1;let i=this.lookAtConstraint?.sources;if(i&&i.length>0){let n=i[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(){if(!this.controls)return;let e=this.context.physics.raycast();for(let t of e)if(t.distance>0&&O.isActiveInHierarchy(t.object)){if(this._lookTargetPosition.copy(t.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;let i=q(this.context.mainCamera);this._cameraTargetPosition=i.clone().sub(this.controls.target).add(this._lookTargetPosition)}break}}};k([A(ji)],gt.prototype,"lookAtConstraint",2);import{Color as ov}from"three";var we=class extends ov{alpha=1;constructor(e,t,i,n){super(e,t,i),this.alpha=n}clone(){let e=super.clone();return e.alpha=this.alpha,e}copy(e){return super.copy(e),"alpha"in e&&typeof e.alpha=="number"&&(this.alpha=e.alpha),typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){let i=e;return i.alpha&&(this.alpha=Q.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}multiply(e){let t=e;return t.alpha&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}};import{PerspectiveCamera as av}from"three";var zu=N("debugcam"),ne=class extends M{get aspect(){return this._cam instanceof av?this._cam.aspect:this.context.domWidth/this.context.domHeight}get fieldOfView(){return this._fov}set fieldOfView(e){let t=this._fov!=e;this._fov=e,t&&this._cam&&this._cam instanceof qt.PerspectiveCamera&&(this._cam.fov=this._fov,this._cam.updateProjectionMatrix())}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){let t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&t&&(this._cam.near=e,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(e){let t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&t&&(this._cam.far=e,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera()}orthographic=!1;orthographicSize=5;ARBackgroundAlpha=0;_nearClipPlane=.1;_farClipPlane=1e3;get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){if(!!e){if(this._backgroundColor)this._backgroundColor.copy(e);else{if(!e.clone)return;this._backgroundColor=e.clone()}this.applyClearFlagsIfIsActiveCamera()}}_backgroundColor;_fov=60;_cam=null;_clearFlags=2;_skybox;get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}awake(){this.sourceId||console.warn("Camera has no source - the camera should be exported inside a gltf",this.name)}onEnable(){zu&&console.log(this),this.buildCamera(),this.tag=="MainCamera"&&this.context.setCurrentCamera(this),this.applyClearFlagsIfIsActiveCamera()}buildCamera(){if(this._cam)return;let e=this.gameObject.isCamera,t=null;if(e?t=this.gameObject:t=this.gameObject.children[0],t&&t.isCamera)t.type==="PerspectiveCamera"&&(t.fov=this._fov,t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new qt.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),t.fov=this.fieldOfView;else{let i=this.orthographicSize*100;t=new qt.OrthographicCamera(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,this._nearClipPlane,this._farClipPlane)}this._cam=t,this.layer===0&&this._cam.layers.enableAll(),this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){if(this._cam&&this.context.mainCameraComponent===this)switch(this._clearFlags){case 1:if(this.context.isInXR&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}this.enableSkybox();break;case 2:if(this.backgroundColor){let e=this.backgroundColor.alpha;this.context.isInXR&&(e=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this.backgroundColor,e)}break;case 4:this.context.scene.background=null,this.context.renderer.setClearColor(0,0);break}}enableSkybox(){this._skybox||(this._skybox=new wc(this)),this._skybox.enable()}};k([A()],ne.prototype,"fieldOfView",1),k([A()],ne.prototype,"nearClipPlane",1),k([A()],ne.prototype,"farClipPlane",1),k([A()],ne.prototype,"clearFlags",1),k([A()],ne.prototype,"orthographic",2),k([A()],ne.prototype,"orthographicSize",2),k([A()],ne.prototype,"ARBackgroundAlpha",2),k([A(we)],ne.prototype,"backgroundColor",1);var wc=class{_camera;_skybox;get context(){return this._camera?.context}constructor(e){this._camera=e}enable(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?(zu&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=qt.sRGBEncoding,this._skybox.mapping=qt.EquirectangularReflectionMapping,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this)}};function Gu(l){let e="created/implictly",t=new qt.Object3D;l.add(t);let i=O.addNewComponent(t,ne,!1);i.sourceId=e;let n=O.addNewComponent(t,gt,!1);return n.sourceId=e,i}import{EffectComposer as TE}from"three/examples/jsm/postprocessing/EffectComposer.js";import{RenderPass as RE}from"three/examples/jsm/postprocessing/RenderPass";import{AnimationClip as lv,MathUtils as cv}from"three";var jr=class{_name;get name(){return this._name}_nameHash;get nameHash(){return this._nameHash}_normalizedTime;get normalizedTime(){return this._normalizedTime}_length;get length(){return this._length}_speed;get speed(){return this._speed}constructor(e,t,i,n){this._name=e.name,this._nameHash=e.hash,this._normalizedTime=t,this._length=i,this._speed=n}};function Vu(l,e){return{name:"",isLooping:!1,guid:e?.generateUUID()??cv.generateUUID(),index:-1,clip:new lv(l,1,[])}}import{AnimationClip as mv,AnimationMixer as gv,AxesHelper as bv,Euler as Xu,LoopOnce as vv,Quaternion as Xt,Vector3 as co}from"three";import*as _a from"three";var _c=class{_types={};add(e,t){let i=this._types[e];i===void 0?this._types[e]=t:i!==t&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",e)}get(e){return this._types[e]}},D=new _c;var di=N("gizmos"),Ie=N("debugextension");var ba=N("debugresolvedependencies"),dv=[{prefix:"nodes/",dependencyName:"node"},{prefix:"meshes/",dependencyName:"mesh"},{prefix:"materials/",dependencyName:"material"},{prefix:"textures/",dependencyName:"texture"},{prefix:"animations/",dependencyName:"animation"}];async function Br(l,e){ba&&console.log(l,e);let t=[];Tc(dv,l,e,t);let i=await Promise.all(t);return typeof e=="string"&&i.length===1?i[0]:i}function Tc(l,e,t,i){if(typeof t=="object"&&t!==void 0&&t!==null)for(let n of Object.keys(t)){let r=t[n];if(typeof r=="string"){let s=Wu(e,r);if(s!==null)typeof s.then=="function"?i.push(s.then(o=>t[n]=o)):t[n]=s;else for(let o of l){let c=Rc(o.prefix,r);if(c>=0){ba&&console.log(o,c,o.dependencyName),i.push(e?.getDependency(o.dependencyName,c).then(d=>(t[n]=d,d)));break}}}else if(Array.isArray(r))for(let s=0;s<r.length;s++){let o=r[s],c=Wu(e,o);if(c!==null){typeof c.then=="function"?i.push(c.then(d=>r[s]=d)):r[s]=c;continue}for(let d of l){let a=Rc(d.prefix,o);if(a>=0){ba&&console.log(d,a,d.dependencyName),i.push(e?.getDependency(d.dependencyName,a).then(h=>r[s]=h));break}}typeof o=="object"&&Tc(l,e,o,i)}else typeof r=="object"&&Tc(l,e,r,i)}else typeof t=="string"&&hv(l,e,t,i)}var xc="extensions/";function Wu(l,e){if(l&&l.plugins&&typeof e=="string"&&e.startsWith(xc)){let t=e.substring(xc.length),i=t.indexOf("/");i>=0&&(t=t.substring(0,i));let n=l.plugins[t];if(Ie&&console.log(t,n),typeof n?.resolve=="function"){let r=e.substring(xc.length+t.length+1);return n.resolve(l,r)}}return null}function hv(l,e,t,i){for(let n of l){let r=Rc(n.prefix,t);if(r>=0)return ba&&console.log(n,r,n.dependencyName),i.push(e?.getDependency(n.dependencyName,r).then(s=>s)),!0}return!1}function Rc(l,e){if(typeof e=="string"&&e.startsWith(l)){let t=e.substring(l.length),i=Number.parseInt(t);if(i>=0)return i}return-1}var Cc="NEEDLE_persistent_assets";function Uu(l){return l?.___persistentAsset===!0}var va=class{get name(){return Cc}parser;constructor(e){this.parser=e}async afterRoot(e){if(!this.parser?.json?.extensions)return;let t=this.parser.json.extensions[Cc];if(!t)return;Ie&&console.log(t);let i=new Array;for(let n of t?.assets){let r=Br(this.parser,n);r&&i.push(r)}await Promise.all(i)}resolve(e,t){let i=Number.parseInt(t);if(i>=0){Ie&&console.log(t);let n=e.json.extensions[Cc];if(n){let r=n?.assets[i];if(r&&typeof r=="object"){r.___persistentAsset=!0;let s=r.__type;if(s){let o=D.get(s)}}return r}}return null}};var tr=N("debugserializer"),Sc=class{register(e,t){if(this.typeMap[e]!==void 0){if(this.typeMap[e]===t)return;console.warn("Type "+e+" is already registered",t,this.typeMap[e])}tr&&console.log("Register type serializer for "+e,t),this.typeMap[e]=t}typeMap={};getSerializer(e){if(!!e)return this.typeMap[e]}getSerializerForConstructor(e,t=0){if(t>20)return;if(!e||!e.constructor){tr&&console.log("invalid type");return}let i=e.name??e.constructor?.name;if(!i){tr&&console.log("invalid name",i);return}let n=this.getSerializer(i);if(n!==void 0)return tr&&console.log("FOUND "+i,e.name,e.constructor.name,n,this.typeMap),n;let r=Object.getPrototypeOf(e);if(!(r.prototype||r.constructor)){tr&&console.warn("No prototype for "+i,e,e.name,e.prototype,e.constructor.name);return}let o=r.prototype??r.constructor;if(o!==e){let c=this.getSerializerForConstructor(o,++t);if(c){tr&&console.log("FOUND "+o.constructor.name,o.name,o,c);let d=o.name??o.constructor.name;d==="Function"?console.error("Registering Function is not allowed, something went wrong",e,o,c):this.register(d,c)}return c}}},Ea=new Sc,Bi=class{constructor(e){if(Array.isArray(e))for(let t of e)Ea.register(t.name,this);else Ea.register(e.name,this)}},Fr=class{root;gltf;gltfId;object;target;nodeId;nodeToObject;objectToNode;context;path;constructor(e){this.root=e}};function Oc(l,e){let t=l.$serializedTypes;if(t===void 0)return null;let i={};for(let n in t){let r=l[n];if(r!=null&&typeof r=="object"){let s=Ea.getSerializerForConstructor(r);if(s){i[n]=s.onSerialize(r,e);continue}}i[n]=r}return i.name=l.constructor.name,typeof l.guid=="string"&&(i.guid=l.guid),i}var ya=[];function qu(l,e){if(!l)return e;typeof l.$serializedTypes=="object"&&(e||(e={}),Object.assign(e,l.$serializedTypes));let t=Object.getPrototypeOf(l);return qu(t,e)}function ao(l,e,t){if(!l)return!1;if(t.target=l,l.onBeforeDeserialize!==void 0){let r=l.onBeforeDeserialize(e,t);if(typeof r=="boolean")return r}let i=qu(l);if(e){if(typeof e.guid=="string"&&(l.guid=e.guid),i)for(let r in i){let s=i[r],o=e[r];if(t.path=r,s===null)l[r]=o;else{let c=function(d){let h=d.type;return h?Pc(o,h,t,void 0,l[r]):Pc(o,d,t,void 0,l[r])};var n=c;if(l.onBeforeDeserializeMember!==void 0&&l.onBeforeDeserializeMember(r,o,t)===!0)continue;if(Array.isArray(s))for(let d=0;d<s.length;d++){let a=s[d],h=c(a);if(h!==void 0||d===s.length-1){l[r]=h;break}}else l[r]=c(s);ya.length=0,l.onAfterDeserializeMember!==void 0&&l.onAfterDeserializeMember(r,o,t)}}uv(l,e)}return l.onAfterDeserialize!==void 0&&l.onAfterDeserialize(e,t),t.path=void 0,!0}function uv(l,e){for(let i of Object.keys(e)){let n=e[i];if(typeof n=="object"&&n!==null&&n!==void 0){let r=l[i];if(!r){tr&&console.log(i,"is undefined on",l);continue}for(let s of Object.keys(n))r[s]===void 0&&t(n[s])&&!t(r)&&(r[s]=n[s])}}function t(i){switch(typeof i){case"number":case"string":case"boolean":return!0}return!1}}function Pc(l,e,t,i,n){let r=typeof e=="function"&&e.prototype===void 0,s=e;if(r)try{if(s=e?.call(e,n),r=!1,s==null)return}catch(a){console.error("Error in callback",a,l)}if(!r&&n instanceof s)return n;if(n&&typeof n=="object"&&Uu(n)){if(n.__concreteInstance)return n.__concreteInstance;let a=n;if(!a.$serializedTypes&&s.prototype.$serializedTypes&&(a.$serializedTypes=s.prototype.$serializedTypes),a.$serializedTypes&&ao(a,l,t),n&&s!==void 0)try{let h=new s;Ie&&console.log("Create concrete instance for persistent asset",n,"instance:",h),lo(h,n),n.__concreteInstance=h,n=h}catch(h){console.error("Error creating instance or creating values on instance",h,n,s)}return n}if(i||(i={serializer:Ea.getSerializerForConstructor(s)}),Array.isArray(l)){let a=[];for(let h=0;h<l.length;h++){let u=l[h],g=Pc(u,e,t,i,u);a.push(g)}return a}let o=i.serializer;if(o)return o.onDeserialize(l,t);let c;l&&(l.isMaterial||l.isTexture||l.isObject3D)?c=l:c=new s(...pv(l));let d=c;return d.$serializedTypes&&ao(d,l,t),c}function pv(l){if(ya.length=0,typeof l=="object"&&l!==null&&l!==void 0)for(let e of Object.keys(l))ya.push(l[e]);return ya}function lo(l,e){if(e==null||l==null)return;let t=!1;for(let i of Object.keys(e)){let n=fv(l,i);t&&n===void 0||(!n||n.writable===!0||n?.set!==void 0)&&(l[i]=e[i])}}function fv(l,e){let t;do t=Object.getOwnPropertyDescriptor(l,e);while(!t&&(l=Object.getPrototypeOf(l)));return t}var yn=N("debuganimatorcontroller"),Ac=N("debugrootmotion"),Yt=class{Play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}let s=this.model.layers[t].stateMachine;for(let o of s.states)if(o.name===e||o.hash===e){yn&&console.log("transition to ",o),this.transitionTo(o,n,i);return}console.warn("Could not find "+e+" to play")}Reset(){this.setStartTransition()}SetBool(e,t){let i=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[i]===e).forEach(n=>n.value=t)}GetBool(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(i=>i[t]===e)?.value??!1}SetFloat(e,t){let i=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[i]===e).forEach(n=>n.value=t)}GetFloat(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(i=>i[t]===e)?.value??0}SetInteger(e,t){let i=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[i]===e).forEach(n=>n.value=t)}GetInteger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(i=>i[t]===e)?.value??0}SetTrigger(e){yn&&console.log("SET TRIGGER",e);let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[t]===e).forEach(i=>i.value=!0)}ResetTrigger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[t]===e).forEach(i=>i.value=!1)}IsInTransition(){return this._activeStates.length>1}SetSpeed(e){this._speed=e}FindState(e){if(!e)return null;for(let t of this.model.layers)for(let i of t.stateMachine.states)if(i.name===e)return i;return null}normalizedStartOffset=0;_speed=1;animator;model;get context(){return this.animator?.context}bind(e){this.animator=e,this._mixer=new gv(this.animator.gameObject),this.createActions(this.animator)}clone(){let e=Vs(this.model,(i,n,r)=>r==null?!0:!(r.type==="Object3D"||r.isObject3D===!0||r?.constructor?.name==="AnimationAction"||r.tracks!==void 0));return console.assert(e!==this.model),new Yt(e)}update(){if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates();let e=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&this.rootMotionHandler?.onBeforeUpdate(),this._mixer.update(e),this.animator.applyRootMotion&&this.rootMotionHandler?.onAfterUpdate()}_mixer;_activeState;constructor(e){this.model=e,yn&&console.log(this)}_activeStates=[];updateActiveStates(){for(let e=0;e<this._activeStates.length;e++){let t=this._activeStates[e],i=t.motion;if(!i.action)this._activeStates.splice(e,1),e--;else{let n=i.action;n.getEffectiveWeight()<=0&&!n.isRunning()&&(yn&&console.debug("REMOVE",t.name,n.getEffectiveWeight(),n.isRunning(),n.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(let e of this.model.layers){let t=e.stateMachine,i=t.states[t.defaultState];this.transitionTo(i,0,this.normalizedStartOffset)}}evaluateTransitions(){let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}let t=this._activeState,i=t.motion.action,n=0;for(let s of t.transitions){if(++n,!s.hasExitTime&&s.conditions.length<=0)continue;let o=!0;for(let c of s.conditions)if(!this.evaluateCondition(c)){o=!1;break}if(!!o){yn&&o&&console.log("All conditions are met",s.conditions,i);for(let c of s.conditions){let d=this.model.parameters.find(a=>a.name===c.parameter);d?.type===9&&(d.value=!1)}if(i){let c=t.motion.clip.duration,d=c<=0?1:i.time/c;if(!s.hasExitTime||d>=s.exitTime&&i.time>=i.getClip().duration){i.clampWhenFinished=!0,yn&&(console.log("transition to "+s.destinationState,s),console.log(i.time,s.exitTime)),this.transitionTo(s.destinationState,s.duration,s.offset);return}}else{this.transitionTo(s.destinationState,s.duration,s.offset);return}break}}let r=!1;if(t.motion.isLooping&&i&&i.time>=i.getClip().duration&&(r=!0,i.reset(),i.time=0,i.play()),!r&&t&&!e&&i&&this.animator&&t.behaviours){let s=i?.getClip().duration,o=i.time/s,c=new jr(this._activeState,o,s,this._speed);for(let d of t.behaviours)d.instance&&d.instance.onStateUpdate?.call(d.instance,this.animator,c,0)}}transitionTo(e,t,i){if(!this.animator)return;let n=0;if(typeof e=="number"&&(e==-1&&(e=this.model.layers[n].stateMachine.defaultState),e=this.model.layers[n].stateMachine.states[e]),!e?.motion||!e.motion.clip)return;let r=this._activeState===e;if(r){let d=e.motion;!d.action_loopback&&d.clip&&(this._mixer.uncacheAction(d.clip,this.animator.gameObject),d.action_loopback=this.createAction(d.clip))}if(this._activeState?.behaviours&&this._activeState.motion.action){let d=this._activeState?.motion.clip.duration,a=this._activeState.motion.action.time/d,h=new jr(this._activeState,a,d,this._speed);for(let u of this._activeState.behaviours)u.instance?.onStateExit?.call(u.instance,this.animator,h,n)}let s=this._activeState?.motion.action;s&&s.fadeOut(t),r&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=s);let o=this._activeState;this._activeState=e;let c=e.motion?.action;if(c){i=Math.max(0,Math.min(1,i)),c.isRunning()&&c.stop(),c.reset(),c.timeScale=this._speed,c.enabled=!0;let d=e.motion.clip.duration;if(c.time=i*d,c.clampWhenFinished=!0,c.setLoop(vv,0),t>0?c.fadeIn(t):c.setEffectiveWeight(1),c.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(c),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){let a=new jr(e,i,d,this._speed);for(let h of this._activeState.behaviours)h.instance?.onStateEnter?.call(h.instance,this.animator,a,n)}}else console.warn("No action",e.motion,this);yn&&console.log("TRANSITION FROM "+o?.name+" TO "+e.name,t,s,c,c?.getEffectiveTimeScale(),c?.getEffectiveWeight(),c?.isRunning(),c?.isScheduled(),c?.paused)}createAction(e){if(this._mixer.uncacheClip(e),this.animator?.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new kc(this));let t=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,t,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){let t=this.model.parameters.find(i=>i.name===e.parameter);if(!t)return!1;switch(e.mode){case 1:return t.value===!0;case 2:return t.value===!1;case 3:return t.value>e.threshold;case 4:return t.value<e.threshold;case 6:return t.value===e.threshold;case 7:return t.value!==e.threshold}return!1}createActions(e){for(let t of this.model.layers){let i=t.stateMachine;for(let n=0;n<i.states.length;n++){let r=i.states[n];if(r.motion||(r.motion=Vu(r.name)),this.animator&&r.motion.clips){let s=r.motion.clips?.find(o=>o.node.name===this.animator?.gameObject?.name);r.motion.clip=s?.clip}if(!r.motion.clip){let s=new mv;r.motion.clip=s}if(r.motion?.clip){let s=r.motion.clip,o=this.createAction(s);r.motion.action=o}if(r.behaviours&&Array.isArray(r.behaviours))for(let s of r.behaviours){if(!s?.typeName)continue;let o=D.get(s.typeName),c=new o;c.isStateMachineBehaviour&&(c._context=this.context??void 0,lo(c,s.properties),s.instance=c),yn&&console.log("Created animator controller behaviour",r.name,s.typeName,s.properties,c)}}}}*enumerateActions(){for(let e of this.model.layers){let t=e.stateMachine;for(let i=0;i<t.states.length;i++){let n=t.states[i];n?.motion&&(n.motion.action&&(yield n.motion.action),n.motion.action_loopback&&(yield n.motion.action_loopback))}}}rootMotionHandler},wa=class{track;createdInterpolant;originalEvaluate;customEvaluate;constructor(e,t){this.track=e;let i=e,n=i.createInterpolant.bind(e);i.createInterpolant=()=>(i.createInterpolant=n,this.createdInterpolant=n(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=r=>{if(!this.originalEvaluate)return;let s=this.originalEvaluate(r);return t(r,s)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}evaluate(e){this.customEvaluate&&this.customEvaluate(e)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}},Re=class{set action(e){this._action=e}get action(){return this._action}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new co;rotationChange=new Xt;constructor(e,t,i,n,r){if(this.context=e,this.root=t,this.clip=i,Re.firstKeyframeRotation[i.uuid]||(Re.firstKeyframeRotation[i.uuid]=new _a.Quaternion),r){let s=r.values;Re.firstKeyframeRotation[i.uuid].set(s[0],s[1],s[2],s[3])}Re.spaceRotation[i.uuid]||(Re.spaceRotation[i.uuid]=new Xt),Re.effectiveSpaceRotation[i.uuid]||(Re.effectiveSpaceRotation[i.uuid]=new Xt),Re.clipOffsetRotation[i.uuid]=new Xt,r&&Re.clipOffsetRotation[i.uuid].set(r.values[0],r.values[1],r.values[2],r.values[3]).invert(),this.handlePosition(i,n),this.handleRotation(i,r)}onStart(e){if(e.getClip()!==this.clip)return;let t=Re.lastObjRotation[this.root.uuid];Re.spaceRotation[this.clip.uuid].copy(t);{let i=new _a.Euler().setFromQuaternion(t);console.log("START",this.clip.name,Q.toDegrees(i.y))}}getClipRotationOffset(){return Re.clipOffsetRotation[this.clip.uuid]}handlePosition(e,t){if(t){let i=this.root;Ac&&i.add(new bv),Re.lastObjPosition[i.uuid]||(Re.lastObjPosition[i.uuid]=new co);let n=new co,r=new co,s=0;this.positionWrapper=new wa(t,(o,c)=>{let d=this.action.getEffectiveWeight();if(Ac&&i.position.length()>8&&i.position.set(0,i.position.y,0),o>s){n.set(c[0],c[1],c[2]),n.sub(r),n.multiplyScalar(d),n.applyQuaternion(this.getClipRotationOffset());let a=this.clip.uuid;n.applyQuaternion(Re.spaceRotation[a]),this.positionChange.copy(n)}return r.fromArray(c),s=o,c[0]=0,c[1]=0,c[2]=0,c})}}handleRotation(e,t){if(t){if(Ac){let o=t.values,c=new Xu().setFromQuaternion(new Xt(o[0],o[1],o[2],o[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",Q.toDegrees(c.y));let d=t.values.length-4,a=new Xt().set(o[d],o[d+1],o[d+2],o[d+3]),h=new Xu().setFromQuaternion(a);console.log(e.name,t.name,"LAST ROTATION IN TRACK",Q.toDegrees(h.y))}let i=this.root;Re.lastObjRotation[i.uuid]||(Re.lastObjRotation[i.uuid]=new Xt);let n=0,r=new Xt,s=new Xt;this.rotationWrapper=new wa(t,(o,c)=>(o>n&&(s.set(c[0],c[1],c[2],c[3]),r.invert(),s.multiply(r),this.rotationChange.copy(s)),r.fromArray(c),n=o,c[0]=0,c[1]=0,c[2]=0,c[3]=1,c))}}onBeforeUpdate(){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(){let e=this.action.getEffectiveWeight();this.positionChange.multiplyScalar(e),this.rotationChange.slerp(Re.identityQuaternion,1-e)}},Qt=Re;z(Qt,"lastObjPosition",{}),z(Qt,"lastObjRotation",{}),z(Qt,"firstKeyframeRotation",{}),z(Qt,"spaceRotation",{}),z(Qt,"effectiveSpaceRotation",{}),z(Qt,"clipOffsetRotation",{}),z(Qt,"identityQuaternion",new Xt);var kc=class{controller;handler=[];root;constructor(e){this.controller=e}createClip(e,t,i){this.root=t;let n="";t&&"name"in t&&(n=t.name);let r=this.findRootTrack(i,".position"),s=this.findRootTrack(i,".quaternion"),o=new Qt(this.controller.context,t,i,r,s);this.handler.push(o);let c=e.clipAction(i);return o.action=c,c}onStart(e){for(let t of this.handler)t.onStart(e)}onBeforeUpdate(){for(let e of this.handler)e.onBeforeUpdate()}summedPosition=new co;summedRotation=new Xt;onAfterUpdate(){this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(let e of this.handler)e.onAfterUpdate(),this.summedPosition.add(e.positionChange),this.summedRotation.multiply(e.rotationChange);this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation),Qt.lastObjRotation[this.root.uuid].copy(this.root.quaternion)}findRootTrack(e,t){let i=e.tracks;for(let n of i)if(n.name.endsWith(t))return n;return null}};var yv=N("debuganimator"),bt=class extends M{applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof Yt?this._animatorController=e:this._animatorController=new Yt(e):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}Play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){this.runtimeAnimatorController?.Play(e,t,i,n)}Reset(){this._animatorController?.Reset()}SetBool(e,t){this.runtimeAnimatorController?.SetBool(e,t)}GetBool(e){return this.runtimeAnimatorController?.GetBool(e)??!1}SetFloat(e,t){this.runtimeAnimatorController?.SetFloat(e,t)}GetFloat(e){return this.runtimeAnimatorController?.GetFloat(e)??-1}SetInteger(e,t){this.runtimeAnimatorController?.SetInteger(e,t)}GetInteger(e){return this.runtimeAnimatorController?.GetInteger(e)??-1}SetTrigger(e){this.runtimeAnimatorController?.SetTrigger(e)}ResetTrigger(e){this.runtimeAnimatorController?.ResetTrigger(e)}IsInTransition(){return this.runtimeAnimatorController?.IsInTransition()??!1}SetSpeed(e){e!==this.speed&&(this.speed=e,this._animatorController?.SetSpeed(e))}set minMaxSpeed(e){this.speed=Q.lerp(e.x,e.y,Math.random())}set minMaxOffsetNormalized(e){this.normalizedStartOffset=Q.lerp(e.x,e.y,Math.random()),this.runtimeAnimatorController&&(this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset)}speed=1;normalizedStartOffset=0;_animatorController=null;awake(){if(!!this.gameObject){if(this.runtimeAnimatorController){let e=this.runtimeAnimatorController.clone();console.assert(this.runtimeAnimatorController!==e),this.runtimeAnimatorController=e,console.assert(this.runtimeAnimatorController===e),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.SetSpeed(this.speed),this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset}yv&&console.log("ANIMATOR",this.name,this)}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.Reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}};k([A()],bt.prototype,"applyRootMotion",2),k([A()],bt.prototype,"hasRootMotion",2),k([A()],bt.prototype,"keepAnimatorControllerStateOnDisable",2),k([A()],bt.prototype,"runtimeAnimatorController",1);import*as Nr from"three";var Zt=class extends M{playAutomatically=!0;randomStartTime=!0;_tempAnimationClipBeforeGameObjectExisted=null;get clip(){return this.animations?.length?this.animations[0]:null}set clip(e){if(!this.gameObject){this._tempAnimationClipBeforeGameObjectExisted=e;return}!e||(this.gameObject.animations||(this.gameObject.animations=[]),this.gameObject.animations.push(e))}set animations(e){this.gameObject.animations=e}get animations(){return this.gameObject.animations}get currentAction(){return this._currentActions[0]}get currentActions(){return this._currentActions}mixer=void 0;get actions(){return this._actions}set actions(e){this._actions=e}_actions=[];_currentActions=[];_handles=[];awake(){this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.playAutomatically&&this.init()}onEnable(){if(this.playAutomatically&&this.actions.length>0&&this.currentActions.length<=0){let e=Math.floor(Math.random()*this.actions.length);this.play(e)}}start(){this.randomStartTime&&this.currentAction&&(this.currentAction.time=Math.random()*this.currentAction.getClip().duration)}update(){if(!!this.mixer){this.mixer.update(this.context.time.deltaTime);for(let e of this._handles)e._update();this._handles?.length>0&&he.markDirty(this.gameObject)}}getAction(e){return this.actions?.find(t=>t.getClip().name===e)}play(e,t){if(this.init(),!this.mixer)return;let i=e;if(typeof e=="number"){if(e>=this.animations.length)return;i=this.animations[e]}else typeof e=="string"&&(i=this.animations.find(r=>r.name===e));if(!i){console.error("Could not find clip",e);return}for(let r of this.actions)if(r.getClip()===i)return this.internalOnPlay(r,t);let n=this.mixer.clipAction(i);return this.actions.push(n),this.internalOnPlay(n,t)}internalOnPlay(e,t){var i=this.currentAction;if(i===e&&i.isRunning()&&i.time<i.getClip().duration){let s=this.tryFindHandle(e);if(s)return s.getPromise()}let n=t?.exclusive??!0;t?.fadeDuration?(n&&i?.fadeOut(t.fadeDuration),e.fadeIn(t.fadeDuration)):n&&i?.stop(),e.reset(),e.enabled=!0,e.time=0,e.timeScale=1,t?.clampWhenFinished&&(e.clampWhenFinished=!0),t?.startTime!==void 0&&(e.time=t.startTime),t?.loop!==void 0&&(e.loop=t.loop?Nr.LoopRepeat:Nr.LoopOnce),e.play();let r=new Ic(e,this.mixer,t,s=>{this._handles.splice(this._handles.indexOf(r),1)});return this._handles.push(r),r.getPromise()}tryFindHandle(e){for(let t of this._handles)if(t.action===e)return t}_didInit=!1;init(){if(!this._didInit&&(this._didInit=!0,!!this.gameObject)){this.actions=[],this.mixer=new Nr.AnimationMixer(this.gameObject);for(let e=0;e<this.animations.length;e++){let t=this.mixer.clipAction(this.animations[e]);this.actions.push(t)}}}};k([A()],Zt.prototype,"playAutomatically",2),k([A()],Zt.prototype,"randomStartTime",2);var Ic=class{mixer;action;promise=null;resolve=null;reject=null;_options;_resolveCallback=null;_rejectCallback=null;_loopCallback;_finishedCallback;_resolvedOrRejectedCallback;constructor(e,t,i,n){this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=n,this._options=i}getPromise(){return this.promise?this.promise:(this.promise=new Promise((e,t)=>{this._resolveCallback=e,this._rejectCallback=t,this.resolve=this.onResolve.bind(this),this.reject=this.onReject.bind(this)}),this._loopCallback=this.onLoop.bind(this),this._finishedCallback=this.onFinished.bind(this),this.mixer.addEventListener("loop",this._loopCallback),this.mixer.addEventListener("finished",this._finishedCallback),this.promise)}_update(){!this._options||this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._resolveCallback?.call(this,this.action)}onReject(e){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._rejectCallback?.call(this,e)}onLoop(e){}onFinished(e){e.action===this.action&&this.onResolve()}dispose(){this._loopCallback&&this.mixer.removeEventListener("loop",this._loopCallback),this._finishedCallback&&this.mixer.removeEventListener("finished",this._finishedCallback),this._loopCallback=void 0,this._finishedCallback=void 0}};import{GLTFLoader as mf}from"three/examples/jsm/loaders/GLTFLoader.js";import*as Qu from"three";var zr=class extends M{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new Qu.Vector3}update(){if(!this.from||!this.to)return;let e=q(this.from).clone(),t=q(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),ie(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(q(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}};var hi=class{time;value;inTangent;inWeight;outTangent;outWeight;weightedMode};k([A()],hi.prototype,"time",2),k([A()],hi.prototype,"value",2),k([A()],hi.prototype,"inTangent",2),k([A()],hi.prototype,"inWeight",2),k([A()],hi.prototype,"outTangent",2),k([A()],hi.prototype,"outWeight",2),k([A()],hi.prototype,"weightedMode",2);var ir=class{keys;get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;let t=null;for(let i of this.keys){if(t&&i.time>e&&e>t.time)return Q.lerp(t.value,i.value,(e-t.time)/(i.time-t.time));t=i}return this.keys[this.keys.length-1].value}};k([A(hi)],ir.prototype,"keys",2);import*as Yu from"three";import*as ho from"three";import{PositionalAudioHelper as Ev}from"three/examples/jsm/helpers/PositionalAudioHelper.js";var xa=class extends EventTarget{context;get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}_isVisible=!0;constructor(e){super(),this.context=e,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}onVisiblityChanged(e){switch(e.target.visibilityState){case"hidden":this._isVisible=!1,this.dispatchEvent(new Event("application-hidden"));break;case"visible":this._isVisible=!0,this.dispatchEvent(new Event("application-visible"));break}}};var at=N("debugaudio");var Be=class extends M{static get userInteractionRegistered(){return Be._didCallBeginWaitForUserInteraction||(Be._didCallBeginWaitForUserInteraction=!0,Be._beginWaitForUserInteraction()),Be._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),Be._didCallBeginWaitForUserInteraction||(Be._didCallBeginWaitForUserInteraction=!0,Be._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);let i=(()=>{if(i!=null&&!Be._userInteractionRegistered){Be._userInteractionRegistered=!0,console.log("registered interaction, can play audio now"),document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i);for(let n of this.callbacks)n();this.callbacks.length=0}}).bind(this);document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)}clip="";playOnAwake=!1;get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}_spatialBlend=0;_minDistance=1;_maxDistance=100;get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&(at&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}_volume=1;rollOffMode=0;_loop=!1;sound=null;helper=null;wasPlaying=!1;audioLoader=null;shouldPlay=!1;_lastClipStartedLoading=null;get Sound(){if(!this.sound&&Be._userInteractionRegistered){let e=O.getComponent(this.context.mainCamera,Jt)??O.findObjectOfType(Jt,this.context);e?.listener&&(this.sound=new ho.PositionalAudio(e.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}_focusCallback;awake(){this.audioLoader=new ho.AudioLoader,this.playOnAwake&&(this.shouldPlay=!0),window.addEventListener("visibilitychange",e=>{switch(document.visibilityState){case"hidden":this.wasPlaying=this.isPlaying,this.pause();break;case"visible":this.wasPlaying&&this.play();break}}),this._focusCallback=()=>{this.enabled&&this.playOnAwake&&!this.isPlaying&&Be._userInteractionRegistered&&this.play()},this.context.application.addEventListener("application-visible",this._focusCallback)}onDestroy(){this.context.application.removeEventListener("application-visible",this._focusCallback)}onEnable(){Be._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Be._beginWaitForUserInteraction(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.loadAndPlay(this.clip)})}onDisable(){this.stop()}lerp=(e,t,i)=>e*(1-i)+t*i;onLoaded(e){at&&console.log("audio buffer loaded"),Be.registerWaitForAllowAudio(()=>{at&&console.log("finished loading",e);let t=this.Sound;if(!t){console.warn("Failed getting sound",this.name);return}t.isPlaying&&t.stop(),t.setBuffer(e),t.loop=this.loop,t.setVolume(this.volume),t.autoplay=this.shouldPlay,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),at&&console.log(this.name,this.shouldPlay,Be.userInteractionRegistered,this),this.shouldPlay&&Be._userInteractionRegistered&&this.play()})}applySpatialDistanceSettings(){let e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;let t=this.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(at&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:break}this.spatialBlend>0?at&&!this.helper&&(this.helper=new Ev(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&(at&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new ho.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){at&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,at&&console.log("load audio",this.clip),this.audioLoader.load(this.clip,this.onLoaded.bind(this),()=>{},console.error)}}play(e=void 0){if(!this.audioLoader||!this.sound||e&&e!==this.clip){this.loadAndPlay(e);return}this.shouldPlay=!0,this._hasEnded=!1,at&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying&&this.sound.play()}pause(){at&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause())}stop(){at&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&(this._lastContextTime=this.sound?.context.currentTime,at&&console.log(this._lastContextTime),this.sound.stop())}_lastContextTime=0;get isPlaying(){return this.sound?.isPlaying??!1}set isPlaying(e){}get time(){return this.sound?.source?this.sound.source?.context.currentTime-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;let t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}_hasEnded=!0;_needUpdateSpatialDistanceSettings=!1;update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,at&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},ue=Be;z(ue,"_didCallBeginWaitForUserInteraction",!1),z(ue,"callbacks",[]),z(ue,"_userInteractionRegistered",!1),k([A()],ue.prototype,"clip",2),k([A()],ue.prototype,"playOnAwake",2),k([A()],ue.prototype,"loop",1),k([A()],ue.prototype,"spatialBlend",1),k([A()],ue.prototype,"minDistance",1),k([A()],ue.prototype,"maxDistance",1),k([A()],ue.prototype,"volume",1),k([A()],ue.prototype,"rollOffMode",2);var Jt=class extends M{get listener(){return this._listener==null&&(this._listener=new Yu.AudioListener),this._listener}_listener=null;awake(){ue.registerWaitForAllowAudio(()=>{let e=this.listener;if(e==null||e.parent)return;let t=O.getComponentInParent(this.gameObject,ne);t?t.cam.add(e):this.gameObject.add(e)})}};import{GLTFLoader as xv}from"three/examples/jsm/loaders/GLTFLoader";import*as Gr from"three";var rp=vl(np(),1),Ta=class{success;filename;hash;size;url;constructor(e,t,i,n){this.success=e,this.filename=t,this.hash=i,this.size=n}};async function sp(l,e){let t=await l.arrayBuffer(),i=op(t),n=l.name.split(".").pop(),r=i+"."+n,s=l.name.split(".").shift();console.assert(s!==void 0);let o={alias:s,filename:r},d=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(o)})).json();if(d.success||console.warn("exists check did fail"),d.exists)return console.log("file already exists",i),new Ta(!0,r,i,l.size);console.log("begin uploading file",s,l.size);let a=new FormData;a.append("file",l);let h={};h.filesize=l.size,s&&(h.alias=s);let g=await(await fetch(e+"/upload/file",{method:"POST",body:a,headers:h})).json();if(g?.success===!1)return g.message!==void 0?console.error("Upload failed:",g.message):console.error("Upload failed"),null;console.assert(g.hash_sum===i,"hash sum did not match","received:",g.hash_sum,"expected:",i),g.success&&console.log("successfully uploaded",i,g.id);let E=new Ta(g.success,r,i,l.size);return E.url=e,E}function op(l){return(0,rp.default)(new Uint8Array(l))}async function Ra(l,e,t,i,n=!1){try{let r=await fetch(i+"/download/file",{method:"POST",body:l});if(r.status!==200)return console.error("download failed",r),null;let s=await r.blob(),o=await s.arrayBuffer();n||console.assert(s.size===t,"size mismatch","expected:",t,"got:",s.size);let c=op(o);return n||console.assert(c===e,"hash mismatch, downloaded file is invalid"),s.arrayBuffer()}catch(r){console.error(r)}return null}async function ap(l,e){let t=await fetch(l),i=t.body?.getReader(),n=t.headers.get("Content-Length"),r=n?parseInt(n):0;if(!i)return null;let s=0,o=[];for(;;){let{done:a,value:h}=await i.read();if(h&&(o.push(h),s+=h.length,e.call(null,new ProgressEvent("progress",{loaded:s,total:r}))),a)break}let c=new Uint8Array(s),d=0;for(let a of o)c.set(a,d),d+=a.length;return c}var uo=N("debugavatar"),nr=class{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(r=>r.layers.set(2))}assignRandomColors(){Fi.assignRandomPlayerColors(this)}},Fi=class{avatarRegistryUrl=null;avatarModelCache=new Map;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){let r=new ye;i=O.instantiate(dn(t,e.scene),r)}}else i=t;if(!i)return null;let n=this.findAvatar(i);return n.assignRandomColors(),n.isValid?(uo&&console.log("[Custom Avatar] valid config",t,uo?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,uo?n:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(uo&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){let n=await fetch("./"+t),r=null;if(n.ok){let o=await n.blob();o&&(r=await o.arrayBuffer())}return!r&&(r=await Ra(t,t,0,"no url here go away",!0),!r)?null:(await Vr(e,r,null,0))?.scene??null}let i=new xv;return Kn(i,e),new Promise((n,r)=>{let s=this.avatarRegistryUrl+"/"+t;i.load(s,async o=>{await Ca(e,s,o),n(o.scene)},o=>{uo&&console.log("[Custom Avatar] "+o.loaded/o.total*100+"% loaded of "+o.total/1024+"kB")},o=>{console.error("[Custom Avatar] Error when loading: "+o),n(null)})})}cacheModel(e,t){}findAvatar(e){let t=e,i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,"head"),r=this.findAvatarPart(i,"left"),s=this.findAvatarPart(i,"right");if(!n){n=t;let c=new Gr.Vector3;new Gr.Box3().setFromObject(n).getSize(c);let d=Math.max(c.x,c.y,c.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+d+" meters! Should be < 0.3m"),d>.3&&n.scale.multiplyScalar(1/d*.3)}return new nr(t,n,r,s)}findAvatarPart(e,t){for(let i of e.children)if(i.name.toLowerCase().indexOf(t)>-1)return i;return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}static assignRandomPlayerColors(e){let t=new Map;function i(n){if(n.type==="Mesh"){let r=n,s=r.material;if(s&&s.name){if(t.has(s.uuid)){let o=t.get(s.uuid);o&&(r.material=o);return}if(s.name.endsWith("_playercolor")||s.name.endsWith("_player_color2")){let o=s.uuid;r.material=s.clone(),r.material.color=new Gr.Color(Math.random(),Math.random(),Math.random()),t.set(o,r.material)}}}}e.head&&e.head.traverse(i),e.leftHand&&e.leftHand.traverse(i),e.rigthHand&&e.rigthHand.traverse(i)}};import{AxesHelper as Tv}from"three";var Ni=class extends M{length=1;depthTest=!0;isGizmo=!0;_axes=null;onEnable(){if(this.isGizmo&&!di)return;this._axes||(this._axes=new Tv(this.length)),this.gameObject.add(this._axes);let e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){!this._axes||this.gameObject.remove(this._axes)}};k([A()],Ni.prototype,"length",2),k([A()],Ni.prototype,"depthTest",2),k([A()],Ni.prototype,"isGizmo",2);import*as cp from"three";var Wr=class extends M{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=q(this.to).clone(),t=q(this.from).clone(),i=e.distanceTo(t),n=e.clone();n.sub(t);let r=t.clone();r.add(e),r.multiplyScalar(.5);let s=q(this.hint).clone();s.sub(r);let o=new cp.Vector3;o.crossVectors(s,n),o.crossVectors(n,o),o.normalize();let c=i*.5,d=Math.max(this.desiredDistance,c),a=Math.sqrt(d*d-c*c),h=o.clone();h.multiplyScalar(a),h.add(r),ie(this.gameObject,h);let u=r.clone();u.sub(o),this.gameObject.lookAt(u)}};import*as zi from"three";import*as ui from"three";var Rv=new ui.BoxGeometry(1,1,1);function Sa(l=null){let e=new ui.Color(l??14540253),t=new ui.EdgesGeometry(Rv);return new ui.LineSegments(t,new ui.LineBasicMaterial({color:e}))}var Sv=N("gizmos"),Pa=class extends M{box=null;testBox=new zi.Box3;_lastMatrixUpdateFrame=-1;isInBox(e){if(!!e){if(this.box||(this.box=new zi.Box3),this.updateBox(!1),e.type==="Mesh")this.testBox.setFromObject(e);else{let t=q(e,Pa._position),i=wh(e,Pa._size);this.testBox.setFromCenterAndSize(t,i)}return this.box?.intersectsBox(this.testBox)}}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){return this.box||(this.box=new zi.Box3),(e||this.context.time.frameCount!=this._lastMatrixUpdateFrame)&&(this._lastMatrixUpdateFrame=this.context.time.frameCount,this.box.setFromCenterAndSize(new zi.Vector3(0,0,0),new zi.Vector3(1,1,1)),this.box.applyMatrix4(this.gameObject.matrixWorld)),this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!Sv&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=Sa(e),this.gameObject.add(this._helper)}}},lt=Pa;z(lt,"_position",new zi.Vector3),z(lt,"_size",new zi.Vector3(.01,.01,.01));import*as po from"three";import{FrontSide as dp,DoubleSide as hp}from"three";function Ur(l,e){if(!l)return;let t=l.material;t?.isMaterial===!0&&(t.depthTest=!e.renderOnTop,t.side=e.doubleSided??!0?hp:dp,t.depthWrite=e.depthWrite??!1,t.shadowSide=e.doubleSided?hp:dp,l.castShadow=e.castShadows?e.castShadows:!1,l.receiveShadow=e.receiveShadows?e.receiveShadows:!1);for(let i of l.children)Ur(i,e)}function qr(l,e,t){l[e]===void 0&&console.warn("Field",e,"is undefined on",l);let i=Proxy.revocable(l[e],{set(s,o,c,d){let a=s[o],h=Reflect.set(s,o,c,d);return t(c,a),h}}),n=i.revoke,r=l[e];return i.revoke=()=>{l[e]=r,n()},l[e]=i.proxy,i}function up(l,e,t=3){let i=l.__scheduledActions;i||(i=l.__scheduledActions={});let n=e.name;i[t]||(i[t]={});let r=i[t];if(r[n])return;function*o(){e?.call(l),r[n]=null}let c=l.startCoroutine(o(),t);r[n]=c}var Xr=class extends M{mass=1;set isKinematic(e){this._isKinematic=e,this._body&&(this._body.type=e?G.KINEMATIC:G.DYNAMIC)}get isKinematic(){return this._isKinematic}_isKinematic=!1;drag=0;angularDrag=1;detectCollision=!0;sleepThreshold=.01;get body(){return this._body===null&&this.initialize(),this._body}_body=null;currentVelocity;_smoothedVelocity;lastWorldPosition;dirty=!0;transformProxy;awake(){this._body=null,this.currentVelocity=new po.Vector3,this._smoothedVelocity=new po.Vector3,this.lastWorldPosition=q(this.gameObject).clone()}start(){this.setBodyFromGameObject()}onEnable(){this._body?this.context.physics.addBody(this.gameObject,this._body):this.initialize(),this.body&&(this.body.wakeUp(),this.gameObject.updateWorldMatrix(!0,!1),this.setBodyFromGameObject()),this.transformProxy=qr(this.gameObject.matrix,"elements",()=>{this.context.physics.isUpdating||(this.dirty=!0)})}onDisable(){this.transformProxy?.revoke(),this._body&&this.context.physics.removeBody(this.gameObject,this._body,!1)}onDestroy(){this._body&&this.context.physics.removeBody(this.gameObject,this._body)}earlyUpdate(){this.dirty&&this.setBodyFromGameObject()}onBeforeRender(){this.updateVelocity()}initialize(){if(this._body)return;let e=new aa;e.drag=this.drag,e.angularDrag=this.angularDrag,e.mass=this.mass,e.kinematic=this.isKinematic,e.physicsEvents=this.detectCollision,e.sleepThreshold=this.sleepThreshold,this._body=this.context.physics.createBody(this.gameObject,e)}wakeUp(){this.body?.wakeUp()}applyForce(e,t){this.body?.applyForce(new _(e.x,e.y,e.z),t?new _(t.x,t.y,t.z):void 0)}getVelocity(){return this.body?Xr.tempPosition.set(this.body?.velocity.x,this.body?.velocity.y,this.body?.velocity.z):Xr.tempPosition.set(0,0,0)}setVelocity(e,t,i){!this.body||(this.body.velocity.x=e/this.context.time.deltaTime,this.body.velocity.y=t/this.context.time.deltaTime,this.body.velocity.z=i/this.context.time.deltaTime)}get smoothedVelocity(){return this._smoothedVelocity}setAngularVelocity(e,t,i){!this.body||(this.body.angularVelocity.x=e/this.context.time.deltaTime,this.body.angularVelocity.y=t/this.context.time.deltaTime,this.body.angularVelocity.z=i/this.context.time.deltaTime)}setBodyFromGameObject(e=null){if(this.dirty=!1,this.body&&this.gameObject&&!this.destroyed){let t=this.worldPosition;this.body.position.set(t.x,t.y,t.z);let i=this.worldQuaternion;if(this.body.quaternion.set(i.x,i.y,i.z,i.w),e){Xr.copyVector3.set(e.x,e.y,e.z),this._smoothedVelocity.lerp(Xr.copyVector3,this.context.time.deltaTime/.1);let n=this._smoothedVelocity;this.body.velocity.x=n.x,this.body.velocity.y=n.y,this.body.velocity.z=n.z}}}updateVelocity(){if(!!this.currentVelocity&&this.body&&this.gameObject){let e=q(this.gameObject);this.currentVelocity.subVectors(e,this.lastWorldPosition),this.lastWorldPosition.copy(e),this._smoothedVelocity.lerp(this.currentVelocity,this.context.time.deltaTime/.1)}}},ce=Xr;z(ce,"tempPosition",new po.Vector3),z(ce,"copyVector3",new po.Vector3),k([A()],ce.prototype,"mass",2),k([A()],ce.prototype,"isKinematic",1),k([A()],ce.prototype,"drag",2),k([A()],ce.prototype,"angularDrag",2),k([A()],ce.prototype,"detectCollision",2),k([A()],ce.prototype,"sleepThreshold",2);import{Vector3 as Oa}from"three";var pi=class extends M{attachedRigidbody=null;isTrigger=!1;_shape=null;awake(){super.awake(),this._shape=null}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(ce))}onDisable(){this._shape}};k([A(ce)],pi.prototype,"attachedRigidbody",2),k([A()],pi.prototype,"isTrigger",2);var En=class extends pi{radius=.5;center=new Oa(0,0,0);onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addSphereCollider(this.gameObject,this.center,this.radius,this.attachedRigidbody))}};k([A()],En.prototype,"radius",2),k([A(Oa)],En.prototype,"center",2);var wn=class extends pi{size;center;onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addBoxCollider(this.gameObject,this.isTrigger,this.center,this.size,this.attachedRigidbody))}};k([A(Oa)],wn.prototype,"size",2),k([A(Oa)],wn.prototype,"center",2);var Qr=class{};var kt=class extends M{canGrab=!0;onPointerClick(e){}},It=class extends M{isUsed=!0;usedBy=null};var rr=class extends lt{},Yr=class extends M{deleteBoxes=[];awake(){this.deleteBoxes=O.findObjectsOfType(rr,this.context)}update(){for(let e of this.deleteBoxes){let t=this.gameObject;e.isInBox(t)===!0&&(O.getComponentInParent(this.gameObject,It)||Sr(this.gameObject,this.context.connection))}}};var sr=class extends M{visibleOn;onEnable(){this.apply()}apply(){this.test()||O.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:Pv()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}};k([A()],sr.prototype,"visibleOn",2);var Aa;function Pv(){if(Aa===!0||Aa===!1)return Aa;let l=!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)))&&(l=!0)}(navigator.userAgent||navigator.vendor||window.opera),Aa=l,l}import*as Gi from"three";var Ce=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(e,t,i,n){return e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var Zr=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Ce).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Ce).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Ce).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,n,r,s,o,c,d,a){return e.prep(4,36),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(d),e.writeFloat32(c),e.prep(4,12),e.writeFloat32(o),e.writeFloat32(s),e.writeFloat32(r),e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var Mt=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new Mt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+4),(t||new Mt).__init(e.readInt32(e.position())+e.position(),e)}guid(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){let e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){let t=this.bb.__offset(this.bb_pos,8);return t?(e||new Zr).__init(this.bb_pos+t,this.bb):null}dontSave(){let e=this.bb.__offset(this.bb_pos,10);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startSyncedTransformModel(e){e.startObject(4)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addFast(e,t){e.addFieldInt8(1,+t,0)}static addTransform(e,t){e.addFieldStruct(2,t,0)}static addDontSave(e,t){e.addFieldInt8(3,+t,0)}static endSyncedTransformModel(e){return e.endObject()}static finishSyncedTransformModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedTransformModelBuffer(e,t){e.finish(t,void 0,!0)}};var _n=N("debugsync"),Jr="STRS";Hr(Jr,Mt.getRootAsSyncedTransformModel);var fi=new ft;function Dc(l,e,t=!0){fi.clear();let i=fi.createString(l);Mt.startSyncedTransformModel(fi),Mt.addGuid(fi,i),Mt.addFast(fi,t);let n=e.worldPosition,r=e.worldEuler,s=e.gameObject.scale;Mt.addTransform(fi,Zr.createTransform(fi,n.x,n.y,n.z,r.x,r.y,r.z,s.x,s.y,s.z));let o=Mt.endSyncedTransformModel(fi);return fi.finish(o,Jr),fi.asUint8Array()}var Qe=class extends M{overridePhysics=!0;interpolatePosition=!0;interpolateRotation=!0;fastMode=!1;syncDestroy=!1;_model=null;_needsUpdate=!0;rb=null;_wasKinematic=!1;_receivedDataBefore=!1;_targetPosition;_targetRotation;_receivedFastUpdate=!1;_shouldRequestOwnership=!1;requestOwnership(){_n&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){return this._model?.hasOwnership??void 0}isOwned(){return this._model?.isOwned}joinedRoomCallback=null;receivedDataCallback=null;awake(){_n&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new Gi.Vector3,this._targetRotation=new Gi.Quaternion,this.lastWorldPos=new Gi.Vector3,this.lastWorldRotation=new Gi.Quaternion,this.rb=O.getComponentInChildren(this.gameObject,ce),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new vn(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen("joined-room",this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinrary(Jr,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Ph(this.guid,this.context.connection),this._model=null,this.context.connection.stopListening("joined-room",this.joinedRoomCallback),this.context.connection.stopListenBinary(Jr,this.receivedDataCallback)}tryGetLastState(){let e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new Gi.Euler;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){_n&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();let t=e.transform();if(t){he.markDirty(this.gameObject,!0);let i=t.position();i&&(this.interpolatePosition&&this._targetPosition?.set(i.x(),i.y(),i.z()),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(i.x(),i.y(),i.z()));let n=t.rotation();n&&(this.tempEuler.set(n.x(),n.y(),n.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&_h(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}receivedUpdate=!1;lastWorldPos;lastWorldRotation;onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){_n&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());let e=this.worldPosition,t=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){let r=e.distanceTo(this.lastWorldPos),s=t.angleTo(this.lastWorldRotation),o=this._model.hasOwnership||this.fastMode?1e-4:.001;(r>o||s>o)&&(this._model.hasOwnership?this._needsUpdate=!0:(_n&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,e.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,t.copy(this.lastWorldRotation),he.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){let s=this._receivedFastUpdate||this.fastMode?.5:.3,o=!1;if(this.interpolatePosition&&this._targetPosition){let c=this.worldPosition;c.lerp(this._targetPosition,s),this.worldPosition=c,o=!0}if(this.interpolateRotation&&this._targetRotation){let c=this.worldQuaternion;c.slerp(this._targetRotation,s),this.worldQuaternion=c,o=!0}o&&he.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(e),this.lastWorldRotation.copy(t),!this._model)return;if(!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership){this.rb&&(this.rb.isKinematic=this._model.isOwned??!1,this.rb.setVelocity(0,0,0),this.rb.setBodyFromGameObject());return}this.rb&&(this._wasKinematic!==void 0&&(_n&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new Gi.Vector3(0,0,0))>1e3&&(_n&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0),this.rb.setBodyFromGameObject()));let i=10,n=this.rb||this.fastMode;if(this._needsUpdate&&(i<=0||i>0&&this.context.time.frameCount%i===0||n)){_n&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this.overridePhysics&&this.rb&&this.rb.setBodyFromGameObject(),this._needsUpdate=!1;let r=Dc(this.guid,this,!!n);this.context.connection.sendBinary(r)}}};import*as ee from"three";var Ia=class{static createButton(e,t={}){let i=document.createElement("button");function n(){if(t.domOverlay===void 0){var c=document.createElement("div");c.style.display="none",document.body.appendChild(c);var d=document.createElementNS("http://www.w3.org/2000/svg","svg");d.setAttribute("width",38),d.setAttribute("height",38),d.style.position="absolute",d.style.right="20px",d.style.top="20px",d.addEventListener("click",function(){h.end()}),c.appendChild(d);var a=document.createElementNS("http://www.w3.org/2000/svg","path");a.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),a.setAttribute("stroke","#fff"),a.setAttribute("stroke-width",2),d.appendChild(a),t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("dom-overlay"),t.domOverlay={root:c}}t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("local-floor"),t.optionalFeatures.push("hand-tracking"),t.optionalFeatures.push("layers");let h=null;async function u(E){E.addEventListener("end",g),await e.xr.setSession(E),i.textContent="STOP AR",t.domOverlay.root.style.display="",h=E}function g(){h.removeEventListener("end",g),i.textContent="START AR",t.domOverlay.root.style.display="none",h=null}i.style.display="",i.style.cursor="pointer",i.style.left="calc(50% - 50px)",i.style.width="100px",i.textContent="START AR",i.onmouseenter=function(){i.style.opacity="1.0"},i.onmouseleave=function(){i.style.opacity="0.5"},i.onclick=function(){h===null?navigator.xr.requestSession("immersive-ar",t).then(u):h.end()}}function r(){i.disabled=!0,i.style.display="",i.style.cursor="auto",i.style.left="calc(50% - 75px)",i.style.width="150px",i.onmouseenter=null,i.onmouseleave=null,i.onclick=null}function s(){r(),i.textContent="AR NOT SUPPORTED"}function o(c){c.style.position="absolute",c.style.bottom="20px",c.style.padding="12px 6px",c.style.border="1px solid #fff",c.style.borderRadius="4px",c.style.background="rgba(0,0,0,0.1)",c.style.color="#fff",c.style.font="normal 13px sans-serif",c.style.textAlign="center",c.style.opacity="0.5",c.style.outline="none",c.style.zIndex="999"}if("xr"in navigator)return i.id="ARButton",i.style.display="none",o(i),navigator.xr.isSessionSupported("immersive-ar").then(function(c){c?n():s()}).catch(s),i;{let c=document.createElement("a");return window.isSecureContext===!1?(c.href=document.location.href.replace(/^http:/,"https:"),c.innerHTML="WEBXR NEEDS HTTPS"):(c.href="https://immersiveweb.dev/",c.innerHTML="WEBXR NOT AVAILABLE"),c.style.left="calc(50% - 90px)",c.style.width="180px",c.style.textDecoration="none",o(c),c}}};var Ma=class{static createButton(e,t){t&&console.error('THREE.VRButton: The "options" parameter has been removed. Please set the reference space type via renderer.xr.setReferenceSpaceType() instead.');let i=document.createElement("button");function n(){let c=null;async function d(h){h.addEventListener("end",a),await e.xr.setSession(h),i.textContent="EXIT VR",c=h}function a(){c.removeEventListener("end",a),i.textContent="ENTER VR",c=null}i.style.display="",i.style.cursor="pointer",i.style.left="calc(50% - 50px)",i.style.width="100px",i.textContent="ENTER VR",i.onmouseenter=function(){i.style.opacity="1.0"},i.onmouseleave=function(){i.style.opacity="0.5"},i.onclick=function(){if(c===null){let h={optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};navigator.xr.requestSession("immersive-vr",h).then(d)}else c.end()}}function r(){i.disabled=!0,i.style.display="",i.style.cursor="auto",i.style.left="calc(50% - 75px)",i.style.width="150px",i.onmouseenter=null,i.onmouseleave=null,i.onclick=null}function s(){r(),i.textContent="VR NOT SUPPORTED"}function o(c){c.style.position="absolute",c.style.bottom="20px",c.style.padding="12px 6px",c.style.border="1px solid #fff",c.style.borderRadius="4px",c.style.background="rgba(0,0,0,0.1)",c.style.color="#fff",c.style.font="normal 13px sans-serif",c.style.textAlign="center",c.style.opacity="0.5",c.style.outline="none",c.style.zIndex="999"}if("xr"in navigator)return i.id="VRButton",i.style.display="none",o(i),navigator.xr.isSessionSupported("immersive-vr").then(function(c){c?n():s(),Ma.xrSessionIsGranted&&(console.log("XR session is granted - will enter immersive web now"),i.click())}),i;{let c=document.createElement("a");return window.isSecureContext===!1?(c.href=document.location.href.replace(/^http:/,"https:"),c.innerHTML="WEBXR NEEDS HTTPS"):(c.href="https://immersiveweb.dev/",c.innerHTML="WEBXR NOT AVAILABLE"),c.style.left="calc(50% - 90px)",c.style.width="180px",c.style.textDecoration="none",o(c),c}}static registerSessionGrantedListener(){if("xr"in navigator)try{navigator.xr.addEventListener("sessiongranted",()=>{console.log("Received session granted event"),Ma.xrSessionIsGranted=!0})}catch(e){console.error(e)}}},$r=Ma;z($r,"xrSessionIsGranted",!1);$r.registerSessionGrantedListener();import*as Pe from"three";import*as La from"three";var pp=vl(gc(),1);import{AudioAnalyser as Av}from"three";var Kr="noVoip",ct=N("debugvoip"),kv=N("voip");var Hc=class{id;constructor(e){this.id=e}};var jc=class{peer;voip;userId;peerId;call=null;callErrorListener=null;stream=null;constructor(e,t,i,n){this.voip=e,this.peer=t,this.userId=i,this.peerId=n}close(){ct&&console.log("close voip call"),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.open&&this.call.close(),this.stream?.getTracks().forEach(function(e){e.stop()})}updateMute(e){if(!this.stream)return;let t=this.stream?.getAudioTracks();for(let i of t)i.enabled=!e}async startVoipCall(){if(!await Ke.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}ct&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),ct&&console.log(this.stream),this.call=this.peer.call(this.peerId,this.stream,{metadata:{userId:this.userId}}),this.call.on("error",t=>{console.error(t)}),this.call.on("stream",t=>{ct&&console.log("received stream from remote again",t)}),this.peer.on("close",this.onCallClose.bind(this)),this.callErrorListener=t=>{t.message.includes(this.peerId)?(console.log("Could not connect to "+this.peerId),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.close(),this.stream?.getTracks().forEach(function(i){i.stop()}),this.stream=null):console.error(t)},this.peer.on("error",this.callErrorListener)}onCallClose(e){ct&&console.log("call closed",e)}},Bc=class{get currentStream(){return this.stream}get currentAudio(){return this.audio}get currentAnalyzer(){return this.analyzer}voip;call;audio=null;stream=null;obj;analyzer=null;waitingForStart=!1;closed=!1;audioElement=null;constructor(e,t,i){this.voip=e,this.obj=t,this.call=i}openAudioStream(e){let t=e.getAudioTracks();for(let i of t)if(i.kind==="audio"&&i.readyState==="live"){this.open(i);return}console.warn("failed finding valid audio stream to begin call")}open(e){console.assert(e.kind==="audio","invalid track kind, expected audio but received "+e.kind),!this.waitingForStart&&(this.waitingForStart=!0,ue.userInteractionRegistered||ct&&console.log("Incoming call, waiting for user interaction before opening audio"),ue.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){ct&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);let t=new La.AudioListener;this.audio=new La.Audio(t),this.audio.setVolume(this.voip.muteInput?0:1),this.audio.setMediaStreamSource(this.stream);let i=document.createElement("audio");this.audioElement=i,i.style.display="none",document.body.appendChild(i),i.srcObject=this.stream,i.sinkId!==void 0&&navigator.mediaDevices.enumerateDevices().then(n=>{if(!!i){console.log(n);for(let r of n)if(r.label==="Speakerphone"){i.sinkId=r.deviceId;break}}}),ct&&console.log("call is setup, you should hear something now"),this.analyzer=new Av(this.audio,32)}}))}close(){this.closed=!0,this.call?.open&&this.call.close(),this.audio?.disconnect(),this.stream?.getTracks().forEach(e=>{e.stop()}),this.stream=null,this.audioElement&&this.audioElement.remove()}},Ke=class extends M{requireParam=!1;set muteInput(e){if(e===this._inputMuted||(this._inputMuted=e,!this.currentIncomingCalls))return;let t=this._inputMuted?0:1;for(let i in this.currentIncomingCalls)this.currentIncomingCalls[i]?.currentAudio?.setVolume(t)}get muteInput(){return this._inputMuted}set muteOutput(e){if(e!==this._outputMuted&&(this._outputMuted=e,!!this.connections))for(let t in this.connections)this.connections[t]?.updateMute(e)}get muteOutput(){return this._outputMuted}getFrequency(e){if(e===null){for(let i in this.currentIncomingCalls){let n=this.currentIncomingCalls[i];if(n&&n.currentAnalyzer)return n.currentAnalyzer.getAverageFrequency()}return null}let t=this.currentIncomingCalls[e];return t&&t.currentAnalyzer?t.currentAnalyzer.getAverageFrequency():null}peer=null;model=null;connections={};currentIncomingCalls={};_inputMuted=!1;_outputMuted=!1;awake(){if(N(Kr)){console.log("VOIP is disabled by url parameter: "+Kr);return}if(this.requireParam&&!kv){console.debug("VOIP must be enabled explicitly by url parameter");return}this.peer=new pp.default,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,this.context.connection.beginListen("joined-room",e=>{navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}),this.context.connection.beginListen("peer-update-id",e=>{if(e.id!==this.context.connection.connectionId){let t=this.connections[e.id];if(t&&t.close(),this.peer&&this.context.connection.connectionId){let i=new jc(this,this.peer,this.context.connection.connectionId,e.peerId);this.connections[e.id]=i,i.startVoipCall()}}}),this.context.connection.beginListen("user-left-room",e=>{let{userId:t}=e,i=this.connections[t];this.connections[t]=null,i&&i.close();let n=this.currentIncomingCalls[t];ct&&console.log("UserLeftRoom",e,t,n),n&&(n.close(),this.currentIncomingCalls[t]=null)}),this.peer.on("open",this.onOpenPeerConnection.bind(this))}onEnable(){}onDisable(){console.log("TODO: close all");for(let e in this.currentIncomingCalls)this.currentIncomingCalls[e]?.close(),this.connections[e]?.close()}async onOpenPeerConnection(e){ct&&console.log("Peer connection established and received id"),this.model=new Hc(e),this.context.connection.send("peer-update-id",this.model,1),this.peer&&(this.peer.on("call",this.onReceiveCall.bind(this)),this.peer.on("connection",function(t){ct&&console.log("CONNECTION",t),t.on("data",function(i){ct&&console.log("Received",i)})}))}async onReceiveCall(e){let{metadata:t}=e;console.assert(t.userId);let{userId:i}=t,{peer:n}=e,r=this.currentIncomingCalls[i];if(r&&r.close(),ct&&console.log("received call"),await Ke.HasMicrophonePermissions()){let s=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(s)}else e.answer(null);this.currentIncomingCalls[i]=new Bc(this,this.gameObject,e),e.on("stream",s=>{ct&&console.log("receive caller stream, will setup audio now"),this.currentIncomingCalls[i]?.openAudioStream(s)}),e.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}};var es=N("debugflags");var Fc=class{Mask=17;Has(e){let t=this.Mask&e;return es&&console.log("HAS",e,this.Mask,"Result="+t),t!==0}Set(e){this.Mask=e,Se.Apply()}Enable(e){this.Mask|=e,Se.Apply()}Disable(e){this.Mask&=~e,Se.Apply()}Toggle(e){this.Mask^=e,Se.Apply()}EnableAll(){this.Mask=-1,Se.Apply()}DisableAll(){this.Mask=0,Se.Apply()}},vt=Fc;z(vt,"Global",new Fc);var mi=class extends M{static Apply(){for(let e of this.registry)e.UpdateVisible(vt.Global)}awake(){mi.registry.push(this)}onEnable(){mi.firstApply||(mi.firstApply=!0,mi.Apply())}onDestroy(){let e=mi.registry.indexOf(this);e>=0&&mi.registry.splice(e,1)}visibleIn;get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(!this.enabled)return;let t,i=e;i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),es&&console.log(i),mi.buffer.Mask=i,e=mi.buffer);let n=e;if(n?(es&&console.log("use passed in mask"),t=n.Has(this.visibleIn)):(es&&console.log("use global mask"),vt.Global.Has(this.visibleIn)),t!==void 0)if(t)es&&console.trace("is visible",this.name,this.gameObject.uuid),O.setActive(this.gameObject,!0);else{if(es&&console.trace("is not visible",this.name,this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},Se=mi;z(Se,"registry",[]),z(Se,"firstApply"),z(Se,"buffer",new vt);import*as K from"three";import{XRControllerModelFactory as Iv}from"three/examples/jsm/webxr/XRControllerModelFactory.js";import{OculusHandModel as Mv}from"three/examples/jsm/webxr/OculusHandModel.js";import{OculusHandPointerModel as Lv}from"three/examples/jsm/webxr/OculusHandPointerModel.js";import*as mp from"three";import*as $t from"three";var xn=N("debugavatar"),Vi=class extends M{static onAvatarMarkerCreated(e){return Vi._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return Vi._onAvatarMarkerDestroyed.push(e),e}connectionId;avatar;awake(){Vi.instances.push(this),xn&&console.log(this);for(let e of Vi._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Vi.instances.splice(Vi.instances.indexOf(this),1);for(let e of Vi._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}setVisible(e){this.avatar&&("setVisible"in this.avatar?this.avatar.setVisible(e):O.setActive(this.avatar,e))}},fe=Vi;z(fe,"instances",[]),z(fe,"_onNewAvatarMarkerAdded",[]),z(fe,"_onAvatarMarkerDestroyed",[]);var fo=class{_isVisible=!0;setVisible(e){this._isVisible=e,this.updateVisibility()}guid;root=null;head=null;handLeft=null;handRight=null;lastUpdate=-1;isLocalAvatar=!1;flags=null;headScale=new $t.Vector3(1,1,1);handLeftScale=new $t.Vector3(1,1,1);handRightScale=new $t.Vector3(1,1,1);webxr;lastAvatarId=null;hasAvatarOverride=!1;context;avatarMarker=null;constructor(e,t,i){this.context=e,this.guid=t,this.webxr=i,this.setupCustomAvatar(this.webxr.defaultAvatar)}updateFlags(){if(!this.flags)return;let e=this.isLocalAvatar?8:16;for(let t of this.flags)t.gameObject.visible=!0,t.UpdateVisible(e)}async setAvatarOverride(e){return this.hasAvatarOverride=e!==null,this.hasAvatarOverride&&this.lastAvatarId!==e&&(this.lastAvatarId=e,e!=null&&e.length>0)?await this.setupCustomAvatar(e):null}_headTarget=new $t.Object3D;_handLeftTarget=new $t.Object3D;_handRightTarget=new $t.Object3D;_canInterpolate=!1;tryUpdate(e,t){if(e.guid===this.guid&&(this.lastAvatarId!==e.avatarId&&e.avatarId&&e.avatarId.length>0&&(this.lastAvatarId=e.avatarId,this.setupCustomAvatar(e.avatarId)),this.lastUpdate=e.time,this.head)){this._canInterpolate=!0;let i=this.isLocalAvatar?this.head:this._headTarget;if(i.position.set(e.position.x,e.position.y,e.position.z),i.quaternion.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),i.scale.set(e.scale,e.scale,e.scale),i.scale.multiply(this.headScale),this.handLeft){let n=this.isLocalAvatar?this.handLeft:this._handLeftTarget;n.position.set(e.posLeftHand.x,e.posLeftHand.y,e.posLeftHand.z),n.quaternion.set(e.rotLeftHand._x,e.rotLeftHand._y,e.rotLeftHand._z,e.rotLeftHand._w),n.quaternion.multiply(fo.invertRotation),n.scale.set(e.scale,e.scale,e.scale),n.scale.multiply(this.handLeftScale)}if(this.handRight){let n=this.isLocalAvatar?this.handRight:this._handRightTarget;n.position.set(e.posRightHand.x,e.posRightHand.y,e.posRightHand.z),n.quaternion.set(e.rotRightHand._x,e.rotRightHand._y,e.rotRightHand._z,e.rotRightHand._w),n.quaternion.multiply(fo.invertRotation),n.scale.set(e.scale,e.scale,e.scale),n.scale.multiply(this.handRightScale)}}}update(){if(this.isLocalAvatar||!this._canInterpolate)return;let e=this.context.time.deltaTime/.1;this.head&&(this.head.position.lerp(this._headTarget.position,e),this.head.quaternion.slerp(this._headTarget.quaternion,e),this.head.scale.lerp(this._headTarget.scale,e)),this.handLeft&&this._handLeftTarget&&(this.handLeft.position.lerp(this._handLeftTarget.position,e),this.handLeft.quaternion.slerp(this._handLeftTarget.quaternion,e),this.handLeft.scale.lerp(this._handLeftTarget.scale,e)),this.handRight&&this._handRightTarget&&(this.handRight.position.lerp(this._handRightTarget.position,e),this.handRight.quaternion.slerp(this._handRightTarget.quaternion,e),this.handRight.scale.lerp(this._handRightTarget.scale,e))}destroy(){xn&&console.log("Destroy avatar",this.guid),this.root?.removeFromParent(),this.avatarMarker?.destroy(),this.lastAvatarId=null,this.head&&_e.Remove(this.context,this.head)}updateVisibility(){let e=this.root;e&&O.setActive(e,this._isVisible)}async setupCustomAvatar(e){if(xn&&console.log("LOAD",e,this),!e||typeof e=="string"&&e.length<=0)return!1;this.head&&_e.Remove(this.context,this.head);let t=e;if(t?.loadAssetAsync!==void 0){await t.loadAssetAsync();let n=t.asset;O.setActive(n,!1),e=O.instantiate(n),O.setActive(e,!0)}xn&&console.log(e);let i=await fo.loader.getOrCreateNewAvatarInstance(this.context,e);if(xn&&console.log(i,i?.isValid,this.lastAvatarId,e),i?.isValid){if(this.root=i.root,this.root.position.set(0,0,0),this.root.quaternion.set(0,0,0,1),this.root.scale.set(1,1,1),this.avatarMarker=O.addNewComponent(this.root,fe),this.avatarMarker.connectionId=this.guid,this.avatarMarker.avatar=this,this.head&&this.head!==i.head&&this.head?.removeFromParent(),this.head=i.head,this.headScale.copy(this.head.scale),this.head&&!this.isLocalAvatar&&_e.Add(this.context,this.head,this.avatarMarker),i.leftHand&&this.handLeft?.removeFromParent(),this.handLeft=i.leftHand??this.handLeft,this.handLeft?this.handLeftScale.copy(this.handLeft.scale):this.handLeftScale.set(1,1,1),i.rigthHand&&this.handRight?.removeFromParent(),this.handRight=i.rigthHand??this.handRight,this.handRight?this.handRightScale.copy(this.handRight.scale):this.handRightScale.set(1,1,1),this.context.scene.add(this.root),this.flags==null&&(this.flags=[]),this.flags.length=0,this.flags.push(...O.getComponentsInChildren(this.root,Se)),this.flags.length<=0&&this.head){let n=O.addNewComponent(this.head,Se);n.visibleIn=20,this.flags.push(n),xn&&console.log("Added flag to head: "+n.visibleIn,this.head.name)}return xn&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return xn&&console.warn("build avatar failed"),!1}},Lt=fo;z(Lt,"loader",new Fi),z(Lt,"invertRotation",new $t.Quaternion().setFromAxisAngle(new $t.Vector3(0,1,0),Math.PI));var _e=class{static Add(e,t,i=null){if(!!t){for(let n of this.Pois)if(n.obj===t)return;this.Pois.push({obj:t,avatar:i}),this.LastChangeTime=e.time.time}}static Remove(e,t){if(!!t){for(let i of this.Pois)if(i.obj===t){this.Pois.splice(this.Pois.indexOf(i),1),this.LastChangeTime=e?.time.time??Z.Current?.time.time;return}}}};z(_e,"Pois",[]),z(_e,"LastChangeTime",0);var Nc=class{guid;position=new mp.Vector3},Wi=class extends M{set controlledTarget(e){this.target=e;let t=D.get("MoveRandom");if(t&&this.target){let i=O.getComponent(this.target,t);i&&i.destroy()}}target=null;avatar=null;_model=null;_targetModel=new Nc;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=O.getComponentInParent(this.gameObject,fe),this.avatar){let e=O.getComponentInParent(this.gameObject,fe);this._model=new vn(this.context.connection,this.guid),e?.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{this.target&&e&&e.guid===this.avatar?.guid&&ie(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(_e.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=_e.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){let t=q(this._currentTargetObject);ie(this.target,t),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(t))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;let t=_e.Pois;if(t.length>0){let i=t[Math.floor(Math.random()*t.length)];if(i&&i.obj){if(i.avatar&&i.avatar===this.avatar)return;this._currentTargetObject=i.obj}}}}};var or=class extends M{},Fe=class extends M{static CreateRaycastLine(){let e=new K.Line(this.geometry),t=e.material;return t.color=this.raycastColor,e.layers.set(1),e.name="line",e.scale.z=1,e}static CreateRaycastHitPoint(){let e=new K.SphereGeometry(.5,22,22),t=new K.MeshBasicMaterial({color:this.raycastColor}),i=new K.Mesh(e,t);return i.visible=!1,i.layers.set(1),i}static Create(e,t,i,n){let r=i?O.addNewComponent(i,Fe,!1):new Fe;r.webXR=e,r.index=t,r.type=n;let s=e.context;return r.controller=s.renderer.xr.getController(t),r.controllerGrip=s.renderer.xr.getControllerGrip(t),r.controllerModel=this.Factory.createControllerModel(r.controller),r.controllerGrip.add(r.controllerModel),r.hand=s.renderer.xr.getHand(t),r.hand.add(new Mv(r.hand)),r.hand.traverse(o=>o.layers.set(2)),r.handPointerModel=new Lv(r.hand,r.controller),r.controller.addEventListener("connected",o=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),setTimeout(()=>{r.setControllerLayers(r.controllerGrip,2)},1e3)}),r.hand.addEventListener("connected",o=>{if(o.data.hand){e.Rig&&e.Rig.add(r.hand),r.type=0,r.handPointerModel.traverse(a=>a.layers.set(2)),r.handPointerModel.pointerObject?.traverse(a=>a.layers.set(2));let d=r.hand.joints;if(d)for(let a of Object.keys(d)){let h=d[a];h.parent||r.hand.add(h)}}}),r}static addEventListener(e,t){let i=this.eventSubs[e]??[];i.push(t),this.eventSubs[e]=i}webXR;index=-1;controllerModel;controller;controllerGrip;hand;handPointerModel;grabbed=null;input=null;type=0;get isUsingHands(){let e=this.input?.hand;return e!=null}get wrist(){if(!this.hand)return null;let e=this.hand.joints;return e?e.wrist:null}_wristQuaternion=null;getWristQuaternion(){let e=this.wrist;return e?(this._wristQuaternion||(this._wristQuaternion=new K.Quaternion),ve(e).multiply(this._wristQuaternion.setFromEuler(new K.Euler(-Math.PI/4,0,0)))):null}movementVector=new K.Vector3;worldRot=new K.Quaternion;joystick=new K.Vector2;didRotate=!1;didTeleport=!1;didChangeScale=!1;lastHit=null;raycastLine=null;_raycastHitPoint=null;_connnectedCallback=null;_disconnectedCallback=null;_selectStartEvt=null;_selectEndEvt=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}_selectionPressed=!1;_selectionPressedLastFrame=!1;_selectionStartTime=0;_selectionEndTime=0;get useSmoothing(){return this._useSmoothing}_useSmoothing=!0;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(){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)),this.hand?.clear(),this.controllerGrip?.clear(),this.controller?.clear()}onEnable(){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=Fe.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=Fe.CreateRaycastHitPoint()),this.webXR.Rig?.add(this.hand),this.webXR.Rig?.add(this.controllerGrip),this.webXR.Rig?.add(this.controller),this.webXR.Rig?.add(this.raycastLine),this.raycastLine?.add(this._raycastHitPoint),this.hand.add(this.handPointerModel),console.log("ADDED TO RIG",this.webXR.Rig)}onDisable(){this.hand?.removeFromParent(),this.controllerGrip?.removeFromParent(),this.controller?.removeFromParent(),this.raycastLine?.removeFromParent(),this._raycastHitPoint?.removeFromParent();let e=this.webXR.Controllers.indexOf(this);e>=0&&this.webXR.Controllers.splice(e,1)}_isConnected=!1;onSourceConnected(e){if(this._isConnected){console.warn("Received connected event for controller that is already connected",this.index,e);return}this._isConnected=!0,this.input=e.data,this.type===1&&(this.onSelectStart(),this.createPointerEvent("down"))}onSourceDisconnected(e){if(!this._isConnected){console.warn("Received discnnected event for controller that is not connected",e);return}this._isConnected=!1,this.type===1&&(this.onSelectEnd(),this.createPointerEvent("up")),this.input=null}createPointerEvent(e){switch(e){case"down":this.context.input.createPointerDown({pointerId:this.index,clientX:0,clientY:0,button:this.index,pointerType:"touch"});break;case"move":break;case"up":this.context.input.createPointerUp({pointerId:this.index,clientX:0,clientY:0,button:this.index,pointerType:"touch"});break}}rayRotation=new K.Quaternion;update(){this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));let e=Fe.eventSubs["update"];if(e&&e.length>0)for(let n of e)n(this);let t=1;this.type===0?t=this.context.time.deltaTime/.1:this.isUsingHands&&this.handPointerModel.pinched&&(t=this.context.time.deltaTime/.3),this.rayRotation.slerp(ve(this.controller),this.useSmoothing?t:1);let i=q(this.controller);if(this.raycastLine)if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed,ie(this.raycastLine,i);let n=this.hand.joints;if(n&&n.wrist&&this.grabbed&&this.grabbed.isCloseGrab){let s=this.getWristQuaternion();s&&this.rayRotation.copy(s)}Ae(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=!0,Ae(this.raycastLine,this.rayRotation),ie(this.raycastLine,i);this.lastHit=this.updateLastHit(),this.grabbed&&this.grabbed.update(),this._selectionPressedLastFrame=this._selectionPressed,this.selectStartCallback&&this.selectStartCallback()}_pinchStartTime=void 0;onUpdate(e){if(this.lastHit=null,!e||e.inputSources.length<=this.index){this.input=null;return}if(this.type===0&&(this.input=e.inputSources[this.index]),!this.input)return;let t=this.webXR.Rig;if(!t)return;this._didNotEndSelection&&!this.handPointerModel.pinched&&(this._didNotEndSelection=!1,this.onSelectEnd()),this.updateStick(this.input);let i=this.input?.gamepad?.buttons;switch(this.input.handedness){case"left":let n=3*Fe.MovementSpeedFactor,r=2,s=Q.clamp01(this.joystick.length()*2),o=this.joystick.x>0?1:-1,c=Math.pow(this.joystick.x,r);c*=o,c*=s;let d=this.joystick.y>0?1:-1,a=Math.pow(this.joystick.y,r);a*=d,c*=s,t.getWorldQuaternion(this.worldRot),this.movementVector.set(c,0,a),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),t.position.add(this.movementVector.multiplyScalar(n*this.context.time.deltaTime)),this.isUsingHands&&this.runTeleport(t,i);break;case"right":let h=this.joystick.x,u=Math.abs(h);if(u<.4)this.didRotate=!1;else if(u>.5&&!this.didRotate){let g=h>0?-1:1;t.rotateY(Q.toRadians(30*g)),this.didRotate=!0}this.runTeleport(t,i);break}}runTeleport(e,t){let i=-this.joystick.y;if(this.hand?.visible&&!this.grabbed){let o=this.handPointerModel.isPinched();o&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),o&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(i=this.handPointerModel.isPinched()?1:0),o||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;let n=i>.5,r=this.webXR.Rig?this.webXR.Rig?.scale?.x<.999:!1,s=null;if(t&&this.input&&!this.input.hand)for(let o=0;o<t.length;o++){let c=t[o];if(o===4)if(c.pressed&&!this.didChangeScale){this.didChangeScale=!0;let d=this.webXR.Rig;if(d)if(r){r=!1,d.scale.set(1,1,1),s=1,Fe.MovementSpeedFactor=1;let a=this.context.mainCamera;Fe.PreviousCameraFarDistance&&(a.far=Fe.PreviousCameraFarDistance)}else{r=!0,n=!0,s=.1,Fe.MovementSpeedFactor=s*2;let a=this.context.mainCamera;Fe.PreviousCameraFarDistance=a.far,a.far/=s}}else c.pressed||(this.didChangeScale=!1)}if(n){if(!this.didTeleport){let o=this.raycast();if(this.didTeleport=!0,o&&o.length>0){let c=o[0];if(r||this.isValidTeleportTarget(c.object)){let d=c.point;ie(e,d)}}}}else i<.1&&(this.didTeleport=!1);s!==null&&(e.scale.set(s,s,s),e.updateMatrixWorld())}isValidTeleportTarget(e){return O.getComponentInParent(e,or)!=null}updateStick(e){!e||!e.gamepad||e.gamepad.axes?.length<4||(this.joystick.x=e.gamepad.axes[2],this.joystick.y=e.gamepad.axes[3])}updateLastHit(){let e=this.raycast(),t=e?e[0]:null;this.lastHit=t;let i=1;if(this.webXR.Rig&&(i/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=i*(this.lastHit?.distance??9999);let n=this.raycastLine.material;t!=null?n.color=Fe.raycastColor:n.color=Fe.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;let n=Q.clamp(this.lastHit.distance*.01*i,.015,.1);this._raycastHitPoint.scale.set(n,n,n)}this._raycastHitPoint.visible=this.lastHit!==null}return t}onSelectStart(){!this.context.connection.allowEditing||(this.selectStartCallback=()=>this.onHandleSelectStart())}selectStartCallback=null;lastSelectStartObject=null;onHandleSelectStart(){this.selectStartCallback=null,this._selectionPressed=!0,this._selectionStartTime=this.context.time.time,this._selectionEndTime=1e3;let e=null,t=!1;if(this.isUsingHands?(e=this.overlap(),e.length<=0?(e=this.raycast(),t=!1):t=!0):e=this.raycast(),e&&e.length>0)for(let i of e){let n=i.object;if(!this.testIsVisible(n)){console.log("not visible");continue}this.lastSelectStartObject=n;let r={selected:n,grab:n},s=Fe.eventSubs["select-start"];if(s&&s.length>0)for(let o of s)o(this,r);r.grab!==n&&console.log("Grabbed object changed","original",n,"new",r.grab),r.grab&&(this.grabbed=dt.TryTake(this,r.grab,i,t));break}else{let i=Fe.eventSubs["select-start"],n={selected:null,grab:null};if(i&&i.length>0)for(let r of i)r(this,n)}}_didNotEndSelection=!1;onSelectEnd(){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;let e={grab:this.grabbed?.selected??this.lastSelectStartObject},t=Fe.eventSubs["select-end"];if(t&&t.length>0)for(let i of t)i(this,e);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(e){return e?O.isActiveInHierarchy(e):!0}setControllerLayers(e,t){if(!!e&&(e.layers.set(t),e.children))for(let i of e.children)this.grabbed?.selected===i||this.grabbed?.selectedMesh===i||this.setControllerLayers(i,t)}getRay(){let e=new K.Ray;return e.origin.copy(q(this.controller)),e.direction.set(0,0,-1).applyQuaternion(this.rayRotation),e}overlap(){let e=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(!e)return new Array;let t=q(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){let e=new je;return e.layerMask=new K.Layers,e.layerMask.set(0),e.ray=this.getRay(),this.context.physics.raycast(e)}},oe=Fe;z(oe,"Factory",new Iv),z(oe,"raycastColor",new K.Color(.9,.3,.3)),z(oe,"raycastNoHitColor",new K.Color(.6,.6,.6)),z(oe,"geometry",new K.BufferGeometry().setFromPoints([new K.Vector3(0,0,0),new K.Vector3(0,0,-1)])),z(oe,"handModels",{}),z(oe,"eventSubs",{}),z(oe,"PreviousCameraFarDistance"),z(oe,"MovementSpeedFactor",1);var et=class{static AddEventListener(e,t){return et.Events[e]||(et.Events[e]=[]),et.Events[e].push(t),t}static RemoveEventListener(e,t){if(!t||!et.Events[e])return;let i=et.Events[e].indexOf(t);i>=0&&et.Events[e].splice(i,1)}static Register(e){this.Current.find(t=>t===e)||this.Current.push(e)}static Remove(e){let t=this.Current.indexOf(e);t>=0&&this.Current.splice(t,1)}static TryTake(e,t,i,n){let r=O.getComponentInParent(t,kt);if(!r)return console.warn("Prevented taking object that is not interactable",t),null;let s=t,o=O.getComponentInParent(t,Qe);o&&(o.requestOwnership(),s=o.gameObject);for(let d of this.Current)if(d.selected===s)return d.controller===e||(d.free(),d.Take(e,s,t,o,r,i,n)),d;let c=new et;return c.Take(e,s,t,o,r,i,n),c}sync=null;selected=null;selectedParent=null;selectedMesh=null;controller=null;grabTime=0;grabUUID="";isCloseGrab=!1;originalMaterial=null;usageMarker=null;rigidbodies=null;didReparent=!1;grabDistance=0;interactable=null;positionSource=null;Take(e,t,i,n,r,s,o){if(console.assert(t!==null,"Expected object to be taken but was",t),e.isUsingHands?this.positionSource=o?e.wrist:e.controller:this.positionSource=e.controller,!this.positionSource)return console.warn("No position source"),this;let c={controller:e,take:t,hit:i,sync:n,interactable:r};et.Events.WillTake?.forEach(g=>g(this,c));let d=i;d?.material&&(this.originalMaterial=d.material,Array.isArray(d.material)||(d.material=d.material.clone(),d.material&&d.material.emissive&&(d.material.emissive.b=.2))),this.selected=t,this.selectedParent||(this.selectedParent=t.parent),this.selectedMesh=d,this.controller=e,this.interactable=r,this.isCloseGrab=o,this.didReparent=!1,this.sync=n,this.grabTime=e.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=O.addNewComponent(this.selected,It),this.rigidbodies=O.getComponentsInChildren(this.selected,ce),q(this.positionSource,this.lastControllerWorldPos);let a=()=>o?this.lastControllerWorldPos.clone():s.point.clone();this.grabDistance=a().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(a());let h=e.isUsingHands&&o?this.controller.getWristQuaternion().clone():e.rayRotation.clone();ve(this.selected,this.localQuaternionToGrab).premultiply(h.invert());let u=this.controller.webXR.Rig;return u&&this.rigPositionLastFrame.copy(q(u)),_e.Add(e.context,this.selected),et.Register(this),this.sync&&(this.sync.fastMode=!0),et.Events.DidTake?.forEach(g=>g(this,c)),this}free(){if(!this.selected)return;let e={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};et.Events.WillFree?.forEach(n=>n(this,e)),_e.Remove(this.controller.context,this.selected),et.Remove(this),this.sync&&(this.sync.fastMode=!1);let t=this.selectedMesh;t&&this.originalMaterial&&t.material&&(t.material=this.originalMaterial);let i=this.selected;if(this.didReparent&&i.parent){let n=this.selectedParent;n?n.attach(i):this.controller?.context.scene.attach(i)}if(this.usageMarker?.destroy(),this.controller&&(this.controller.grabbed=null),this.selected=null,this.selectedParent=null,this.selectedMesh=null,this.sync=null,this.rigidbodies)for(let n of this.rigidbodies)n.wakeUp(),n.smoothedVelocity&&n.setVelocity(n.smoothedVelocity.x,n.smoothedVelocity.y,n.smoothedVelocity.z);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,et.Events.DidFree?.forEach(n=>n(this,e))}grabPoint=new K.Vector3;localPositionOffsetToGrab=null;localPositionOffsetToGrab_worldSpace=new K.Vector3;localQuaternionToGrab=new K.Quaternion(0,0,0,1);targetDir=null;quaternionLerp=null;controllerDir=new K.Vector3;controllerWorldPos=new K.Vector3;lastControllerWorldPos=new K.Vector3;controllerPosDelta=new K.Vector3;totalChangeAlongDirection=0;rigPositionLastFrame=new K.Vector3;controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),q(this.positionSource,this.controllerWorldPos),this.controllerPosDelta.copy(this.controllerWorldPos),this.controllerPosDelta.sub(this.lastControllerWorldPos),this.lastControllerWorldPos.copy(this.controllerWorldPos);let e=this.controller.webXR.Rig;if(e){let i=q(e),n=this.rigPositionLastFrame.sub(i);this.controllerPosDelta.add(n),this.rigPositionLastFrame.copy(i)}return this.controllerDir.dot(this.controllerPosDelta)}update(){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){let e=this.controller.webXR.Rig?.scale.x??1;this.totalChangeAlongDirection+=this.controllerMovementSinceLastFrame();let t=1;this.controller.type===0&&(t=Math.max(0,1+this.totalChangeAlongDirection*2/e),t=t*t*t),this.grabDistance/e<.8&&(t=1),this.targetDir||(this.targetDir=new K.Vector3),this.targetDir.set(0,0,-this.grabDistance*t);let i=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),n=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=n.clone()),this.quaternionLerp.slerp(n,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),Ae(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(i),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(q(this.selected)),i.sub(this.localPositionOffsetToGrab_worldSpace)),ie(this.selected,i)}if(this.rigidbodies!=null)for(let e of this.rigidbodies)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0});he.markDirty(this.selected,!0)}}},dt=et;z(dt,"Events",{}),z(dt,"Current",[]);import*as Da from"three";var Dt=class extends M{webAR=null;invertForward=!1;get arScale(){return this._arScale}set arScale(e){e!==this._arScale&&(this._arScale=e,this.setScale(e))}_arScale=5;_rig=null;_startPose=null;_placementPose=null;_isTouching=!1;onBegin(e){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose=this.gameObject.matrix.clone(),e.addEventListener("selectstart",this.onSelectStart.bind(this)),e.addEventListener("selectend",this.onSelectEnd.bind(this)),setTimeout(()=>this.gameObject.visible=!1,1e3)}onUpdate(e,t,i){if(i&&!this._placementPose&&this._isTouching){if(this.webAR&&this.webAR.setReticleActive(!1),this._placementPose=new Da.Matrix4().fromArray(i.transform.matrix).invert(),e){if(this.invertForward){let n=new Da.Matrix4().makeRotationY(Math.PI);this._placementPose.premultiply(n)}this._rig=e,this.setScale(this.arScale)}else this._rig=null;this.gameObject.visible=!0}}onEnd(e,t){this._placementPose=null,this.gameObject.visible=!1,this._startPose&&this.gameObject.matrix.copy(this._startPose),this.gameObject.matrixAutoUpdate=!0,e&&(e.matrixAutoUpdate=!0),he.markDirty(this.gameObject,!0),setTimeout(()=>this.gameObject.visible=!0,100)}onSelectStart(){this._isTouching=!0}onSelectEnd(){this._isTouching=!1}setScale(e){let t=this._rig;!t||!this._placementPose||(t.matrixAutoUpdate=!1,t.matrix.multiplyMatrices(new Da.Matrix4().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld())}};k([A()],Dt.prototype,"invertForward",2),k([A()],Dt.prototype,"arScale",1);var Tn=class extends M{awake(){}};import{Object3D as Dv}from"three";var ar=N("debugaddressables"),Ha=class{_context;constructor(e){this._context=e,this._context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){}_assetReferences={};findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.uri&&(this._assetReferences[e.uri]?console.warn("Asset reference already registered",e):this._assetReferences[e.uri]=e),e}},tt=class{static getOrCreate(e,t,i){let n=Ao(e,t);ar&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",n);let r=i.addressables,s=r.findAssetReference(n);if(s)return s;let o=new tt(n);return r.registerAssetReference(o),o}get asset(){return this._glbRoot??this._asset}set asset(e){this._asset=e}_loading;get uri(){return this._uri}get rawAsset(){return this._asset}_asset;_glbRoot;_uri;_progressListeners=[];_isLoadingRawBinary=!1;_rawBinary;constructor(e){this._uri=e,Ih(this._uri,this.onResolvePrefab.bind(this))}async onResolvePrefab(e){return e===this.uri&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(ar&&console.log("Unload",this.asset),this.asset.scene?O.destroy(this.asset.scene):O.destroy(this.asset)),this.asset=null}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,ar&&console.log("Preload",this.uri);let e=await ap(this.uri,t=>{this.raiseProgressEvent(t)});return this._rawBinary=e?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(e){if(!this.mustLoad)return;if(e&&this._progressListeners.push(e),this._loading!==void 0)return this._loading;let t=Z.Current;this._rawBinary?(this._loading=Vr(t,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(ar&&console.log("Load async",this.uri),this._loading=lr(t,this.uri,null,!0,n=>{this.raiseProgressEvent(n)}));let i=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(i),this._loading=void 0,i)return Ai(t),i.scene!==void 0&&(this.asset=i),this.asset}async instantiate(e){return this.onInstantiate(e,!1)}async instantiateSynced(e,t=!0){return this.onInstantiate(e,!0,t)}beginListenDownload(e){this._progressListeners.indexOf(e)<0&&this._progressListeners.push(e)}endListenDownload(e){let t=this._progressListeners.indexOf(e);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(e){for(let t of this._progressListeners)t(this,e)}async onInstantiate(e,t=!1,i){let n=Z.Current;if(e||(e=n.scene),this.mustLoad&&await this.loadAssetAsync(),ar&&console.log("Instantiate",this.uri,"parent:",e),this.asset){ar&&console.log("Add to scene",this.asset);let r=e instanceof ye?e:null;if(r||(r=new ye),typeof e=="object"&&(e instanceof Dv?r.parent=e:Object.assign(r,e)),t){r.context=n;let s=this.asset;s.guid=this.uri;let o=Vo(s,r,void 0,i);if(o)return o}else{let s=O.instantiate(this.asset,r);if(s)return s}}else ar&&console.warn("Failed to load asset",this.uri);return null}tryGetActualGameObjectRoot(e){if(e&&e.scene){let t=e.scene;return t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name?t.children[0]:t}return null}},zc=class extends Bi{constructor(){super([tt])}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){return typeof e=="string"?t.context?t.gltfId?tt.getOrCreate(t.gltfId,e,t.context):(console.error("Missing spurce id"),null):(console.error("Missing context"),null):null}};new zc;import*as yt from"three";var gi=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}w(){return this.bb.readFloat32(this.bb_pos+12)}static sizeOf(){return 16}static createVec4(e,t,i,n,r){return e.prep(4,16),e.writeFloat32(r),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var Me=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsVrUserStateBuffer(e,t){return(t||new Me).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+4),(t||new Me).__init(e.readInt32(e.position())+e.position(),e)}guid(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}time(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}avatarId(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__string(this.bb_pos+t,e):null}position(e){let t=this.bb.__offset(this.bb_pos,10);return t?(e||new Ce).__init(this.bb_pos+t,this.bb):null}rotation(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new gi).__init(this.bb_pos+t,this.bb):null}scale(){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.readFloat32(this.bb_pos+e):0}posLeftHand(e){let t=this.bb.__offset(this.bb_pos,16);return t?(e||new Ce).__init(this.bb_pos+t,this.bb):null}posRightHand(e){let t=this.bb.__offset(this.bb_pos,18);return t?(e||new Ce).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){let t=this.bb.__offset(this.bb_pos,20);return t?(e||new gi).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){let t=this.bb.__offset(this.bb_pos,22);return t?(e||new gi).__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)}};var gp=N("debugxr"),mo=N("debugavatar");var Vc="VRUS";Hr(Vc,Me.getRootAsVrUserStateBuffer);function Gc(){return new Date().getTime()}function Hv(l){let e=l&4294967295,t=l/Math.pow(2,32)&1048575;return Xe.create(e,t)}var go=class{guid;time;avatarId;position=new yt.Vector3;rotation=new yt.Vector4;scale=1;posLeftHand=new yt.Vector3;posRightHand=new yt.Vector3;rotLeftHand=new yt.Quaternion;rotRightHand=new yt.Quaternion;constructor(e){this.guid=e}update(e,t,i,n,r){this.time=Gc(),this.avatarId=r,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let s=go.quat0,o=go.quat1;s.set(i.x,i.y,i.z,i.w),s=s.multiplyQuaternions(s,go.invertRotation),e&&(e.getWorldQuaternion(o),s.multiplyQuaternions(o,s)),this.rotation.set(s.x,s.y,s.z,s.w),this.scale=e.scale.x;let c=n.LeftController?.controllerGrip;c&&(c.getWorldPosition(this.posLeftHand),c.getWorldQuaternion(this.rotLeftHand));let d=n.RightController?.controllerGrip;if(d&&(d.getWorldPosition(this.posRightHand),d.getWorldQuaternion(this.rotRightHand)),n.LeftController?.hand?.visible){let a=n.LeftController.wrist;a&&(a.getWorldPosition(this.posLeftHand),a.getWorldQuaternion(this.rotLeftHand))}if(n.RightController?.hand?.visible){let a=n.RightController.wrist;a&&(a.getWorldPosition(this.posRightHand),a.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(e,t){e.clear();let i=e.createString(this.guid),n=e.createString(this.avatarId);Me.startVrUserStateBuffer(e),Me.addGuid(e,i),Me.addTime(e,Hv(this.time)),Me.addAvatarId(e,n),Me.addPosition(e,Ce.createVec3(e,this.position.x,this.position.y,this.position.z)),Me.addRotation(e,gi.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),Me.addScale(e,this.scale),Me.addPosLeftHand(e,Ce.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),Me.addPosRightHand(e,Ce.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),Me.addRotLeftHand(e,gi.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),Me.addRotRightHand(e,gi.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));let r=Me.endVrUserStateBuffer(e);e.finish(r,Vc);let s=e.asUint8Array();t.sendBinary(s)}setFromBuffer(e,t){if(!e)return;this.guid=e,this.time=t.time().toFloat64();let i=t.avatarId();i&&(this.avatarId=i);let n=t.position();n&&this.position.set(n.x(),n.y(),n.z());let r=t.rotation();r&&this.rotation.set(r.x(),r.y(),r.z(),r.w());let s=t.posLeftHand();s&&this.posLeftHand.set(s.x(),s.y(),s.z());let o=t.posRightHand();o&&this.posRightHand.set(o.x(),o.y(),o.z());let c=t.rotLeftHand();c&&this.rotLeftHand.set(c.x(),c.y(),c.z(),c.w());let d=t.rotRightHand();d&&this.rotRightHand.set(d.x(),d.y(),d.z(),d.w()),this.scale=t.scale()}},Ht=go;z(Ht,"invertRotation",new yt.Quaternion().setFromAxisAngle(new yt.Vector3(0,1,0),Math.PI)),z(Ht,"quat0",new yt.Quaternion),z(Ht,"quat1",new yt.Quaternion);var Ui=class extends M{webXR=null;debugAvatarUser=null;voip=null;async awake(){if(this.webXR||(this.webXR=this.gameObject.getComponent($)),this.webXR||(this.webXR=O.findObjectOfType($,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=O.findObjectOfType($,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=O.findObjectOfType(Ke,this.context)),mo){let e="debug-avatar-"+mo,t=new Lt(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof mo=="string"&&mo.length>0)if(await t.setAvatarOverride(mo)){let i=new Ht(e);i.position.y+=1;let n=.5;i.posLeftHand.y+=n,i.posLeftHand.x+=n,i.posRightHand.y+=n,i.posRightHand.x-=n,t.tryUpdate(i,0)}else t.destroy()}}onEnable(){if(!this.webXR&&(this.webXR=O.getComponent(this.gameObject,$),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),$.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),$.addEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),$.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.eventSub_ConnectionEvent=this.onConnected.bind(this),this.context.connection.beginListen("joined-room",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=>{let t=e.id!==null&&e.id!==void 0;!t||(console.log("webxr user left evt"),t&&(this.avatars[e.id]?.destroy(),this.avatars[e.id]=void 0))}),this.context.connection.beginListenBinrary(Vc,e=>{let t=e.guid();if(!t)return;let i=e.time().toFloat64(),n=this.tempState;n.setFromBuffer(t,e),this.onTryGetAvatar(t,i)?.tryUpdate(n,i)}),this.context.connection.beginListen("vr-session-update",e=>{let t=e.guid,i=e.time;this.onTryGetAvatar(t,i)?.tryUpdate(e,i)})}tempState=new Ht("");onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;let i=new Date().getTime()-t;if(i>5e3)return gp&&console.log("old data",i,e),null;let n=this.avatars[e];if(n===void 0)try{console.log("create new avatar");let r=new Lt(this.context,e,this.webXR);n=r,this.avatars[e]=r}catch(r){this.avatars[e]=null,console.error(r)}return n}onDisable(){this.eventSub_ConnectionEvent&&this.context.connection.stopListening("joined-room",this.eventSub_ConnectionEvent),$.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),$.removeEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),$.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}update(){let e=Gc();this.debugAvatarUser&&(this.debugAvatarUser.lastUpdate=e),this.detectPotentiallyDisconnectedAvatarsAndRemove();for(let t in this.avatars){let i=this.avatars[t];!i||i.update()}}_removeAvatarsList=[];detectPotentiallyDisconnectedAvatarsAndRemove(){let e=Gc();for(let t in this.avatars){let i=this.avatars[t];if(!i){this._removeAvatarsList.push(t);continue}e-i.lastUpdate>1e4&&(console.log("avatar timed out (didnt receive any updates in a while) - destroying it now"),i.destroy(),this.avatars[t]=void 0)}for(let t of this._removeAvatarsList)delete this.avatars[t];this._removeAvatarsList.length=0}buildLocalAvatar(){if(this.localAvatar)return;let e=this.context.connection?.connectionId??this.k_LocalAvatarNoNetworkingGuid;this.localAvatar=new Lt(this.context,e,this.webXR),this.localAvatar.isLocalAvatar=!0,this.localAvatar.setAvatarOverride(this.getAvatarId()),this.avatars[this.localAvatar.guid]=this.localAvatar}eventSub_ConnectionEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;eventSub_WebXRUpdateEvent=null;avatars={};localAvatar=null;k_LocalAvatarNoNetworkingGuid="local";onConnected(){gp&&console.log("Hey you are connected as "+this.context.connection.connectionId),this.localAvatar?.guid===this.k_LocalAvatarNoNetworkingGuid&&(this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0),this.localAvatar=null,this.xrState=null,this.ownership?.freeOwnership(),this.ownership=null)}onXRSessionStart(e){if(console.log("XR session started"),this.context.connection.send("webxr-user-joined",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null),this.xrState=null,this.ownership?.freeOwnership(),this.ownership=null,this.avatars)for(let t in this.avatars)this.avatars[t]?.updateFlags()}onXRSessionEnded(e){console.log("XR session ended"),this.context.connection.send("webxr-user-left",{id:this.context.connection.connectionId,mode:"vr"})}ownership=null;xrState=null;builder=new ft(1024);onXRSessionUpdate(e){this.xrState??=new Ht(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership??=new vn(this.context.connection,this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership.guid=this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid,this.buildLocalAvatar();let{frame:t,xr:i,rig:n}=e,r=t.getViewerPose(i.getReferenceSpace());if(!r)return;let s=r?.transform,o=s.position,c=s.orientation;this.xrState.update(n,o,c,this.webXR,this.getAvatarId()),this.localAvatar&&(this.context.connection.connectionId&&(this.localAvatar.guid=this.context.connection.connectionId),this.localAvatar.tryUpdate(this.xrState,0)),!(this.ownership&&!this.ownership.hasOwnership&&this.context.connection.isConnected&&(this.context.time.frameCount%120===0&&this.ownership.requestOwnership(),!this.ownership.hasOwnership))&&(!this.context.connection.isConnected||!this.context.connection.connectionId||this.xrState.sendAsBuffer(this.builder,this.context.connection))}getAvatarId(){return N("avatar")}};async function jv(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function Bv(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}var Wc=!1,Uc=!1;jv().then(l=>Wc=l);Bv().then(l=>Uc=l);var Ne=class extends M{enableVR=!0;enableAR=!0;defaultAvatar;createVRButton=!0;createARButton=!0;static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(Wc||Uc)}static get IsARSupported(){return Wc}static get IsVRSupported(){return Uc}static addEventListener(e,t){return this.events.addEventListener(e,t),t}static removeEventListener(e,t){return this.events.removeEventListener(e,t),t}static createVRButton(e,t){Ne.XRSupported||console.warn("WebXR is not supported on this device");let i=$r.createButton(e.context.renderer);return i.classList.add("webxr-ar-button"),i.classList.add("webxr-button"),this.resetButtonStyles(i),(t?.registerClick??!0)&&i.addEventListener("click",e.onClickedVRButton.bind(e)),i}static createARButton(e,t){let i=e.webAR?.getAROverlayContainer(),n={requiredFeatures:["hit-test"]};i&&(n.domOverlay={root:i},n.optionalFeatures=["dom-overlay"]);let r=Ia.createButton(e.context.renderer,n);return r.classList.add("webxr-ar-button"),r.classList.add("webxr-button"),Ne.resetButtonStyles(r),(t?.registerClick??!0)&&r.addEventListener("click",e.onClickedARButton.bind(e)),r}static resetButtonStyles(e){!e||(e.style.position="",e.style.bottom="",e.style.left="")}endSession(){let e=this.context.renderer.xr.getSession();e&&e.end()}get Rig(){return this.rig}controllers=[];get Controllers(){return this.controllers}get LeftController(){return this.controllers.length>0&&this.controllers[0].input?.handedness==="left"?this.controllers[0]:this.controllers.length>1&&this.controllers[1].input?.handedness==="left"?this.controllers[1]:null}get RightController(){return this.controllers.length>0&&this.controllers[0].input?.handedness==="right"?this.controllers[0]:this.controllers.length>1&&this.controllers[1].input?.handedness==="right"?this.controllers[1]:null}get ARButton(){return this._arButton}get VRButton(){return this._vrButton}rig;isInit=!1;_requestedAR=!1;_requestedVR=!1;_isInAR=!1;_isInVR=!1;_arButton;_vrButton;webAR=null;awake(){if(this.defaultAvatar&&typeof this.defaultAvatar=="string"&&(this.defaultAvatar=tt.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!O.findObjectOfType(Ui,this.context)){let e=O.addNewComponent(this.gameObject,Ui,!1);e.webXR=this}}onEnable(){if(this.isInit||!this.enableAR&&!this.enableVR)return;this.isInit=!0,this.context.renderer.xr.enabled=!0,this.webAR=new Rn(this);let e=Ne.XRSupported,t,i,n=document.createElement("div");n.classList.add("webxr-buttons"),this.context.domElement.append(n),this.enableAR&&this.createARButton&&(t=Ne.createARButton(this),this._arButton=t,n.appendChild(t)),this.createVRButton&&this.enableVR&&(e||!this.enableAR)&&(i=Ne.createVRButton(this),this._vrButton=i,n.appendChild(i)),setTimeout(()=>{Ne.resetButtonStyles(i),Ne.resetButtonStyles(t)},1e3)}_transformOrientation=new Pe.Quaternion;get TransformOrientation(){return this._transformOrientation}_currentHeadPose=null;get HeadPose(){return this._currentHeadPose}onBeforeRender(e){if(!e)return;let t=this.context.renderer.xr.getSession();if(t){let i=e.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(this._currentHeadPose=i,!i)return;let n=i?.transform;n&&this._transformOrientation.set(n.orientation.x,n.orientation.y,n.orientation.z,n.orientation.w);for(let r of this.controllers)r.onUpdate(t);this._isInAR&&this.webAR?.onUpdate(t,e)}Ne._isInXr===!1&&t&&this.onEnterXR(t,e),Ne.events.dispatchEvent({type:"xrUpdate",frame:e,xr:this.context.renderer.xr,rig:this.rig})}onClickedARButton(){this._isInAR||(this._requestedAR=!0,this._requestedVR=!1,this.captureCameraState())}onClickedVRButton(){if(!this._isInVR){if(this._requestedVR){this.onExitXR(null);return}this._requestedAR=!1,this._requestedVR=!0,this.captureCameraState(),this.ensureRig();for(let e=0;e<2;e++)oe.Create(this,e,this.gameObject,0);Ne.events.dispatchEvent({type:"requestVRSession"})}}captureCameraState(){this.context.mainCamera&&(this._originalCameraPosition.copy(q(this.context.mainCamera)),this._originalCameraRotation.copy(ve(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent)}ensureRig(){if(!this.rig){let e=O.findObjectOfType(Tn,this.context);e?(this.rig=e.gameObject,this.rig.rotateY(Math.PI)):(this.rig=new Pe.Group,this.rig.name="XRRig",this.context.scene.add(this.rig))}}_originalCameraParent=null;_originalCameraPosition=new Pe.Vector3;_originalCameraRotation=new Pe.Quaternion;onEnterXR(e,t){console.log("[XR] session begin",e),Ne._isInXr=!0,this.ensureRig();let i=this.context.renderer.xr.getReferenceSpace();if(i&&this.rig){let o=t.getViewerPose(i)?.transform.orientation;if(o){let c=new Pe.Quaternion(o.x,o.y,o.z,o.w),d=new Pe.Euler().setFromQuaternion(c);this.rig.rotateY(d.y)}}let n=this.context.renderer.xr;if(this.context.mainCamera){let s=n.getCamera(this.context.mainCamera);for(let o of s.cameras)o.layers.enableAll();this.rig.add(this.context.mainCamera)}let r=this._requestedAR?2:4;switch(vt.Global.Set(r),r){case 2:this._isInAR=!0,this.webAR?.onBegin(e);break;case 4:this._isInVR=!0,this.onEnterVR(e);break}e.addEventListener("end",()=>{console.log("[XR] session end"),Ne._isInXr=!1,this.onExitXR(e)}),this.onEnterXR_HandleMirrorWindow(e),Ne.events.dispatchEvent({type:"xrStarted",session:e})}onExitXR(e){this._isInAR&&e&&this.webAR?.onEnd(e),this._isInAR=!1,this._isInVR=!1,this._requestedAR=!1,this._requestedVR=!1,this.xrMirrorWindow&&(this.xrMirrorWindow.close(),this.xrMirrorWindow=null),this.destroyControllers(),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),ie(this.context.mainCamera,this._originalCameraPosition),Ae(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),vt.Global.Set(17),Ne.events.dispatchEvent({type:"xrStopped",session:e})}onEnterVR(e){}destroyControllers(){for(let e=this.controllers.length-1;e>=0;e-=1)this.controllers[e]?.destroy();this.controllers.length=0}xrMirrorWindow=null;onEnterXR_HandleMirrorWindow(e){!N("mirror")||setTimeout(()=>{if(!Ne.IsInWebXR)return;let t=new URL(window.location.href);Rr(t.searchParams,Kr,1),Rr(t.searchParams,"isMirror",1);let i=t.toString();this.xrMirrorWindow=window.open(i,"webxr sync","popup=yes"),this.xrMirrorWindow&&(this.xrMirrorWindow.onload=()=>{this.xrMirrorWindow&&(this.xrMirrorWindow.onbeforeunload=()=>{Ne.IsInWebXR&&e.end()})})},1e3)}},$=Ne;z($,"_isInXr",!1),z($,"events",new Pe.EventDispatcher),k([A(tt)],$.prototype,"defaultAvatar",2);var ts=class{webxr;reticle=null;hitTestSource=null;reticleActive=!0;previousBackground=null;previousEnvironment=null;sessionRoot=null;_previousParent=null;get context(){return this.webxr.context}constructor(e){this.webxr=e}arDomOverlay=null;arOverlayElement=null;getAROverlayContainer(){return this.arDomOverlay=this.webxr.context.domElement,this.arOverlayElement=this.arDomOverlay.getAROverlayContainer(),this.arOverlayElement}setReticleActive(e){this.reticleActive=e}onBegin(e){let t=this.webxr.context;this.reticleActive=!0;for(let i=0;i<4;i++)oe.Create(this.webxr,i,this.webxr.gameObject,1);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=O.findObjectOfType(Dt,t)),this.previousBackground=t.scene.background,this.previousEnvironment=t.scene.environment,t.scene.background=null,e.requestReferenceSpace("viewer").then(i=>{e.requestHitTestSource({space:i}).then(n=>{this.hitTestSource=n})}),!this.reticle&&this.sessionRoot&&(this.reticle=new Pe.Mesh(new Pe.RingGeometry(.07,.09,32).rotateX(-Math.PI/2),new Pe.MeshBasicMaterial),this.reticle.name="AR Placement reticle",this.reticle.matrixAutoUpdate=!1,this.reticle.visible=!1,this.webxr.scene?(this.webxr.scene.add(this.reticle),this.webxr.scene.visible=!0):console.warn("Could not found WebXR Rig")),this._previousParent=this.webxr.gameObject,ts.tempWebXRObject||(ts.tempWebXRObject=new Pe.Object3D),this.context.scene.add(ts.tempWebXRObject),O.addComponent(ts.tempWebXRObject,this.webxr),this.sessionRoot?(this.sessionRoot.webAR=this,this.sessionRoot?.onBegin(e)):console.warn("No WebARSessionRoot found in scene"),this.arDomOverlay&&this.arOverlayElement&&this.arDomOverlay.onEnterAR(e,this.arOverlayElement),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onEnd(e){this._previousParent&&(console.log("ADD",this._previousParent),O.addComponent(this._previousParent,this.webxr),this._previousParent=null),this.hitTestSource=null;let t=this.webxr.context;t.scene.background=this.previousBackground,t.scene.environment=this.previousEnvironment,this.sessionRoot&&this.sessionRoot.onEnd(this.webxr.Rig,e),this.arDomOverlay&&this.arDomOverlay.onExitAR(e),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onUpdate(e,t){if(!this.hitTestSource)return;let i=t.getHitTestResults(this.hitTestSource);if(i.length){let n=i[0],r=this.webxr.context.renderer.xr.getReferenceSpace();if(r){let s=n.getPose(r);if(this.sessionRoot?.onUpdate(this.webxr.Rig,e,s),this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&s)){let o=s.transform.matrix;this.reticle.matrix.fromArray(o),this.webxr.Rig&&this.reticle.matrix.premultiply(this.webxr.Rig.matrix)}}}else this.sessionRoot?.onUpdate(this.webxr.Rig,e,null),this.reticle&&(this.reticle.visible=!1)}},Rn=ts;z(Rn,"tempWebXRObject");var qc=!1;var is=class extends kt{static get HasAnySelected(){return this._active!==null}transformSelf=!0;selectStartEventListener=[];selectEndEventListener=[];constructor(){super(),this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new ee.Vector2}addDragEventListener(e,t){switch(e){case"selectstart":this.selectStartEventListener.push(t);break;case"selectend":this.selectEndEventListener.push(t);break}}_dragHelper=null;start(){}_draggingRigidbodies=[];allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||$.IsInWebXR)return;let t=O.getComponentInParent(e.object,is);!t||t!==this||(is.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){!this.allowEdit(this.gameObject)||$.IsInWebXR||is.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}_waitingForDragStart=null;onPointerDown(e){!this.allowEdit(this.gameObject)||$.IsInWebXR||(this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation())}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&($.IsInWebXR||(this.onDragEnd(e),e.StopPropagation()))}update(){if(!$.IsInWebXR){if(this._waitingForDragStart){if(!this._didDrag){let t=this.context.input.getPointerPositionDelta(0);if(t&&this._dragDelta.add(t),this._dragDelta.length()>2)this._didDrag=!0;else return}let e=this._waitingForDragStart;this._waitingForDragStart=null,this.onDragStart(e)}this._dragHelper&&this._dragHelper.hasSelected&&this.onUpdateDrag(),this._isDragging&&!this._dragHelper?.hasSelected&&this.onDragEnd(null)}}_isDragging=!1;_marker=null;_dragDelta;_didDrag=!1;onDragStart(e){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new ja(this.context.mainCamera);else return;if(!e||!e.object)return;let t=O.getComponentInParent(e.object,is);if(!t||t!==this)return;let i=e.object;this.transformSelf&&(i=this.gameObject);let n={selected:i,attached:i};for(let c of this.selectStartEventListener)c(this,n);if(!n.attached)return;n.attached,i=n.attached,this._isDragging=!0,this._dragHelper.setSelected(i,this.context);let r=O.getComponentInChildren(i,Qe);qc&&console.log("DRAG START",r,i),r&&(r.fastMode=!0,r?.requestOwnership()),this._marker=O.addNewComponent(i,It),this._draggingRigidbodies.length=0;let s=O.getComponentsInChildren(i,ce);s&&this._draggingRigidbodies.push(...s);let o=El();O.invokeOnChildren(this._dragHelper.selected,o("onDragStart"))}onUpdateDrag(){if(!!this._dragHelper){this._dragHelper.onUpdate(this.context);for(let e of this._draggingRigidbodies)e.wakeUp(),e.setBodyFromGameObject()}}onDragEnd(e){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;this._draggingRigidbodies.length=0;let t=this._dragHelper.selected;if(qc&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context),e?.object){let n=O.getComponentInChildren(e.object,Qe);n&&(n.fastMode=!1),this._marker&&this._marker.destroy()}for(let n of this.selectEndEventListener)n(this);let i=El();O.invokeOnChildren(t,i("onDragEnd"))}},Et=is;z(Et,"_active",null),z(Et,"lastHovered");var Qc=class{get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}_selected=null;_context=null;_camera;_cameraPlane=new ee.Plane;_hasGroundPlane=!1;_groundPlane=new ee.Plane;_groundOffset=new ee.Vector3;_groundOffsetFactor=0;_groundDistance=0;_groundPlanePoint=new ee.Vector3;_raycaster=new ee.Raycaster;_cameraPlaneOffset=new ee.Vector3;_intersection=new ee.Vector3;_worldPosition=new ee.Vector3;_inverseMatrix=new ee.Matrix4;_rbs=[];_groundLine;_groundMarker;constructor(e){this._camera=e;let t=new ee.Line(Qc.geometry),i=t.material;i.color=new ee.Color(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;let n=new ee.SphereGeometry(.5,22,22),r=new ee.MeshBasicMaterial({color:i.color}),s=new ee.Mesh(n,r);s.visible=!1,s.layers.set(2),this._groundMarker=s}setSelected(e,t){if(this._selected&&t)for(let i of this._rbs)i.wakeUp(),i.smoothedVelocity&&i.setVelocity(i.smoothedVelocity.x,i.smoothedVelocity.y,i.smoothedVelocity.z);if(this._selected&&_e.Remove(t,this._selected),this._selected=e,this._context=t,this._rbs.length=0,e?(t.scene.add(this._groundLine),t.scene.add(this._groundMarker)):(this._groundLine.removeFromParent(),this._groundMarker.removeFromParent()),this._selected){if(!t){console.error("DragHelper: no context");return}_e.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this._rbs=O.getComponentsInChildren(this._selected,ce),this.onUpdateScreenSpacePlane()}}_groundOffsetVector=new ee.Vector3(0,1,0);_requireUpdateGroundPlane=!0;_didDragOnGroundPlaneLastFrame=!1;onUpdate(e){if(!this._context)return;let t=32,i=68,n=83,r=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(i),s=this._context.input.getTouchesPressedCount()>=2||r;if(s){let c=this._context.input.getPointerPositionDelta(0);c&&(this._groundOffsetVector.set(0,1,0),this._selected?.rotateOnWorldAxis(this._groundOffsetVector,c.x*this._context.time.deltaTime))}let o=this._context.input.getPointerPositionRC(0);if(!!o&&(this._raycaster.setFromCamera(o,this._camera),this._selected)){qc&&console.log("UPDATE DRAG",this._selected),this._groundOffsetVector.set(0,1,0);let c=q(this._camera).clone().sub(q(this._selected)).normalize(),d=Math.abs(c.dot(this._groundOffsetVector)),a=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(i),h=!s&&d>.2&&!a&&this._context.input.getPointerPressedCount()<=1,u=this._didDragOnGroundPlaneLastFrame!==h;if(this._didDragOnGroundPlaneLastFrame=h,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!h||u)&&this.onUpdateGroundPlane(),this._requireUpdateGroundPlane=!1,this._hasGroundPlane)if(this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection)){let g=this._intersection.y;if(this._groundPlanePoint.copy(this._intersection).sub(this._groundOffset),this._groundPlanePoint.y=g,h){this._groundOffsetVector.set(0,1,0);let E=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(E,this._groundPlanePoint,!1),this.onDidUpdate();return}}else this._groundPlanePoint.set(0,99999,0);u&&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(e,t,i){if(!!this._selected){if(i){let n=q(this._selected);n.y=e.y,e=n}if(ie(this._selected,e),ie(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=t!==null,t){let n=q(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(n,n,n),ie(this._groundMarker,t)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;let e=this._context.input.getPointerPositionRC(0);!e||(this._raycaster.setFromCamera(e,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;let e=q(this._selected),t=new ee.Ray(new ee.Vector3(0,.1,0).add(e),new ee.Vector3(0,-1,0)),i=new je;i.ignore=[this._selected];let n=this._context.physics.raycastFromRay(t,i);for(let r=0;r<n.length;r++){let s=n[r];if(!s.face||this.contains(this._selected,s.object))continue;let o=new ee.Vector3(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(o,s.point);break}this._hasGroundPlane=!0,this._groundPlane.setFromNormalAndCoplanarPoint(t.direction.multiplyScalar(-1),t.origin),this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection),this._groundDistance=this._intersection.distanceTo(e),this._groundOffset.copy(this._intersection).sub(e)}onDidUpdate(){he.markDirty(this._selected);for(let e of this._rbs)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0}),e.setAngularVelocity(0,0,0)}contains(e,t){if(e===t)return!0;if(e.children){for(let i of e.children)if(this.contains(i,t))return!0}return!1}},ja=Qc;z(ja,"geometry",new ee.BufferGeometry().setFromPoints([new ee.Vector3(0,0,0),new ee.Vector3(0,-1,0)]));var Cn=class extends M{filesBackendUrl;localhost;_dragOver;_drop;onEnable(){this.filesBackendUrl=this.filesBackendUrl?pt.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 onDrop(e){if(console.log(e),!e.dataTransfer)return;e.preventDefault();let t=e.dataTransfer.items;if(!!t)for(let i in t){let n=t[i];if(n.kind==="file"){let r=n.getAsFile();if(!r)continue;console.log("Register file "+r.name+" to",this.filesBackendUrl,r);let s=await vp(r,this.context,this.filesBackendUrl);s&&this.addObject(e,s)}else n.kind==="string"&&n.type=="text/plain"&&n.getAsString(async r=>{console.log("dropped url",r);try{let s=new URL(r);if(!s)return;let o=await yp(s,this.context);o&&this.addObject(e,o)}catch{console.log("dropped string is not a valid URL!",r)}})}}async addObject(e,t){console.log("Dropped",t);let i=new je;i.setMask(16777215),i.screenPointFromOffset(e.offsetX,e.offsetY);let n=this.context.physics.raycast(i),r=t.scene;if(n&&n.length>0)for(let s of n){r.position.copy(s.point);break}this.gameObject.add(r),this.dispatchEvent(new CustomEvent("object-added",{detail:r}))}};k([A()],Cn.prototype,"filesBackendUrl",2),k([A()],Cn.prototype,"localhost",2);import{Vector3 as Nv,Quaternion as zv,Object3D as Ep}from"three";var bi=class extends kt{parent=null;object=null;limitCount=10;limitInterval=60;_currentCount=0;_startPosition=null;_startQuaternion=null;awake(){if(this.object){if(this.object===this.gameObject){console.error("Can not duplicate self");return}this.object.visible=!1,this._startPosition=this.object.position?.clone()??new Nv(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new zv(0,0,0,1)}let e=O.getComponentInParent(this.gameObject,Et);e?e.addDragEventListener("selectstart",(t,i)=>{if(this._currentCount>=this.limitCount){i.attached=null;return}let n=this.handleDuplication(i.selected);n&&(console.assert(n!==i.selected,"Duplicated object is original"),i.attached=n)}):console.warn("Could no find drag controls in parent",this.name),oe.addEventListener("select-start",(t,i)=>{if(this._currentCount>=this.limitCount){i.grab=null;return}let n=this.handleDuplication(i.selected);n&&(i.grab=n)}),this.cloneLimitIntervalFn()}cloneLimitIntervalFn(){this.destroyed||(this._currentCount>0&&(this._currentCount-=1),setTimeout(()=>{this.cloneLimitIntervalFn()},this.limitInterval/this.limitCount*1e3))}handleDuplication(e){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);let t=new ye;this.parent||(this.parent=this.gameObject.parent),this.parent&&(t.parent=this.parent.guid??this.parent.userData?.guid,t.keepWorldPosition=!0),t.position=this.worldPosition,t.rotation=this.worldQuaternion,t.context=this.context,this._currentCount+=1;let i=O.instantiateSynced(this.object,t);return console.assert(i!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),i}return null}handleMultiObject(e){return this.gameObject.type==="Group"||this.gameObject.type==="Object3D"?this.isInChildren(this.gameObject,e):!1}isInChildren(e,t){if(!e)return!1;if(e===t)return!0;if(e.children){for(let i of e.children)if(this.isInChildren(i,t))return!0}return!1}};k([A(Ep)],bi.prototype,"parent",2),k([A(Ep)],bi.prototype,"object",2),k([A()],bi.prototype,"limitCount",2),k([A()],bi.prototype,"limitInterval",2);var vi=class{method;enabled;constructor(e,t){this.method=e,this.enabled=t!==void 0?t:!0}invoke(...e){if(this.enabled!==!1){if(!this.method){console.warn("No function. Please check you assigned a method to invoke on export",this);return}this.method(...e)}}},Gv=l=>/^[A-Z]*$/.test(l),cr=class extends Event{args},Oe=class{target;key;setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let i="",n=!1;for(let r of this.key)n&&Gv(r)&&(i+="-"),n=!0,i+=r.toLowerCase();this.key=i}}_isInvoking=!1;methods=[];constructor(e){this.methods=e??[]}invoke(...e){if(this._isInvoking){console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this);return}this._isInvoking=!0;try{for(let t of this.methods)t.invoke(...e);if(typeof this.target=="object"&&typeof this.key=="string"){let t=this.target.dispatchEvent;if(typeof t=="function"){let i=new cr(this.key);i.args=e,t.call(this.target,i)}}}finally{this._isInvoking=!1}}addEventListener(e){return this.methods.push(new vi(e,!0)),e}removeEventListener(e){if(!!e)for(let t=this.methods.length-1;t>=0;t--)this.methods[t].method===e&&(this.methods[t].enabled=!1,this.methods.splice(t,1))}removeAllEventListeners(){this.methods.length=0}};var ns=class extends M{};import{FlyControls as Vv}from"three/examples/jsm/controls/FlyControls";var rs=class extends M{_controls=null;onEnable(){let e=O.getComponent(this.gameObject,ne)?.cam;this._controls=new Vv(e,this.context.renderer.domElement),this._controls.rollSpeed=.5,this._controls.movementSpeed=3,this._controls.dragToLook=!0}onDisable(){this._controls?.dispose(),this._controls=null}update(){this._controls&&this._controls.update(this.context.time.deltaTime)}};import*as _p from"three";import{Color as Wv}from"three";var qi=class extends M{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!di||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new _p.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=Sa(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),3)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}};k([A()],qi.prototype,"objectBounds",2),k([A(Wv)],qi.prototype,"color",2),k([A()],qi.prototype,"isGizmo",2);import{GLTFExporter as Qv}from"three/examples/jsm/exporters/GLTFExporter.js";import{BufferAttribute as Yc,Matrix4 as Uv,Vector3 as xp,Quaternion as qv}from"three";var bo=class{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;let i=this.writer,n=i.extensionsUsed,r={};t.extensions=t.extensions||{},t.extensions[this.name]=r;let s=new Uv,o=new Array,c=new Array,d=new Array;for(let g=0;g<e.count;g++){e.getMatrixAt(g,s);let E=new xp,b=new qv,y=new xp;s.decompose(E,b,y),o.push(E.x,E.y,E.z),c.push(b.x,b.y,b.z,b.w),d.push(y.x,y.y,y.z)}let a=new Float32Array(o),h=new Float32Array(c),u=new Float32Array(d);r.attributes={TRANSLATION:i.processAccessor(new Yc(a,3)),ROTATION:i.processAccessor(new Yc(h,4)),SCALE:i.processAccessor(new Yc(u,3))},n[this.name]=!0}};import{Object3D as Yv,Vector3 as Zv}from"three";var Sn=Ie,Ba="$___Export_Components",Xv="NEEDLE_components",Zc=class{[Gn]},Jc=class{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}},ss=class{get name(){return Xv}parser;nodeToObjectMap={};exportContext;objectToNodeMap={};context;writer;registerExport(e){e.register(t=>{let i=t.serializeUserData.bind(t);return this.writer=t,t.serializeUserData=(n,r)=>{try{this.serializeUserData(n,r),i(n,r)}finally{this.afterSerializeUserData(n,r)}},this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){let i=e.userData?.components;!i||i.length<=0||(delete e.userData.components,e[Ba]=i)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Sn&&console.log("DONE",JSON.stringify(t)),e[Ba]===void 0)return;let i=e[Ba];delete e[Ba],i!==null&&(e.userData.components=i)}writeNode(e,t){let i=this.writer.json.nodes.length;console.log(e.name,i,e.uuid);let n=new Jc(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){Sn&&console.log("AFTER",e);for(let t in this.exportContext){let i=this.exportContext[t],n=i.node,r=i.nodeDef,s=i.nodeIndex,o=n.userData?.components;if(!o||o.length<=0)continue;let c=new Zc;r.extensions=r.extensions||{},r.extensions[this.name]=c,this.context.object=n,this.context.nodeId=s,this.context.objectToNode=this.objectToNodeMap;let d=[];for(let a of o){this.context.target=a;let h=Tp(a,this.context);h!==null&&d.push(h)}d.length>0&&(c[Gn]=d,Sn&&console.log("DID WRITE",n,"nodeIndex",s,d))}}beforeRoot(){return Sn&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){let t=e.parser,i=t?.extensions;if(!i)return;let n=i[this.name];Sn&&console.log("After root",e,this.parser,i);let r=[];if(n===!0){let s=t.json.nodes;for(let o=0;o<s.length;o++){let c=await t.getDependency("node",o);this.nodeToObjectMap[o]=c}for(let o=0;o<s.length;o++){let c=s[o],d=o,a=c.extensions;if(!a)continue;let h=a[this.name];if(!h)continue;Sn&&console.log("NODE",c);let u=this.nodeToObjectMap[d];if(!u){console.error("Could not find object for node index: "+d,c,t);continue}r.push(this.createComponents(u,h))}}await Promise.all(r)}async createComponents(e,t){if(!t)return;let i=t[Gn];if(i){Sn&&console.log(e.name,i);for(let n in i){let r=i[n];Sn&&console.log("Serialized data",JSON.parse(JSON.stringify(r))),r&&this.parser&&await Br(this.parser,r),e.userData=e.userData||{},e.userData[Gn]=e.userData[Gn]||[],e.userData[Gn].push(r)}}}};var os=class extends lt{sceneRoot;start(){this.startCoroutine(this.updateGltfBox())}*updateGltfBox(){for(;;)for(let e=0;e<10;e++)yield}},jt=class extends M{binary=!0;objects=[];exporter;ext;async exportNow(e){console.log("DO EXPORT",this.objects);let t={binary:this.binary,pivot:jt.calculateCenter(this.objects)},i=await this.export(this.objects,t);this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?jt.saveArrayBuffer(i,e):jt.saveJson(i,e)}async export(e,t){if(e===null||e.length<=0){console.log("no objects set to export");return}this.exporter||(this.exporter=new Qv,this.exporter.register(o=>new bo(o)),this.ext=new ss,this.ext.registerExport(this.exporter)),jt.filterTopmostParent(e);let i={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:t?.binary??!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:jt.collectAnimations(e)},n=new Yv;t?.pivot&&n.position.sub(t.pivot),console.log("EXPORT",e),e.forEach(o=>{o&&(n.children.push(o),o.matrixAutoUpdate=!1,o.matrix.copy(o.matrixWorld),O.getComponentsInChildren(o,Te).forEach(c=>{O.isActiveInHierarchy(c.gameObject)&&c.setInstancingEnabled(!1)}))});let r=new Fr(n);return this.ext.context=r,new Promise((o,c)=>{try{this.exporter?.parse(n,d=>{s(),o(d)},d=>{s(),c(d)},i)}catch(d){console.error(d),c(d)}finally{console.log("FINALLY")}});function s(){e.forEach(o=>{!o||(o.matrixAutoUpdate=!0,O.getComponentsInChildren(o,Te).forEach(c=>{O.isActiveInHierarchy(c.gameObject)&&c.setInstancingEnabled(!1)}))})}}static saveArrayBuffer(e,t){this.save(new Blob([e],{type:"application/octet-stream"}),t)}static saveJson(e,t){this.save("data: text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(e)),t)}static save(e,t){let i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}static collectAnimations(e,t){t=t||[];for(let i of e)!i||i.traverseVisible(n=>{n.animations&&n.animations.length>0&&t.push(...n.animations)});return t}static calculateCenter(e,t){let i=t||new Zv;return i.set(0,0,0),e.forEach(n=>{i.add(q(n))}),console.log(i),i.divideScalar(e.length),i}static filterTopmostParent(e){if(!(e.length<=0))for(let t=0;t<e.length;t++){let i=e[t];if(!i){e.splice(t,1),t--;continue}for(;i.parent;){if(e.includes(i.parent)){e.splice(t,1),t--;break}i=i.parent}}}};import{Color as Fa,GridHelper as Jv}from"three";var Xi=class extends M{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!di)return;let e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new Jv(e,t,this.color0??new Fa(.4,.4,.4),this.color1??new Fa(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset),this.gameObject.add(this.gridHelper))}};k([A()],Xi.prototype,"isGizmo",2),k([A(Fa)],Xi.prototype,"color0",2),k([A(Fa)],Xi.prototype,"color1",2);import{GroundProjectedEnv as $v}from"three/examples/jsm/objects/GroundProjectedEnv.js";var Qi=class extends M{set scale(e){this._scale=e,this.env?.scale.setScalar(e)}get scale(){return this._scale}_scale=20;set radius(e){this._radius=e,this.env&&(this.env.height=e)}get radius(){return this._radius}_radius=100;set height(e){this._height=e,this.env&&(this.env.height=e)}get height(){return this._height}_height=100;_lastEnvironment;env;_watcher;onEnable(){this.updateProjection(),this._watcher||(this._watcher=new Oo(this.context.scene,"environment"),this._watcher.subscribeWrite(this.updateProjection.bind(this))),this._watcher.apply()}onDisable(){this._watcher?.revoke(),this.env?.removeFromParent()}updateProjection(){!this.context.scene.environment||((!this.env||this.context.scene.environment!==this._lastEnvironment)&&(console.log("Create/Update Ground Projection",this.context.scene.environment.name),this.env=new $v(this.context.scene.environment)),this._lastEnvironment=this.context.scene.environment,this.env.parent||this.gameObject.add(this.env),this.env.scale.setScalar(this._scale),this.env.radius=this._radius,this.env.height=this._height,this.env.isObject3D===!0&&this.env.layers.set(2))}};k([A()],Qi.prototype,"scale",1),k([A()],Qi.prototype,"radius",1),k([A()],Qi.prototype,"height",1);import*as it from"three";import{Color as Kv}from"three";function $c(l){return l*Math.PI/180}var Rp=300,Cp=N("debuglights");var Ye=class extends M{type=0;range=1;spotAngle=1;innerSpotAngle=1;color=new it.Color(16777215);set shadowNearPlane(e){if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,this.light?.shadow?.camera!==void 0)){let t=this.light.shadow.camera;t.near=e}}get shadowNearPlane(){return this._shadowNearPlane}_shadowNearPlane=.1;set shadowBias(e){e!==this._shadowBias&&(this._shadowBias=e,this.light?.shadow?.bias!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}_shadowBias=0;set shadowNormalBias(e){e!==this._shadowNormalBias&&(this._shadowNormalBias=e,this.light?.shadow?.normalBias!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}_shadowNormalBias=1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e===1||e===2)}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=4;set intensity(e){if(this._intensity=e,this.light){let t=1;if(this.context.isInXR&&this._webARRoot){let i=this._webARRoot?.arScale;typeof i=="number"&&i>0&&(t/=i)}this.light.intensity=e*t}}get intensity(){return this._intensity}_intensity=1;get shadowDistance(){let e=this.light;return e?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;let t=this.light;if(t){let i=t.shadow.camera;i.far=e,i.updateProjectionMatrix()}}_shadowDistance;shadowWidth;shadowHeight;get shadowResolution(){let e=this.light;return e?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;let t=this.light;t&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!0)}_shadowResolution=void 0;get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}light=void 0;getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}updateIntensity(){this.intensity=this._intensity}awake(){this.color=new it.Color(this.color??16777215)}onEnable(){this.createLight(),!this.isBaked&&(this.light&&(this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),2),this._webXRStartedListener=$.addEventListener("xrStarted",this.onWebXRStarted.bind(this)),this._webXREndedListener=$.addEventListener("xrStopped",this.onWebXREnded.bind(this)))}onDisable(){$.removeEventListener("xrStarted",this._webXRStartedListener),$.removeEventListener("xrStopped",this._webXREndedListener)}_webXRStartedListener;_webXREndedListener;_webARRoot;onWebXRStarted(){this._webARRoot=this.gameObject.getComponentInParent(Dt)??void 0,this.startCoroutine(this._updateLightIntensityInARRoutine())}*_updateLightIntensityInARRoutine(){for(;this.context.isInXR;){yield,this.updateIntensity();for(let e=0;e<30;e++)yield}}onWebXREnded(){this.updateIntensity()}createLight(){if(this.light)return;let e=this.selfIsLight;if(e)switch(this.light=this.gameObject,this.type){case 1:this.setDirectionalLight(this.light);break}else switch(this.type){case 1:let t=new it.DirectionalLight(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-Rp*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),Cr(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Cp){let s=new it.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(s)}break;case 0:let i=new it.SpotLight(this.color,this.intensity*Math.PI,this.range,$c(this.spotAngle/2),1-$c(this.innerSpotAngle/2)/$c(this.spotAngle/2),2);i.position.set(0,0,0),i.rotation.set(0,0,0),this.light=i;let n=i.target;i.add(n),n.position.set(0,0,this.range),n.rotation.set(0,0,0);break;case 2:let r=new it.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=r;break}if(this.light!==void 0){this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this._shadowResolution!==void 0&&this._shadowResolution>4?(this.light.shadow.mapSize.width=this._shadowResolution,this.light.shadow.mapSize.height=this._shadowResolution):(this.light.shadow.mapSize.width=2048,this.light.shadow.mapSize.height=2048),this.light.shadow.bias=this.shadowBias*1e-5,this.light.shadow.normalBias=this.shadowNormalBias*1e-4;let t=this.light.shadow.camera;if(t.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?t.far=this._shadowDistance:t.far=Rp*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)t.left=-this.shadowWidth/2,t.right=this.shadowWidth/2;else{let i=this.gameObject.scale.x;t.left*=i,t.right*=i}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{let i=this.gameObject.scale.y;t.top*=i,t.bottom*=i}this.light.shadow.needsUpdate=!0,Cp&&this.context.scene.add(new it.CameraHelper(t)),this.isBaked?this.light.removeFromParent():e||this.gameObject.add(this.light)}}*updateMainLightRoutine(){for(;;){this.type===1&&((!this.context.mainLight||this.intensity>this.context.mainLight.intensity)&&(this.context.mainLight=this),yield);break}}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}};k([A()],Ye.prototype,"type",2),k([A(Kv)],Ye.prototype,"color",2),k([A()],Ye.prototype,"shadowNearPlane",1),k([A()],Ye.prototype,"shadowBias",1),k([A()],Ye.prototype,"shadowNormalBias",1),k([A()],Ye.prototype,"shadows",1),k([A()],Ye.prototype,"lightmapBakeType",2),k([A()],Ye.prototype,"intensity",1),k([A()],Ye.prototype,"shadowDistance",1),k([A()],Ye.prototype,"shadowResolution",1);var FO=new it.Vector3(0,0,0);import*as Na from"three";import{Vector3 as ey}from"three";var as=N("debugLODs"),ty=N("noLODs");var yi=class{screenRelativeTransitionHeight;distance;renderers};k([A()],yi.prototype,"screenRelativeTransitionHeight",2),k([A()],yi.prototype,"distance",2),k([A()],yi.prototype,"renderers",2);var Kc=class{model;renderers;constructor(e,t){this.model=t,this.renderers=[];for(let i of t.renderers){let n=this.findRenderer(i,e.gameObject);n&&n.gameObject?this.renderers.push(n):as&&console.warn("Renderer not found: "+i,e.gameObject)}}findRenderer(e,t){let i=O.foreachComponent(t,n=>n.guid===e||Object.getPrototypeOf(n)?.guid===e?n:null);if(i)return i;for(let n of t.children){let r=this.findRenderer(e,n);if(r)return r}return null}},Pn=class extends M{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(!ty&&!this._lodsHandler&&!!this.gameObject&&(as&&console.log(this),this.lodModels&&Array.isArray(this.lodModels))){let e=0,t=[];for(let n of this.lodModels){e=Math.max(n.distance,e);let r=new Kc(this,n);this._lods.push(r);for(let s of r.renderers)t.includes(s)||t.push(s)}this._lodsHandler=new Array;for(let n=0;n<t.length;n++){let r=new Na.LOD;this._lodsHandler.push(r),this.gameObject.add(r)}let i=new Na.Object3D;as&&console.log(t);for(let n=0;n<t.length;n++){let r=t[n],s=this._lodsHandler[n],o=r.gameObject,c=0,d=0;as&&console.log(n,o.name);for(let h of this._lods){let u=null;h.renderers.includes(r)?u=o:u=i,as&&console.log("add",h.model.distance,u.name);let g=h.model.distance;d=g-c,c=Math.max(g,c),this.onAddLodLevel(s,u,g)}let a=c+d;as&&console.log("cull",a),this.onAddLodLevel(s,i,a)}}}update(){if(!this.gameObject||!this._lodsHandler)return;let e=this.context.mainCamera;if(!!e)for(let t of this._lodsHandler)t.update(e)}onAddLodLevel(e,t,i){e.addLevel(t,i*this._distanceFactor);let n={lod:e,levelIndex:e.levels.length-1,distance:i};this._settings.push(n)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(let t of this._settings){let i=t.lod.levels[t.levelIndex];i.distance=t.distance*e}}}};k([A(ey)],Pn.prototype,"localReferencePoint",2),k([A(yi)],Pn.prototype,"lodModels",2);var ls=class extends M{onEnable(){this.enabled&&this.context.physics.addMeshCollider(this.gameObject)}};var cs=class extends M{},ds=class extends M{};var ed=N("debugnestedgltf"),dr=class extends M{filePath;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){this.filePath?.preload()}async start(){if(this._isLoadingOrDoneLoading)return;ed&&console.log(this,this.guid);let e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;let t=new ye;t.idProvider=new We(this.hash(this.guid)),t.parent=e,this.gameObject.updateMatrix();let i=this.gameObject.matrix;ed&&console.log("Load nested:",this.filePath?.uri??this.filePath,this.gameObject.position);let n=await this.filePath?.instantiate?.call(this.filePath,t);n&&(n.matrixAutoUpdate=!1,n.matrix.identity(),n.applyMatrix4(i),n.matrixAutoUpdate=!0),this.destroy(),ed&&console.log("Nested loading done:",this.filePath?.uri??this.filePath,n)}}hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}};k([A(tt)],dr.prototype,"filePath",2);import*as us from"three";var hs=class extends M{from;affectPosition;affectRotation;alignLookDirection;levelLookDirection;positionOffset;rotationOffset;update(){if(!this.from)return;var e=q(this.from),t=ve(this.from);this.affectPosition&&ie(this.gameObject,e.add(this.positionOffset));let i=new us.Euler(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),n=new us.Quaternion().setFromEuler(i);this.affectRotation&&Ae(this.gameObject,t.multiply(n));let r=new us.Vector3;this.from.getWorldDirection(r).multiplyScalar(50),this.levelLookDirection&&(r.y=0),this.alignLookDirection&&this.gameObject.lookAt(r)}};import*as xe from"three";import*as Kt from"three";var ps=class{randomizeRotationDirection=0;duration=5;loop=!0;prewarm=!1;startDelay=void 0;startDelayMultiplier=0;startLifetime=void 0;startLifetimeMultiplier=5;startSpeed=void 0;startSpeedMultiplier=5;startSize3D=!1;startSize=void 0;startSizeMultiplier=1;startSizeX=void 0;startSizeXMultiplier=1;startSizeY=void 0;startSizeYMultiplier=1;startSizeZ=void 0;startSizeZMultiplier=1;startRotation3D=!1;startRotation=void 0;startRotationMultiplier=0;startRotationX=void 0;startRotationXMultiplier=0;startRotationY=void 0;startRotationYMultiplier=0;startRotationZ=void 0;startRotationZMultiplier=0;flipRotation=0;startColor=new Kt.Color(1,1,1);startColor1=new Kt.Color(0,0,0);gravityModifier=void 0;gravityModifierMultiplier=0;simulationSpace=0;customSimulationSpace=null;simulationSpeed=1;useUnscaledTime=!1;scalingMode=1;playOnAwake=!0;maxParticles=1e3;emitterVelocityMode=1;stopAction=0;ringBufferMode=0;ringBufferLoopRange=new Kt.Vector2(0,1);cullingMode=0},fs=class{burstCount=0;enabled=!0;rate=10;rateMutliplier=1;rateOverDistance=0;rateOverDistanceMultiplier=0;rateOverTime=0;rateOverTimeMultiplier=0},ms=class{shapeType=td.Box;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcmode=0;box=new Kt.Vector3(1,1,1);boxThickness=new Kt.Vector3(0,0,0);position=new Kt.Vector3(0,0,0);rotation=new Kt.Vector3(0,0,0);scale=new Kt.Vector3(1,1,1);radius=1;sphericalDirectionAmount=0},td=(p=>(p[p.Sphere=0]="Sphere",p[p.SphereShell=1]="SphereShell",p[p.Hemisphere=2]="Hemisphere",p[p.HemisphereShell=3]="HemisphereShell",p[p.Cone=4]="Cone",p[p.Box=5]="Box",p[p.Mesh=6]="Mesh",p[p.ConeVolume=7]="ConeVolume",p[p.Circle=10]="Circle",p[p.SingleSidedEdge=11]="SingleSidedEdge",p[p.MeshRenderer=12]="MeshRenderer",p[p.SkinnedMeshRenderer=13]="SkinnedMeshRenderer",p[p.BoxShell=14]="BoxShell",p[p.BoxEdge=15]="BoxEdge",p[p.Donut=16]="Donut",p[p.Rectangle=17]="Rectangle",p[p.Sprite=18]="Sprite",p[p.SpriteRenderer=19]="SpriteRenderer",p))(td||{});var Sp=N("debugparticles"),id=class{age=0;lifetime=0;position;velocity;color},hr=class extends M{get mainTexture(){if(this.sharedMaterial){let e=this.context.assets.findTexture(this.sharedMaterial);if(e)return e}return null}getMesh(e){return this.mesh?this.context.assets.findMesh(this.mesh):null}sharedMaterial;mesh;awake(){Sp&&console.log(this)}},gs=class extends M{main;emission;shape;renderer;geometry;material;particlesMesh;positions;positionsArray;particleStates=[];activeCount=0;shapeRotation=new xe.Quaternion;tempVec3=new xe.Vector3;tempQuat=new xe.Quaternion;awake(){this.renderer=O.getComponent(this.gameObject,hr),Sp&&console.log(this)}onEnable(){if(this.geometry)return;this.particleStates=[],this.shapeRotation.setFromEuler(new xe.Euler(this.shape.rotation.x,this.shape.rotation.y,this.shape.rotation.z)),this.geometry=new xe.BufferGeometry,this.positionsArray=new Float32Array(this.main.maxParticles*3),this.positions=new xe.Float32BufferAttribute(this.positionsArray,3),this.geometry.setAttribute("position",this.positions);let e=new Float32Array(this.main.maxParticles*3);for(let i=0;i<e.length;i++)e[i*3]=1,e[i*3+1]=1,e[i*3+2]=1;let t=new xe.Float32BufferAttribute(e,3);this.geometry.setAttribute("color",t),this.material=new xe.PointsMaterial({size:this.main.startSize,color:16777215,vertexColors:!0}),this.material.map=this.renderer.mainTexture,this.particlesMesh=new xe.Points(this.geometry,this.material),this.particlesMesh.layers.enable(2),this.gameObject.add(this.particlesMesh),this.activeCount=this.main.prewarm?this.main.maxParticles:0}update(){if(!this.geometry)return;let e=this.context.time.deltaTime;this.emit(e);for(let t=0;t<this.activeCount;t+=1){let i=this.particleStates[t];if(!i)continue;let n=i.velocity.x*e,r=i.velocity.y*e,s=i.velocity.z*e;i.position.x+=n,i.position.y+=r,i.position.z+=s,this.updateOverLifetime(t,i),this.geometry.attributes.position.setXYZ(t,i.position.x,i.position.y,i.position.z),this.geometry.attributes.color.setXYZ(t,i.color.r,i.color.g,i.color.b)}this.geometry&&(this.geometry.attributes.position.needsUpdate=!0,this.geometry.setDrawRange(0,this.activeCount))}emit(e){let t=this.activeCount;for(let i=0;i<t;i+=1){if(i>=this.particleStates.length){let r=new id;r.lifetime=this.main.startLifetime??1,r.position=new xe.Vector3,r.velocity=new xe.Vector3,r.color=new xe.Color(1,0,0),this.particleStates.push(r),this.initializeParticle(i,r),r.age=r.lifetime*Math.random()}let n=this.particleStates[i];if(n.age>n.lifetime){this.activeCount-=1,this.activeCount=Math.max(0,this.activeCount),this.initializeParticle(i,n);continue}n.age+=e,this.particleStates[i]=n}this.activeCount+=e*this.emission.rate,this.activeCount=Math.min(this.main.maxParticles,this.activeCount)}initializeParticle(e,t){if(!this.geometry)return;t.age=0,t.color.set(this.main.startColor),this.main.startColor1&&t.color.lerp(this.main.startColor1,Math.random()),this.geometry.attributes.color.needsUpdate=!0,this.assignPosition(t.position),this.assignVelocity(t.position,t.velocity);let i=t.position;i.multiply(this.shape.scale),i.applyQuaternion(this.shapeRotation),i.add(this.shape.position),this.particleStates.splice(e,1),this.particleStates.push(t)}updateOverLifetime(e,t){}assignPosition(e){switch(this.shape.shapeType){case 0:e.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).multiplyScalar(this.shape.radius);break;case 5:e.set(Math.random()-.5,Math.random()-.5,Math.random()-.5);break;default:e.set(0,0,0);break}}assignVelocity(e,t){switch(this.shape.shapeType){case 0:t.set(e.x,e.y,e.z);break;case 5:t.set(0,0,1),this.shape.sphericalDirectionAmount>0&&(this.tempVec3.set(e.x,e.y,e.z).multiply(this.shape.scale).normalize(),t.lerp(this.tempVec3,this.shape.sphericalDirectionAmount));break;case 4:let i=new xe.Vector3(0,1,0);t.copy(i);break;case 10:this.tempQuat.setFromAxisAngle(this.tempVec3.set(0,0,1),Math.random()*Q.toRadians(this.shape.arc)),t.copy(this.tempVec3.set(1,0,0).applyQuaternion(this.tempQuat));break;default:t.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1);break}switch(t.normalize(),this.shape.shapeType){case 10:e.add(t).multiplyScalar(this.shape.radius);break}t.multiplyScalar(this.main.startSpeedMultiplier)}};import*as Op from"three";function*Pp(l,e=null){let t=e?e.time:Z.Current.time,i=t.time;for(;t.time-i<l;)yield}var ht=class extends M{awake(){this.context.connection.beginListen("joined-room",this.tryAssignColor.bind(this))}_didAssignPlayerColor=!1;onEnable(){this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}*waitForConnection(){for(;!this.destroyed&&this.enabled&&(yield Pp(.2),!this.tryAssignColor()););}tryAssignColor(){let e=O.getComponentInParent(this.gameObject,fe);return e&&e.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(e.connectionId),!0):!1}assignUserColor(e){let t=ht.hashCode(e),i=ht.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){let n=this.gameObject;this.assignColor(i,e,n)}else if(this.gameObject.children)for(let n of this.gameObject.children){let r=n;r.material&&r.material.color&&this.assignColor(i,e,r)}}assignColor(e,t,i){let n=i.material;!n||(n._playerMaterial!==t?(n=n.clone(),n._playerMaterial=t,i.material=n):console.log("DONT CLONE",n),n.color=e)}static hashCode(e){var t=0,i,n;if(e.length===0)return t;for(i=0;i<e.length;i++)n=e.charCodeAt(i),t=(t<<5)-t+n,t|=0;return t}static colorFromHashCode(e){let t=(e&16711680)>>16,i=(e&65280)>>8,n=e&255;return new Op.Color(t/255,i/255,n/255)}};import*as za from"three";import{Object3D as ry}from"three";function ny(){return new Promise((l,e)=>{let i=()=>{i!=null&&(document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i),l())};document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)})}async function Ap(l){await ny(),l()}var nd=N("debugvideo");var nt=class extends M{renderer=null;playOnAwake=!0;playOnEnable;targetMaterialProperty;time=0;_playbackSpeed=1;get playbackSpeed(){return this.videoElement?.playbackRate??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this.videoElement&&(this.videoElement.playbackRate=e)}_isLooping=!1;get isLooping(){return this.videoElement?.loop??this._isLooping}set isLooping(e){this._isLooping=e,this.videoElement&&(this.videoElement.loop=e)}get currentTime(){return this.videoElement?.currentTime??this.time}set currentTime(e){this.videoElement?this.videoElement.currentTime=e:this.time=e}get isPlaying(){let e=this.videoElement;return e?e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA:!1}get crossOrigin(){return this.videoElement?.crossOrigin??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this.videoElement&&(e!==null?this.videoElement.setAttribute("crossorigin",e):this.videoElement.removeAttribute("crossorigin"))}_crossOrigin="anonymous";audioOutputMode=1;source;clip=null;url=null;videoElement=null;videoTexture=null;videoMaterial=null;_isPlaying=!1;wasPlaying=!1;setClipURL(e){this.url!==e&&(this.url=e,this.source=1,nd&&console.log("set url",e),this.videoElement&&(this.videoElement.src=e,this._isPlaying&&this.videoElement.play()))}awake(){this.create(this.playOnAwake),window.addEventListener("visibilitychange",e=>{switch(document.visibilityState){case"hidden":this.wasPlaying=this._isPlaying,this.pause();break;case"visible":this.wasPlaying&&this.play();break}})}onEnable(){this.playOnEnable===!0&&this.handleBeginPlaying(!0)}onDisable(){this.pause()}onDestroy(){this.videoElement&&(this.videoElement.parentElement?.removeChild(this.videoElement),this.videoElement=null),this.videoTexture&&(this.videoTexture.dispose(),this.videoTexture=null)}_receivedInput=!1;constructor(){super(),Ap(()=>{this._receivedInput=!0,this.updateVideoElementSettings()})}play(){!this.videoElement||this._isPlaying&&!this.videoElement?.ended&&!this.videoElement?.paused||(this._isPlaying=!0,this._receivedInput||(this.videoElement.muted=!0),this.updateVideoElementSettings(),this.videoElement?.play().catch(e=>{console.warn(e)}),nd&&console.log("play",this.videoElement))}stop(){this._isPlaying=!1,this.videoElement&&(this.videoElement.currentTime=0,this.videoElement.pause())}pause(){this._isPlaying=!1,this.videoElement?.pause()}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url;break}!t||(this.videoElement||(this.videoElement=this.createVideoElement(),this.context.domElement?.prepend(this.videoElement),this.updateVideoElementStyles()),typeof t=="string"?this.videoElement.src=t:this.videoElement.srcObject=t,this.videoTexture||(this.videoTexture=new za.VideoTexture(this.videoElement)),this.videoTexture.flipY=!1,this.videoTexture.encoding=za.sRGBEncoding,this.handleBeginPlaying(e))}createVideoElement(){let e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),nd&&console.log("create video elment",e),e}handleBeginPlaying(e){if(!this.enabled||!this.videoElement)return;let t=this.gameObject.material;if(t)if(t!==this.videoMaterial&&(this.videoMaterial=t.clone(),this.gameObject.material=this.videoMaterial),!this.targetMaterialProperty)this.videoMaterial.map=this.videoTexture;else switch(this.targetMaterialProperty){default:this.videoMaterial.map=this.videoTexture;break}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&this.play()}updateVideoElementSettings(){!this.videoElement||(this.videoElement.loop=this._isLooping,this.videoElement.currentTime=this.currentTime,this.videoElement.playbackRate=this._playbackSpeed,this.videoElement.playsInline=!0,this.videoElement.muted=!this._receivedInput&&this.audioOutputMode!==0,(this.playOnAwake||this.playOnEnable)&&(this.videoElement.autoplay=!0))}updateVideoElementStyles(){!this.videoElement||(this.videoElement.style.userSelect="none",this.videoElement.style.visibility="hidden",this.videoElement.style.display="none")}};k([A(ry)],nt.prototype,"renderer",2),k([A()],nt.prototype,"playOnAwake",2),k([A()],nt.prototype,"playOnEnable",2),k([A()],nt.prototype,"targetMaterialProperty",2),k([A()],nt.prototype,"time",2),k([A()],nt.prototype,"playbackSpeed",1),k([A()],nt.prototype,"isLooping",1);var bs=class extends M{streamOnAwake=!0;start(){this.streamOnAwake&&this.open()}requestOpen=!1;captureStream=null;async open(e=!1){if(!(this.captureStream&&!e)){this.close(),this.requestOpen=!0;try{let t=O.getComponentInChildren(this.gameObject,nt);if(t){let i={video:!0,audio:!1};this.captureStream=await navigator.mediaDevices.getDisplayMedia(i),this.captureStream&&this.requestOpen&&(t.clip=this.captureStream,t.create(!0))}}catch(t){console.error("Error: "+t)}}}close(){if(this.requestOpen=!1,this.captureStream){for(let e of this.captureStream.getTracks())e.stop();this.captureStream=null}}};import{ShadowMaterial as sy,AdditiveBlending as oy}from"three";var On=class extends M{mode=0;shadowColor=new we(0,0,0,1);awake(){switch(this.mode){case 0:this.applyShadowMaterial();break;case 1:this.applyLightBlendMaterial();break}}applyLightBlendMaterial(){let e=O.getComponent(this.gameObject,Te);if(e){let t=e.material;t.blending=oy,this.applyMaterialOptions(t),t.onBeforeCompile=i=>{i.fragmentShader=i.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
123
+ `,defines:{USE_LIGHTMAP:""}})}};var A=function(l){if(l===void 0&&(l=null),!Array.isArray(l))l=Bu(l);else for(let e=0;e<l.length;e++){let t=l[e];l[e]=Bu(t)}return function(e,t){Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});let i=e.$serializedTypes=e.$serializedTypes||{};i[t]=l}};function Bu(l){switch(l?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return l}import{Vector4 as Kb}from"three";import{NeverStencilFunc as Ib,LessStencilFunc as Mb,EqualStencilFunc as Lb,LessEqualStencilFunc as Db,GreaterStencilFunc as Hb,NotEqualStencilFunc as jb,GreaterEqualStencilFunc as Bb,AlwaysStencilFunc as Fb,ZeroStencilOp as Nb,KeepStencilOp as zb,ReplaceStencilOp as Gb,IncrementStencilOp as Vb,DecrementStencilOp as Wb,IncrementWrapStencilOp as Ub,DecrementWrapStencilOp as qb,InvertStencilOp as Xb}from"three";var rc=N("debugstencil");function Qb(l,e){return(l&1<<e.layer)!=0}var Kn=class{static applyStencil(e){if(!e)return;let t=e.sourceId;if(rc&&console.log(t,Kn.stencils),!t)return;let i=Kn.stencils[t];if(!!i)for(let n=i.length-1;n>=0;n--){let r=i[n];if(Qb(r.layer,e)){rc&&console.log(r);let o=e.material?.clone();o&&(e.material=o,e.gameObject.renderOrder=r.event*1e3+r.index*50,o.stencilWrite=!0,o.stencilWriteMask=255,o.stencilFuncMask=255,o.stencilRef=r.value,o.stencilFunc=r.compareFunc,o.stencilZPass=r.passOp,o.stencilFail=r.failOp,o.stencilZFail=r.zFailOp);break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){let t=this.parser.json.extensions;if(t){let i=t[Zb];if(i){rc&&console.log(i);let n=i.stencil;if(n&&Array.isArray(n))for(let r of n){let o={...r};o.compareFunc=Yb(o.compareFunc),o.passOp=oc(o.passOp),o.failOp=oc(o.failOp),o.zFailOp=oc(o.zFailOp),Kn.stencils[this.source]||(Kn.stencils[this.source]=[]),Kn.stencils[this.source].push(o)}}}return null}},er=Kn;z(er,"stencils",{});function oc(l){switch(l){case 0:return zb;case 1:return Nb;case 2:return Gb;case 3:return Vb;case 4:return Wb;case 6:return Ub;case 7:return qb;case 5:return Xb}return 0}function Yb(l){switch(l){case 1:return Ib;case 2:return Mb;case 3:return Lb;case 4:return Db;case 5:return Hb;case 6:return jb;case 7:return Bb;case 8:return Fb}return 0}var Zb="NEEDLE_render_objects";import{TextureLoader as Jb}from"three";import{GLTFLoader as $b}from"three/examples/jsm/loaders/GLTFLoader";import{DRACOLoader as sc}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as Fu}from"three/examples/jsm/loaders/KTX2Loader.js";var os=N("debugdecoders"),Ut,bn;function ac(l){l!==void 0&&typeof l=="string"&&(Ut||(Ut=new sc),os&&console.log("Setting draco decoder path to",l),Ut.setDecoderPath(l))}function lc(l){l!==void 0&&typeof l=="string"&&(Ut||(Ut=new sc),os&&console.log("Setting draco decoder type to",l),Ut.setDecoderConfig({type:l}))}function cc(l){l!==void 0&&typeof l=="string"&&(bn||(bn=new Fu),os&&console.log("Setting ktx2 transcoder path to",l),bn.setTranscoderPath(l))}function tr(l,e){Ut||(Ut=new sc,Ut.setDecoderPath("./include/draco/"),Ut.setDecoderConfig({type:"js"}),os&&console.log("Setting draco decoder path to","./include/draco/")),bn||(bn=new Fu,bn.setTranscoderPath("./include/ktx2/"),os&&console.log("Setting ktx2 transcoder path to","./include/ktx2/"),e.renderer&&bn.detectSupport(e.renderer)),l.setDRACOLoader(Ut),l.setKTX2Loader(bn)}var dc="NEEDLE_deferred_texture",vn=N("debugdeferredtextures"),ss=class{static assignTextureLOD(e,t,i=0){if(!!t)for(let n of Object.keys(t)){let r=t[n];r?.isTexture===!0&&(vn&&console.log("FIND",n,r?.name,r?.userData,r),ss.getOrLoadTexture(e,t,n,r,i).then(o=>{o?.isTexture===!0&&(o.needsUpdate=!0,t[n]=o,t.needsUpdate=!0)}))}}get name(){return dc}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}_loading=[];afterRoot(e){return vn&&console.log("AFTER",e),this.parser.json.textures?.forEach((t,i)=>{if(t?.extensions){let n=t?.extensions[dc];if(n){let r=this.parser.getDependency("texture",i);this._loading.splice(this._loading.indexOf(i),1),r.then(o=>{vn&&console.log("register texture",o.name,o.uuid,n),o.userData.deferred=n,ss.cache.set(o.uuid,n)})}}}),null}static async getOrLoadTexture(e,t,i,n,r){let o=n.uuid,s=ss.cache.get(o)||n.userData.deferred;if(s){vn&&console.log(o,s.uri,s.guid);let c=s.uri;if(c.endsWith(".glb")||c.endsWith(".gltf")){if(!s.guid)return console.warn("missing pointer for glb/gltf texture",s),null;let d=s.uri+"_"+s.guid;if(this.resolved[d])return this.resolved[d];let a=new $b;tr(a,e),vn&&console.log("Load "+c,t.name,i);let h=await a.loadAsync(c),u=h.parser,f=-1,E=!1;for(let y of h.parser.json.textures)if(f++,y?.extensions){let g=y?.extensions[dc];if(g?.guid&&g.guid===s.guid){E=!0;break}}if(!E)return null;let b=await u.getDependency("texture",f);return this.resolved[d]=b,vn&&console.log(t.name,i,'change "'+n.name+'" \u2192 "'+b.name+'"',c,f,b,t),b}else{let a=await new Jb().loadAsync(s.uri);return a&&vn?console.log(s,a):console.warn("failed loading",s.uri),a}}else vn&&console.warn("unknown uuid",n.name,n.uuid,n);return null}},ji=ss;z(ji,"cache",new Map),z(ji,"resolved",{});var zu=N("noInstancing"),Gu=!!N("debuglightmaps"),ev=N("debuginstancing"),tv=N("debugprogressiveload"),Hr=class{path=null;asset=null;default};var hc=class{_renderer;_targets=[];is(e){return this._renderer===e}constructor(e){this._renderer=e;let t=this.setMaterial.bind(this),i=this.getMaterial.bind(this),n=e.gameObject;if(this._targets=[],n)switch(n.type){case"Group":this._targets=[...n.children];break;case"Mesh":this._targets.push(n);break}return new Proxy(this,{get(r,o){if(typeof o=="string"){let s=parseInt(o);if(!isNaN(s))return i(s)}return r[o]},set(r,o,s){return typeof o=="string"&&t(s,Number.parseInt(o)),Reflect.set(r,o,s)}})}get length(){return this._targets.length}setMaterial(e,t){if(t<0||t>=this._targets.length)return;let i=this._targets[t];!i||(i.material=e)}getMaterial(e){if(e<0)return null;let t=this._targets;if(e>=t.length)return null;let i=t[e];return i?i.material:null}},gc=class extends M{receiveShadows=!1;shadowCastingMode=uc.Off;lightmapIndex=-1;lightmapScaleOffset=new li.Vector4(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;_lightmaps;get material(){return this.gameObject.material}set material(e){this.gameObject.material=e}_sharedMaterials;get sharedMaterials(){return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._sharedMaterials=new hc(this)),this._sharedMaterials}static get shouldSuppressInstancing(){return zu}_lightmapTextureOverride=void 0;get lightmap(){return this._lightmaps?.length?this._lightmaps[0].lightmap:null}set lightmap(e){if(this._lightmapTextureOverride=e,e===void 0&&(e=this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex)),this._lightmaps?.length)for(let t of this._lightmaps)t.lightmap=e}get hasLightmap(){let e=this.lightmap;return e!=null}get activeSelf(){return this.enabled}set activeSelf(e){let t=typeof e=="number"?e>.5:e;this.enabled=t,t&&(this.gameObject.visible=!0)}awake(){let e=this.gameObject.type;if(e==="Group"){for(let t of this.gameObject.children)this.context.addBeforeRenderListener(t,this.onBeforeRenderThree.bind(this)),t.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let t=0;for(let i=0;i<this.gameObject.children.length;i++){let n=this.gameObject.children[i];if(!(n.type!=="Mesh"||O.getComponent(n,gc))){if(this.renderOrder.length<=t){console.error("Incorrect element count",this);break}n.renderOrder=this.renderOrder[t],t+=1}}}}else(e==="Mesh"||e==="SkinnedMesh")&&(this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree.bind(this)),this.renderOrder!==void 0&&this.renderOrder.length>0&&(this.gameObject.renderOrder=this.renderOrder[0]));if(this.lightmapIndex>=0){let t=this._lightmapTextureOverride!==void 0?this._lightmapTextureOverride:this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex);if(t){if(this._lightmaps=[],e==="Mesh"){if(!this.gameObject.material?.isMeshBasicMaterial){let i=new Hi(this.gameObject,this.context);this._lightmaps.push(i),i.init(this.lightmapIndex,this.lightmapScaleOffset,t,Gu)}}else if(e==="Group"){for(let i of this.gameObject.children)if(!i.material?.isMeshBasicMaterial){let n=new Hi(i,this.context);this._lightmaps.push(n),n.init(this.lightmapIndex,this.lightmapScaleOffset,t,Gu),n.bindOnBeforeRender()}}}}}_isInstancingEnabled=!1;handles=void 0;prevLayers=void 0;setInstancingEnabled(e){if(this._isInstancingEnabled===e)return e&&(this.handles===void 0||this.handles!=null&&this.handles.length>0);if(this._isInstancingEnabled=e,e){if(this.handles===void 0){if(this.handles=iv.setup(this.gameObject,this.context,null,{rend:this,foundMeshes:0}),this.handles)return O.markAsInstancedRendered(this.gameObject,!0),!0}else if(this.handles!==null){for(let t of this.handles)t.updateInstanceMatrix(!0),t.add();return O.markAsInstancedRendered(this.gameObject,!0),!0}}else{if(this.handles)for(let t of this.handles)t.remove();return!0}return!1}start(){if(this.enableInstancing&&!zu&&this.setInstancingEnabled(!0),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.gameObject.type==="Group")for(let e=0;e<this.gameObject.children.length;e++){let t=this.gameObject.children[e];t.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this._isInstancingEnabled?this.setInstancingEnabled(!0):this.enabled&&(this.gameObject.visible=!0,this.applyStencil())}onDisable(){this.handles&&this.handles.length>0?this.setInstancingEnabled(!1):this.enabled||(this.gameObject.visible=!1)}onDestroy(){this.handles=null}applyStencil(){er.applyStencil(this)}onBeforeRenderThree(e,t,i,n,r,o){if(r._didRequestTextureLOD===void 0&&(r._didRequestTextureLOD=0,tv?(console.log("Load material LOD (with delay)",r.name),setTimeout(()=>{ji.assignTextureLOD(this.context,r)},2e3)):ji.assignTextureLOD(this.context,r)),r.envMapIntensity!==void 0){let s=this.hasLightmap?Math.PI:1;r.envMapIntensity=Math.max(0,this.context.rendererData.environmentIntensity/s)}if(this._lightmaps)for(let s of this._lightmaps)s.onBeforeRenderThree(r)}onBeforeRender(){if(!this.gameObject)return;let e=this.gameObject[pc]===!0||this.gameObject.matrixWorldNeedsUpdate;if(this.gameObject.type==="Group"&&this.gameObject.children?.length>0)for(let t of this.gameObject.children)this.applySettings(t);else this.applySettings(this.gameObject);if(e&&(delete this.gameObject[pc],this.handles)){for(let i=this.handles.length-1;i>=0;i--)this.handles[i].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this.handles&&this.handles.length<=0&&O.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this.handles)for(let t=0;t<this.handles.length;t++){let i=this.handles[t];this.prevLayers||(this.prevLayers=[]);let n=i.object.layers.mask;t>=this.prevLayers.length?this.prevLayers.push(n):this.prevLayers[t]=n,i.object.layers.disableAll()}}onAfterRender(){if(this._isInstancingEnabled&&this.handles&&this.prevLayers&&this.prevLayers.length>=this.handles.length)for(let e=0;e<this.handles.length;e++){let t=this.handles[e];t.object.layers.mask=this.prevLayers[e]}}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==uc.On?e.castShadow=!0:e.castShadow=!1}},Te=gc;k([A()],Te.prototype,"receiveShadows",2),k([A()],Te.prototype,"shadowCastingMode",2),k([A()],Te.prototype,"lightmapIndex",2),k([A(Kb)],Te.prototype,"lightmapScaleOffset",2),k([A()],Te.prototype,"enableInstancing",2),k([A()],Te.prototype,"renderOrder",2),k([A()],Te.prototype,"allowOcclusionWhenDynamic",2);var ir=class extends Te{},jr=class extends ir{awake(){super.awake(),this.allowOcclusionWhenDynamic=!1}},uc=(n=>(n[n.Off=0]="Off",n[n.On=1]="On",n[n.TwoSided=2]="TwoSided",n[n.ShadowsOnly=3]="ShadowsOnly",n))(uc||{}),pc="NEEDLE_NEED_UPDATE_INSTANCE",he=class{static markDirty(e,t=!0){if(!!e&&(O.isUsingInstancing(e)&&(e[pc]=!0,e.matrixWorldNeedsUpdate=!0),t))for(let i of e.children)he.markDirty(i,!0)}},fc=class{objs=[];setup(e,t,i,n,r=0){let o=this.tryCreateOrAddInstance(e,t,n);if(o)return i===null&&(i=[]),i.push(o),i;if(r<=0&&e.type!=="Mesh"){let s=r+1;for(let c of e.children)i=this.setup(c,t,i,n,s)}return i}tryCreateOrAddInstance(e,t,i){if(e.type==="Mesh"){let n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing||n>=i.rend.enableInstancing.length||!i.rend.enableInstancing[n])return null;let r=e,o=r.geometry,s=r.material;for(let d of this.objs)if(!d.isFull()&&d.geo===o&&d.material===s)return d.addInstance(r);let c=new aa(e.name,o,s,200,t);return this.objs.push(c),c.addInstance(r)}return null}},iv=new fc,mc=class{get name(){return this.object.name}instanceIndex=-1;object;instancer;constructor(e,t,i){this.instanceIndex=e,this.object=t,this.instancer=i,O.markAsInstancedRendered(t,!0)}updateInstanceMatrix(e=!1){this.instanceIndex<0||(this.object.updateWorldMatrix(!0,e),this.instancer.updateInstance(this.object.matrixWorld,this.instanceIndex))}add(){this.instanceIndex>=0||this.instancer.add(this)}remove(){this.instanceIndex<0||this.instancer.remove(this)}},bc=class{name="";geo;material;get currentCount(){return this.inst.count}context;inst;handles=[];maxCount;isFull(){return this.currentCount>=this.maxCount}constructor(e,t,i,n,r){this.name=e,this.geo=t,this.material=i,this.context=r,this.maxCount=n,ev&&(i=new li.MeshBasicMaterial({color:this.randomColor()})),this.inst=new li.InstancedMesh(t,i,n),this.inst.count=0,this.inst.layers.set(2),this.inst.visible=!0,this.context.scene.add(this.inst)}randomColor(){return new li.Color(Math.random(),Math.random(),Math.random())}addInstance(e){if(this.currentCount>=this.maxCount)return console.error("TOO MANY INSTANCES - resize is not yet implemented!",this.inst.count),null;let t=new mc(-1,e,this);return this.add(t),t}add(e){e.instanceIndex<0&&(e.instanceIndex=this.currentCount,e.instanceIndex>=this.handles.length?this.handles.push(e):this.handles[e.instanceIndex]=e),e.object.updateWorldMatrix(!0,!0),this.inst.setMatrixAt(e.instanceIndex,e.object.matrixWorld),this.inst.instanceMatrix.needsUpdate=!0,this.inst.count+=1,this.inst.count>0&&(this.inst.visible=!0)}remove(e){if(!e||e.instanceIndex<0||e.instanceIndex>=this.handles.length||this.inst.count<=0)return;if(this.handles[e.instanceIndex]!==e){console.error("instance handle is not part of renderer, was it removed before?",e.instanceIndex,this.name);let i=this.handles.indexOf(e);if(i<0)return;e.instanceIndex=i}if(this.handles[e.instanceIndex]=null,this.inst.setMatrixAt(e.instanceIndex,bc.nullMatrix),!(e.instanceIndex>=this.currentCount-1)&&this.currentCount>0){let i=this.handles[this.currentCount-1];i&&(i.instanceIndex=e.instanceIndex,i.updateInstanceMatrix(),this.handles[e.instanceIndex]=i,this.handles[this.currentCount-1]=null)}this.inst.count>0&&(this.inst.count-=1),e.instanceIndex=-1,this.inst.count<=0&&(this.inst.visible=!1),this.inst.instanceMatrix.needsUpdate=!0}updateInstance(e,t){this.inst.setMatrixAt(t,e),this.inst.instanceMatrix.needsUpdate=!0}},aa=bc;z(aa,"nullMatrix",new li.Matrix4);var as=N("debugphysics"),nv=N("debugcollisions"),la=class{mass=1;kinematic=!1;physicsEvents=!1;drag=0;angularDrag=.05;sleepThreshold=.01},ls=class{obj;parent;body;shapes=[];collisonCallback=null;_hasRigidbody=!1;_didSleepLastStep=!1;constructor(e,t){this.obj=e,this.parent=e.parent,this.body=t}},vc=class{obj;contact;target;type;constructor(e,t){this.contact=e,this.type=t,this.obj=null,this.target=null}};var je=class{ray=void 0;screenPoint=void 0;raycaster=void 0;results=void 0;targets=void 0;recursive=!0;minDistance=void 0;maxDistance=void 0;lineThreshold=void 0;layerMask=void 0;ignore=void 0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new ke.Vector2),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setMask(e){this.layerMask||(this.layerMask=new ke.Layers);let t=this.layerMask;t?t.mask=e:this.layerMask=e}};z(je,"AllLayers",4294967295);var yc=class{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}},ca=class{raycaster=new ke.Raycaster;defaultRaycastOptions=new je;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:0},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new ke.Layers;sphereOverlap(e,t){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;let i=new ke.Sphere(e,t),n=this.sphereMask;n.enableAll(),n.disable(2);for(let r of this.context.scene.children){let o=this.onSphereOverlap(r,i,n);o&&this.sphereResults.push(o)}return this.sphereResults.sort((r,o)=>r.distance-o.distance)}tempBoundingBox=new ke.Box3;onSphereOverlap(e,t,i){if(e.type==="Mesh"){if(!e.layers.test(i))return null;let n=e,r=n.geometry;if(r.boundingBox||r.computeBoundingBox(),!r.boundingBox)return null;n.matrixWorldNeedsUpdate&&n.updateMatrixWorld();let o=this.tempBoundingBox.copy(r.boundingBox).applyMatrix4(n.matrixWorld);if(t.intersectsBox(o)){let c=q(e).distanceTo(t.center);return new yc(e,c,t.center.clone())}}else if(e.children)for(let n of e.children){let r=this.onSphereOverlap(n,t,i);if(r)return r}return null}raycastFromRay(e,t=null){let i=t??this.defaultRaycastOptions;return i.ray=e,this.raycast(i)}raycast(e=null){e||(e=this.defaultRaycastOptions);let t=e.screenPoint??this.context.input.mousePositionRC,i=e.raycaster??this.raycaster;if(i.near=e.minDistance??0,i.far=e.maxDistance??1/0,i.params=this.defaultThresholds,e.lineThreshold?i.params.Line={threshold:e.lineThreshold}:i.params.Line={threshold:0},e.ray)i.ray.copy(e.ray);else{let s=this.context.mainCamera;if(!s)return console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];i.setFromCamera(t,s)}let n=e.targets;n||(n=this.targetBuffer,n[0]=this.context.scene);let r=e.results;r||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),r=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof ke.Layers?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),r.length=0,i.intersectObjects(n,e.recursive,r);let o=e.ignore;return o!==void 0&&o.length>0&&(r=r.filter(s=>!o.includes(s.object))),r}get isUpdating(){return this._isUpdatingPhysicsWorld}_isUpdatingPhysicsWorld=!1;context;world=new sa;objects=[];tempPosition=new ke.Vector3;tempQuaternion=new ke.Quaternion;constructor(e){if(this.context=e,this.world.gravity.set(0,-9.82,0),as){let t={};t.onInit=(i,n,r)=>{n.layers.set(-1)},ju(e.scene,this.world.bodies,t)}}addPreStepListener(e){this.world.addEventListener("preStep",e)}addPostStepListener(e){this.world.addEventListener("postStep",e)}addConstraint(e){this.world.addConstraint(e)}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}multiplyGravity(e){this.world.gravity.x*=e.x,this.world.gravity.y*=e.y,this.world.gravity.z*=e.z}addBody(e,t){for(let i=0;i<this.objects.length;i++){let n=this.objects[i];if(n.obj===e){n._hasRigidbody=!0;break}}this.world.addBody(t)}removeBody(e,t,i=!0){this.world.removeBody(t);for(let n=0;n<this.objects.length;n++){let r=this.objects[n];if(r.obj===e){r._hasRigidbody=!1,i&&this.objects.splice(n,1);break}}}removeShape(e,t){for(let i of this.objects)if(i.obj===e){i.body&&(i.body.removeShape(t),i.body.updateMassProperties());return}}createBody(e,t){let i=this.internalCreateBody(e,null);t.mass&&(i.mass=t.mass),t.kinematic?i.type=G.KINEMATIC:i.type=G.DYNAMIC,t.drag&&(i.linearDamping=t.drag),t.angularDrag&&(i.angularDamping=t.angularDrag),t.sleepThreshold&&(i.sleepSpeedLimit=t.sleepThreshold),this.world.addBody(i);let n=new ls(e,i);return n._hasRigidbody=!0,this.objects.push(n),as&&console.log("created new body",e.name,i,i.sleepState,this.world.gravity),t.physicsEvents&&this.registerCollisionEvents(n),i}addBoxCollider(e,t,i,n,r){let o=this.tempPosition;e.getWorldScale(o);let s=new _(.5*o.x*n.x,.5*o.y*n.y,.5*o.z*n.z),c=new Jn(s);c.collisionResponse=!t,i=i.clone(),i.multiply(o);let d=this.addShape(e,c,i,r);if(d!==null){if(this.isAlreadyRegistered(d))return c;let a=new ls(e,d);this.objects.push(a)}return c}addSphereCollider(e,t,i,n){let r=this.tempPosition;e.getWorldScale(r);let o=Math.max(r.x,r.y,r.z),s=new ra(i*o);t=t.clone(),t.multiply(r);let c=this.addShape(e,s,t,n);if(c!==null){if(this.isAlreadyRegistered(c))return s;let d=new ls(e,c);this.objects.push(d)}return s}addMeshCollider(e){as&&console.warn("TODO mesh collider not yet supported")}isAlreadyRegistered(e){for(let t of this.objects)if(t.body===e)return!0;return!1}addShape(e,t,i,n){let r=null;if(n?(n.initialize(),console.assert(!!n.body,"rigidbody didn't initialize / produce a physics body",n),r=n.body):(r=this.internalCreateBody(e,null),r.type=G.KINEMATIC,this.world.addBody(r)),r){i.x*=-1;let o=ve(e),s=q(e);s.add(i);let c=new ke.Quaternion(r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w);o.multiply(c.invert());let d=r.position,a=new _(s.x-d.x,s.y-d.y,s.z-d.z),h=new le(o.x,o.y,o.z,o.w);r.addShape(t,a,h),r.updateMassProperties()}return r}step(e){this._isUpdatingPhysicsWorld=!0,e=Math.min(e,1/30),this.world.step(e),this._isUpdatingPhysicsWorld=!1,as&&this.context.time.frameCount%60===0&&console.log("physics world has "+this.world.bodies.length+" bodies",this.world)}temp=new ke.Vector3;tempQuat=new ke.Quaternion;postStep(){this._isUpdatingPhysicsWorld=!0;for(let e=0;e<this.objects.length;e++){let t=this.objects[e],i=t.body;if(!i||!i.world)continue;i.sleepTick(this.context.time.time),as&&(!t._didSleepLastStep&&i.sleepState===G.SLEEPING?console.log("BODY SLEEPING",i):t._didSleepLastStep&&i.sleepState!==G.SLEEPING&&console.log("BODY WOKE UP",i)),t._didSleepLastStep=i.sleepState===G.SLEEPING;let n=t.obj;if(i.type===G.KINEMATIC){let r=q(n,this.temp);i.position.set(r.x,r.y,r.z);let o=ve(n,this.tempQuat);i.quaternion.set(o.x,o.y,o.z,o.w);continue}if(t.parent&&n.parent===t.parent){Ch(n,i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w);let r=i.position;Ar(n,r.x,r.y,r.z),i.velocity.length()>i.sleepSpeedLimit&&he.markDirty(n)}}this._isUpdatingPhysicsWorld=!1}internalCreateBody(e,t){let i=new G;i._owner=e,i._name=e.name,e.getWorldPosition(this.tempPosition);let n=this.tempPosition;i.position=new _(n.x,n.y,n.z);let r=this.tempQuaternion;return e.getWorldQuaternion(r),i.quaternion=new le(r.x,r.y,r.z,r.w),i.type=G.KINEMATIC,t&&(i.addShape(t),i.updateMassProperties()),i}registerCollisionEvents(e){if(e.collisonCallback&&this.unregisterCollisionEvents(e),!e.body)return;let t=i=>this.raiseCollisionEvents(e.obj,i);e.collisonCallback=t.bind(this),e.body.addEventListener("collide",e.collisonCallback)}unregisterCollisionEvents(e){!e.collisonCallback||!e.body||e.body.removeEventListener("collide",e.collisonCallback)}raiseCollisionEvents(e,t){let i=new vc(t.contact,t.type),n=0,r=this.objects;function o(){if(!(n>0))for(let s=0;s<r.length;s++){if(n==2)return;let c=r[s];c.body==t.body?(i.obj=c.obj,++n):c.body==t.target&&(i.target=c.obj,++n)}}nv&&console.log("collision between",t.contact.bi,t.contact.bj,e,t);for(let s=0;s<e.userData?.components?.length;s++){let c=e.userData.components[s];c.onCollision&&(o(),c.onCollision(i))}}};import{Clock as rv}from"three";var da=class{deltaTime=0;time=0;frame=0;get realtimeSinceStartup(){return this.clock.elapsedTime}get frameCount(){return this.frame}get smoothedFps(){return this._smoothedFps}clock=new rv;_smoothedFps=0;_fpsSamples=[];_fpsSampleIndex=0;update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<30?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%30]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedFps=1/(e/this._fpsSamples.length)}};import{WebsocketBuilder as sv}from"websocket-ts";function Vu(l=window.location.hostname){return new RegExp("[0-9]{3}.[0-9]{2,3}.[0-9]{2,3}.[0-9]{2,3}|localhost","gm").test(l)===!0}var pt=class extends M{url=null;urlParameterName=null;localhost=null;getWebsocketUrl(){let e=this.url?pt.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){let r=N(this.urlParameterName);r&&typeof r=="string"&&(e=r)}if(!e)return null;let i=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return i?.groups?i?.groups.socket_prefix?e:"wss://"+i?.groups.url:null}static GetUrl(e,t){let i=e,n=pt.IsLocalNetwork()&&t;return n&&(i=t),e?.startsWith("/")&&(i=(n?i:window.location.origin)+e),i}static IsLocalNetwork(e=window.location.hostname){return Vu(e)}};var ci=new Int32Array(2),ha=new Float32Array(ci.buffer),ua=new Float64Array(ci.buffer),Br=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;var Xe=class{constructor(e,t){this.low=e|0,this.high=t|0}static create(e,t){return e==0&&t==0?Xe.ZERO:new Xe(e,t)}toFloat64(){return(this.low>>>0)+this.high*4294967296}equals(e){return this.low==e.low&&this.high==e.high}};Xe.ZERO=new Xe(0,0);var cs;(function(l){l[l.UTF8_BYTES=1]="UTF8_BYTES",l[l.UTF16_STRING=2]="UTF16_STRING"})(cs||(cs={}));var di=class{constructor(e){this.bytes_=e,this.position_=0}static allocate(e){return new di(new Uint8Array(e))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(e){this.position_=e}capacity(){return this.bytes_.length}readInt8(e){return this.readUint8(e)<<24>>24}readUint8(e){return this.bytes_[e]}readInt16(e){return this.readUint16(e)<<16>>16}readUint16(e){return this.bytes_[e]|this.bytes_[e+1]<<8}readInt32(e){return this.bytes_[e]|this.bytes_[e+1]<<8|this.bytes_[e+2]<<16|this.bytes_[e+3]<<24}readUint32(e){return this.readInt32(e)>>>0}readInt64(e){return new Xe(this.readInt32(e),this.readInt32(e+4))}readUint64(e){return new Xe(this.readUint32(e),this.readUint32(e+4))}readFloat32(e){return ci[0]=this.readInt32(e),ha[0]}readFloat64(e){return ci[Br?0:1]=this.readInt32(e),ci[Br?1:0]=this.readInt32(e+4),ua[0]}writeInt8(e,t){this.bytes_[e]=t}writeUint8(e,t){this.bytes_[e]=t}writeInt16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeUint16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeInt32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeUint32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeInt64(e,t){this.writeInt32(e,t.low),this.writeInt32(e+4,t.high)}writeUint64(e,t){this.writeUint32(e,t.low),this.writeUint32(e+4,t.high)}writeFloat32(e,t){ha[0]=t,this.writeInt32(e,ci[0])}writeFloat64(e,t){ua[0]=t,this.writeInt32(e,ci[Br?0:1]),this.writeInt32(e+4,ci[Br?1:0])}getBufferIdentifier(){if(this.bytes_.length<this.position_+4+4)throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");let e="";for(let t=0;t<4;t++)e+=String.fromCharCode(this.readInt8(this.position_+4+t));return e}__offset(e,t){let i=e-this.readInt32(e);return t<this.readInt16(i)?this.readInt16(i+t):0}__union(e,t){return e.bb_pos=t+this.readInt32(t),e.bb=this,e}__string(e,t){e+=this.readInt32(e);let i=this.readInt32(e),n="",r=0;if(e+=4,t===cs.UTF8_BYTES)return this.bytes_.subarray(e,e+i);for(;r<i;){let o,s=this.readUint8(e+r++);if(s<192)o=s;else{let c=this.readUint8(e+r++);if(s<224)o=(s&31)<<6|c&63;else{let d=this.readUint8(e+r++);if(s<240)o=(s&15)<<12|(c&63)<<6|d&63;else{let a=this.readUint8(e+r++);o=(s&7)<<18|(c&63)<<12|(d&63)<<6|a&63}}}o<65536?n+=String.fromCharCode(o):(o-=65536,n+=String.fromCharCode((o>>10)+55296,(o&(1<<10)-1)+56320))}return n}__union_with_string(e,t){return typeof e=="string"?this.__string(t):this.__union(e,t)}__indirect(e){return e+this.readInt32(e)}__vector(e){return e+this.readInt32(e)+4}__vector_len(e){return this.readInt32(e+this.readInt32(e))}__has_identifier(e){if(e.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let t=0;t<4;t++)if(e.charCodeAt(t)!=this.readInt8(this.position()+4+t))return!1;return!0}createLong(e,t){return Xe.create(e,t)}createScalarList(e,t){let i=[];for(let n=0;n<t;++n)e(n)!==null&&i.push(e(n));return i}createObjList(e,t){let i=[];for(let n=0;n<t;++n){let r=e(n);r!==null&&i.push(r.unpack())}return i}};var ft=class{constructor(e){this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null;let t;e?t=e:t=1024,this.bb=di.allocate(t),this.space=t}clear(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null}forceDefaults(e){this.force_defaults=e}dataBuffer(){return this.bb}asUint8Array(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())}prep(e,t){e>this.minalign&&(this.minalign=e);let i=~(this.bb.capacity()-this.space+t)+1&e-1;for(;this.space<i+e+t;){let n=this.bb.capacity();this.bb=ft.growByteBuffer(this.bb),this.space+=this.bb.capacity()-n}this.pad(i)}pad(e){for(let t=0;t<e;t++)this.bb.writeInt8(--this.space,0)}writeInt8(e){this.bb.writeInt8(this.space-=1,e)}writeInt16(e){this.bb.writeInt16(this.space-=2,e)}writeInt32(e){this.bb.writeInt32(this.space-=4,e)}writeInt64(e){this.bb.writeInt64(this.space-=8,e)}writeFloat32(e){this.bb.writeFloat32(this.space-=4,e)}writeFloat64(e){this.bb.writeFloat64(this.space-=8,e)}addInt8(e){this.prep(1,0),this.writeInt8(e)}addInt16(e){this.prep(2,0),this.writeInt16(e)}addInt32(e){this.prep(4,0),this.writeInt32(e)}addInt64(e){this.prep(8,0),this.writeInt64(e)}addFloat32(e){this.prep(4,0),this.writeFloat32(e)}addFloat64(e){this.prep(8,0),this.writeFloat64(e)}addFieldInt8(e,t,i){(this.force_defaults||t!=i)&&(this.addInt8(t),this.slot(e))}addFieldInt16(e,t,i){(this.force_defaults||t!=i)&&(this.addInt16(t),this.slot(e))}addFieldInt32(e,t,i){(this.force_defaults||t!=i)&&(this.addInt32(t),this.slot(e))}addFieldInt64(e,t,i){(this.force_defaults||!t.equals(i))&&(this.addInt64(t),this.slot(e))}addFieldFloat32(e,t,i){(this.force_defaults||t!=i)&&(this.addFloat32(t),this.slot(e))}addFieldFloat64(e,t,i){(this.force_defaults||t!=i)&&(this.addFloat64(t),this.slot(e))}addFieldOffset(e,t,i){(this.force_defaults||t!=i)&&(this.addOffset(t),this.slot(e))}addFieldStruct(e,t,i){t!=i&&(this.nested(t),this.slot(e))}nested(e){if(e!=this.offset())throw new Error("FlatBuffers: struct must be serialized inline.")}notNested(){if(this.isNested)throw new Error("FlatBuffers: object serialization must not be nested.")}slot(e){this.vtable!==null&&(this.vtable[e]=this.offset())}offset(){return this.bb.capacity()-this.space}static growByteBuffer(e){let t=e.capacity();if(t&3221225472)throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");let i=t<<1,n=di.allocate(i);return n.setPosition(i-t),n.bytes().set(e.bytes(),i-t),n}addOffset(e){this.prep(4,0),this.writeInt32(this.offset()-e+4)}startObject(e){this.notNested(),this.vtable==null&&(this.vtable=[]),this.vtable_in_use=e;for(let t=0;t<e;t++)this.vtable[t]=0;this.isNested=!0,this.object_start=this.offset()}endObject(){if(this.vtable==null||!this.isNested)throw new Error("FlatBuffers: endObject called without startObject");this.addInt32(0);let e=this.offset(),t=this.vtable_in_use-1;for(;t>=0&&this.vtable[t]==0;t--);let i=t+1;for(;t>=0;t--)this.addInt16(this.vtable[t]!=0?e-this.vtable[t]:0);let n=2;this.addInt16(e-this.object_start);let r=(i+n)*2;this.addInt16(r);let o=0,s=this.space;e:for(t=0;t<this.vtables.length;t++){let c=this.bb.capacity()-this.vtables[t];if(r==this.bb.readInt16(c)){for(let d=2;d<r;d+=2)if(this.bb.readInt16(s+d)!=this.bb.readInt16(c+d))continue e;o=this.vtables[t];break}}return o?(this.space=this.bb.capacity()-e,this.bb.writeInt32(this.space,o-e)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-e,this.offset()-e)),this.isNested=!1,e}finish(e,t,i){let n=i?4:0;if(t){let r=t;if(this.prep(this.minalign,4+4+n),r.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let o=4-1;o>=0;o--)this.writeInt8(r.charCodeAt(o))}this.prep(this.minalign,4+n),this.addOffset(e),n&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(e,t){this.finish(e,t,!0)}requiredField(e,t){let i=this.bb.capacity()-e,n=i-this.bb.readInt32(i);if(!(this.bb.readInt16(n+t)!=0))throw new Error("FlatBuffers: field "+t+" must be set")}startVector(e,t,i){this.notNested(),this.vector_num_elems=t,this.prep(4,e*t),this.prep(i,e*t)}endVector(){return this.writeInt32(this.vector_num_elems),this.offset()}createSharedString(e){if(!e)return 0;if(this.string_maps||(this.string_maps=new Map),this.string_maps.has(e))return this.string_maps.get(e);let t=this.createString(e);return this.string_maps.set(e,t),t}createString(e){if(!e)return 0;let t;if(e instanceof Uint8Array)t=e;else{t=[];let i=0;for(;i<e.length;){let n,r=e.charCodeAt(i++);if(r<55296||r>=56320)n=r;else{let o=e.charCodeAt(i++);n=(r<<10)+o+(65536-(55296<<10)-56320)}n<128?t.push(n):(n<2048?t.push(n>>6&31|192):(n<65536?t.push(n>>12&15|224):t.push(n>>18&7|240,n>>12&63|128),t.push(n>>6&63|128)),t.push(n&63|128))}}this.addInt8(0),this.startVector(1,t.length,1),this.bb.setPosition(this.space-=t.length);for(let i=0,n=this.space,r=this.bb.bytes();i<t.length;i++)r[n++]=t[i];return this.endVector()}createLong(e,t){return Xe.create(e,t)}createObjectOffset(e){return e===null?0:typeof e=="string"?this.createString(e):e.pack(this)}createObjectOffsetList(e){let t=[];for(let i=0;i<e.length;++i){let n=e[i];if(n!==null)t.push(this.createObjectOffset(n));else throw new Error("FlatBuffers: Argument for createObjectOffsetList cannot contain null.")}return t}createStructOffsetList(e,t){return t(this,e.length),this.createObjectOffsetList(e),this.endVector()}};var Wu={};function Nr(l,e){Wu[l]=e}function Uu(l){let e=l.getBufferIdentifier(),t=Wu[e];return t(l)}function qu(l){return typeof l.guid=="function"?l.guid():null}var _c=vl(wc(),1);var fa=class{get isHost(){return this._host!==void 0}_host;_client;_clientData;constructor(){this.onEnable()}onEnable(){let e="HOST-5980e65c-8438-453e-8b35-f13c736dcd81";this.trySetupHost(e)}trySetupHost(e){let t=new _c.default(e);t.on("error",i=>{console.error(i),this._host=void 0,this.trySetupClient(e)}),t.on("open",i=>{this._host=new Tc(t)})}trySetupClient(e){this._client=new _c.default,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",i=>{console.log("<<",i)})})}},xc=class{_peer;constructor(e){this._peer=e}};var Tc=class extends xc{get isHost(){return!0}_connections=[];constructor(e){super(e),console.log("I AM THE HOST"),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){let t=this._connections.map(i=>i.metadata?.id).filter(i=>i!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(let t in this._peer.connections){let i=this._peer.connections[t];if(!!i)if(Array.isArray(i))for(let n of i)!n||n.send(e);else console.warn(i)}}}};var Rc="wss://needle-tiny-starter.glitch.me/socket",mt=!!N("debugnet"),ma=!!(mt||N("debugowner"));var En=class{guid;connection;get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}_hasOwnership=!1;_isOwned=void 0;_gainSubscription;_lostSubscription;_hasOwnerResponse;constructor(e,t){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)}_isWaitingForOwnershipResponseCallback=null;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.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(ma&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let i=0,n=()=>{if(i++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):n()},100)};n()})}requestOwnership(){return ma&&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.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListening("gained-ownership",this._gainSubscription),this.connection.stopListening("lost-ownership",this._lostSubscription),this.connection.stopListening("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(ma&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(ma&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}};var ga=class{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new fa),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return mt}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}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}_usersInRoomCopy=[];usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(let t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){this.connect(),mt&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},0)}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,i=2){if(t===null&&(t={}),i===2){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,i)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendBinary(e){mt&&console.log("<< bin",e.length),this._ws?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._ws)return;this._defaultMessagesBufferArray.length=0;let e=Object.keys(this._defaultMessagesBuffer).length;for(let i in this._defaultMessagesBuffer){let n=this._defaultMessagesBuffer[i];if(e<=1){this.sendWithWebsocket(n.key,n.value,3);break}let r=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(r)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&mt&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;let t=JSON.stringify(this._defaultMessagesBufferArray);this._ws?.send(t)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){if(!t||!this._listeners[e])return;let i=this._listeners[e].indexOf(t);i>=0&&this._listeners[e].splice(i,1)}beginListenBinrary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;let i=this._listenersBinary[e].indexOf(t);i>=0&&this._listenersBinary[e].splice(i,1)}connect(){if(this.connected)return;mt&&console.log("connecting");let t=O.findObjectOfType(pt,this.context,!1)?.getWebsocketUrl();t&&(Rc=t),this.connectWebsocket()}_listeners={};_listenersBinary={};connected=!1;channelId;_connectionId=null;_isConnectingToWebsocket=!1;_ws;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;connectWebsocket(){if(this._isConnectingToWebsocket)return;this._isConnectingToWebsocket=!0,console.log("Connecting to "+Rc);let e=new sv(Rc).onOpen(()=>{this._ws=e,this._isConnectingToWebsocket=!1,this.connected=!0,console.log("Connected to websocket"),this.onSendQueued(0)}).onClose(t=>{this.connected=!1,this._isInRoom=!1}).onError((t,i)=>{console.error(t,i)}).onMessage(this.onMessage.bind(this)).onRetry(()=>{console.log("websocket connection retry")}).build()}onMessage(e,t){let i=t.data;try{if(typeof i!="string"){i.size&&this.handleIncomingBinaryMessage(i);return}let n=JSON.parse(i);if(Array.isArray(n))for(let r of n)this.handleIncomingStringMessage(r);else this.handleIncomingStringMessage(n);return}catch{mt&&i==="pong"&&console.log("<<",i)}}async handleIncomingBinaryMessage(e){let t=await e.arrayBuffer();var i=new Uint8Array(t);let n=new di(i),r=n.getBufferIdentifier(),o=this._listenersBinary[r],s=Uu(n),c=qu(s);if(c&&typeof c=="string"&&(this._state[c]=s),!o)return;let d=s??n;for(let a of o)a(d)}handleIncomingStringMessage(e){if(mt&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){let o=e.data;o&&(console.assert(o.id!==void 0&&o.id!==null&&o.id.length>0,"server did not send connection id",o.id),console.log("Your id is: "+o.id,this.context.alias??""),this._connectionId=o.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(mt&&console.log(e),e){this._isInRoom=!0;let o=e;this._currentRoomName=o.room,this._currentRoomViewId=o.viewId,this._currentRoomAllowEditing=o.allowEditing??!0,console.log("Room view id",this._currentRoomViewId),this._currentInRoom.length=0,this._currentInRoom.push(...o.inRoom),mt&&console.log("joined room with",this._currentInRoom,this.context.alias??"")}this.onSendQueued(1);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){let o=e.data;this._currentInRoom.push(o.userId),mt&&console.log(o.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){let o=e.data,s=this._currentInRoom.indexOf(o.userId);s>=0&&(console.log(o.userId+" left",this.context.alias??""),this._currentInRoom.splice(s,1)),o.userId===this.connectionId&&console.log("you left the room")}break;case"ping":case"pong":let r=e.data?.time;r&&(this._currentDelay=this.context.time.time-r),mt&&console.log("Current latency: "+this._currentDelay.toFixed(1)+" sec","Clients in room: "+this._currentInRoom?.length);break}let t=this._listeners[e.key];if(t)for(let n of t)n(e.data);let i=e.data;i&&(this._state[i.guid]=i)}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=1){if(!this._ws){let r=this._waitingForSocket[i]||[];r.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=r;return}let n=JSON.stringify(this.toMessage(e,t));mt&&console.log(">>",e),this._ws.send(n)}onSendQueued(e){let t=this._waitingForSocket[e];if(t){for(let i of t)i();t.length=0}}};import*as Xt from"three";import{OrbitControls as lv}from"three/examples/jsm/controls/OrbitControls";import{Object3D as av}from"three";var Bi=class extends M{constraintActive=!0;locked=!1;sources=[]};k([A(av)],Bi.prototype,"sources",2);import*as ds from"three";var gt=class extends M{get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){this.controls?.addEventListener("start",e)}autoRotate=!1;autoRotateSpeed=1;enableKeys=!0;enableDamping=!0;dampingFactor=.1;enableZoom=!0;minZoom=0;maxZoom=1/0;enablePan=!0;lookAtConstraint=null;lookAtConstraint01=1;middleClickToFocus=!0;doubleClickToFocus=!0;useSlerp=!1;debugLog=!1;targetLerpSpeed=5;_lookTargetPosition;_controls=null;_cameraObject=null;_lerpToTargetPosition=!1;_lerpCameraToTarget=!1;_cameraTargetPosition=null;_inputs=0;_enableTime=0;awake(){this._lookTargetPosition=new ds.Vector3}onEnable(){this._enableTime=this.context.time.time;let t=O.getComponent(this.gameObject,ne)?.cam;this._controls||(console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t),this._controls=new lv(t,this.context.renderer.domElement)),this._controls&&(this._controls.enableDamping=this.enableDamping,this._controls.enableKeys=this.enableKeys,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,t?.type==="PerspectiveCamera"?(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan)}onDisable(){this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1)}start(){if(this._controls){let e=O.getComponent(this.gameObject,ne);if(e&&!this.setFromTargetPosition()){console.log("NO TARGET");let t=new ds.Vector3(0,0,-1).applyMatrix4(e.cam.matrixWorld);this.setTarget(t,!0)}}this.startCoroutine(this.startRaycastDelayed())}*startRaycastDelayed(){if(yield,!this.setFromTargetPosition()){let e=new je;e.screenPoint=new ds.Vector2(0,0),e.lineThreshold=.1;let t=this.context.physics.raycast(e);t.length>0&&this.setTarget(t[0].point,!0)}}onBeforeRender(){if(!this._controls)return;(this.context.input.getPointerDown(0)||this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2))&&(this._inputs+=1),this._inputs>0&&(this._controls.autoRotate=!1,this._lerpCameraToTarget=!1,this._lerpToTargetPosition=!1),this._inputs=0;let e=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(e||=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3,e?this.setTargetFromRaycast():(this.context.input.getPointerDown(0)||this.context.input.mouseWheelChanged)&&(this._lerpToTargetPosition=!1,this._lerpCameraToTarget=!1),this._lerpToTargetPosition||this._lerpCameraToTarget){let t=this.context.time.deltaTime*this.targetLerpSpeed;this._lerpCameraToTarget&&this._cameraTargetPosition&&this._cameraObject&&(this.useSlerp&&typeof this._cameraObject?.position.slerp=="function"?(this._cameraObject?.position).slerp(this._cameraTargetPosition,t):this._cameraObject?.position.lerp(this._cameraTargetPosition,t),this._cameraObject.position.distanceTo(this._cameraTargetPosition)<.01&&(this._lerpCameraToTarget=!1)),this._lerpToTargetPosition&&(this.lerpTarget(this._lookTargetPosition,t),this._lookTargetPosition.distanceTo(this._controls.target)<.005&&(this._lerpToTargetPosition=!1))}this.lookAtConstraint?.locked&&this.setFromTargetPosition(0,this.lookAtConstraint01),this._controls&&(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!0,this._controls.update())}setCameraTarget(e,t=!1){e?(this._lerpCameraToTarget=!0,this._cameraTargetPosition=e.clone(),t&&this._cameraTargetPosition&&this.controllerObject?.position.copy(this._cameraTargetPosition)):this._lerpCameraToTarget=!1}setFromTargetPosition(e=0,t=1){if(!this._controls)return!1;let i=this.lookAtConstraint?.sources;if(i&&i.length>0){let n=i[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(){if(!this.controls)return;let e=this.context.physics.raycast();for(let t of e)if(t.distance>0&&O.isActiveInHierarchy(t.object)){if(this._lookTargetPosition.copy(t.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;let i=q(this.context.mainCamera);this._cameraTargetPosition=i.clone().sub(this.controls.target).add(this._lookTargetPosition)}break}}};k([A(Bi)],gt.prototype,"lookAtConstraint",2);import{Color as cv}from"three";var we=class extends cv{alpha=1;constructor(e,t,i,n){super(e,t,i),this.alpha=n}clone(){let e=super.clone();return e.alpha=this.alpha,e}copy(e){return super.copy(e),"alpha"in e&&typeof e.alpha=="number"&&(this.alpha=e.alpha),typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){let i=e;return i.alpha&&(this.alpha=Q.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}multiply(e){let t=e;return t.alpha&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}};import{PerspectiveCamera as dv}from"three";var Qu=N("debugcam"),ne=class extends M{get aspect(){return this._cam instanceof dv?this._cam.aspect:this.context.domWidth/this.context.domHeight}get fieldOfView(){return this._fov}set fieldOfView(e){let t=this._fov!=e;this._fov=e,t&&this._cam&&this._cam instanceof Xt.PerspectiveCamera&&(this._cam.fov=this._fov,this._cam.updateProjectionMatrix())}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){let t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&t&&(this._cam.near=e,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(e){let t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&t&&(this._cam.far=e,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera()}orthographic=!1;orthographicSize=5;ARBackgroundAlpha=0;_nearClipPlane=.1;_farClipPlane=1e3;get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){if(!!e){if(this._backgroundColor)this._backgroundColor.copy(e);else{if(!e.clone)return;this._backgroundColor=e.clone()}this.applyClearFlagsIfIsActiveCamera()}}_backgroundColor;_fov=60;_cam=null;_clearFlags=2;_skybox;get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}awake(){this.sourceId||console.warn("Camera has no source - the camera should be exported inside a gltf",this.name)}onEnable(){Qu&&console.log(this),this.buildCamera(),this.tag=="MainCamera"&&this.context.setCurrentCamera(this),this.applyClearFlagsIfIsActiveCamera()}buildCamera(){if(this._cam)return;let e=this.gameObject.isCamera,t=null;if(e?t=this.gameObject:t=this.gameObject.children[0],t&&t.isCamera)t.type==="PerspectiveCamera"&&(t.fov=this._fov,t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new Xt.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),t.fov=this.fieldOfView;else{let i=this.orthographicSize*100;t=new Xt.OrthographicCamera(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,this._nearClipPlane,this._farClipPlane)}this._cam=t,this.layer===0&&this._cam.layers.enableAll(),this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){if(this._cam&&this.context.mainCameraComponent===this)switch(this._clearFlags){case 1:if(this.context.isInXR&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}this.enableSkybox();break;case 2:if(this.backgroundColor){let e=this.backgroundColor.alpha;this.context.isInXR&&(e=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this.backgroundColor,e)}break;case 4:this.context.scene.background=null,this.context.renderer.setClearColor(0,0);break}}enableSkybox(){this._skybox||(this._skybox=new Cc(this)),this._skybox.enable()}};k([A()],ne.prototype,"fieldOfView",1),k([A()],ne.prototype,"nearClipPlane",1),k([A()],ne.prototype,"farClipPlane",1),k([A()],ne.prototype,"clearFlags",1),k([A()],ne.prototype,"orthographic",2),k([A()],ne.prototype,"orthographicSize",2),k([A()],ne.prototype,"ARBackgroundAlpha",2),k([A(we)],ne.prototype,"backgroundColor",1);var Cc=class{_camera;_skybox;get context(){return this._camera?.context}constructor(e){this._camera=e}enable(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?(Qu&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=Xt.sRGBEncoding,this._skybox.mapping=Xt.EquirectangularReflectionMapping,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this)}};function Yu(l){let e="created/implictly",t=new Xt.Object3D;l.add(t);let i=O.addNewComponent(t,ne,!1);i.sourceId=e;let n=O.addNewComponent(t,gt,!1);return n.sourceId=e,i}import{EffectComposer as SE}from"three/examples/jsm/postprocessing/EffectComposer.js";import{RenderPass as PE}from"three/examples/jsm/postprocessing/RenderPass";import{AnimationClip as hv,MathUtils as uv}from"three";var zr=class{_name;get name(){return this._name}_nameHash;get nameHash(){return this._nameHash}_normalizedTime;get normalizedTime(){return this._normalizedTime}_length;get length(){return this._length}_speed;get speed(){return this._speed}constructor(e,t,i,n){this._name=e.name,this._nameHash=e.hash,this._normalizedTime=t,this._length=i,this._speed=n}};function Zu(l,e){return{name:"",isLooping:!1,guid:e?.generateUUID()??uv.generateUUID(),index:-1,clip:new hv(l,1,[])}}import{AnimationClip as vv,AnimationMixer as yv,AxesHelper as Ev,Euler as ep,LoopOnce as wv,Quaternion as Qt,Vector3 as ps}from"three";import*as xa from"three";var Sc=class{_types={};add(e,t){let i=this._types[e];i===void 0?this._types[e]=t:i!==t&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",e)}get(e){return this._types[e]}},D=new Sc;var hi=N("gizmos"),Ie=N("debugextension");var va=N("debugresolvedependencies"),pv=[{prefix:"nodes/",dependencyName:"node"},{prefix:"meshes/",dependencyName:"mesh"},{prefix:"materials/",dependencyName:"material"},{prefix:"textures/",dependencyName:"texture"},{prefix:"animations/",dependencyName:"animation"}];async function Gr(l,e){va&&console.log(l,e);let t=[];Oc(pv,l,e,t);let i=await Promise.all(t);return typeof e=="string"&&i.length===1?i[0]:i}function Oc(l,e,t,i){if(typeof t=="object"&&t!==void 0&&t!==null)for(let n of Object.keys(t)){let r=t[n];if(typeof r=="string"){let o=Ju(e,r);if(o!==null)typeof o.then=="function"?i.push(o.then(s=>t[n]=s)):t[n]=o;else for(let s of l){let c=Ac(s.prefix,r);if(c>=0){va&&console.log(s,c,s.dependencyName),i.push(e?.getDependency(s.dependencyName,c).then(d=>(t[n]=d,d)));break}}}else if(Array.isArray(r))for(let o=0;o<r.length;o++){let s=r[o],c=Ju(e,s);if(c!==null){typeof c.then=="function"?i.push(c.then(d=>r[o]=d)):r[o]=c;continue}for(let d of l){let a=Ac(d.prefix,s);if(a>=0){va&&console.log(d,a,d.dependencyName),i.push(e?.getDependency(d.dependencyName,a).then(h=>r[o]=h));break}}typeof s=="object"&&Oc(l,e,s,i)}else typeof r=="object"&&Oc(l,e,r,i)}else typeof t=="string"&&fv(l,e,t,i)}var Pc="extensions/";function Ju(l,e){if(l&&l.plugins&&typeof e=="string"&&e.startsWith(Pc)){let t=e.substring(Pc.length),i=t.indexOf("/");i>=0&&(t=t.substring(0,i));let n=l.plugins[t];if(Ie&&console.log(t,n),typeof n?.resolve=="function"){let r=e.substring(Pc.length+t.length+1);return n.resolve(l,r)}}return null}function fv(l,e,t,i){for(let n of l){let r=Ac(n.prefix,t);if(r>=0)return va&&console.log(n,r,n.dependencyName),i.push(e?.getDependency(n.dependencyName,r).then(o=>o)),!0}return!1}function Ac(l,e){if(typeof e=="string"&&e.startsWith(l)){let t=e.substring(l.length),i=Number.parseInt(t);if(i>=0)return i}return-1}var kc="NEEDLE_persistent_assets";function $u(l){return l?.___persistentAsset===!0}var ya=class{get name(){return kc}parser;constructor(e){this.parser=e}async afterRoot(e){if(!this.parser?.json?.extensions)return;let t=this.parser.json.extensions[kc];if(!t)return;Ie&&console.log(t);let i=new Array;for(let n of t?.assets){let r=Gr(this.parser,n);r&&i.push(r)}await Promise.all(i)}resolve(e,t){let i=Number.parseInt(t);if(i>=0){Ie&&console.log(t);let n=e.json.extensions[kc];if(n){let r=n?.assets[i];if(r&&typeof r=="object"){r.___persistentAsset=!0;let o=r.__type;if(o){let s=D.get(o)}}return r}}return null}};var nr=N("debugserializer"),Ic=class{register(e,t){if(this.typeMap[e]!==void 0){if(this.typeMap[e]===t)return;console.warn("Type "+e+" is already registered",t,this.typeMap[e])}nr&&console.log("Register type serializer for "+e,t),this.typeMap[e]=t}typeMap={};getSerializer(e){if(!!e)return this.typeMap[e]}getSerializerForConstructor(e,t=0){if(t>20)return;if(!e||!e.constructor){nr&&console.log("invalid type");return}let i=e.name??e.constructor?.name;if(!i){nr&&console.log("invalid name",i);return}let n=this.getSerializer(i);if(n!==void 0)return nr&&console.log("FOUND "+i,e.name,e.constructor.name,n,this.typeMap),n;let r=Object.getPrototypeOf(e);if(!(r.prototype||r.constructor)){nr&&console.warn("No prototype for "+i,e,e.name,e.prototype,e.constructor.name);return}let s=r.prototype??r.constructor;if(s!==e){let c=this.getSerializerForConstructor(s,++t);if(c){nr&&console.log("FOUND "+s.constructor.name,s.name,s,c);let d=s.name??s.constructor.name;d==="Function"?console.error("Registering Function is not allowed, something went wrong",e,s,c):this.register(d,c)}return c}}},wa=new Ic,Fi=class{constructor(e){if(Array.isArray(e))for(let t of e)wa.register(t.name,this);else wa.register(e.name,this)}},Vr=class{root;gltf;gltfId;object;target;nodeId;nodeToObject;objectToNode;context;path;constructor(e){this.root=e}};function Lc(l,e){let t=l.$serializedTypes;if(t===void 0)return null;let i={};for(let n in t){let r=l[n];if(r!=null&&typeof r=="object"){let o=wa.getSerializerForConstructor(r);if(o){i[n]=o.onSerialize(r,e);continue}}i[n]=r}return i.name=l.constructor.name,typeof l.guid=="string"&&(i.guid=l.guid),i}var Ea=[];function Ku(l,e){if(!l)return e;typeof l.$serializedTypes=="object"&&(e||(e={}),Object.assign(e,l.$serializedTypes));let t=Object.getPrototypeOf(l);return Ku(t,e)}function hs(l,e,t){if(!l)return!1;if(t.target=l,l.onBeforeDeserialize!==void 0){let r=l.onBeforeDeserialize(e,t);if(typeof r=="boolean")return r}let i=Ku(l);if(e){if(typeof e.guid=="string"&&(l.guid=e.guid),i)for(let r in i){let o=i[r],s=e[r];if(t.path=r,o===null)l[r]=s;else{let c=function(d){let h=d.type;return h?Mc(s,h,t,void 0,l[r]):Mc(s,d,t,void 0,l[r])};var n=c;if(l.onBeforeDeserializeMember!==void 0&&l.onBeforeDeserializeMember(r,s,t)===!0)continue;if(Array.isArray(o))for(let d=0;d<o.length;d++){let a=o[d],h=c(a);if(h!==void 0||d===o.length-1){l[r]=h;break}}else l[r]=c(o);Ea.length=0,l.onAfterDeserializeMember!==void 0&&l.onAfterDeserializeMember(r,s,t)}}mv(l,e)}return l.onAfterDeserialize!==void 0&&l.onAfterDeserialize(e,t),t.path=void 0,!0}function mv(l,e){for(let i of Object.keys(e)){let n=e[i];if(typeof n=="object"&&n!==null&&n!==void 0){let r=l[i];if(!r){nr&&console.log(i,"is undefined on",l);continue}for(let o of Object.keys(n))r[o]===void 0&&t(n[o])&&!t(r)&&(r[o]=n[o])}}function t(i){switch(typeof i){case"number":case"string":case"boolean":return!0}return!1}}function Mc(l,e,t,i,n){let r=typeof e=="function"&&e.prototype===void 0,o=e;if(r)try{if(o=e?.call(e,n),r=!1,o==null)return}catch(a){console.error("Error in callback",a,l)}if(!r&&n instanceof o)return n;if(n&&typeof n=="object"&&$u(n)){if(n.__concreteInstance)return n.__concreteInstance;let a=n;if(!a.$serializedTypes&&o.prototype.$serializedTypes&&(a.$serializedTypes=o.prototype.$serializedTypes),a.$serializedTypes&&hs(a,l,t),n&&o!==void 0)try{let h=new o;Ie&&console.log("Create concrete instance for persistent asset",n,"instance:",h),us(h,n),n.__concreteInstance=h,n=h}catch(h){console.error("Error creating instance or creating values on instance",h,n,o)}return n}if(i||(i={serializer:wa.getSerializerForConstructor(o)}),Array.isArray(l)){let a=[];for(let h=0;h<l.length;h++){let u=l[h],f=Mc(u,e,t,i,u);a.push(f)}return a}let s=i.serializer;if(s)return s.onDeserialize(l,t);let c;l&&(l.isMaterial||l.isTexture||l.isObject3D)?c=l:c=new o(...gv(l));let d=c;return d.$serializedTypes&&hs(d,l,t),c}function gv(l){if(Ea.length=0,typeof l=="object"&&l!==null&&l!==void 0)for(let e of Object.keys(l))Ea.push(l[e]);return Ea}function us(l,e){if(e==null||l==null)return;let t=!1;for(let i of Object.keys(e)){let n=bv(l,i);t&&n===void 0||(!n||n.writable===!0||n?.set!==void 0)&&(l[i]=e[i])}}function bv(l,e){let t;do t=Object.getOwnPropertyDescriptor(l,e);while(!t&&(l=Object.getPrototypeOf(l)));return t}var wn=N("debuganimatorcontroller"),Dc=N("debugrootmotion"),Zt=class{Play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}let o=this.model.layers[t].stateMachine;for(let s of o.states)if(s.name===e||s.hash===e){wn&&console.log("transition to ",s),this.transitionTo(s,n,i);return}console.warn("Could not find "+e+" to play")}Reset(){this.setStartTransition()}SetBool(e,t){let i=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[i]===e).forEach(n=>n.value=t)}GetBool(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(i=>i[t]===e)?.value??!1}SetFloat(e,t){let i=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[i]===e).forEach(n=>n.value=t)}GetFloat(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(i=>i[t]===e)?.value??0}SetInteger(e,t){let i=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[i]===e).forEach(n=>n.value=t)}GetInteger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(i=>i[t]===e)?.value??0}SetTrigger(e){wn&&console.log("SET TRIGGER",e);let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[t]===e).forEach(i=>i.value=!0)}ResetTrigger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[t]===e).forEach(i=>i.value=!1)}IsInTransition(){return this._activeStates.length>1}SetSpeed(e){this._speed=e}FindState(e){if(!e)return null;for(let t of this.model.layers)for(let i of t.stateMachine.states)if(i.name===e)return i;return null}normalizedStartOffset=0;_speed=1;animator;model;get context(){return this.animator?.context}bind(e){this.animator=e,this._mixer=new yv(this.animator.gameObject),this.createActions(this.animator)}clone(){let e=Qo(this.model,(i,n,r)=>r==null?!0:!(r.type==="Object3D"||r.isObject3D===!0||r?.constructor?.name==="AnimationAction"||r.tracks!==void 0));return console.assert(e!==this.model),new Zt(e)}update(){if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates();let e=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&this.rootMotionHandler?.onBeforeUpdate(),this._mixer.update(e),this.animator.applyRootMotion&&this.rootMotionHandler?.onAfterUpdate()}_mixer;_activeState;constructor(e){this.model=e,wn&&console.log(this)}_activeStates=[];updateActiveStates(){for(let e=0;e<this._activeStates.length;e++){let t=this._activeStates[e],i=t.motion;if(!i.action)this._activeStates.splice(e,1),e--;else{let n=i.action;n.getEffectiveWeight()<=0&&!n.isRunning()&&(wn&&console.debug("REMOVE",t.name,n.getEffectiveWeight(),n.isRunning(),n.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(let e of this.model.layers){let t=e.stateMachine,i=t.states[t.defaultState];this.transitionTo(i,0,this.normalizedStartOffset)}}evaluateTransitions(){let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}let t=this._activeState,i=t.motion.action,n=0;for(let o of t.transitions){if(++n,!o.hasExitTime&&o.conditions.length<=0)continue;let s=!0;for(let c of o.conditions)if(!this.evaluateCondition(c)){s=!1;break}if(!!s){wn&&s&&console.log("All conditions are met",o.conditions,i);for(let c of o.conditions){let d=this.model.parameters.find(a=>a.name===c.parameter);d?.type===9&&(d.value=!1)}if(i){let c=t.motion.clip.duration,d=c<=0?1:i.time/c;if(!o.hasExitTime||d>=o.exitTime&&i.time>=i.getClip().duration){i.clampWhenFinished=!0,wn&&(console.log("transition to "+o.destinationState,o),console.log(i.time,o.exitTime)),this.transitionTo(o.destinationState,o.duration,o.offset);return}}else{this.transitionTo(o.destinationState,o.duration,o.offset);return}break}}let r=!1;if(t.motion.isLooping&&i&&i.time>=i.getClip().duration&&(r=!0,i.reset(),i.time=0,i.play()),!r&&t&&!e&&i&&this.animator&&t.behaviours){let o=i?.getClip().duration,s=i.time/o,c=new zr(this._activeState,s,o,this._speed);for(let d of t.behaviours)d.instance&&d.instance.onStateUpdate?.call(d.instance,this.animator,c,0)}}transitionTo(e,t,i){if(!this.animator)return;let n=0;if(typeof e=="number"&&(e==-1&&(e=this.model.layers[n].stateMachine.defaultState),e=this.model.layers[n].stateMachine.states[e]),!e?.motion||!e.motion.clip)return;let r=this._activeState===e;if(r){let d=e.motion;!d.action_loopback&&d.clip&&(this._mixer.uncacheAction(d.clip,this.animator.gameObject),d.action_loopback=this.createAction(d.clip))}if(this._activeState?.behaviours&&this._activeState.motion.action){let d=this._activeState?.motion.clip.duration,a=this._activeState.motion.action.time/d,h=new zr(this._activeState,a,d,this._speed);for(let u of this._activeState.behaviours)u.instance?.onStateExit?.call(u.instance,this.animator,h,n)}let o=this._activeState?.motion.action;o&&o.fadeOut(t),r&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=o);let s=this._activeState;this._activeState=e;let c=e.motion?.action;if(c){i=Math.max(0,Math.min(1,i)),c.isRunning()&&c.stop(),c.reset(),c.timeScale=this._speed,c.enabled=!0;let d=e.motion.clip.duration;if(c.time=i*d,c.clampWhenFinished=!0,c.setLoop(wv,0),t>0?c.fadeIn(t):c.setEffectiveWeight(1),c.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(c),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){let a=new zr(e,i,d,this._speed);for(let h of this._activeState.behaviours)h.instance?.onStateEnter?.call(h.instance,this.animator,a,n)}}else console.warn("No action",e.motion,this);wn&&console.log("TRANSITION FROM "+s?.name+" TO "+e.name,t,o,c,c?.getEffectiveTimeScale(),c?.getEffectiveWeight(),c?.isRunning(),c?.isScheduled(),c?.paused)}createAction(e){if(this._mixer.uncacheClip(e),this.animator?.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new Hc(this));let t=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,t,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){let t=this.model.parameters.find(i=>i.name===e.parameter);if(!t)return!1;switch(e.mode){case 1:return t.value===!0;case 2:return t.value===!1;case 3:return t.value>e.threshold;case 4:return t.value<e.threshold;case 6:return t.value===e.threshold;case 7:return t.value!==e.threshold}return!1}createActions(e){for(let t of this.model.layers){let i=t.stateMachine;for(let n=0;n<i.states.length;n++){let r=i.states[n];if(r.motion||(r.motion=Zu(r.name)),this.animator&&r.motion.clips){let o=r.motion.clips?.find(s=>s.node.name===this.animator?.gameObject?.name);r.motion.clip=o?.clip}if(!r.motion.clip){let o=new vv;r.motion.clip=o}if(r.motion?.clip){let o=r.motion.clip,s=this.createAction(o);r.motion.action=s}if(r.behaviours&&Array.isArray(r.behaviours))for(let o of r.behaviours){if(!o?.typeName)continue;let s=D.get(o.typeName),c=new s;c.isStateMachineBehaviour&&(c._context=this.context??void 0,us(c,o.properties),o.instance=c),wn&&console.log("Created animator controller behaviour",r.name,o.typeName,o.properties,c)}}}}*enumerateActions(){for(let e of this.model.layers){let t=e.stateMachine;for(let i=0;i<t.states.length;i++){let n=t.states[i];n?.motion&&(n.motion.action&&(yield n.motion.action),n.motion.action_loopback&&(yield n.motion.action_loopback))}}}rootMotionHandler},_a=class{track;createdInterpolant;originalEvaluate;customEvaluate;constructor(e,t){this.track=e;let i=e,n=i.createInterpolant.bind(e);i.createInterpolant=()=>(i.createInterpolant=n,this.createdInterpolant=n(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=r=>{if(!this.originalEvaluate)return;let o=this.originalEvaluate(r);return t(r,o)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}evaluate(e){this.customEvaluate&&this.customEvaluate(e)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}},Re=class{set action(e){this._action=e}get action(){return this._action}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new ps;rotationChange=new Qt;constructor(e,t,i,n,r){if(this.context=e,this.root=t,this.clip=i,Re.firstKeyframeRotation[i.uuid]||(Re.firstKeyframeRotation[i.uuid]=new xa.Quaternion),r){let o=r.values;Re.firstKeyframeRotation[i.uuid].set(o[0],o[1],o[2],o[3])}Re.spaceRotation[i.uuid]||(Re.spaceRotation[i.uuid]=new Qt),Re.effectiveSpaceRotation[i.uuid]||(Re.effectiveSpaceRotation[i.uuid]=new Qt),Re.clipOffsetRotation[i.uuid]=new Qt,r&&Re.clipOffsetRotation[i.uuid].set(r.values[0],r.values[1],r.values[2],r.values[3]).invert(),this.handlePosition(i,n),this.handleRotation(i,r)}onStart(e){if(e.getClip()!==this.clip)return;let t=Re.lastObjRotation[this.root.uuid];Re.spaceRotation[this.clip.uuid].copy(t);{let i=new xa.Euler().setFromQuaternion(t);console.log("START",this.clip.name,Q.toDegrees(i.y))}}getClipRotationOffset(){return Re.clipOffsetRotation[this.clip.uuid]}handlePosition(e,t){if(t){let i=this.root;Dc&&i.add(new Ev),Re.lastObjPosition[i.uuid]||(Re.lastObjPosition[i.uuid]=new ps);let n=new ps,r=new ps,o=0;this.positionWrapper=new _a(t,(s,c)=>{let d=this.action.getEffectiveWeight();if(Dc&&i.position.length()>8&&i.position.set(0,i.position.y,0),s>o){n.set(c[0],c[1],c[2]),n.sub(r),n.multiplyScalar(d),n.applyQuaternion(this.getClipRotationOffset());let a=this.clip.uuid;n.applyQuaternion(Re.spaceRotation[a]),this.positionChange.copy(n)}return r.fromArray(c),o=s,c[0]=0,c[1]=0,c[2]=0,c})}}handleRotation(e,t){if(t){if(Dc){let s=t.values,c=new ep().setFromQuaternion(new Qt(s[0],s[1],s[2],s[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",Q.toDegrees(c.y));let d=t.values.length-4,a=new Qt().set(s[d],s[d+1],s[d+2],s[d+3]),h=new ep().setFromQuaternion(a);console.log(e.name,t.name,"LAST ROTATION IN TRACK",Q.toDegrees(h.y))}let i=this.root;Re.lastObjRotation[i.uuid]||(Re.lastObjRotation[i.uuid]=new Qt);let n=0,r=new Qt,o=new Qt;this.rotationWrapper=new _a(t,(s,c)=>(s>n&&(o.set(c[0],c[1],c[2],c[3]),r.invert(),o.multiply(r),this.rotationChange.copy(o)),r.fromArray(c),n=s,c[0]=0,c[1]=0,c[2]=0,c[3]=1,c))}}onBeforeUpdate(){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(){let e=this.action.getEffectiveWeight();this.positionChange.multiplyScalar(e),this.rotationChange.slerp(Re.identityQuaternion,1-e)}},Yt=Re;z(Yt,"lastObjPosition",{}),z(Yt,"lastObjRotation",{}),z(Yt,"firstKeyframeRotation",{}),z(Yt,"spaceRotation",{}),z(Yt,"effectiveSpaceRotation",{}),z(Yt,"clipOffsetRotation",{}),z(Yt,"identityQuaternion",new Qt);var Hc=class{controller;handler=[];root;constructor(e){this.controller=e}createClip(e,t,i){this.root=t;let n="";t&&"name"in t&&(n=t.name);let r=this.findRootTrack(i,".position"),o=this.findRootTrack(i,".quaternion"),s=new Yt(this.controller.context,t,i,r,o);this.handler.push(s);let c=e.clipAction(i);return s.action=c,c}onStart(e){for(let t of this.handler)t.onStart(e)}onBeforeUpdate(){for(let e of this.handler)e.onBeforeUpdate()}summedPosition=new ps;summedRotation=new Qt;onAfterUpdate(){this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(let e of this.handler)e.onAfterUpdate(),this.summedPosition.add(e.positionChange),this.summedRotation.multiply(e.rotationChange);this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation),Yt.lastObjRotation[this.root.uuid].copy(this.root.quaternion)}findRootTrack(e,t){let i=e.tracks;for(let n of i)if(n.name.endsWith(t))return n;return null}};var _v=N("debuganimator"),bt=class extends M{applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof Zt?this._animatorController=e:this._animatorController=new Zt(e):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}Play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){this.runtimeAnimatorController?.Play(e,t,i,n)}Reset(){this._animatorController?.Reset()}SetBool(e,t){this.runtimeAnimatorController?.SetBool(e,t)}GetBool(e){return this.runtimeAnimatorController?.GetBool(e)??!1}SetFloat(e,t){this.runtimeAnimatorController?.SetFloat(e,t)}GetFloat(e){return this.runtimeAnimatorController?.GetFloat(e)??-1}SetInteger(e,t){this.runtimeAnimatorController?.SetInteger(e,t)}GetInteger(e){return this.runtimeAnimatorController?.GetInteger(e)??-1}SetTrigger(e){this.runtimeAnimatorController?.SetTrigger(e)}ResetTrigger(e){this.runtimeAnimatorController?.ResetTrigger(e)}IsInTransition(){return this.runtimeAnimatorController?.IsInTransition()??!1}SetSpeed(e){e!==this.speed&&(this.speed=e,this._animatorController?.SetSpeed(e))}set minMaxSpeed(e){this.speed=Q.lerp(e.x,e.y,Math.random())}set minMaxOffsetNormalized(e){this.normalizedStartOffset=Q.lerp(e.x,e.y,Math.random()),this.runtimeAnimatorController&&(this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset)}speed=1;normalizedStartOffset=0;_animatorController=null;awake(){if(!!this.gameObject){if(this.runtimeAnimatorController){let e=this.runtimeAnimatorController.clone();console.assert(this.runtimeAnimatorController!==e),this.runtimeAnimatorController=e,console.assert(this.runtimeAnimatorController===e),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.SetSpeed(this.speed),this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset}_v&&console.log("ANIMATOR",this.name,this)}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.Reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}};k([A()],bt.prototype,"applyRootMotion",2),k([A()],bt.prototype,"hasRootMotion",2),k([A()],bt.prototype,"keepAnimatorControllerStateOnDisable",2),k([A()],bt.prototype,"runtimeAnimatorController",1);import*as Wr from"three";var Jt=class extends M{playAutomatically=!0;randomStartTime=!0;_tempAnimationClipBeforeGameObjectExisted=null;get clip(){return this.animations?.length?this.animations[0]:null}set clip(e){if(!this.gameObject){this._tempAnimationClipBeforeGameObjectExisted=e;return}!e||(this.gameObject.animations||(this.gameObject.animations=[]),this.gameObject.animations.push(e))}set animations(e){this.gameObject.animations=e}get animations(){return this.gameObject.animations}get currentAction(){return this._currentActions[0]}get currentActions(){return this._currentActions}mixer=void 0;get actions(){return this._actions}set actions(e){this._actions=e}_actions=[];_currentActions=[];_handles=[];awake(){this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.playAutomatically&&this.init()}onEnable(){if(this.playAutomatically&&this.actions.length>0&&this.currentActions.length<=0){let e=Math.floor(Math.random()*this.actions.length);this.play(e)}}start(){this.randomStartTime&&this.currentAction&&(this.currentAction.time=Math.random()*this.currentAction.getClip().duration)}update(){if(!!this.mixer){this.mixer.update(this.context.time.deltaTime);for(let e of this._handles)e._update();this._handles?.length>0&&he.markDirty(this.gameObject)}}getAction(e){return this.actions?.find(t=>t.getClip().name===e)}play(e,t){if(this.init(),!this.mixer)return;let i=e;if(typeof e=="number"){if(e>=this.animations.length)return;i=this.animations[e]}else typeof e=="string"&&(i=this.animations.find(r=>r.name===e));if(!i){console.error("Could not find clip",e);return}for(let r of this.actions)if(r.getClip()===i)return this.internalOnPlay(r,t);let n=this.mixer.clipAction(i);return this.actions.push(n),this.internalOnPlay(n,t)}internalOnPlay(e,t){var i=this.currentAction;if(i===e&&i.isRunning()&&i.time<i.getClip().duration){let o=this.tryFindHandle(e);if(o)return o.getPromise()}let n=t?.exclusive??!0;t?.fadeDuration?(n&&i?.fadeOut(t.fadeDuration),e.fadeIn(t.fadeDuration)):n&&i?.stop(),e.reset(),e.enabled=!0,e.time=0,e.timeScale=1,t?.clampWhenFinished&&(e.clampWhenFinished=!0),t?.startTime!==void 0&&(e.time=t.startTime),t?.loop!==void 0&&(e.loop=t.loop?Wr.LoopRepeat:Wr.LoopOnce),e.play();let r=new jc(e,this.mixer,t,o=>{this._handles.splice(this._handles.indexOf(r),1)});return this._handles.push(r),r.getPromise()}tryFindHandle(e){for(let t of this._handles)if(t.action===e)return t}_didInit=!1;init(){if(!this._didInit&&(this._didInit=!0,!!this.gameObject)){this.actions=[],this.mixer=new Wr.AnimationMixer(this.gameObject);for(let e=0;e<this.animations.length;e++){let t=this.mixer.clipAction(this.animations[e]);this.actions.push(t)}}}};k([A()],Jt.prototype,"playAutomatically",2),k([A()],Jt.prototype,"randomStartTime",2);var jc=class{mixer;action;promise=null;resolve=null;reject=null;_options;_resolveCallback=null;_rejectCallback=null;_loopCallback;_finishedCallback;_resolvedOrRejectedCallback;constructor(e,t,i,n){this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=n,this._options=i}getPromise(){return this.promise?this.promise:(this.promise=new Promise((e,t)=>{this._resolveCallback=e,this._rejectCallback=t,this.resolve=this.onResolve.bind(this),this.reject=this.onReject.bind(this)}),this._loopCallback=this.onLoop.bind(this),this._finishedCallback=this.onFinished.bind(this),this.mixer.addEventListener("loop",this._loopCallback),this.mixer.addEventListener("finished",this._finishedCallback),this.promise)}_update(){!this._options||this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._resolveCallback?.call(this,this.action)}onReject(e){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._rejectCallback?.call(this,e)}onLoop(e){}onFinished(e){e.action===this.action&&this.onResolve()}dispose(){this._loopCallback&&this.mixer.removeEventListener("loop",this._loopCallback),this._finishedCallback&&this.mixer.removeEventListener("finished",this._finishedCallback),this._loopCallback=void 0,this._finishedCallback=void 0}};import{GLTFLoader as wf}from"three/examples/jsm/loaders/GLTFLoader.js";import*as tp from"three";var Ur=class extends M{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new tp.Vector3}update(){if(!this.from||!this.to)return;let e=q(this.from).clone(),t=q(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),ie(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(q(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}};var ui=class{time;value;inTangent;inWeight;outTangent;outWeight;weightedMode};k([A()],ui.prototype,"time",2),k([A()],ui.prototype,"value",2),k([A()],ui.prototype,"inTangent",2),k([A()],ui.prototype,"inWeight",2),k([A()],ui.prototype,"outTangent",2),k([A()],ui.prototype,"outWeight",2),k([A()],ui.prototype,"weightedMode",2);var rr=class{keys;get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;let t=null;for(let i of this.keys){if(t&&i.time>e&&e>t.time)return Q.lerp(t.value,i.value,(e-t.time)/(i.time-t.time));t=i}return this.keys[this.keys.length-1].value}};k([A(ui)],rr.prototype,"keys",2);import*as ip from"three";import*as fs from"three";import{PositionalAudioHelper as xv}from"three/examples/jsm/helpers/PositionalAudioHelper.js";var Ta=class extends EventTarget{context;get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}_isVisible=!0;constructor(e){super(),this.context=e,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}onVisiblityChanged(e){switch(e.target.visibilityState){case"hidden":this._isVisible=!1,this.dispatchEvent(new Event("application-hidden"));break;case"visible":this._isVisible=!0,this.dispatchEvent(new Event("application-visible"));break}}};var at=N("debugaudio");var Be=class extends M{static get userInteractionRegistered(){return Be._didCallBeginWaitForUserInteraction||(Be._didCallBeginWaitForUserInteraction=!0,Be._beginWaitForUserInteraction()),Be._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),Be._didCallBeginWaitForUserInteraction||(Be._didCallBeginWaitForUserInteraction=!0,Be._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);let i=(()=>{if(i!=null&&!Be._userInteractionRegistered){Be._userInteractionRegistered=!0,console.log("registered interaction, can play audio now"),document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i);for(let n of this.callbacks)n();this.callbacks.length=0}}).bind(this);document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)}clip="";playOnAwake=!1;get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}_spatialBlend=0;_minDistance=1;_maxDistance=100;get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&(at&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}_volume=1;rollOffMode=0;_loop=!1;sound=null;helper=null;wasPlaying=!1;audioLoader=null;shouldPlay=!1;_lastClipStartedLoading=null;get Sound(){if(!this.sound&&Be._userInteractionRegistered){let e=O.getComponent(this.context.mainCamera,$t)??O.findObjectOfType($t,this.context);e?.listener&&(this.sound=new fs.PositionalAudio(e.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}_focusCallback;awake(){this.audioLoader=new fs.AudioLoader,this.playOnAwake&&(this.shouldPlay=!0),window.addEventListener("visibilitychange",e=>{switch(document.visibilityState){case"hidden":this.wasPlaying=this.isPlaying,this.pause();break;case"visible":this.wasPlaying&&this.play();break}}),this._focusCallback=()=>{this.enabled&&this.playOnAwake&&!this.isPlaying&&Be._userInteractionRegistered&&this.play()},this.context.application.addEventListener("application-visible",this._focusCallback)}onDestroy(){this.context.application.removeEventListener("application-visible",this._focusCallback)}onEnable(){Be._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Be._beginWaitForUserInteraction(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.loadAndPlay(this.clip)})}onDisable(){this.stop()}lerp=(e,t,i)=>e*(1-i)+t*i;onLoaded(e){at&&console.log("audio buffer loaded"),Be.registerWaitForAllowAudio(()=>{at&&console.log("finished loading",e);let t=this.Sound;if(!t){console.warn("Failed getting sound",this.name);return}t.isPlaying&&t.stop(),t.setBuffer(e),t.loop=this.loop,t.setVolume(this.volume),t.autoplay=this.shouldPlay,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),at&&console.log(this.name,this.shouldPlay,Be.userInteractionRegistered,this),this.shouldPlay&&Be._userInteractionRegistered&&this.play()})}applySpatialDistanceSettings(){let e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;let t=this.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(at&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:break}this.spatialBlend>0?at&&!this.helper&&(this.helper=new xv(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&(at&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new fs.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){at&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,at&&console.log("load audio",this.clip),this.audioLoader.load(this.clip,this.onLoaded.bind(this),()=>{},console.error)}}play(e=void 0){if(!this.audioLoader||!this.sound||e&&e!==this.clip){this.loadAndPlay(e);return}this.shouldPlay=!0,this._hasEnded=!1,at&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying&&this.sound.play()}pause(){at&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause())}stop(){at&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&(this._lastContextTime=this.sound?.context.currentTime,at&&console.log(this._lastContextTime),this.sound.stop())}_lastContextTime=0;get isPlaying(){return this.sound?.isPlaying??!1}set isPlaying(e){}get time(){return this.sound?.source?this.sound.source?.context.currentTime-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;let t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}_hasEnded=!0;_needUpdateSpatialDistanceSettings=!1;update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,at&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},ue=Be;z(ue,"_didCallBeginWaitForUserInteraction",!1),z(ue,"callbacks",[]),z(ue,"_userInteractionRegistered",!1),k([A()],ue.prototype,"clip",2),k([A()],ue.prototype,"playOnAwake",2),k([A()],ue.prototype,"loop",1),k([A()],ue.prototype,"spatialBlend",1),k([A()],ue.prototype,"minDistance",1),k([A()],ue.prototype,"maxDistance",1),k([A()],ue.prototype,"volume",1),k([A()],ue.prototype,"rollOffMode",2);var $t=class extends M{get listener(){return this._listener==null&&(this._listener=new ip.AudioListener),this._listener}_listener=null;awake(){ue.registerWaitForAllowAudio(()=>{let e=this.listener;if(e==null||e.parent)return;let t=O.getComponentInParent(this.gameObject,ne);t?t.cam.add(e):this.gameObject.add(e)})}};import{GLTFLoader as Cv}from"three/examples/jsm/loaders/GLTFLoader";import*as qr from"three";var hp=vl(dp(),1),Ra=class{success;filename;hash;size;url;constructor(e,t,i,n){this.success=e,this.filename=t,this.hash=i,this.size=n}};async function up(l,e){let t=await l.arrayBuffer(),i=pp(t),n=l.name.split(".").pop(),r=i+"."+n,o=l.name.split(".").shift();console.assert(o!==void 0);let s={alias:o,filename:r},d=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(s)})).json();if(d.success||console.warn("exists check did fail"),d.exists)return console.log("file already exists",i),new Ra(!0,r,i,l.size);console.log("begin uploading file",o,l.size);let a=new FormData;a.append("file",l);let h={};h.filesize=l.size,o&&(h.alias=o);let f=await(await fetch(e+"/upload/file",{method:"POST",body:a,headers:h})).json();if(f?.success===!1)return f.message!==void 0?console.error("Upload failed:",f.message):console.error("Upload failed"),null;console.assert(f.hash_sum===i,"hash sum did not match","received:",f.hash_sum,"expected:",i),f.success&&console.log("successfully uploaded",i,f.id);let E=new Ra(f.success,r,i,l.size);return E.url=e,E}function pp(l){return(0,hp.default)(new Uint8Array(l))}async function Ca(l,e,t,i,n=!1){try{let r=await fetch(i+"/download/file",{method:"POST",body:l});if(r.status!==200)return console.error("download failed",r),null;let o=await r.blob(),s=await o.arrayBuffer();n||console.assert(o.size===t,"size mismatch","expected:",t,"got:",o.size);let c=pp(s);return n||console.assert(c===e,"hash mismatch, downloaded file is invalid"),o.arrayBuffer()}catch(r){console.error(r)}return null}async function fp(l,e){let t=await fetch(l),i=t.body?.getReader(),n=t.headers.get("Content-Length"),r=n?parseInt(n):0;if(!i)return null;let o=0,s=[];for(;;){let{done:a,value:h}=await i.read();if(h&&(s.push(h),o+=h.length,e.call(null,new ProgressEvent("progress",{loaded:o,total:r}))),a)break}let c=new Uint8Array(o),d=0;for(let a of s)c.set(a,d),d+=a.length;return c}var ms=N("debugavatar"),or=class{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(r=>r.layers.set(2))}assignRandomColors(){Ni.assignRandomPlayerColors(this)}},Ni=class{avatarRegistryUrl=null;avatarModelCache=new Map;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){let r=new ye;i=O.instantiate(hn(t,e.scene),r)}}else i=t;if(!i)return null;let n=this.findAvatar(i);return n.assignRandomColors(),n.isValid?(ms&&console.log("[Custom Avatar] valid config",t,ms?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,ms?n:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(ms&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){let n=await fetch("./"+t),r=null;if(n.ok){let s=await n.blob();s&&(r=await s.arrayBuffer())}return!r&&(r=await Ca(t,t,0,"no url here go away",!0),!r)?null:(await Xr(e,r,null,0))?.scene??null}let i=new Cv;return tr(i,e),new Promise((n,r)=>{let o=this.avatarRegistryUrl+"/"+t;i.load(o,async s=>{await Sa(e,o,s),n(s.scene)},s=>{ms&&console.log("[Custom Avatar] "+s.loaded/s.total*100+"% loaded of "+s.total/1024+"kB")},s=>{console.error("[Custom Avatar] Error when loading: "+s),n(null)})})}cacheModel(e,t){}findAvatar(e){let t=e,i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,"head"),r=this.findAvatarPart(i,"left"),o=this.findAvatarPart(i,"right");if(!n){n=t;let c=new qr.Vector3;new qr.Box3().setFromObject(n).getSize(c);let d=Math.max(c.x,c.y,c.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+d+" meters! Should be < 0.3m"),d>.3&&n.scale.multiplyScalar(1/d*.3)}return new or(t,n,r,o)}findAvatarPart(e,t){for(let i of e.children)if(i.name.toLowerCase().indexOf(t)>-1)return i;return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}static assignRandomPlayerColors(e){let t=new Map;function i(n){if(n.type==="Mesh"){let r=n,o=r.material;if(o&&o.name){if(t.has(o.uuid)){let s=t.get(o.uuid);s&&(r.material=s);return}if(o.name.endsWith("_playercolor")||o.name.endsWith("_player_color2")){let s=o.uuid;r.material=o.clone(),r.material.color=new qr.Color(Math.random(),Math.random(),Math.random()),t.set(s,r.material)}}}}e.head&&e.head.traverse(i),e.leftHand&&e.leftHand.traverse(i),e.rigthHand&&e.rigthHand.traverse(i)}};import{AxesHelper as Sv}from"three";var zi=class extends M{length=1;depthTest=!0;isGizmo=!0;_axes=null;onEnable(){if(this.isGizmo&&!hi)return;this._axes||(this._axes=new Sv(this.length)),this.gameObject.add(this._axes);let e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){!this._axes||this.gameObject.remove(this._axes)}};k([A()],zi.prototype,"length",2),k([A()],zi.prototype,"depthTest",2),k([A()],zi.prototype,"isGizmo",2);import*as gp from"three";var Qr=class extends M{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=q(this.to).clone(),t=q(this.from).clone(),i=e.distanceTo(t),n=e.clone();n.sub(t);let r=t.clone();r.add(e),r.multiplyScalar(.5);let o=q(this.hint).clone();o.sub(r);let s=new gp.Vector3;s.crossVectors(o,n),s.crossVectors(n,s),s.normalize();let c=i*.5,d=Math.max(this.desiredDistance,c),a=Math.sqrt(d*d-c*c),h=s.clone();h.multiplyScalar(a),h.add(r),ie(this.gameObject,h);let u=r.clone();u.sub(s),this.gameObject.lookAt(u)}};import*as Gi from"three";import*as pi from"three";var Pv=new pi.BoxGeometry(1,1,1);function Pa(l=null){let e=new pi.Color(l??14540253),t=new pi.EdgesGeometry(Pv);return new pi.LineSegments(t,new pi.LineBasicMaterial({color:e}))}var Av=N("gizmos"),Oa=class extends M{box=null;testBox=new Gi.Box3;_lastMatrixUpdateFrame=-1;isInBox(e){if(!!e){if(this.box||(this.box=new Gi.Box3),this.updateBox(!1),e.type==="Mesh")this.testBox.setFromObject(e);else{let t=q(e,Oa._position),i=Sh(e,Oa._size);this.testBox.setFromCenterAndSize(t,i)}return this.box?.intersectsBox(this.testBox)}}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){return this.box||(this.box=new Gi.Box3),(e||this.context.time.frameCount!=this._lastMatrixUpdateFrame)&&(this._lastMatrixUpdateFrame=this.context.time.frameCount,this.box.setFromCenterAndSize(new Gi.Vector3(0,0,0),new Gi.Vector3(1,1,1)),this.box.applyMatrix4(this.gameObject.matrixWorld)),this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!Av&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=Pa(e),this.gameObject.add(this._helper)}}},lt=Oa;z(lt,"_position",new Gi.Vector3),z(lt,"_size",new Gi.Vector3(.01,.01,.01));import*as gs from"three";import{FrontSide as bp,DoubleSide as vp}from"three";function Yr(l,e){if(!l)return;let t=l.material;t?.isMaterial===!0&&(t.depthTest=!e.renderOnTop,t.side=e.doubleSided??!0?vp:bp,t.depthWrite=e.depthWrite??!1,t.shadowSide=e.doubleSided?vp:bp,l.castShadow=e.castShadows?e.castShadows:!1,l.receiveShadow=e.receiveShadows?e.receiveShadows:!1);for(let i of l.children)Yr(i,e)}function Zr(l,e,t){l[e]===void 0&&console.warn("Field",e,"is undefined on",l);let i=Proxy.revocable(l[e],{set(o,s,c,d){let a=o[s],h=Reflect.set(o,s,c,d);return t(c,a),h}}),n=i.revoke,r=l[e];return i.revoke=()=>{l[e]=r,n()},l[e]=i.proxy,i}function yp(l,e,t=3){let i=l.__scheduledActions;i||(i=l.__scheduledActions={});let n=e.name;i[t]||(i[t]={});let r=i[t];if(r[n])return;function*s(){e?.call(l),r[n]=null}let c=l.startCoroutine(s(),t);r[n]=c}var Jr=class extends M{mass=1;set isKinematic(e){this._isKinematic=e,this._body&&(this._body.type=e?G.KINEMATIC:G.DYNAMIC)}get isKinematic(){return this._isKinematic}_isKinematic=!1;drag=0;angularDrag=1;detectCollision=!0;sleepThreshold=.01;get body(){return this._body===null&&this.initialize(),this._body}_body=null;currentVelocity;_smoothedVelocity;lastWorldPosition;dirty=!0;transformProxy;awake(){this._body=null,this.currentVelocity=new gs.Vector3,this._smoothedVelocity=new gs.Vector3,this.lastWorldPosition=q(this.gameObject).clone()}start(){this.setBodyFromGameObject()}onEnable(){this._body?this.context.physics.addBody(this.gameObject,this._body):this.initialize(),this.body&&(this.body.wakeUp(),this.gameObject.updateWorldMatrix(!0,!1),this.setBodyFromGameObject()),this.transformProxy=Zr(this.gameObject.matrix,"elements",()=>{this.context.physics.isUpdating||(this.dirty=!0)})}onDisable(){this.transformProxy?.revoke(),this._body&&this.context.physics.removeBody(this.gameObject,this._body,!1)}onDestroy(){this._body&&this.context.physics.removeBody(this.gameObject,this._body)}earlyUpdate(){this.dirty&&this.setBodyFromGameObject()}onBeforeRender(){this.updateVelocity()}initialize(){if(this._body)return;let e=new la;e.drag=this.drag,e.angularDrag=this.angularDrag,e.mass=this.mass,e.kinematic=this.isKinematic,e.physicsEvents=this.detectCollision,e.sleepThreshold=this.sleepThreshold,this._body=this.context.physics.createBody(this.gameObject,e)}wakeUp(){this.body?.wakeUp()}applyForce(e,t){this.body?.applyForce(new _(e.x,e.y,e.z),t?new _(t.x,t.y,t.z):void 0)}getVelocity(){return this.body?Jr.tempPosition.set(this.body?.velocity.x,this.body?.velocity.y,this.body?.velocity.z):Jr.tempPosition.set(0,0,0)}setVelocity(e,t,i){!this.body||(this.body.velocity.x=e/this.context.time.deltaTime,this.body.velocity.y=t/this.context.time.deltaTime,this.body.velocity.z=i/this.context.time.deltaTime)}get smoothedVelocity(){return this._smoothedVelocity}setAngularVelocity(e,t,i){!this.body||(this.body.angularVelocity.x=e/this.context.time.deltaTime,this.body.angularVelocity.y=t/this.context.time.deltaTime,this.body.angularVelocity.z=i/this.context.time.deltaTime)}setBodyFromGameObject(e=null){if(this.dirty=!1,this.body&&this.gameObject&&!this.destroyed){let t=this.worldPosition;this.body.position.set(t.x,t.y,t.z);let i=this.worldQuaternion;if(this.body.quaternion.set(i.x,i.y,i.z,i.w),e){Jr.copyVector3.set(e.x,e.y,e.z),this._smoothedVelocity.lerp(Jr.copyVector3,this.context.time.deltaTime/.1);let n=this._smoothedVelocity;this.body.velocity.x=n.x,this.body.velocity.y=n.y,this.body.velocity.z=n.z}}}updateVelocity(){if(!!this.currentVelocity&&this.body&&this.gameObject){let e=q(this.gameObject);this.currentVelocity.subVectors(e,this.lastWorldPosition),this.lastWorldPosition.copy(e),this._smoothedVelocity.lerp(this.currentVelocity,this.context.time.deltaTime/.1)}}},ce=Jr;z(ce,"tempPosition",new gs.Vector3),z(ce,"copyVector3",new gs.Vector3),k([A()],ce.prototype,"mass",2),k([A()],ce.prototype,"isKinematic",1),k([A()],ce.prototype,"drag",2),k([A()],ce.prototype,"angularDrag",2),k([A()],ce.prototype,"detectCollision",2),k([A()],ce.prototype,"sleepThreshold",2);import{Vector3 as Aa}from"three";var fi=class extends M{attachedRigidbody=null;isTrigger=!1;_shape=null;awake(){super.awake(),this._shape=null}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(ce))}onDisable(){this._shape}};k([A(ce)],fi.prototype,"attachedRigidbody",2),k([A()],fi.prototype,"isTrigger",2);var _n=class extends fi{radius=.5;center=new Aa(0,0,0);onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addSphereCollider(this.gameObject,this.center,this.radius,this.attachedRigidbody))}};k([A()],_n.prototype,"radius",2),k([A(Aa)],_n.prototype,"center",2);var xn=class extends fi{size;center;onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addBoxCollider(this.gameObject,this.isTrigger,this.center,this.size,this.attachedRigidbody))}};k([A(Aa)],xn.prototype,"size",2),k([A(Aa)],xn.prototype,"center",2);var $r=class{};var kt=class extends M{canGrab=!0;onPointerClick(e){}},It=class extends M{isUsed=!0;usedBy=null};var sr=class extends lt{},Kr=class extends M{deleteBoxes=[];awake(){this.deleteBoxes=O.findObjectsOfType(sr,this.context)}update(){for(let e of this.deleteBoxes){let t=this.gameObject;e.isInBox(t)===!0&&(O.getComponentInParent(this.gameObject,It)||kr(this.gameObject,this.context.connection))}}};var ar=class extends M{visibleOn;onEnable(){this.apply()}apply(){this.test()||O.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:kv()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}};k([A()],ar.prototype,"visibleOn",2);var ka;function kv(){if(ka===!0||ka===!1)return ka;let l=!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)))&&(l=!0)}(navigator.userAgent||navigator.vendor||window.opera),ka=l,l}import*as Vi from"three";var Ce=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(e,t,i,n){return e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var eo=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Ce).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Ce).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Ce).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,n,r,o,s,c,d,a){return e.prep(4,36),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(d),e.writeFloat32(c),e.prep(4,12),e.writeFloat32(s),e.writeFloat32(o),e.writeFloat32(r),e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var Mt=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new Mt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+4),(t||new Mt).__init(e.readInt32(e.position())+e.position(),e)}guid(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){let e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){let t=this.bb.__offset(this.bb_pos,8);return t?(e||new eo).__init(this.bb_pos+t,this.bb):null}dontSave(){let e=this.bb.__offset(this.bb_pos,10);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startSyncedTransformModel(e){e.startObject(4)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addFast(e,t){e.addFieldInt8(1,+t,0)}static addTransform(e,t){e.addFieldStruct(2,t,0)}static addDontSave(e,t){e.addFieldInt8(3,+t,0)}static endSyncedTransformModel(e){return e.endObject()}static finishSyncedTransformModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedTransformModelBuffer(e,t){e.finish(t,void 0,!0)}};var Tn=N("debugsync"),to="STRS";Nr(to,Mt.getRootAsSyncedTransformModel);var mi=new ft;function Nc(l,e,t=!0){mi.clear();let i=mi.createString(l);Mt.startSyncedTransformModel(mi),Mt.addGuid(mi,i),Mt.addFast(mi,t);let n=e.worldPosition,r=e.worldEuler,o=e.gameObject.scale;Mt.addTransform(mi,eo.createTransform(mi,n.x,n.y,n.z,r.x,r.y,r.z,o.x,o.y,o.z));let s=Mt.endSyncedTransformModel(mi);return mi.finish(s,to),mi.asUint8Array()}var Qe=class extends M{overridePhysics=!0;interpolatePosition=!0;interpolateRotation=!0;fastMode=!1;syncDestroy=!1;_model=null;_needsUpdate=!0;rb=null;_wasKinematic=!1;_receivedDataBefore=!1;_targetPosition;_targetRotation;_receivedFastUpdate=!1;_shouldRequestOwnership=!1;requestOwnership(){Tn&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){return this._model?.hasOwnership??void 0}isOwned(){return this._model?.isOwned}joinedRoomCallback=null;receivedDataCallback=null;awake(){Tn&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new Vi.Vector3,this._targetRotation=new Vi.Quaternion,this.lastWorldPos=new Vi.Vector3,this.lastWorldRotation=new Vi.Quaternion,this.rb=O.getComponentInChildren(this.gameObject,ce),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new En(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen("joined-room",this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinrary(to,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Lh(this.guid,this.context.connection),this._model=null,this.context.connection.stopListening("joined-room",this.joinedRoomCallback),this.context.connection.stopListenBinary(to,this.receivedDataCallback)}tryGetLastState(){let e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new Vi.Euler;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){Tn&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();let t=e.transform();if(t){he.markDirty(this.gameObject,!0);let i=t.position();i&&(this.interpolatePosition&&this._targetPosition?.set(i.x(),i.y(),i.z()),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(i.x(),i.y(),i.z()));let n=t.rotation();n&&(this.tempEuler.set(n.x(),n.y(),n.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&Ph(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}receivedUpdate=!1;lastWorldPos;lastWorldRotation;onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){Tn&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());let e=this.worldPosition,t=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){let r=e.distanceTo(this.lastWorldPos),o=t.angleTo(this.lastWorldRotation),s=this._model.hasOwnership||this.fastMode?1e-4:.001;(r>s||o>s)&&(this._model.hasOwnership?this._needsUpdate=!0:(Tn&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,e.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,t.copy(this.lastWorldRotation),he.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){let o=this._receivedFastUpdate||this.fastMode?.5:.3,s=!1;if(this.interpolatePosition&&this._targetPosition){let c=this.worldPosition;c.lerp(this._targetPosition,o),this.worldPosition=c,s=!0}if(this.interpolateRotation&&this._targetRotation){let c=this.worldQuaternion;c.slerp(this._targetRotation,o),this.worldQuaternion=c,s=!0}s&&he.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(e),this.lastWorldRotation.copy(t),!this._model)return;if(!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership){this.rb&&(this.rb.isKinematic=this._model.isOwned??!1,this.rb.setVelocity(0,0,0),this.rb.setBodyFromGameObject());return}this.rb&&(this._wasKinematic!==void 0&&(Tn&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new Vi.Vector3(0,0,0))>1e3&&(Tn&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0),this.rb.setBodyFromGameObject()));let i=10,n=this.rb||this.fastMode;if(this._needsUpdate&&(i<=0||i>0&&this.context.time.frameCount%i===0||n)){Tn&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this.overridePhysics&&this.rb&&this.rb.setBodyFromGameObject(),this._needsUpdate=!1;let r=Nc(this.guid,this,!!n);this.context.connection.sendBinary(r)}}};import*as ee from"three";var Ma=class{static createButton(e,t={}){let i=document.createElement("button");function n(){if(t.domOverlay===void 0){var c=document.createElement("div");c.style.display="none",document.body.appendChild(c);var d=document.createElementNS("http://www.w3.org/2000/svg","svg");d.setAttribute("width",38),d.setAttribute("height",38),d.style.position="absolute",d.style.right="20px",d.style.top="20px",d.addEventListener("click",function(){h.end()}),c.appendChild(d);var a=document.createElementNS("http://www.w3.org/2000/svg","path");a.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),a.setAttribute("stroke","#fff"),a.setAttribute("stroke-width",2),d.appendChild(a),t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("dom-overlay"),t.domOverlay={root:c}}t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("local-floor"),t.optionalFeatures.push("hand-tracking"),t.optionalFeatures.push("layers");let h=null;async function u(E){E.addEventListener("end",f),await e.xr.setSession(E),i.textContent="STOP AR",t.domOverlay.root.style.display="",h=E}function f(){h.removeEventListener("end",f),i.textContent="START AR",t.domOverlay.root.style.display="none",h=null}i.style.display="",i.style.cursor="pointer",i.style.left="calc(50% - 50px)",i.style.width="100px",i.textContent="START AR",i.onmouseenter=function(){i.style.opacity="1.0"},i.onmouseleave=function(){i.style.opacity="0.5"},i.onclick=function(){h===null?navigator.xr.requestSession("immersive-ar",t).then(u):h.end()}}function r(){i.disabled=!0,i.style.display="",i.style.cursor="auto",i.style.left="calc(50% - 75px)",i.style.width="150px",i.onmouseenter=null,i.onmouseleave=null,i.onclick=null}function o(){r(),i.textContent="AR NOT SUPPORTED"}function s(c){c.style.position="absolute",c.style.bottom="20px",c.style.padding="12px 6px",c.style.border="1px solid #fff",c.style.borderRadius="4px",c.style.background="rgba(0,0,0,0.1)",c.style.color="#fff",c.style.font="normal 13px sans-serif",c.style.textAlign="center",c.style.opacity="0.5",c.style.outline="none",c.style.zIndex="999"}if("xr"in navigator)return i.id="ARButton",i.style.display="none",s(i),navigator.xr.isSessionSupported("immersive-ar").then(function(c){c?n():o()}).catch(o),i;{let c=document.createElement("a");return window.isSecureContext===!1?(c.href=document.location.href.replace(/^http:/,"https:"),c.innerHTML="WEBXR NEEDS HTTPS"):(c.href="https://immersiveweb.dev/",c.innerHTML="WEBXR NOT AVAILABLE"),c.style.left="calc(50% - 90px)",c.style.width="180px",c.style.textDecoration="none",s(c),c}}};var La=class{static createButton(e,t){t&&console.error('THREE.VRButton: The "options" parameter has been removed. Please set the reference space type via renderer.xr.setReferenceSpaceType() instead.');let i=document.createElement("button");function n(){let c=null;async function d(h){h.addEventListener("end",a),await e.xr.setSession(h),i.textContent="EXIT VR",c=h}function a(){c.removeEventListener("end",a),i.textContent="ENTER VR",c=null}i.style.display="",i.style.cursor="pointer",i.style.left="calc(50% - 50px)",i.style.width="100px",i.textContent="ENTER VR",i.onmouseenter=function(){i.style.opacity="1.0"},i.onmouseleave=function(){i.style.opacity="0.5"},i.onclick=function(){if(c===null){let h={optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};navigator.xr.requestSession("immersive-vr",h).then(d)}else c.end()}}function r(){i.disabled=!0,i.style.display="",i.style.cursor="auto",i.style.left="calc(50% - 75px)",i.style.width="150px",i.onmouseenter=null,i.onmouseleave=null,i.onclick=null}function o(){r(),i.textContent="VR NOT SUPPORTED"}function s(c){c.style.position="absolute",c.style.bottom="20px",c.style.padding="12px 6px",c.style.border="1px solid #fff",c.style.borderRadius="4px",c.style.background="rgba(0,0,0,0.1)",c.style.color="#fff",c.style.font="normal 13px sans-serif",c.style.textAlign="center",c.style.opacity="0.5",c.style.outline="none",c.style.zIndex="999"}if("xr"in navigator)return i.id="VRButton",i.style.display="none",s(i),navigator.xr.isSessionSupported("immersive-vr").then(function(c){c?n():o(),La.xrSessionIsGranted&&(console.log("XR session is granted - will enter immersive web now"),i.click())}),i;{let c=document.createElement("a");return window.isSecureContext===!1?(c.href=document.location.href.replace(/^http:/,"https:"),c.innerHTML="WEBXR NEEDS HTTPS"):(c.href="https://immersiveweb.dev/",c.innerHTML="WEBXR NOT AVAILABLE"),c.style.left="calc(50% - 90px)",c.style.width="180px",c.style.textDecoration="none",s(c),c}}static registerSessionGrantedListener(){if("xr"in navigator)try{navigator.xr.addEventListener("sessiongranted",()=>{console.log("Received session granted event"),La.xrSessionIsGranted=!0})}catch(e){console.error(e)}}},io=La;z(io,"xrSessionIsGranted",!1);io.registerSessionGrantedListener();import*as Pe from"three";import*as Da from"three";var Ep=vl(wc(),1);import{AudioAnalyser as Mv}from"three";var no="noVoip",ct=N("debugvoip"),Lv=N("voip");var zc=class{id;constructor(e){this.id=e}};var Gc=class{peer;voip;userId;peerId;call=null;callErrorListener=null;stream=null;constructor(e,t,i,n){this.voip=e,this.peer=t,this.userId=i,this.peerId=n}close(){ct&&console.log("close voip call"),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.open&&this.call.close(),this.stream?.getTracks().forEach(function(e){e.stop()})}updateMute(e){if(!this.stream)return;let t=this.stream?.getAudioTracks();for(let i of t)i.enabled=!e}async startVoipCall(){if(!await Ke.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}ct&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),ct&&console.log(this.stream),this.call=this.peer.call(this.peerId,this.stream,{metadata:{userId:this.userId}}),this.call.on("error",t=>{console.error(t)}),this.call.on("stream",t=>{ct&&console.log("received stream from remote again",t)}),this.peer.on("close",this.onCallClose.bind(this)),this.callErrorListener=t=>{t.message.includes(this.peerId)?(console.log("Could not connect to "+this.peerId),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.close(),this.stream?.getTracks().forEach(function(i){i.stop()}),this.stream=null):console.error(t)},this.peer.on("error",this.callErrorListener)}onCallClose(e){ct&&console.log("call closed",e)}},Vc=class{get currentStream(){return this.stream}get currentAudio(){return this.audio}get currentAnalyzer(){return this.analyzer}voip;call;audio=null;stream=null;obj;analyzer=null;waitingForStart=!1;closed=!1;audioElement=null;constructor(e,t,i){this.voip=e,this.obj=t,this.call=i}openAudioStream(e){let t=e.getAudioTracks();for(let i of t)if(i.kind==="audio"&&i.readyState==="live"){this.open(i);return}console.warn("failed finding valid audio stream to begin call")}open(e){console.assert(e.kind==="audio","invalid track kind, expected audio but received "+e.kind),!this.waitingForStart&&(this.waitingForStart=!0,ue.userInteractionRegistered||ct&&console.log("Incoming call, waiting for user interaction before opening audio"),ue.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){ct&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);let t=new Da.AudioListener;this.audio=new Da.Audio(t),this.audio.setVolume(this.voip.muteInput?0:1),this.audio.setMediaStreamSource(this.stream);let i=document.createElement("audio");this.audioElement=i,i.style.display="none",document.body.appendChild(i),i.srcObject=this.stream,i.sinkId!==void 0&&navigator.mediaDevices.enumerateDevices().then(n=>{if(!!i){console.log(n);for(let r of n)if(r.label==="Speakerphone"){i.sinkId=r.deviceId;break}}}),ct&&console.log("call is setup, you should hear something now"),this.analyzer=new Mv(this.audio,32)}}))}close(){this.closed=!0,this.call?.open&&this.call.close(),this.audio?.disconnect(),this.stream?.getTracks().forEach(e=>{e.stop()}),this.stream=null,this.audioElement&&this.audioElement.remove()}},Ke=class extends M{requireParam=!1;set muteInput(e){if(e===this._inputMuted||(this._inputMuted=e,!this.currentIncomingCalls))return;let t=this._inputMuted?0:1;for(let i in this.currentIncomingCalls)this.currentIncomingCalls[i]?.currentAudio?.setVolume(t)}get muteInput(){return this._inputMuted}set muteOutput(e){if(e!==this._outputMuted&&(this._outputMuted=e,!!this.connections))for(let t in this.connections)this.connections[t]?.updateMute(e)}get muteOutput(){return this._outputMuted}getFrequency(e){if(e===null){for(let i in this.currentIncomingCalls){let n=this.currentIncomingCalls[i];if(n&&n.currentAnalyzer)return n.currentAnalyzer.getAverageFrequency()}return null}let t=this.currentIncomingCalls[e];return t&&t.currentAnalyzer?t.currentAnalyzer.getAverageFrequency():null}peer=null;model=null;connections={};currentIncomingCalls={};_inputMuted=!1;_outputMuted=!1;awake(){if(N(no)){console.log("VOIP is disabled by url parameter: "+no);return}if(this.requireParam&&!Lv){console.debug("VOIP must be enabled explicitly by url parameter");return}this.peer=new Ep.default,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,this.context.connection.beginListen("joined-room",e=>{navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}),this.context.connection.beginListen("peer-update-id",e=>{if(e.id!==this.context.connection.connectionId){let t=this.connections[e.id];if(t&&t.close(),this.peer&&this.context.connection.connectionId){let i=new Gc(this,this.peer,this.context.connection.connectionId,e.peerId);this.connections[e.id]=i,i.startVoipCall()}}}),this.context.connection.beginListen("user-left-room",e=>{let{userId:t}=e,i=this.connections[t];this.connections[t]=null,i&&i.close();let n=this.currentIncomingCalls[t];ct&&console.log("UserLeftRoom",e,t,n),n&&(n.close(),this.currentIncomingCalls[t]=null)}),this.peer.on("open",this.onOpenPeerConnection.bind(this))}onEnable(){}onDisable(){console.log("TODO: close all");for(let e in this.currentIncomingCalls)this.currentIncomingCalls[e]?.close(),this.connections[e]?.close()}async onOpenPeerConnection(e){ct&&console.log("Peer connection established and received id"),this.model=new zc(e),this.context.connection.send("peer-update-id",this.model,1),this.peer&&(this.peer.on("call",this.onReceiveCall.bind(this)),this.peer.on("connection",function(t){ct&&console.log("CONNECTION",t),t.on("data",function(i){ct&&console.log("Received",i)})}))}async onReceiveCall(e){let{metadata:t}=e;console.assert(t.userId);let{userId:i}=t,{peer:n}=e,r=this.currentIncomingCalls[i];if(r&&r.close(),ct&&console.log("received call"),await Ke.HasMicrophonePermissions()){let o=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(o)}else e.answer(null);this.currentIncomingCalls[i]=new Vc(this,this.gameObject,e),e.on("stream",o=>{ct&&console.log("receive caller stream, will setup audio now"),this.currentIncomingCalls[i]?.openAudioStream(o)}),e.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}};var ro=N("debugflags");var Wc=class{Mask=17;Has(e){let t=this.Mask&e;return ro&&console.log("HAS",e,this.Mask,"Result="+t),t!==0}Set(e){this.Mask=e,Se.Apply()}Enable(e){this.Mask|=e,Se.Apply()}Disable(e){this.Mask&=~e,Se.Apply()}Toggle(e){this.Mask^=e,Se.Apply()}EnableAll(){this.Mask=-1,Se.Apply()}DisableAll(){this.Mask=0,Se.Apply()}},vt=Wc;z(vt,"Global",new Wc);var gi=class extends M{static Apply(){for(let e of this.registry)e.UpdateVisible(vt.Global)}awake(){gi.registry.push(this)}onEnable(){gi.firstApply||(gi.firstApply=!0,gi.Apply())}onDestroy(){let e=gi.registry.indexOf(this);e>=0&&gi.registry.splice(e,1)}visibleIn;get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(!this.enabled)return;let t,i=e;i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),ro&&console.log(i),gi.buffer.Mask=i,e=gi.buffer);let n=e;if(n?(ro&&console.log("use passed in mask"),t=n.Has(this.visibleIn)):(ro&&console.log("use global mask"),vt.Global.Has(this.visibleIn)),t!==void 0)if(t)ro&&console.trace("is visible",this.name,this.gameObject.uuid),O.setActive(this.gameObject,!0);else{if(ro&&console.trace("is not visible",this.name,this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},Se=gi;z(Se,"registry",[]),z(Se,"firstApply"),z(Se,"buffer",new vt);import*as K from"three";import{XRControllerModelFactory as Dv}from"three/examples/jsm/webxr/XRControllerModelFactory.js";import{OculusHandModel as Hv}from"three/examples/jsm/webxr/OculusHandModel.js";import{OculusHandPointerModel as jv}from"three/examples/jsm/webxr/OculusHandPointerModel.js";import*as _p from"three";import*as Kt from"three";var Rn=N("debugavatar"),Wi=class extends M{static onAvatarMarkerCreated(e){return Wi._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return Wi._onAvatarMarkerDestroyed.push(e),e}connectionId;avatar;awake(){Wi.instances.push(this),Rn&&console.log(this);for(let e of Wi._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Wi.instances.splice(Wi.instances.indexOf(this),1);for(let e of Wi._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}setVisible(e){this.avatar&&("setVisible"in this.avatar?this.avatar.setVisible(e):O.setActive(this.avatar,e))}},fe=Wi;z(fe,"instances",[]),z(fe,"_onNewAvatarMarkerAdded",[]),z(fe,"_onAvatarMarkerDestroyed",[]);var bs=class{_isVisible=!0;setVisible(e){this._isVisible=e,this.updateVisibility()}guid;root=null;head=null;handLeft=null;handRight=null;lastUpdate=-1;isLocalAvatar=!1;flags=null;headScale=new Kt.Vector3(1,1,1);handLeftScale=new Kt.Vector3(1,1,1);handRightScale=new Kt.Vector3(1,1,1);webxr;lastAvatarId=null;hasAvatarOverride=!1;context;avatarMarker=null;constructor(e,t,i){this.context=e,this.guid=t,this.webxr=i,this.setupCustomAvatar(this.webxr.defaultAvatar)}updateFlags(){if(!this.flags)return;let e=this.isLocalAvatar?8:16;for(let t of this.flags)t.gameObject.visible=!0,t.UpdateVisible(e)}async setAvatarOverride(e){return this.hasAvatarOverride=e!==null,this.hasAvatarOverride&&this.lastAvatarId!==e&&(this.lastAvatarId=e,e!=null&&e.length>0)?await this.setupCustomAvatar(e):null}_headTarget=new Kt.Object3D;_handLeftTarget=new Kt.Object3D;_handRightTarget=new Kt.Object3D;_canInterpolate=!1;tryUpdate(e,t){if(e.guid===this.guid&&(this.lastAvatarId!==e.avatarId&&e.avatarId&&e.avatarId.length>0&&(this.lastAvatarId=e.avatarId,this.setupCustomAvatar(e.avatarId)),this.lastUpdate=e.time,this.head)){this._canInterpolate=!0;let i=this.isLocalAvatar?this.head:this._headTarget;if(i.position.set(e.position.x,e.position.y,e.position.z),i.quaternion.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),i.scale.set(e.scale,e.scale,e.scale),i.scale.multiply(this.headScale),this.handLeft){let n=this.isLocalAvatar?this.handLeft:this._handLeftTarget;n.position.set(e.posLeftHand.x,e.posLeftHand.y,e.posLeftHand.z),n.quaternion.set(e.rotLeftHand._x,e.rotLeftHand._y,e.rotLeftHand._z,e.rotLeftHand._w),n.quaternion.multiply(bs.invertRotation),n.scale.set(e.scale,e.scale,e.scale),n.scale.multiply(this.handLeftScale)}if(this.handRight){let n=this.isLocalAvatar?this.handRight:this._handRightTarget;n.position.set(e.posRightHand.x,e.posRightHand.y,e.posRightHand.z),n.quaternion.set(e.rotRightHand._x,e.rotRightHand._y,e.rotRightHand._z,e.rotRightHand._w),n.quaternion.multiply(bs.invertRotation),n.scale.set(e.scale,e.scale,e.scale),n.scale.multiply(this.handRightScale)}}}update(){if(this.isLocalAvatar||!this._canInterpolate)return;let e=this.context.time.deltaTime/.1;this.head&&(this.head.position.lerp(this._headTarget.position,e),this.head.quaternion.slerp(this._headTarget.quaternion,e),this.head.scale.lerp(this._headTarget.scale,e)),this.handLeft&&this._handLeftTarget&&(this.handLeft.position.lerp(this._handLeftTarget.position,e),this.handLeft.quaternion.slerp(this._handLeftTarget.quaternion,e),this.handLeft.scale.lerp(this._handLeftTarget.scale,e)),this.handRight&&this._handRightTarget&&(this.handRight.position.lerp(this._handRightTarget.position,e),this.handRight.quaternion.slerp(this._handRightTarget.quaternion,e),this.handRight.scale.lerp(this._handRightTarget.scale,e))}destroy(){Rn&&console.log("Destroy avatar",this.guid),this.root?.removeFromParent(),this.avatarMarker?.destroy(),this.lastAvatarId=null,this.head&&_e.Remove(this.context,this.head)}updateVisibility(){let e=this.root;e&&O.setActive(e,this._isVisible)}async setupCustomAvatar(e){if(Rn&&console.log("LOAD",e,this),!e||typeof e=="string"&&e.length<=0)return!1;this.head&&_e.Remove(this.context,this.head);let t=e;if(t?.loadAssetAsync!==void 0){await t.loadAssetAsync();let n=t.asset;O.setActive(n,!1),e=O.instantiate(n),O.setActive(e,!0)}Rn&&console.log(e);let i=await bs.loader.getOrCreateNewAvatarInstance(this.context,e);if(Rn&&console.log(i,i?.isValid,this.lastAvatarId,e),i?.isValid){if(this.root=i.root,this.root.position.set(0,0,0),this.root.quaternion.set(0,0,0,1),this.root.scale.set(1,1,1),this.avatarMarker=O.addNewComponent(this.root,fe),this.avatarMarker.connectionId=this.guid,this.avatarMarker.avatar=this,this.head&&this.head!==i.head&&this.head?.removeFromParent(),this.head=i.head,this.headScale.copy(this.head.scale),this.head&&!this.isLocalAvatar&&_e.Add(this.context,this.head,this.avatarMarker),i.leftHand&&this.handLeft?.removeFromParent(),this.handLeft=i.leftHand??this.handLeft,this.handLeft?this.handLeftScale.copy(this.handLeft.scale):this.handLeftScale.set(1,1,1),i.rigthHand&&this.handRight?.removeFromParent(),this.handRight=i.rigthHand??this.handRight,this.handRight?this.handRightScale.copy(this.handRight.scale):this.handRightScale.set(1,1,1),this.context.scene.add(this.root),this.flags==null&&(this.flags=[]),this.flags.length=0,this.flags.push(...O.getComponentsInChildren(this.root,Se)),this.flags.length<=0&&this.head){let n=O.addNewComponent(this.head,Se);n.visibleIn=20,this.flags.push(n),Rn&&console.log("Added flag to head: "+n.visibleIn,this.head.name)}return Rn&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return Rn&&console.warn("build avatar failed"),!1}},Lt=bs;z(Lt,"loader",new Ni),z(Lt,"invertRotation",new Kt.Quaternion().setFromAxisAngle(new Kt.Vector3(0,1,0),Math.PI));var _e=class{static Add(e,t,i=null){if(!!t){for(let n of this.Pois)if(n.obj===t)return;this.Pois.push({obj:t,avatar:i}),this.LastChangeTime=e.time.time}}static Remove(e,t){if(!!t){for(let i of this.Pois)if(i.obj===t){this.Pois.splice(this.Pois.indexOf(i),1),this.LastChangeTime=e?.time.time??Z.Current?.time.time;return}}}};z(_e,"Pois",[]),z(_e,"LastChangeTime",0);var Uc=class{guid;position=new _p.Vector3},Ui=class extends M{set controlledTarget(e){this.target=e;let t=D.get("MoveRandom");if(t&&this.target){let i=O.getComponent(this.target,t);i&&i.destroy()}}target=null;avatar=null;_model=null;_targetModel=new Uc;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=O.getComponentInParent(this.gameObject,fe),this.avatar){let e=O.getComponentInParent(this.gameObject,fe);this._model=new En(this.context.connection,this.guid),e?.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{this.target&&e&&e.guid===this.avatar?.guid&&ie(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(_e.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=_e.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){let t=q(this._currentTargetObject);ie(this.target,t),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(t))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;let t=_e.Pois;if(t.length>0){let i=t[Math.floor(Math.random()*t.length)];if(i&&i.obj){if(i.avatar&&i.avatar===this.avatar)return;this._currentTargetObject=i.obj}}}}};var lr=class extends M{},Fe=class extends M{static CreateRaycastLine(){let e=new K.Line(this.geometry),t=e.material;return t.color=this.raycastColor,e.layers.set(1),e.name="line",e.scale.z=1,e}static CreateRaycastHitPoint(){let e=new K.SphereGeometry(.5,22,22),t=new K.MeshBasicMaterial({color:this.raycastColor}),i=new K.Mesh(e,t);return i.visible=!1,i.layers.set(1),i}static Create(e,t,i,n){let r=i?O.addNewComponent(i,Fe,!1):new Fe;r.webXR=e,r.index=t,r.type=n;let o=e.context;return r.controller=o.renderer.xr.getController(t),r.controllerGrip=o.renderer.xr.getControllerGrip(t),r.controllerModel=this.Factory.createControllerModel(r.controller),r.controllerGrip.add(r.controllerModel),r.hand=o.renderer.xr.getHand(t),r.hand.add(new Hv(r.hand)),r.hand.traverse(s=>s.layers.set(2)),r.handPointerModel=new jv(r.hand,r.controller),r.controller.addEventListener("connected",s=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),setTimeout(()=>{r.setControllerLayers(r.controllerGrip,2)},1e3)}),r.hand.addEventListener("connected",s=>{if(s.data.hand){e.Rig&&e.Rig.add(r.hand),r.type=0,r.handPointerModel.traverse(a=>a.layers.set(2)),r.handPointerModel.pointerObject?.traverse(a=>a.layers.set(2));let d=r.hand.joints;if(d)for(let a of Object.keys(d)){let h=d[a];h.parent||r.hand.add(h)}}}),r}static addEventListener(e,t){let i=this.eventSubs[e]??[];i.push(t),this.eventSubs[e]=i}webXR;index=-1;controllerModel;controller;controllerGrip;hand;handPointerModel;grabbed=null;input=null;type=0;get isUsingHands(){let e=this.input?.hand;return e!=null}get wrist(){if(!this.hand)return null;let e=this.hand.joints;return e?e.wrist:null}_wristQuaternion=null;getWristQuaternion(){let e=this.wrist;return e?(this._wristQuaternion||(this._wristQuaternion=new K.Quaternion),ve(e).multiply(this._wristQuaternion.setFromEuler(new K.Euler(-Math.PI/4,0,0)))):null}movementVector=new K.Vector3;worldRot=new K.Quaternion;joystick=new K.Vector2;didRotate=!1;didTeleport=!1;didChangeScale=!1;lastHit=null;raycastLine=null;_raycastHitPoint=null;_connnectedCallback=null;_disconnectedCallback=null;_selectStartEvt=null;_selectEndEvt=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}_selectionPressed=!1;_selectionPressedLastFrame=!1;_selectionStartTime=0;_selectionEndTime=0;get useSmoothing(){return this._useSmoothing}_useSmoothing=!0;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(){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)),this.hand?.clear(),this.controllerGrip?.clear(),this.controller?.clear()}onEnable(){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=Fe.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=Fe.CreateRaycastHitPoint()),this.webXR.Rig?.add(this.hand),this.webXR.Rig?.add(this.controllerGrip),this.webXR.Rig?.add(this.controller),this.webXR.Rig?.add(this.raycastLine),this.raycastLine?.add(this._raycastHitPoint),this.hand.add(this.handPointerModel),console.log("ADDED TO RIG",this.webXR.Rig)}onDisable(){this.hand?.removeFromParent(),this.controllerGrip?.removeFromParent(),this.controller?.removeFromParent(),this.raycastLine?.removeFromParent(),this._raycastHitPoint?.removeFromParent();let e=this.webXR.Controllers.indexOf(this);e>=0&&this.webXR.Controllers.splice(e,1)}_isConnected=!1;onSourceConnected(e){if(this._isConnected){console.warn("Received connected event for controller that is already connected",this.index,e);return}this._isConnected=!0,this.input=e.data,this.type===1&&(this.onSelectStart(),this.createPointerEvent("down"))}onSourceDisconnected(e){if(!this._isConnected){console.warn("Received discnnected event for controller that is not connected",e);return}this._isConnected=!1,this.type===1&&(this.onSelectEnd(),this.createPointerEvent("up")),this.input=null}createPointerEvent(e){switch(e){case"down":this.context.input.createPointerDown({pointerId:this.index,clientX:0,clientY:0,button:this.index,pointerType:"touch"});break;case"move":break;case"up":this.context.input.createPointerUp({pointerId:this.index,clientX:0,clientY:0,button:this.index,pointerType:"touch"});break}}rayRotation=new K.Quaternion;update(){this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));let e=Fe.eventSubs["update"];if(e&&e.length>0)for(let n of e)n(this);let t=1;this.type===0?t=this.context.time.deltaTime/.1:this.isUsingHands&&this.handPointerModel.pinched&&(t=this.context.time.deltaTime/.3),this.rayRotation.slerp(ve(this.controller),this.useSmoothing?t:1);let i=q(this.controller);if(this.raycastLine)if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed,ie(this.raycastLine,i);let n=this.hand.joints;if(n&&n.wrist&&this.grabbed&&this.grabbed.isCloseGrab){let o=this.getWristQuaternion();o&&this.rayRotation.copy(o)}Ae(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=!0,Ae(this.raycastLine,this.rayRotation),ie(this.raycastLine,i);this.lastHit=this.updateLastHit(),this.grabbed&&this.grabbed.update(),this._selectionPressedLastFrame=this._selectionPressed,this.selectStartCallback&&this.selectStartCallback()}_pinchStartTime=void 0;onUpdate(e){if(this.lastHit=null,!e||e.inputSources.length<=this.index){this.input=null;return}if(this.type===0&&(this.input=e.inputSources[this.index]),!this.input)return;let t=this.webXR.Rig;if(!t)return;this._didNotEndSelection&&!this.handPointerModel.pinched&&(this._didNotEndSelection=!1,this.onSelectEnd()),this.updateStick(this.input);let i=this.input?.gamepad?.buttons;switch(this.input.handedness){case"left":let n=3*Fe.MovementSpeedFactor,r=2,o=Q.clamp01(this.joystick.length()*2),s=this.joystick.x>0?1:-1,c=Math.pow(this.joystick.x,r);c*=s,c*=o;let d=this.joystick.y>0?1:-1,a=Math.pow(this.joystick.y,r);a*=d,c*=o,t.getWorldQuaternion(this.worldRot),this.movementVector.set(c,0,a),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),t.position.add(this.movementVector.multiplyScalar(n*this.context.time.deltaTime)),this.isUsingHands&&this.runTeleport(t,i);break;case"right":let h=this.joystick.x,u=Math.abs(h);if(u<.4)this.didRotate=!1;else if(u>.5&&!this.didRotate){let f=h>0?-1:1;t.rotateY(Q.toRadians(30*f)),this.didRotate=!0}this.runTeleport(t,i);break}}runTeleport(e,t){let i=-this.joystick.y;if(this.hand?.visible&&!this.grabbed){let s=this.handPointerModel.isPinched();s&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),s&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(i=this.handPointerModel.isPinched()?1:0),s||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;let n=i>.5,r=this.webXR.Rig?this.webXR.Rig?.scale?.x<.999:!1,o=null;if(t&&this.input&&!this.input.hand)for(let s=0;s<t.length;s++){let c=t[s];if(s===4)if(c.pressed&&!this.didChangeScale){this.didChangeScale=!0;let d=this.webXR.Rig;if(d)if(r){r=!1,d.scale.set(1,1,1),o=1,Fe.MovementSpeedFactor=1;let a=this.context.mainCamera;Fe.PreviousCameraFarDistance&&(a.far=Fe.PreviousCameraFarDistance)}else{r=!0,n=!0,o=.1,Fe.MovementSpeedFactor=o*2;let a=this.context.mainCamera;Fe.PreviousCameraFarDistance=a.far,a.far/=o}}else c.pressed||(this.didChangeScale=!1)}if(n){if(!this.didTeleport){let s=this.raycast();if(this.didTeleport=!0,s&&s.length>0){let c=s[0];if(r||this.isValidTeleportTarget(c.object)){let d=c.point;ie(e,d)}}}}else i<.1&&(this.didTeleport=!1);o!==null&&(e.scale.set(o,o,o),e.updateMatrixWorld())}isValidTeleportTarget(e){return O.getComponentInParent(e,lr)!=null}updateStick(e){!e||!e.gamepad||e.gamepad.axes?.length<4||(this.joystick.x=e.gamepad.axes[2],this.joystick.y=e.gamepad.axes[3])}updateLastHit(){let e=this.raycast(),t=e?e[0]:null;this.lastHit=t;let i=1;if(this.webXR.Rig&&(i/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=i*(this.lastHit?.distance??9999);let n=this.raycastLine.material;t!=null?n.color=Fe.raycastColor:n.color=Fe.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;let n=Q.clamp(this.lastHit.distance*.01*i,.015,.1);this._raycastHitPoint.scale.set(n,n,n)}this._raycastHitPoint.visible=this.lastHit!==null}return t}onSelectStart(){!this.context.connection.allowEditing||(this.selectStartCallback=()=>this.onHandleSelectStart())}selectStartCallback=null;lastSelectStartObject=null;onHandleSelectStart(){this.selectStartCallback=null,this._selectionPressed=!0,this._selectionStartTime=this.context.time.time,this._selectionEndTime=1e3;let e=null,t=!1;if(this.isUsingHands?(e=this.overlap(),e.length<=0?(e=this.raycast(),t=!1):t=!0):e=this.raycast(),e&&e.length>0)for(let i of e){let n=i.object;if(!this.testIsVisible(n)){console.log("not visible");continue}this.lastSelectStartObject=n;let r={selected:n,grab:n},o=Fe.eventSubs["select-start"];if(o&&o.length>0)for(let s of o)s(this,r);r.grab!==n&&console.log("Grabbed object changed","original",n,"new",r.grab),r.grab&&(this.grabbed=dt.TryTake(this,r.grab,i,t));break}else{let i=Fe.eventSubs["select-start"],n={selected:null,grab:null};if(i&&i.length>0)for(let r of i)r(this,n)}}_didNotEndSelection=!1;onSelectEnd(){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;let e={grab:this.grabbed?.selected??this.lastSelectStartObject},t=Fe.eventSubs["select-end"];if(t&&t.length>0)for(let i of t)i(this,e);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(e){return e?O.isActiveInHierarchy(e):!0}setControllerLayers(e,t){if(!!e&&(e.layers.set(t),e.children))for(let i of e.children)this.grabbed?.selected===i||this.grabbed?.selectedMesh===i||this.setControllerLayers(i,t)}getRay(){let e=new K.Ray;return e.origin.copy(q(this.controller)),e.direction.set(0,0,-1).applyQuaternion(this.rayRotation),e}overlap(){let e=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(!e)return new Array;let t=q(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){let e=new je;return e.layerMask=new K.Layers,e.layerMask.set(0),e.ray=this.getRay(),this.context.physics.raycast(e)}},se=Fe;z(se,"Factory",new Dv),z(se,"raycastColor",new K.Color(.9,.3,.3)),z(se,"raycastNoHitColor",new K.Color(.6,.6,.6)),z(se,"geometry",new K.BufferGeometry().setFromPoints([new K.Vector3(0,0,0),new K.Vector3(0,0,-1)])),z(se,"handModels",{}),z(se,"eventSubs",{}),z(se,"PreviousCameraFarDistance"),z(se,"MovementSpeedFactor",1);var et=class{static AddEventListener(e,t){return et.Events[e]||(et.Events[e]=[]),et.Events[e].push(t),t}static RemoveEventListener(e,t){if(!t||!et.Events[e])return;let i=et.Events[e].indexOf(t);i>=0&&et.Events[e].splice(i,1)}static Register(e){this.Current.find(t=>t===e)||this.Current.push(e)}static Remove(e){let t=this.Current.indexOf(e);t>=0&&this.Current.splice(t,1)}static TryTake(e,t,i,n){let r=O.getComponentInParent(t,kt);if(!r)return console.warn("Prevented taking object that is not interactable",t),null;let o=t,s=O.getComponentInParent(t,Qe);s&&(s.requestOwnership(),o=s.gameObject);for(let d of this.Current)if(d.selected===o)return d.controller===e||(d.free(),d.Take(e,o,t,s,r,i,n)),d;let c=new et;return c.Take(e,o,t,s,r,i,n),c}sync=null;selected=null;selectedParent=null;selectedMesh=null;controller=null;grabTime=0;grabUUID="";isCloseGrab=!1;originalMaterial=null;usageMarker=null;rigidbodies=null;didReparent=!1;grabDistance=0;interactable=null;positionSource=null;Take(e,t,i,n,r,o,s){if(console.assert(t!==null,"Expected object to be taken but was",t),e.isUsingHands?this.positionSource=s?e.wrist:e.controller:this.positionSource=e.controller,!this.positionSource)return console.warn("No position source"),this;let c={controller:e,take:t,hit:i,sync:n,interactable:r};et.Events.WillTake?.forEach(f=>f(this,c));let d=i;d?.material&&(this.originalMaterial=d.material,Array.isArray(d.material)||(d.material=d.material.clone(),d.material&&d.material.emissive&&(d.material.emissive.b=.2))),this.selected=t,this.selectedParent||(this.selectedParent=t.parent),this.selectedMesh=d,this.controller=e,this.interactable=r,this.isCloseGrab=s,this.didReparent=!1,this.sync=n,this.grabTime=e.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=O.addNewComponent(this.selected,It),this.rigidbodies=O.getComponentsInChildren(this.selected,ce),q(this.positionSource,this.lastControllerWorldPos);let a=()=>s?this.lastControllerWorldPos.clone():o.point.clone();this.grabDistance=a().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(a());let h=e.isUsingHands&&s?this.controller.getWristQuaternion().clone():e.rayRotation.clone();ve(this.selected,this.localQuaternionToGrab).premultiply(h.invert());let u=this.controller.webXR.Rig;return u&&this.rigPositionLastFrame.copy(q(u)),_e.Add(e.context,this.selected),et.Register(this),this.sync&&(this.sync.fastMode=!0),et.Events.DidTake?.forEach(f=>f(this,c)),this}free(){if(!this.selected)return;let e={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};et.Events.WillFree?.forEach(n=>n(this,e)),_e.Remove(this.controller.context,this.selected),et.Remove(this),this.sync&&(this.sync.fastMode=!1);let t=this.selectedMesh;t&&this.originalMaterial&&t.material&&(t.material=this.originalMaterial);let i=this.selected;if(this.didReparent&&i.parent){let n=this.selectedParent;n?n.attach(i):this.controller?.context.scene.attach(i)}if(this.usageMarker?.destroy(),this.controller&&(this.controller.grabbed=null),this.selected=null,this.selectedParent=null,this.selectedMesh=null,this.sync=null,this.rigidbodies)for(let n of this.rigidbodies)n.wakeUp(),n.smoothedVelocity&&n.setVelocity(n.smoothedVelocity.x,n.smoothedVelocity.y,n.smoothedVelocity.z);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,et.Events.DidFree?.forEach(n=>n(this,e))}grabPoint=new K.Vector3;localPositionOffsetToGrab=null;localPositionOffsetToGrab_worldSpace=new K.Vector3;localQuaternionToGrab=new K.Quaternion(0,0,0,1);targetDir=null;quaternionLerp=null;controllerDir=new K.Vector3;controllerWorldPos=new K.Vector3;lastControllerWorldPos=new K.Vector3;controllerPosDelta=new K.Vector3;totalChangeAlongDirection=0;rigPositionLastFrame=new K.Vector3;controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),q(this.positionSource,this.controllerWorldPos),this.controllerPosDelta.copy(this.controllerWorldPos),this.controllerPosDelta.sub(this.lastControllerWorldPos),this.lastControllerWorldPos.copy(this.controllerWorldPos);let e=this.controller.webXR.Rig;if(e){let i=q(e),n=this.rigPositionLastFrame.sub(i);this.controllerPosDelta.add(n),this.rigPositionLastFrame.copy(i)}return this.controllerDir.dot(this.controllerPosDelta)}update(){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){let e=this.controller.webXR.Rig?.scale.x??1;this.totalChangeAlongDirection+=this.controllerMovementSinceLastFrame();let t=1;this.controller.type===0&&(t=Math.max(0,1+this.totalChangeAlongDirection*2/e),t=t*t*t),this.grabDistance/e<.8&&(t=1),this.targetDir||(this.targetDir=new K.Vector3),this.targetDir.set(0,0,-this.grabDistance*t);let i=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),n=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=n.clone()),this.quaternionLerp.slerp(n,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),Ae(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(i),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(q(this.selected)),i.sub(this.localPositionOffsetToGrab_worldSpace)),ie(this.selected,i)}if(this.rigidbodies!=null)for(let e of this.rigidbodies)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0});he.markDirty(this.selected,!0)}}},dt=et;z(dt,"Events",{}),z(dt,"Current",[]);import*as Ha from"three";var Dt=class extends M{webAR=null;invertForward=!1;get arScale(){return this._arScale}set arScale(e){e!==this._arScale&&(this._arScale=e,this.setScale(e))}_arScale=5;_rig=null;_startPose=null;_placementPose=null;_isTouching=!1;onBegin(e){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose=this.gameObject.matrix.clone(),e.addEventListener("selectstart",this.onSelectStart.bind(this)),e.addEventListener("selectend",this.onSelectEnd.bind(this)),setTimeout(()=>this.gameObject.visible=!1,1e3)}onUpdate(e,t,i){if(i&&!this._placementPose&&this._isTouching){if(this.webAR&&this.webAR.setReticleActive(!1),this._placementPose=new Ha.Matrix4().fromArray(i.transform.matrix).invert(),e){if(this.invertForward){let n=new Ha.Matrix4().makeRotationY(Math.PI);this._placementPose.premultiply(n)}this._rig=e,this.setScale(this.arScale)}else this._rig=null;this.gameObject.visible=!0}}onEnd(e,t){this._placementPose=null,this.gameObject.visible=!1,this._startPose&&this.gameObject.matrix.copy(this._startPose),this.gameObject.matrixAutoUpdate=!0,e&&(e.matrixAutoUpdate=!0),he.markDirty(this.gameObject,!0),setTimeout(()=>this.gameObject.visible=!0,100)}onSelectStart(){this._isTouching=!0}onSelectEnd(){this._isTouching=!1}setScale(e){let t=this._rig;!t||!this._placementPose||(t.matrixAutoUpdate=!1,t.matrix.multiplyMatrices(new Ha.Matrix4().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld())}};k([A()],Dt.prototype,"invertForward",2),k([A()],Dt.prototype,"arScale",1);var Cn=class extends M{awake(){}};import{Object3D as Bv}from"three";var cr=N("debugaddressables"),ja=class{_context;constructor(e){this._context=e,this._context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){}_assetReferences={};findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.uri&&(this._assetReferences[e.uri]?console.warn("Asset reference already registered",e):this._assetReferences[e.uri]=e),e}},tt=class{static getOrCreate(e,t,i){let n=Ms(e,t);cr&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",n);let r=i.addressables,o=r.findAssetReference(n);if(o)return o;let s=new tt(n);return r.registerAssetReference(s),s}get asset(){return this._glbRoot??this._asset}set asset(e){this._asset=e}_loading;get uri(){return this._uri}get rawAsset(){return this._asset}_asset;_glbRoot;_uri;_progressListeners=[];_isLoadingRawBinary=!1;_rawBinary;constructor(e){this._uri=e,Bh(this._uri,this.onResolvePrefab.bind(this))}async onResolvePrefab(e){return e===this.uri&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(cr&&console.log("Unload",this.asset),this.asset.scene?O.destroy(this.asset.scene):O.destroy(this.asset)),this.asset=null}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,cr&&console.log("Preload",this.uri);let e=await fp(this.uri,t=>{this.raiseProgressEvent(t)});return this._rawBinary=e?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(e){if(!this.mustLoad)return;if(e&&this._progressListeners.push(e),this._loading!==void 0)return this._loading;let t=Z.Current;this._rawBinary?(this._loading=Xr(t,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(cr&&console.log("Load async",this.uri),this._loading=dr(t,this.uri,null,!0,n=>{this.raiseProgressEvent(n)}));let i=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(i),this._loading=void 0,i)return ki(t),i.scene!==void 0&&(this.asset=i),this.asset}async instantiate(e){return this.onInstantiate(e,!1)}async instantiateSynced(e,t=!0){return this.onInstantiate(e,!0,t)}beginListenDownload(e){this._progressListeners.indexOf(e)<0&&this._progressListeners.push(e)}endListenDownload(e){let t=this._progressListeners.indexOf(e);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(e){for(let t of this._progressListeners)t(this,e)}async onInstantiate(e,t=!1,i){let n=Z.Current;if(e||(e=n.scene),this.mustLoad&&await this.loadAssetAsync(),cr&&console.log("Instantiate",this.uri,"parent:",e),this.asset){cr&&console.log("Add to scene",this.asset);let r=e instanceof ye?e:null;if(r||(r=new ye),typeof e=="object"&&(e instanceof Bv?r.parent=e:Object.assign(r,e)),t){r.context=n;let o=this.asset;o.guid=this.uri;let s=Ws(o,r,void 0,i);if(s)return s}else{let o=O.instantiate(this.asset,r);if(o)return o}}else cr&&console.warn("Failed to load asset",this.uri);return null}tryGetActualGameObjectRoot(e){if(e&&e.scene){let t=e.scene;return t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name?t.children[0]:t}return null}},qc=class extends Fi{constructor(){super([tt])}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){return typeof e=="string"?t.context?t.gltfId?tt.getOrCreate(t.gltfId,e,t.context):(console.error("Missing spurce id"),null):(console.error("Missing context"),null):null}};new qc;import*as yt from"three";var bi=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}w(){return this.bb.readFloat32(this.bb_pos+12)}static sizeOf(){return 16}static createVec4(e,t,i,n,r){return e.prep(4,16),e.writeFloat32(r),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var Me=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsVrUserStateBuffer(e,t){return(t||new Me).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+4),(t||new Me).__init(e.readInt32(e.position())+e.position(),e)}guid(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}time(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}avatarId(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__string(this.bb_pos+t,e):null}position(e){let t=this.bb.__offset(this.bb_pos,10);return t?(e||new Ce).__init(this.bb_pos+t,this.bb):null}rotation(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new bi).__init(this.bb_pos+t,this.bb):null}scale(){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.readFloat32(this.bb_pos+e):0}posLeftHand(e){let t=this.bb.__offset(this.bb_pos,16);return t?(e||new Ce).__init(this.bb_pos+t,this.bb):null}posRightHand(e){let t=this.bb.__offset(this.bb_pos,18);return t?(e||new Ce).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){let t=this.bb.__offset(this.bb_pos,20);return t?(e||new bi).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){let t=this.bb.__offset(this.bb_pos,22);return t?(e||new bi).__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)}};var xp=N("debugxr"),vs=N("debugavatar");var Qc="VRUS";Nr(Qc,Me.getRootAsVrUserStateBuffer);function Xc(){return new Date().getTime()}function Fv(l){let e=l&4294967295,t=l/Math.pow(2,32)&1048575;return Xe.create(e,t)}var ys=class{guid;time;avatarId;position=new yt.Vector3;rotation=new yt.Vector4;scale=1;posLeftHand=new yt.Vector3;posRightHand=new yt.Vector3;rotLeftHand=new yt.Quaternion;rotRightHand=new yt.Quaternion;constructor(e){this.guid=e}update(e,t,i,n,r){this.time=Xc(),this.avatarId=r,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let o=ys.quat0,s=ys.quat1;o.set(i.x,i.y,i.z,i.w),o=o.multiplyQuaternions(o,ys.invertRotation),e&&(e.getWorldQuaternion(s),o.multiplyQuaternions(s,o)),this.rotation.set(o.x,o.y,o.z,o.w),this.scale=e.scale.x;let c=n.LeftController?.controllerGrip;c&&(c.getWorldPosition(this.posLeftHand),c.getWorldQuaternion(this.rotLeftHand));let d=n.RightController?.controllerGrip;if(d&&(d.getWorldPosition(this.posRightHand),d.getWorldQuaternion(this.rotRightHand)),n.LeftController?.hand?.visible){let a=n.LeftController.wrist;a&&(a.getWorldPosition(this.posLeftHand),a.getWorldQuaternion(this.rotLeftHand))}if(n.RightController?.hand?.visible){let a=n.RightController.wrist;a&&(a.getWorldPosition(this.posRightHand),a.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(e,t){e.clear();let i=e.createString(this.guid),n=e.createString(this.avatarId);Me.startVrUserStateBuffer(e),Me.addGuid(e,i),Me.addTime(e,Fv(this.time)),Me.addAvatarId(e,n),Me.addPosition(e,Ce.createVec3(e,this.position.x,this.position.y,this.position.z)),Me.addRotation(e,bi.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),Me.addScale(e,this.scale),Me.addPosLeftHand(e,Ce.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),Me.addPosRightHand(e,Ce.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),Me.addRotLeftHand(e,bi.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),Me.addRotRightHand(e,bi.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));let r=Me.endVrUserStateBuffer(e);e.finish(r,Qc);let o=e.asUint8Array();t.sendBinary(o)}setFromBuffer(e,t){if(!e)return;this.guid=e,this.time=t.time().toFloat64();let i=t.avatarId();i&&(this.avatarId=i);let n=t.position();n&&this.position.set(n.x(),n.y(),n.z());let r=t.rotation();r&&this.rotation.set(r.x(),r.y(),r.z(),r.w());let o=t.posLeftHand();o&&this.posLeftHand.set(o.x(),o.y(),o.z());let s=t.posRightHand();s&&this.posRightHand.set(s.x(),s.y(),s.z());let c=t.rotLeftHand();c&&this.rotLeftHand.set(c.x(),c.y(),c.z(),c.w());let d=t.rotRightHand();d&&this.rotRightHand.set(d.x(),d.y(),d.z(),d.w()),this.scale=t.scale()}},Ht=ys;z(Ht,"invertRotation",new yt.Quaternion().setFromAxisAngle(new yt.Vector3(0,1,0),Math.PI)),z(Ht,"quat0",new yt.Quaternion),z(Ht,"quat1",new yt.Quaternion);var qi=class extends M{webXR=null;debugAvatarUser=null;voip=null;async awake(){if(this.webXR||(this.webXR=this.gameObject.getComponent($)),this.webXR||(this.webXR=O.findObjectOfType($,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=O.findObjectOfType($,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=O.findObjectOfType(Ke,this.context)),vs){let e="debug-avatar-"+vs,t=new Lt(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof vs=="string"&&vs.length>0)if(await t.setAvatarOverride(vs)){let i=new Ht(e);i.position.y+=1;let n=.5;i.posLeftHand.y+=n,i.posLeftHand.x+=n,i.posRightHand.y+=n,i.posRightHand.x-=n,t.tryUpdate(i,0)}else t.destroy()}}onEnable(){if(!this.webXR&&(this.webXR=O.getComponent(this.gameObject,$),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),$.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),$.addEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),$.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.eventSub_ConnectionEvent=this.onConnected.bind(this),this.context.connection.beginListen("joined-room",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=>{let t=e.id!==null&&e.id!==void 0;!t||(console.log("webxr user left evt"),t&&(this.avatars[e.id]?.destroy(),this.avatars[e.id]=void 0))}),this.context.connection.beginListenBinrary(Qc,e=>{let t=e.guid();if(!t)return;let i=e.time().toFloat64(),n=this.tempState;n.setFromBuffer(t,e),this.onTryGetAvatar(t,i)?.tryUpdate(n,i)}),this.context.connection.beginListen("vr-session-update",e=>{let t=e.guid,i=e.time;this.onTryGetAvatar(t,i)?.tryUpdate(e,i)})}tempState=new Ht("");onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;let i=new Date().getTime()-t;if(i>5e3)return xp&&console.log("old data",i,e),null;let n=this.avatars[e];if(n===void 0)try{console.log("create new avatar");let r=new Lt(this.context,e,this.webXR);n=r,this.avatars[e]=r}catch(r){this.avatars[e]=null,console.error(r)}return n}onDisable(){this.eventSub_ConnectionEvent&&this.context.connection.stopListening("joined-room",this.eventSub_ConnectionEvent),$.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),$.removeEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),$.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}update(){let e=Xc();this.debugAvatarUser&&(this.debugAvatarUser.lastUpdate=e),this.detectPotentiallyDisconnectedAvatarsAndRemove();for(let t in this.avatars){let i=this.avatars[t];!i||i.update()}}_removeAvatarsList=[];detectPotentiallyDisconnectedAvatarsAndRemove(){let e=Xc();for(let t in this.avatars){let i=this.avatars[t];if(!i){this._removeAvatarsList.push(t);continue}e-i.lastUpdate>1e4&&(console.log("avatar timed out (didnt receive any updates in a while) - destroying it now"),i.destroy(),this.avatars[t]=void 0)}for(let t of this._removeAvatarsList)delete this.avatars[t];this._removeAvatarsList.length=0}buildLocalAvatar(){if(this.localAvatar)return;let e=this.context.connection?.connectionId??this.k_LocalAvatarNoNetworkingGuid;this.localAvatar=new Lt(this.context,e,this.webXR),this.localAvatar.isLocalAvatar=!0,this.localAvatar.setAvatarOverride(this.getAvatarId()),this.avatars[this.localAvatar.guid]=this.localAvatar}eventSub_ConnectionEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;eventSub_WebXRUpdateEvent=null;avatars={};localAvatar=null;k_LocalAvatarNoNetworkingGuid="local";onConnected(){xp&&console.log("Hey you are connected as "+this.context.connection.connectionId),this.localAvatar?.guid===this.k_LocalAvatarNoNetworkingGuid&&(this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0),this.localAvatar=null,this.xrState=null,this.ownership?.freeOwnership(),this.ownership=null)}onXRSessionStart(e){if(console.log("XR session started"),this.context.connection.send("webxr-user-joined",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null),this.xrState=null,this.ownership?.freeOwnership(),this.ownership=null,this.avatars)for(let t in this.avatars)this.avatars[t]?.updateFlags()}onXRSessionEnded(e){console.log("XR session ended"),this.context.connection.send("webxr-user-left",{id:this.context.connection.connectionId,mode:"vr"})}ownership=null;xrState=null;builder=new ft(1024);onXRSessionUpdate(e){this.xrState??=new Ht(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership??=new En(this.context.connection,this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership.guid=this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid,this.buildLocalAvatar();let{frame:t,xr:i,rig:n}=e,r=t.getViewerPose(i.getReferenceSpace());if(!r)return;let o=r?.transform,s=o.position,c=o.orientation;this.xrState.update(n,s,c,this.webXR,this.getAvatarId()),this.localAvatar&&(this.context.connection.connectionId&&(this.localAvatar.guid=this.context.connection.connectionId),this.localAvatar.tryUpdate(this.xrState,0)),!(this.ownership&&!this.ownership.hasOwnership&&this.context.connection.isConnected&&(this.context.time.frameCount%120===0&&this.ownership.requestOwnership(),!this.ownership.hasOwnership))&&(!this.context.connection.isConnected||!this.context.connection.connectionId||this.xrState.sendAsBuffer(this.builder,this.context.connection))}getAvatarId(){return N("avatar")}};async function Nv(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function zv(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}var Yc=!1,Zc=!1;Nv().then(l=>Yc=l);zv().then(l=>Zc=l);var Ne=class extends M{enableVR=!0;enableAR=!0;defaultAvatar;createVRButton=!0;createARButton=!0;static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(Yc||Zc)}static get IsARSupported(){return Yc}static get IsVRSupported(){return Zc}static addEventListener(e,t){return this.events.addEventListener(e,t),t}static removeEventListener(e,t){return this.events.removeEventListener(e,t),t}static createVRButton(e,t){Ne.XRSupported||console.warn("WebXR is not supported on this device");let i=io.createButton(e.context.renderer);return i.classList.add("webxr-ar-button"),i.classList.add("webxr-button"),this.resetButtonStyles(i),(t?.registerClick??!0)&&i.addEventListener("click",e.onClickedVRButton.bind(e)),i}static createARButton(e,t){let i=e.webAR?.getAROverlayContainer(),n={requiredFeatures:["hit-test"]};i&&(n.domOverlay={root:i},n.optionalFeatures=["dom-overlay"]);let r=Ma.createButton(e.context.renderer,n);return r.classList.add("webxr-ar-button"),r.classList.add("webxr-button"),Ne.resetButtonStyles(r),(t?.registerClick??!0)&&r.addEventListener("click",e.onClickedARButton.bind(e)),r}static resetButtonStyles(e){!e||(e.style.position="",e.style.bottom="",e.style.left="")}endSession(){let e=this.context.renderer.xr.getSession();e&&e.end()}get Rig(){return this.rig}controllers=[];get Controllers(){return this.controllers}get LeftController(){return this.controllers.length>0&&this.controllers[0].input?.handedness==="left"?this.controllers[0]:this.controllers.length>1&&this.controllers[1].input?.handedness==="left"?this.controllers[1]:null}get RightController(){return this.controllers.length>0&&this.controllers[0].input?.handedness==="right"?this.controllers[0]:this.controllers.length>1&&this.controllers[1].input?.handedness==="right"?this.controllers[1]:null}get ARButton(){return this._arButton}get VRButton(){return this._vrButton}rig;isInit=!1;_requestedAR=!1;_requestedVR=!1;_isInAR=!1;_isInVR=!1;_arButton;_vrButton;webAR=null;awake(){if(this.defaultAvatar&&typeof this.defaultAvatar=="string"&&(this.defaultAvatar=tt.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!O.findObjectOfType(qi,this.context)){let e=O.addNewComponent(this.gameObject,qi,!1);e.webXR=this}}onEnable(){if(this.isInit||!this.enableAR&&!this.enableVR)return;this.isInit=!0,this.context.renderer.xr.enabled=!0,this.webAR=new Sn(this);let e=Ne.XRSupported,t,i,n=document.createElement("div");n.classList.add("webxr-buttons"),this.context.domElement.append(n),this.enableAR&&this.createARButton&&(t=Ne.createARButton(this),this._arButton=t,n.appendChild(t)),this.createVRButton&&this.enableVR&&(e||!this.enableAR)&&(i=Ne.createVRButton(this),this._vrButton=i,n.appendChild(i)),setTimeout(()=>{Ne.resetButtonStyles(i),Ne.resetButtonStyles(t)},1e3)}_transformOrientation=new Pe.Quaternion;get TransformOrientation(){return this._transformOrientation}_currentHeadPose=null;get HeadPose(){return this._currentHeadPose}onBeforeRender(e){if(!e)return;let t=this.context.renderer.xr.getSession();if(t){let i=e.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(this._currentHeadPose=i,!i)return;let n=i?.transform;n&&this._transformOrientation.set(n.orientation.x,n.orientation.y,n.orientation.z,n.orientation.w);for(let r of this.controllers)r.onUpdate(t);this._isInAR&&this.webAR?.onUpdate(t,e)}Ne._isInXr===!1&&t&&this.onEnterXR(t,e),Ne.events.dispatchEvent({type:"xrUpdate",frame:e,xr:this.context.renderer.xr,rig:this.rig})}onClickedARButton(){this._isInAR||(this._requestedAR=!0,this._requestedVR=!1,this.captureCameraState())}onClickedVRButton(){if(!this._isInVR){if(this._requestedVR){this.onExitXR(null);return}this._requestedAR=!1,this._requestedVR=!0,this.captureCameraState(),this.ensureRig();for(let e=0;e<2;e++)se.Create(this,e,this.gameObject,0);Ne.events.dispatchEvent({type:"requestVRSession"})}}captureCameraState(){this.context.mainCamera&&(this._originalCameraPosition.copy(q(this.context.mainCamera)),this._originalCameraRotation.copy(ve(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent)}ensureRig(){if(!this.rig){let e=O.findObjectOfType(Cn,this.context);e?(this.rig=e.gameObject,this.rig.rotateY(Math.PI)):(this.rig=new Pe.Group,this.rig.name="XRRig",this.context.scene.add(this.rig))}}_originalCameraParent=null;_originalCameraPosition=new Pe.Vector3;_originalCameraRotation=new Pe.Quaternion;onEnterXR(e,t){console.log("[XR] session begin",e),Ne._isInXr=!0,this.ensureRig();let i=this.context.renderer.xr.getReferenceSpace();if(i&&this.rig){let s=t.getViewerPose(i)?.transform.orientation;if(s){let c=new Pe.Quaternion(s.x,s.y,s.z,s.w),d=new Pe.Euler().setFromQuaternion(c);this.rig.rotateY(d.y)}}let n=this.context.renderer.xr;if(this.context.mainCamera){let o=n.getCamera(this.context.mainCamera);for(let s of o.cameras)s.layers.enableAll();this.rig.add(this.context.mainCamera)}let r=this._requestedAR?2:4;switch(vt.Global.Set(r),r){case 2:this._isInAR=!0,this.webAR?.onBegin(e);break;case 4:this._isInVR=!0,this.onEnterVR(e);break}e.addEventListener("end",()=>{console.log("[XR] session end"),Ne._isInXr=!1,this.onExitXR(e)}),this.onEnterXR_HandleMirrorWindow(e),Ne.events.dispatchEvent({type:"xrStarted",session:e})}onExitXR(e){this._isInAR&&e&&this.webAR?.onEnd(e),this._isInAR=!1,this._isInVR=!1,this._requestedAR=!1,this._requestedVR=!1,this.xrMirrorWindow&&(this.xrMirrorWindow.close(),this.xrMirrorWindow=null),this.destroyControllers(),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),ie(this.context.mainCamera,this._originalCameraPosition),Ae(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),vt.Global.Set(17),Ne.events.dispatchEvent({type:"xrStopped",session:e})}onEnterVR(e){}destroyControllers(){for(let e=this.controllers.length-1;e>=0;e-=1)this.controllers[e]?.destroy();this.controllers.length=0}xrMirrorWindow=null;onEnterXR_HandleMirrorWindow(e){!N("mirror")||setTimeout(()=>{if(!Ne.IsInWebXR)return;let t=new URL(window.location.href);Or(t.searchParams,no,1),Or(t.searchParams,"isMirror",1);let i=t.toString();this.xrMirrorWindow=window.open(i,"webxr sync","popup=yes"),this.xrMirrorWindow&&(this.xrMirrorWindow.onload=()=>{this.xrMirrorWindow&&(this.xrMirrorWindow.onbeforeunload=()=>{Ne.IsInWebXR&&e.end()})})},1e3)}},$=Ne;z($,"_isInXr",!1),z($,"events",new Pe.EventDispatcher),k([A(tt)],$.prototype,"defaultAvatar",2);var oo=class{webxr;reticle=null;hitTestSource=null;reticleActive=!0;previousBackground=null;previousEnvironment=null;sessionRoot=null;_previousParent=null;get context(){return this.webxr.context}constructor(e){this.webxr=e}arDomOverlay=null;arOverlayElement=null;getAROverlayContainer(){return this.arDomOverlay=this.webxr.context.domElement,this.arOverlayElement=this.arDomOverlay.getAROverlayContainer(),this.arOverlayElement}setReticleActive(e){this.reticleActive=e}onBegin(e){let t=this.webxr.context;this.reticleActive=!0;for(let i=0;i<4;i++)se.Create(this.webxr,i,this.webxr.gameObject,1);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=O.findObjectOfType(Dt,t)),this.previousBackground=t.scene.background,this.previousEnvironment=t.scene.environment,t.scene.background=null,e.requestReferenceSpace("viewer").then(i=>{e.requestHitTestSource({space:i}).then(n=>{this.hitTestSource=n})}),!this.reticle&&this.sessionRoot&&(this.reticle=new Pe.Mesh(new Pe.RingGeometry(.07,.09,32).rotateX(-Math.PI/2),new Pe.MeshBasicMaterial),this.reticle.name="AR Placement reticle",this.reticle.matrixAutoUpdate=!1,this.reticle.visible=!1,this.webxr.scene?(this.webxr.scene.add(this.reticle),this.webxr.scene.visible=!0):console.warn("Could not found WebXR Rig")),this._previousParent=this.webxr.gameObject,oo.tempWebXRObject||(oo.tempWebXRObject=new Pe.Object3D),this.context.scene.add(oo.tempWebXRObject),O.addComponent(oo.tempWebXRObject,this.webxr),this.sessionRoot?(this.sessionRoot.webAR=this,this.sessionRoot?.onBegin(e)):console.warn("No WebARSessionRoot found in scene"),this.arDomOverlay&&this.arOverlayElement&&this.arDomOverlay.onEnterAR(e,this.arOverlayElement),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onEnd(e){this._previousParent&&(console.log("ADD",this._previousParent),O.addComponent(this._previousParent,this.webxr),this._previousParent=null),this.hitTestSource=null;let t=this.webxr.context;t.scene.background=this.previousBackground,t.scene.environment=this.previousEnvironment,this.sessionRoot&&this.sessionRoot.onEnd(this.webxr.Rig,e),this.arDomOverlay&&this.arDomOverlay.onExitAR(e),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onUpdate(e,t){if(!this.hitTestSource)return;let i=t.getHitTestResults(this.hitTestSource);if(i.length){let n=i[0],r=this.webxr.context.renderer.xr.getReferenceSpace();if(r){let o=n.getPose(r);if(this.sessionRoot?.onUpdate(this.webxr.Rig,e,o),this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&o)){let s=o.transform.matrix;this.reticle.matrix.fromArray(s),this.webxr.Rig&&this.reticle.matrix.premultiply(this.webxr.Rig.matrix)}}}else this.sessionRoot?.onUpdate(this.webxr.Rig,e,null),this.reticle&&(this.reticle.visible=!1)}},Sn=oo;z(Sn,"tempWebXRObject");var Jc=!1;var so=class extends kt{static get HasAnySelected(){return this._active!==null}transformSelf=!0;selectStartEventListener=[];selectEndEventListener=[];constructor(){super(),this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new ee.Vector2}addDragEventListener(e,t){switch(e){case"selectstart":this.selectStartEventListener.push(t);break;case"selectend":this.selectEndEventListener.push(t);break}}_dragHelper=null;start(){}_draggingRigidbodies=[];allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||$.IsInWebXR)return;let t=O.getComponentInParent(e.object,so);!t||t!==this||(so.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){!this.allowEdit(this.gameObject)||$.IsInWebXR||so.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}_waitingForDragStart=null;onPointerDown(e){!this.allowEdit(this.gameObject)||$.IsInWebXR||(this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation())}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&($.IsInWebXR||(this.onDragEnd(e),e.StopPropagation()))}update(){if(!$.IsInWebXR){if(this._waitingForDragStart){if(!this._didDrag){let t=this.context.input.getPointerPositionDelta(0);if(t&&this._dragDelta.add(t),this._dragDelta.length()>2)this._didDrag=!0;else return}let e=this._waitingForDragStart;this._waitingForDragStart=null,this.onDragStart(e)}this._dragHelper&&this._dragHelper.hasSelected&&this.onUpdateDrag(),this._isDragging&&!this._dragHelper?.hasSelected&&this.onDragEnd(null)}}_isDragging=!1;_marker=null;_dragDelta;_didDrag=!1;onDragStart(e){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new Ba(this.context.mainCamera);else return;if(!e||!e.object)return;let t=O.getComponentInParent(e.object,so);if(!t||t!==this)return;let i=e.object;this.transformSelf&&(i=this.gameObject);let n={selected:i,attached:i};for(let c of this.selectStartEventListener)c(this,n);if(!n.attached)return;n.attached,i=n.attached,this._isDragging=!0,this._dragHelper.setSelected(i,this.context);let r=O.getComponentInChildren(i,Qe);Jc&&console.log("DRAG START",r,i),r&&(r.fastMode=!0,r?.requestOwnership()),this._marker=O.addNewComponent(i,It),this._draggingRigidbodies.length=0;let o=O.getComponentsInChildren(i,ce);o&&this._draggingRigidbodies.push(...o);let s=El();O.invokeOnChildren(this._dragHelper.selected,s("onDragStart"))}onUpdateDrag(){if(!!this._dragHelper){this._dragHelper.onUpdate(this.context);for(let e of this._draggingRigidbodies)e.wakeUp(),e.setBodyFromGameObject()}}onDragEnd(e){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;this._draggingRigidbodies.length=0;let t=this._dragHelper.selected;if(Jc&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context),e?.object){let n=O.getComponentInChildren(e.object,Qe);n&&(n.fastMode=!1),this._marker&&this._marker.destroy()}for(let n of this.selectEndEventListener)n(this);let i=El();O.invokeOnChildren(t,i("onDragEnd"))}},Et=so;z(Et,"_active",null),z(Et,"lastHovered");var Kc=class{get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}_selected=null;_context=null;_camera;_cameraPlane=new ee.Plane;_hasGroundPlane=!1;_groundPlane=new ee.Plane;_groundOffset=new ee.Vector3;_groundOffsetFactor=0;_groundDistance=0;_groundPlanePoint=new ee.Vector3;_raycaster=new ee.Raycaster;_cameraPlaneOffset=new ee.Vector3;_intersection=new ee.Vector3;_worldPosition=new ee.Vector3;_inverseMatrix=new ee.Matrix4;_rbs=[];_groundLine;_groundMarker;constructor(e){this._camera=e;let t=new ee.Line(Kc.geometry),i=t.material;i.color=new ee.Color(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;let n=new ee.SphereGeometry(.5,22,22),r=new ee.MeshBasicMaterial({color:i.color}),o=new ee.Mesh(n,r);o.visible=!1,o.layers.set(2),this._groundMarker=o}setSelected(e,t){if(this._selected&&t)for(let i of this._rbs)i.wakeUp(),i.smoothedVelocity&&i.setVelocity(i.smoothedVelocity.x,i.smoothedVelocity.y,i.smoothedVelocity.z);if(this._selected&&_e.Remove(t,this._selected),this._selected=e,this._context=t,this._rbs.length=0,e?(t.scene.add(this._groundLine),t.scene.add(this._groundMarker)):(this._groundLine.removeFromParent(),this._groundMarker.removeFromParent()),this._selected){if(!t){console.error("DragHelper: no context");return}_e.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this._rbs=O.getComponentsInChildren(this._selected,ce),this.onUpdateScreenSpacePlane()}}_groundOffsetVector=new ee.Vector3(0,1,0);_requireUpdateGroundPlane=!0;_didDragOnGroundPlaneLastFrame=!1;onUpdate(e){if(!this._context)return;let t=32,i=68,n=83,r=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(i),o=this._context.input.getTouchesPressedCount()>=2||r;if(o){let c=this._context.input.getPointerPositionDelta(0);c&&(this._groundOffsetVector.set(0,1,0),this._selected?.rotateOnWorldAxis(this._groundOffsetVector,c.x*this._context.time.deltaTime))}let s=this._context.input.getPointerPositionRC(0);if(!!s&&(this._raycaster.setFromCamera(s,this._camera),this._selected)){Jc&&console.log("UPDATE DRAG",this._selected),this._groundOffsetVector.set(0,1,0);let c=q(this._camera).clone().sub(q(this._selected)).normalize(),d=Math.abs(c.dot(this._groundOffsetVector)),a=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(i),h=!o&&d>.2&&!a&&this._context.input.getPointerPressedCount()<=1,u=this._didDragOnGroundPlaneLastFrame!==h;if(this._didDragOnGroundPlaneLastFrame=h,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!h||u)&&this.onUpdateGroundPlane(),this._requireUpdateGroundPlane=!1,this._hasGroundPlane)if(this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection)){let f=this._intersection.y;if(this._groundPlanePoint.copy(this._intersection).sub(this._groundOffset),this._groundPlanePoint.y=f,h){this._groundOffsetVector.set(0,1,0);let E=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(E,this._groundPlanePoint,!1),this.onDidUpdate();return}}else this._groundPlanePoint.set(0,99999,0);u&&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(e,t,i){if(!!this._selected){if(i){let n=q(this._selected);n.y=e.y,e=n}if(ie(this._selected,e),ie(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=t!==null,t){let n=q(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(n,n,n),ie(this._groundMarker,t)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;let e=this._context.input.getPointerPositionRC(0);!e||(this._raycaster.setFromCamera(e,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;let e=q(this._selected),t=new ee.Ray(new ee.Vector3(0,.1,0).add(e),new ee.Vector3(0,-1,0)),i=new je;i.ignore=[this._selected];let n=this._context.physics.raycastFromRay(t,i);for(let r=0;r<n.length;r++){let o=n[r];if(!o.face||this.contains(this._selected,o.object))continue;let s=new ee.Vector3(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(s,o.point);break}this._hasGroundPlane=!0,this._groundPlane.setFromNormalAndCoplanarPoint(t.direction.multiplyScalar(-1),t.origin),this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection),this._groundDistance=this._intersection.distanceTo(e),this._groundOffset.copy(this._intersection).sub(e)}onDidUpdate(){he.markDirty(this._selected);for(let e of this._rbs)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0}),e.setAngularVelocity(0,0,0)}contains(e,t){if(e===t)return!0;if(e.children){for(let i of e.children)if(this.contains(i,t))return!0}return!1}},Ba=Kc;z(Ba,"geometry",new ee.BufferGeometry().setFromPoints([new ee.Vector3(0,0,0),new ee.Vector3(0,-1,0)]));var Pn=class extends M{filesBackendUrl;localhost;_dragOver;_drop;onEnable(){this.filesBackendUrl=this.filesBackendUrl?pt.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 onDrop(e){if(console.log(e),!e.dataTransfer)return;e.preventDefault();let t=e.dataTransfer.items;if(!!t)for(let i in t){let n=t[i];if(n.kind==="file"){let r=n.getAsFile();if(!r)continue;console.log("Register file "+r.name+" to",this.filesBackendUrl,r);let o=await Rp(r,this.context,this.filesBackendUrl);o&&this.addObject(e,o)}else n.kind==="string"&&n.type=="text/plain"&&n.getAsString(async r=>{console.log("dropped url",r);try{let o=new URL(r);if(!o)return;let s=await Cp(o,this.context);s&&this.addObject(e,s)}catch{console.log("dropped string is not a valid URL!",r)}})}}async addObject(e,t){console.log("Dropped",t);let i=new je;i.setMask(16777215),i.screenPointFromOffset(e.offsetX,e.offsetY);let n=this.context.physics.raycast(i),r=t.scene;if(n&&n.length>0)for(let o of n){r.position.copy(o.point);break}this.gameObject.add(r),this.dispatchEvent(new CustomEvent("object-added",{detail:r}))}};k([A()],Pn.prototype,"filesBackendUrl",2),k([A()],Pn.prototype,"localhost",2);import{Vector3 as Vv,Quaternion as Wv,Object3D as Sp}from"three";var vi=class extends kt{parent=null;object=null;limitCount=10;limitInterval=60;_currentCount=0;_startPosition=null;_startQuaternion=null;awake(){if(this.object){if(this.object===this.gameObject){console.error("Can not duplicate self");return}this.object.visible=!1,this._startPosition=this.object.position?.clone()??new Vv(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new Wv(0,0,0,1)}let e=O.getComponentInParent(this.gameObject,Et);e?e.addDragEventListener("selectstart",(t,i)=>{if(this._currentCount>=this.limitCount){i.attached=null;return}let n=this.handleDuplication(i.selected);n&&(console.assert(n!==i.selected,"Duplicated object is original"),i.attached=n)}):console.warn("Could no find drag controls in parent",this.name),se.addEventListener("select-start",(t,i)=>{if(this._currentCount>=this.limitCount){i.grab=null;return}let n=this.handleDuplication(i.selected);n&&(i.grab=n)}),this.cloneLimitIntervalFn()}cloneLimitIntervalFn(){this.destroyed||(this._currentCount>0&&(this._currentCount-=1),setTimeout(()=>{this.cloneLimitIntervalFn()},this.limitInterval/this.limitCount*1e3))}handleDuplication(e){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);let t=new ye;this.parent||(this.parent=this.gameObject.parent),this.parent&&(t.parent=this.parent.guid??this.parent.userData?.guid,t.keepWorldPosition=!0),t.position=this.worldPosition,t.rotation=this.worldQuaternion,t.context=this.context,this._currentCount+=1;let i=O.instantiateSynced(this.object,t);return console.assert(i!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),i}return null}handleMultiObject(e){return this.gameObject.type==="Group"||this.gameObject.type==="Object3D"?this.isInChildren(this.gameObject,e):!1}isInChildren(e,t){if(!e)return!1;if(e===t)return!0;if(e.children){for(let i of e.children)if(this.isInChildren(i,t))return!0}return!1}};k([A(Sp)],vi.prototype,"parent",2),k([A(Sp)],vi.prototype,"object",2),k([A()],vi.prototype,"limitCount",2),k([A()],vi.prototype,"limitInterval",2);var yi=class{method;enabled;constructor(e,t){this.method=e,this.enabled=t!==void 0?t:!0}invoke(...e){if(this.enabled!==!1){if(!this.method){console.warn("No function. Please check you assigned a method to invoke on export",this);return}this.method(...e)}}},Uv=l=>/^[A-Z]*$/.test(l),hr=class extends Event{args},Oe=class{target;key;setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let i="",n=!1;for(let r of this.key)n&&Uv(r)&&(i+="-"),n=!0,i+=r.toLowerCase();this.key=i}}_isInvoking=!1;methods=[];constructor(e){this.methods=e??[]}invoke(...e){if(this._isInvoking){console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this);return}this._isInvoking=!0;try{for(let t of this.methods)t.invoke(...e);if(typeof this.target=="object"&&typeof this.key=="string"){let t=this.target.dispatchEvent;if(typeof t=="function"){let i=new hr(this.key);i.args=e,t.call(this.target,i)}}}finally{this._isInvoking=!1}}addEventListener(e){return this.methods.push(new yi(e,!0)),e}removeEventListener(e){if(!!e)for(let t=this.methods.length-1;t>=0;t--)this.methods[t].method===e&&(this.methods[t].enabled=!1,this.methods.splice(t,1))}removeAllEventListeners(){this.methods.length=0}};var ao=class extends M{};import{FlyControls as qv}from"three/examples/jsm/controls/FlyControls";var lo=class extends M{_controls=null;onEnable(){let e=O.getComponent(this.gameObject,ne)?.cam;this._controls=new qv(e,this.context.renderer.domElement),this._controls.rollSpeed=.5,this._controls.movementSpeed=3,this._controls.dragToLook=!0}onDisable(){this._controls?.dispose(),this._controls=null}update(){this._controls&&this._controls.update(this.context.time.deltaTime)}};import*as Op from"three";import{Color as Xv}from"three";var Xi=class extends M{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!hi||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new Op.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=Pa(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),3)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}};k([A()],Xi.prototype,"objectBounds",2),k([A(Xv)],Xi.prototype,"color",2),k([A()],Xi.prototype,"isGizmo",2);import{GLTFExporter as Jv}from"three/examples/jsm/exporters/GLTFExporter.js";import{BufferAttribute as ed,Matrix4 as Qv,Vector3 as Ap,Quaternion as Yv}from"three";var Es=class{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;let i=this.writer,n=i.extensionsUsed,r={};t.extensions=t.extensions||{},t.extensions[this.name]=r;let o=new Qv,s=new Array,c=new Array,d=new Array;for(let f=0;f<e.count;f++){e.getMatrixAt(f,o);let E=new Ap,b=new Yv,y=new Ap;o.decompose(E,b,y),s.push(E.x,E.y,E.z),c.push(b.x,b.y,b.z,b.w),d.push(y.x,y.y,y.z)}let a=new Float32Array(s),h=new Float32Array(c),u=new Float32Array(d);r.attributes={TRANSLATION:i.processAccessor(new ed(a,3)),ROTATION:i.processAccessor(new ed(h,4)),SCALE:i.processAccessor(new ed(u,3))},n[this.name]=!0}};import{Object3D as $v,Vector3 as Kv}from"three";var On=Ie,Fa="$___Export_Components",Zv="NEEDLE_components",td=class{[Wn]},id=class{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}},co=class{get name(){return Zv}parser;nodeToObjectMap={};exportContext;objectToNodeMap={};context;writer;registerExport(e){e.register(t=>{let i=t.serializeUserData.bind(t);return this.writer=t,t.serializeUserData=(n,r)=>{try{this.serializeUserData(n,r),i(n,r)}finally{this.afterSerializeUserData(n,r)}},this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){let i=e.userData?.components;!i||i.length<=0||(delete e.userData.components,e[Fa]=i)}afterSerializeUserData(e,t){if(e.type==="Scene"&&On&&console.log("DONE",JSON.stringify(t)),e[Fa]===void 0)return;let i=e[Fa];delete e[Fa],i!==null&&(e.userData.components=i)}writeNode(e,t){let i=this.writer.json.nodes.length;console.log(e.name,i,e.uuid);let n=new id(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){On&&console.log("AFTER",e);for(let t in this.exportContext){let i=this.exportContext[t],n=i.node,r=i.nodeDef,o=i.nodeIndex,s=n.userData?.components;if(!s||s.length<=0)continue;let c=new td;r.extensions=r.extensions||{},r.extensions[this.name]=c,this.context.object=n,this.context.nodeId=o,this.context.objectToNode=this.objectToNodeMap;let d=[];for(let a of s){this.context.target=a;let h=kp(a,this.context);h!==null&&d.push(h)}d.length>0&&(c[Wn]=d,On&&console.log("DID WRITE",n,"nodeIndex",o,d))}}beforeRoot(){return On&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){let t=e.parser,i=t?.extensions;if(!i)return;let n=i[this.name];On&&console.log("After root",e,this.parser,i);let r=[];if(n===!0){let o=t.json.nodes;for(let s=0;s<o.length;s++){let c=await t.getDependency("node",s);this.nodeToObjectMap[s]=c}for(let s=0;s<o.length;s++){let c=o[s],d=s,a=c.extensions;if(!a)continue;let h=a[this.name];if(!h)continue;On&&console.log("NODE",c);let u=this.nodeToObjectMap[d];if(!u){console.error("Could not find object for node index: "+d,c,t);continue}r.push(this.createComponents(u,h))}}await Promise.all(r)}async createComponents(e,t){if(!t)return;let i=t[Wn];if(i){On&&console.log(e.name,i);for(let n in i){let r=i[n];On&&console.log("Serialized data",JSON.parse(JSON.stringify(r))),r&&this.parser&&await Gr(this.parser,r),e.userData=e.userData||{},e.userData[Wn]=e.userData[Wn]||[],e.userData[Wn].push(r)}}}};var ho=class extends lt{sceneRoot;start(){this.startCoroutine(this.updateGltfBox())}*updateGltfBox(){for(;;)for(let e=0;e<10;e++)yield}},jt=class extends M{binary=!0;objects=[];exporter;ext;async exportNow(e){console.log("DO EXPORT",this.objects);let t={binary:this.binary,pivot:jt.calculateCenter(this.objects)},i=await this.export(this.objects,t);this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?jt.saveArrayBuffer(i,e):jt.saveJson(i,e)}async export(e,t){if(e===null||e.length<=0){console.log("no objects set to export");return}this.exporter||(this.exporter=new Jv,this.exporter.register(s=>new Es(s)),this.ext=new co,this.ext.registerExport(this.exporter)),jt.filterTopmostParent(e);let i={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:t?.binary??!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:jt.collectAnimations(e)},n=new $v;t?.pivot&&n.position.sub(t.pivot),console.log("EXPORT",e),e.forEach(s=>{s&&(n.children.push(s),s.matrixAutoUpdate=!1,s.matrix.copy(s.matrixWorld),O.getComponentsInChildren(s,Te).forEach(c=>{O.isActiveInHierarchy(c.gameObject)&&c.setInstancingEnabled(!1)}))});let r=new Vr(n);return this.ext.context=r,new Promise((s,c)=>{try{this.exporter?.parse(n,d=>{o(),s(d)},d=>{o(),c(d)},i)}catch(d){console.error(d),c(d)}finally{console.log("FINALLY")}});function o(){e.forEach(s=>{!s||(s.matrixAutoUpdate=!0,O.getComponentsInChildren(s,Te).forEach(c=>{O.isActiveInHierarchy(c.gameObject)&&c.setInstancingEnabled(!1)}))})}}static saveArrayBuffer(e,t){this.save(new Blob([e],{type:"application/octet-stream"}),t)}static saveJson(e,t){this.save("data: text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(e)),t)}static save(e,t){let i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}static collectAnimations(e,t){t=t||[];for(let i of e)!i||i.traverseVisible(n=>{n.animations&&n.animations.length>0&&t.push(...n.animations)});return t}static calculateCenter(e,t){let i=t||new Kv;return i.set(0,0,0),e.forEach(n=>{i.add(q(n))}),console.log(i),i.divideScalar(e.length),i}static filterTopmostParent(e){if(!(e.length<=0))for(let t=0;t<e.length;t++){let i=e[t];if(!i){e.splice(t,1),t--;continue}for(;i.parent;){if(e.includes(i.parent)){e.splice(t,1),t--;break}i=i.parent}}}};import{Color as Na,GridHelper as ey}from"three";var Qi=class extends M{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!hi)return;let e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new ey(e,t,this.color0??new Na(.4,.4,.4),this.color1??new Na(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset),this.gameObject.add(this.gridHelper))}};k([A()],Qi.prototype,"isGizmo",2),k([A(Na)],Qi.prototype,"color0",2),k([A(Na)],Qi.prototype,"color1",2);import{GroundProjectedEnv as ty}from"three/examples/jsm/objects/GroundProjectedEnv.js";var Yi=class extends M{set scale(e){this._scale=e,this.env?.scale.setScalar(e)}get scale(){return this._scale}_scale=20;set radius(e){this._radius=e,this.env&&(this.env.height=e)}get radius(){return this._radius}_radius=100;set height(e){this._height=e,this.env&&(this.env.height=e)}get height(){return this._height}_height=100;_lastEnvironment;env;_watcher;onEnable(){this.updateProjection(),this._watcher||(this._watcher=new Is(this.context.scene,"environment"),this._watcher.subscribeWrite(this.updateProjection.bind(this))),this._watcher.apply()}onDisable(){this._watcher?.revoke(),this.env?.removeFromParent()}updateProjection(){!this.context.scene.environment||((!this.env||this.context.scene.environment!==this._lastEnvironment)&&(console.log("Create/Update Ground Projection",this.context.scene.environment.name),this.env=new ty(this.context.scene.environment)),this._lastEnvironment=this.context.scene.environment,this.env.parent||this.gameObject.add(this.env),this.env.scale.setScalar(this._scale),this.env.radius=this._radius,this.env.height=this._height,this.env.isObject3D===!0&&this.env.layers.set(2))}};k([A()],Yi.prototype,"scale",1),k([A()],Yi.prototype,"radius",1),k([A()],Yi.prototype,"height",1);import*as it from"three";import{Color as iy}from"three";function nd(l){return l*Math.PI/180}var Ip=300,Mp=N("debuglights");var Ye=class extends M{type=0;range=1;spotAngle=1;innerSpotAngle=1;color=new it.Color(16777215);set shadowNearPlane(e){if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,this.light?.shadow?.camera!==void 0)){let t=this.light.shadow.camera;t.near=e}}get shadowNearPlane(){return this._shadowNearPlane}_shadowNearPlane=.1;set shadowBias(e){e!==this._shadowBias&&(this._shadowBias=e,this.light?.shadow?.bias!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}_shadowBias=0;set shadowNormalBias(e){e!==this._shadowNormalBias&&(this._shadowNormalBias=e,this.light?.shadow?.normalBias!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}_shadowNormalBias=1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e===1||e===2)}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=4;set intensity(e){if(this._intensity=e,this.light){let t=1;if(this.context.isInXR&&this._webARRoot){let i=this._webARRoot?.arScale;typeof i=="number"&&i>0&&(t/=i)}this.light.intensity=e*t}}get intensity(){return this._intensity}_intensity=1;get shadowDistance(){let e=this.light;return e?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;let t=this.light;if(t){let i=t.shadow.camera;i.far=e,i.updateProjectionMatrix()}}_shadowDistance;shadowWidth;shadowHeight;get shadowResolution(){let e=this.light;return e?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;let t=this.light;t&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!0)}_shadowResolution=void 0;get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}light=void 0;getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}updateIntensity(){this.intensity=this._intensity}awake(){this.color=new it.Color(this.color??16777215)}onEnable(){this.createLight(),!this.isBaked&&(this.light&&(this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),2),this._webXRStartedListener=$.addEventListener("xrStarted",this.onWebXRStarted.bind(this)),this._webXREndedListener=$.addEventListener("xrStopped",this.onWebXREnded.bind(this)))}onDisable(){$.removeEventListener("xrStarted",this._webXRStartedListener),$.removeEventListener("xrStopped",this._webXREndedListener)}_webXRStartedListener;_webXREndedListener;_webARRoot;onWebXRStarted(){this._webARRoot=this.gameObject.getComponentInParent(Dt)??void 0,this.startCoroutine(this._updateLightIntensityInARRoutine())}*_updateLightIntensityInARRoutine(){for(;this.context.isInXR;){yield,this.updateIntensity();for(let e=0;e<30;e++)yield}}onWebXREnded(){this.updateIntensity()}createLight(){if(this.light)return;let e=this.selfIsLight;if(e)switch(this.light=this.gameObject,this.type){case 1:this.setDirectionalLight(this.light);break}else switch(this.type){case 1:let t=new it.DirectionalLight(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-Ip*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),Ar(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Mp){let o=new it.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(o)}break;case 0:let i=new it.SpotLight(this.color,this.intensity*Math.PI,this.range,nd(this.spotAngle/2),1-nd(this.innerSpotAngle/2)/nd(this.spotAngle/2),2);i.position.set(0,0,0),i.rotation.set(0,0,0),this.light=i;let n=i.target;i.add(n),n.position.set(0,0,this.range),n.rotation.set(0,0,0);break;case 2:let r=new it.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=r;break}if(this.light!==void 0){this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this._shadowResolution!==void 0&&this._shadowResolution>4?(this.light.shadow.mapSize.width=this._shadowResolution,this.light.shadow.mapSize.height=this._shadowResolution):(this.light.shadow.mapSize.width=2048,this.light.shadow.mapSize.height=2048),this.light.shadow.bias=this.shadowBias*1e-5,this.light.shadow.normalBias=this.shadowNormalBias*1e-4;let t=this.light.shadow.camera;if(t.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?t.far=this._shadowDistance:t.far=Ip*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)t.left=-this.shadowWidth/2,t.right=this.shadowWidth/2;else{let i=this.gameObject.scale.x;t.left*=i,t.right*=i}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{let i=this.gameObject.scale.y;t.top*=i,t.bottom*=i}this.light.shadow.needsUpdate=!0,Mp&&this.context.scene.add(new it.CameraHelper(t)),this.isBaked?this.light.removeFromParent():e||this.gameObject.add(this.light)}}*updateMainLightRoutine(){for(;;){this.type===1&&((!this.context.mainLight||this.intensity>this.context.mainLight.intensity)&&(this.context.mainLight=this),yield);break}}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}};k([A()],Ye.prototype,"type",2),k([A(iy)],Ye.prototype,"color",2),k([A()],Ye.prototype,"shadowNearPlane",1),k([A()],Ye.prototype,"shadowBias",1),k([A()],Ye.prototype,"shadowNormalBias",1),k([A()],Ye.prototype,"shadows",1),k([A()],Ye.prototype,"lightmapBakeType",2),k([A()],Ye.prototype,"intensity",1),k([A()],Ye.prototype,"shadowDistance",1),k([A()],Ye.prototype,"shadowResolution",1);var VO=new it.Vector3(0,0,0);import*as za from"three";import{Vector3 as ny}from"three";var uo=N("debugLODs"),ry=N("noLODs");var Ei=class{screenRelativeTransitionHeight;distance;renderers};k([A()],Ei.prototype,"screenRelativeTransitionHeight",2),k([A()],Ei.prototype,"distance",2),k([A()],Ei.prototype,"renderers",2);var rd=class{model;renderers;constructor(e,t){this.model=t,this.renderers=[];for(let i of t.renderers){let n=this.findRenderer(i,e.gameObject);n&&n.gameObject?this.renderers.push(n):uo&&console.warn("Renderer not found: "+i,e.gameObject)}}findRenderer(e,t){let i=O.foreachComponent(t,n=>n.guid===e||Object.getPrototypeOf(n)?.guid===e?n:null);if(i)return i;for(let n of t.children){let r=this.findRenderer(e,n);if(r)return r}return null}},An=class extends M{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(!ry&&!this._lodsHandler&&!!this.gameObject&&(uo&&console.log(this),this.lodModels&&Array.isArray(this.lodModels))){let e=0,t=[];for(let n of this.lodModels){e=Math.max(n.distance,e);let r=new rd(this,n);this._lods.push(r);for(let o of r.renderers)t.includes(o)||t.push(o)}this._lodsHandler=new Array;for(let n=0;n<t.length;n++){let r=new za.LOD;this._lodsHandler.push(r),this.gameObject.add(r)}let i=new za.Object3D;uo&&console.log(t);for(let n=0;n<t.length;n++){let r=t[n],o=this._lodsHandler[n],s=r.gameObject,c=0,d=0;uo&&console.log(n,s.name);for(let h of this._lods){let u=null;h.renderers.includes(r)?u=s:u=i,uo&&console.log("add",h.model.distance,u.name);let f=h.model.distance;d=f-c,c=Math.max(f,c),this.onAddLodLevel(o,u,f)}let a=c+d;uo&&console.log("cull",a),this.onAddLodLevel(o,i,a)}}}update(){if(!this.gameObject||!this._lodsHandler)return;let e=this.context.mainCamera;if(!!e)for(let t of this._lodsHandler)t.update(e)}onAddLodLevel(e,t,i){e.addLevel(t,i*this._distanceFactor);let n={lod:e,levelIndex:e.levels.length-1,distance:i};this._settings.push(n)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(let t of this._settings){let i=t.lod.levels[t.levelIndex];i.distance=t.distance*e}}}};k([A(ny)],An.prototype,"localReferencePoint",2),k([A(Ei)],An.prototype,"lodModels",2);var po=class extends M{onEnable(){this.enabled&&this.context.physics.addMeshCollider(this.gameObject)}};var fo=class extends M{},mo=class extends M{};var od=N("debugnestedgltf"),ur=class extends M{filePath;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){this.filePath?.preload()}async start(){if(this._isLoadingOrDoneLoading)return;od&&console.log(this,this.guid);let e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;let t=new ye;t.idProvider=new We(this.hash(this.guid)),t.parent=e,this.gameObject.updateMatrix();let i=this.gameObject.matrix;od&&console.log("Load nested:",this.filePath?.uri??this.filePath,this.gameObject.position);let n=await this.filePath?.instantiate?.call(this.filePath,t);n&&(n.matrixAutoUpdate=!1,n.matrix.identity(),n.applyMatrix4(i),n.matrixAutoUpdate=!0),this.destroy(),od&&console.log("Nested loading done:",this.filePath?.uri??this.filePath,n)}}hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}};k([A(tt)],ur.prototype,"filePath",2);import*as bo from"three";var go=class extends M{from;affectPosition;affectRotation;alignLookDirection;levelLookDirection;positionOffset;rotationOffset;update(){if(!this.from)return;var e=q(this.from),t=ve(this.from);this.affectPosition&&ie(this.gameObject,e.add(this.positionOffset));let i=new bo.Euler(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),n=new bo.Quaternion().setFromEuler(i);this.affectRotation&&Ae(this.gameObject,t.multiply(n));let r=new bo.Vector3;this.from.getWorldDirection(r).multiplyScalar(50),this.levelLookDirection&&(r.y=0),this.alignLookDirection&&this.gameObject.lookAt(r)}};import*as xe from"three";import*as ei from"three";var vo=class{randomizeRotationDirection=0;duration=5;loop=!0;prewarm=!1;startDelay=void 0;startDelayMultiplier=0;startLifetime=void 0;startLifetimeMultiplier=5;startSpeed=void 0;startSpeedMultiplier=5;startSize3D=!1;startSize=void 0;startSizeMultiplier=1;startSizeX=void 0;startSizeXMultiplier=1;startSizeY=void 0;startSizeYMultiplier=1;startSizeZ=void 0;startSizeZMultiplier=1;startRotation3D=!1;startRotation=void 0;startRotationMultiplier=0;startRotationX=void 0;startRotationXMultiplier=0;startRotationY=void 0;startRotationYMultiplier=0;startRotationZ=void 0;startRotationZMultiplier=0;flipRotation=0;startColor=new ei.Color(1,1,1);startColor1=new ei.Color(0,0,0);gravityModifier=void 0;gravityModifierMultiplier=0;simulationSpace=0;customSimulationSpace=null;simulationSpeed=1;useUnscaledTime=!1;scalingMode=1;playOnAwake=!0;maxParticles=1e3;emitterVelocityMode=1;stopAction=0;ringBufferMode=0;ringBufferLoopRange=new ei.Vector2(0,1);cullingMode=0},yo=class{burstCount=0;enabled=!0;rate=10;rateMutliplier=1;rateOverDistance=0;rateOverDistanceMultiplier=0;rateOverTime=0;rateOverTimeMultiplier=0},Eo=class{shapeType=sd.Box;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcmode=0;box=new ei.Vector3(1,1,1);boxThickness=new ei.Vector3(0,0,0);position=new ei.Vector3(0,0,0);rotation=new ei.Vector3(0,0,0);scale=new ei.Vector3(1,1,1);radius=1;sphericalDirectionAmount=0},sd=(p=>(p[p.Sphere=0]="Sphere",p[p.SphereShell=1]="SphereShell",p[p.Hemisphere=2]="Hemisphere",p[p.HemisphereShell=3]="HemisphereShell",p[p.Cone=4]="Cone",p[p.Box=5]="Box",p[p.Mesh=6]="Mesh",p[p.ConeVolume=7]="ConeVolume",p[p.Circle=10]="Circle",p[p.SingleSidedEdge=11]="SingleSidedEdge",p[p.MeshRenderer=12]="MeshRenderer",p[p.SkinnedMeshRenderer=13]="SkinnedMeshRenderer",p[p.BoxShell=14]="BoxShell",p[p.BoxEdge=15]="BoxEdge",p[p.Donut=16]="Donut",p[p.Rectangle=17]="Rectangle",p[p.Sprite=18]="Sprite",p[p.SpriteRenderer=19]="SpriteRenderer",p))(sd||{});var Lp=N("debugparticles"),ad=class{age=0;lifetime=0;position;velocity;color},pr=class extends M{get mainTexture(){if(this.sharedMaterial){let e=this.context.assets.findTexture(this.sharedMaterial);if(e)return e}return null}getMesh(e){return this.mesh?this.context.assets.findMesh(this.mesh):null}sharedMaterial;mesh;awake(){Lp&&console.log(this)}},wo=class extends M{main;emission;shape;renderer;geometry;material;particlesMesh;positions;positionsArray;particleStates=[];activeCount=0;shapeRotation=new xe.Quaternion;tempVec3=new xe.Vector3;tempQuat=new xe.Quaternion;awake(){this.renderer=O.getComponent(this.gameObject,pr),Lp&&console.log(this)}onEnable(){if(this.geometry)return;this.particleStates=[],this.shapeRotation.setFromEuler(new xe.Euler(this.shape.rotation.x,this.shape.rotation.y,this.shape.rotation.z)),this.geometry=new xe.BufferGeometry,this.positionsArray=new Float32Array(this.main.maxParticles*3),this.positions=new xe.Float32BufferAttribute(this.positionsArray,3),this.geometry.setAttribute("position",this.positions);let e=new Float32Array(this.main.maxParticles*3);for(let i=0;i<e.length;i++)e[i*3]=1,e[i*3+1]=1,e[i*3+2]=1;let t=new xe.Float32BufferAttribute(e,3);this.geometry.setAttribute("color",t),this.material=new xe.PointsMaterial({size:this.main.startSize,color:16777215,vertexColors:!0}),this.material.map=this.renderer.mainTexture,this.particlesMesh=new xe.Points(this.geometry,this.material),this.particlesMesh.layers.enable(2),this.gameObject.add(this.particlesMesh),this.activeCount=this.main.prewarm?this.main.maxParticles:0}update(){if(!this.geometry)return;let e=this.context.time.deltaTime;this.emit(e);for(let t=0;t<this.activeCount;t+=1){let i=this.particleStates[t];if(!i)continue;let n=i.velocity.x*e,r=i.velocity.y*e,o=i.velocity.z*e;i.position.x+=n,i.position.y+=r,i.position.z+=o,this.updateOverLifetime(t,i),this.geometry.attributes.position.setXYZ(t,i.position.x,i.position.y,i.position.z),this.geometry.attributes.color.setXYZ(t,i.color.r,i.color.g,i.color.b)}this.geometry&&(this.geometry.attributes.position.needsUpdate=!0,this.geometry.setDrawRange(0,this.activeCount))}emit(e){let t=this.activeCount;for(let i=0;i<t;i+=1){if(i>=this.particleStates.length){let r=new ad;r.lifetime=this.main.startLifetime??1,r.position=new xe.Vector3,r.velocity=new xe.Vector3,r.color=new xe.Color(1,0,0),this.particleStates.push(r),this.initializeParticle(i,r),r.age=r.lifetime*Math.random()}let n=this.particleStates[i];if(n.age>n.lifetime){this.activeCount-=1,this.activeCount=Math.max(0,this.activeCount),this.initializeParticle(i,n);continue}n.age+=e,this.particleStates[i]=n}this.activeCount+=e*this.emission.rate,this.activeCount=Math.min(this.main.maxParticles,this.activeCount)}initializeParticle(e,t){if(!this.geometry)return;t.age=0,t.color.set(this.main.startColor),this.main.startColor1&&t.color.lerp(this.main.startColor1,Math.random()),this.geometry.attributes.color.needsUpdate=!0,this.assignPosition(t.position),this.assignVelocity(t.position,t.velocity);let i=t.position;i.multiply(this.shape.scale),i.applyQuaternion(this.shapeRotation),i.add(this.shape.position),this.particleStates.splice(e,1),this.particleStates.push(t)}updateOverLifetime(e,t){}assignPosition(e){switch(this.shape.shapeType){case 0:e.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).multiplyScalar(this.shape.radius);break;case 5:e.set(Math.random()-.5,Math.random()-.5,Math.random()-.5);break;default:e.set(0,0,0);break}}assignVelocity(e,t){switch(this.shape.shapeType){case 0:t.set(e.x,e.y,e.z);break;case 5:t.set(0,0,1),this.shape.sphericalDirectionAmount>0&&(this.tempVec3.set(e.x,e.y,e.z).multiply(this.shape.scale).normalize(),t.lerp(this.tempVec3,this.shape.sphericalDirectionAmount));break;case 4:let i=new xe.Vector3(0,1,0);t.copy(i);break;case 10:this.tempQuat.setFromAxisAngle(this.tempVec3.set(0,0,1),Math.random()*Q.toRadians(this.shape.arc)),t.copy(this.tempVec3.set(1,0,0).applyQuaternion(this.tempQuat));break;default:t.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1);break}switch(t.normalize(),this.shape.shapeType){case 10:e.add(t).multiplyScalar(this.shape.radius);break}t.multiplyScalar(this.main.startSpeedMultiplier)}};import*as Hp from"three";function*Dp(l,e=null){let t=e?e.time:Z.Current.time,i=t.time;for(;t.time-i<l;)yield}var ht=class extends M{awake(){this.context.connection.beginListen("joined-room",this.tryAssignColor.bind(this))}_didAssignPlayerColor=!1;onEnable(){this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}*waitForConnection(){for(;!this.destroyed&&this.enabled&&(yield Dp(.2),!this.tryAssignColor()););}tryAssignColor(){let e=O.getComponentInParent(this.gameObject,fe);return e&&e.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(e.connectionId),!0):!1}assignUserColor(e){let t=ht.hashCode(e),i=ht.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){let n=this.gameObject;this.assignColor(i,e,n)}else if(this.gameObject.children)for(let n of this.gameObject.children){let r=n;r.material&&r.material.color&&this.assignColor(i,e,r)}}assignColor(e,t,i){let n=i.material;!n||(n._playerMaterial!==t?(n=n.clone(),n._playerMaterial=t,i.material=n):console.log("DONT CLONE",n),n.color=e)}static hashCode(e){var t=0,i,n;if(e.length===0)return t;for(i=0;i<e.length;i++)n=e.charCodeAt(i),t=(t<<5)-t+n,t|=0;return t}static colorFromHashCode(e){let t=(e&16711680)>>16,i=(e&65280)>>8,n=e&255;return new Hp.Color(t/255,i/255,n/255)}};import*as Ga from"three";import{Object3D as ay}from"three";function sy(){return new Promise((l,e)=>{let i=()=>{i!=null&&(document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i),l())};document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)})}async function jp(l){await sy(),l()}var ld=N("debugvideo");var nt=class extends M{renderer=null;playOnAwake=!0;playOnEnable;targetMaterialProperty;time=0;_playbackSpeed=1;get playbackSpeed(){return this.videoElement?.playbackRate??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this.videoElement&&(this.videoElement.playbackRate=e)}_isLooping=!1;get isLooping(){return this.videoElement?.loop??this._isLooping}set isLooping(e){this._isLooping=e,this.videoElement&&(this.videoElement.loop=e)}get currentTime(){return this.videoElement?.currentTime??this.time}set currentTime(e){this.videoElement?this.videoElement.currentTime=e:this.time=e}get isPlaying(){let e=this.videoElement;return e?e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA:!1}get crossOrigin(){return this.videoElement?.crossOrigin??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this.videoElement&&(e!==null?this.videoElement.setAttribute("crossorigin",e):this.videoElement.removeAttribute("crossorigin"))}_crossOrigin="anonymous";audioOutputMode=1;source;clip=null;url=null;videoElement=null;videoTexture=null;videoMaterial=null;_isPlaying=!1;wasPlaying=!1;setClipURL(e){this.url!==e&&(this.url=e,this.source=1,ld&&console.log("set url",e),this.videoElement&&(this.videoElement.src=e,this._isPlaying&&this.videoElement.play()))}awake(){this.create(this.playOnAwake),window.addEventListener("visibilitychange",e=>{switch(document.visibilityState){case"hidden":this.wasPlaying=this._isPlaying,this.pause();break;case"visible":this.wasPlaying&&this.play();break}})}onEnable(){this.playOnEnable===!0&&this.handleBeginPlaying(!0)}onDisable(){this.pause()}onDestroy(){this.videoElement&&(this.videoElement.parentElement?.removeChild(this.videoElement),this.videoElement=null),this.videoTexture&&(this.videoTexture.dispose(),this.videoTexture=null)}_receivedInput=!1;constructor(){super(),jp(()=>{this._receivedInput=!0,this.updateVideoElementSettings()})}play(){!this.videoElement||this._isPlaying&&!this.videoElement?.ended&&!this.videoElement?.paused||(this._isPlaying=!0,this._receivedInput||(this.videoElement.muted=!0),this.updateVideoElementSettings(),this.videoElement?.play().catch(e=>{console.warn(e)}),ld&&console.log("play",this.videoElement))}stop(){this._isPlaying=!1,this.videoElement&&(this.videoElement.currentTime=0,this.videoElement.pause())}pause(){this._isPlaying=!1,this.videoElement?.pause()}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url;break}!t||(this.videoElement||(this.videoElement=this.createVideoElement(),this.context.domElement?.prepend(this.videoElement),this.updateVideoElementStyles()),typeof t=="string"?this.videoElement.src=t:this.videoElement.srcObject=t,this.videoTexture||(this.videoTexture=new Ga.VideoTexture(this.videoElement)),this.videoTexture.flipY=!1,this.videoTexture.encoding=Ga.sRGBEncoding,this.handleBeginPlaying(e))}createVideoElement(){let e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),ld&&console.log("create video elment",e),e}handleBeginPlaying(e){if(!this.enabled||!this.videoElement)return;let t=this.gameObject.material;if(t)if(t!==this.videoMaterial&&(this.videoMaterial=t.clone(),this.gameObject.material=this.videoMaterial),!this.targetMaterialProperty)this.videoMaterial.map=this.videoTexture;else switch(this.targetMaterialProperty){default:this.videoMaterial.map=this.videoTexture;break}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&this.play()}updateVideoElementSettings(){!this.videoElement||(this.videoElement.loop=this._isLooping,this.videoElement.currentTime=this.currentTime,this.videoElement.playbackRate=this._playbackSpeed,this.videoElement.playsInline=!0,this.videoElement.muted=!this._receivedInput&&this.audioOutputMode!==0,(this.playOnAwake||this.playOnEnable)&&(this.videoElement.autoplay=!0))}updateVideoElementStyles(){!this.videoElement||(this.videoElement.style.userSelect="none",this.videoElement.style.visibility="hidden",this.videoElement.style.display="none")}};k([A(ay)],nt.prototype,"renderer",2),k([A()],nt.prototype,"playOnAwake",2),k([A()],nt.prototype,"playOnEnable",2),k([A()],nt.prototype,"targetMaterialProperty",2),k([A()],nt.prototype,"time",2),k([A()],nt.prototype,"playbackSpeed",1),k([A()],nt.prototype,"isLooping",1);var _o=class extends M{streamOnAwake=!0;start(){this.streamOnAwake&&this.open()}requestOpen=!1;captureStream=null;async open(e=!1){if(!(this.captureStream&&!e)){this.close(),this.requestOpen=!0;try{let t=O.getComponentInChildren(this.gameObject,nt);if(t){let i={video:!0,audio:!1};this.captureStream=await navigator.mediaDevices.getDisplayMedia(i),this.captureStream&&this.requestOpen&&(t.clip=this.captureStream,t.create(!0))}}catch(t){console.error("Error: "+t)}}}close(){if(this.requestOpen=!1,this.captureStream){for(let e of this.captureStream.getTracks())e.stop();this.captureStream=null}}};import{ShadowMaterial as ly,AdditiveBlending as cy}from"three";var kn=class extends M{mode=0;shadowColor=new we(0,0,0,1);awake(){switch(this.mode){case 0:this.applyShadowMaterial();break;case 1:this.applyLightBlendMaterial();break}}applyLightBlendMaterial(){let e=O.getComponent(this.gameObject,Te);if(e){let t=e.material;t.blending=cy,this.applyMaterialOptions(t),t.onBeforeCompile=i=>{i.fragmentShader=i.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
124
124
 
125
125
  // diffuse-only lighting with overdrive to somewhat compensate
126
126
  // for the loss of indirect lighting and to make it more visible.
@@ -131,9 +131,9 @@ a=extmap-allow-mixed`)!==-1){var f=p.sdp.split(`
131
131
  // be blended onto the scene.
132
132
  gl_FragColor = vec4(direct, max);
133
133
  return;
134
- `)}}}applyShadowMaterial(){let e=O.getComponent(this.gameObject,Te);if(e)if(e.material?.type!=="ShadowMaterial"){let t=new sy;t.color=this.shadowColor,t.opacity=this.shadowColor.alpha,this.applyMaterialOptions(t),e.material=t}else{let t=e.material;t.color=this.shadowColor,t.opacity=this.shadowColor.alpha,this.applyMaterialOptions(t)}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}};k([A()],On.prototype,"mode",2),k([A(we)],On.prototype,"shadowColor",2);import{RGBELoader as cy}from"three/examples/jsm/loaders/RGBELoader.js";import{EXRLoader as dy}from"three/examples/jsm/loaders/EXRLoader";import{EquirectangularRefractionMapping as hy}from"three";var kp=N("debugautosync"),rd=class{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];let t=new sd(e);return this._syncers[e.guid]=t,t}},Ip=new rd,sd=class{comp;constructor(e){this.comp=e}hasChanges=!1;changedProperties={};data={};_boundEvent;get networkingKey(){return this.comp.constructor.name}_isReceiving=!1;_isInit=!1;init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,this._boundEvent=this.onHandleSending.bind(this),this.comp.context.post_render_callbacks.push(this._boundEvent),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving.bind(this));let t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}notifyChanged(e,t){this._isReceiving||(this.hasChanges=!0,this.changedProperties[e]=t)}onHandleSending(){if(!this.hasChanges)return;this.hasChanges=!1;let e=this.comp.context.connection;if(!e||!e.isConnected){for(let t in this.changedProperties)delete this.changedProperties[t];return}for(let t in this.data)delete this.data[t];this.data.guid=this.comp.guid;for(let t in this.changedProperties){let i=this.changedProperties[t];delete this.changedProperties[t],this.data[t]=i}e.send(this.networkingKey,this.data)}onHandleReceiving(e){if(!this._isInit||!this.comp)return;let t=e.guid;if(!(t&&t!==this.comp.guid)){kp&&console.log("RECEIVED",this.comp.name,this.comp.guid,e);try{this._isReceiving=!0;for(let i in e){if(i==="guid")continue;let n=e[i];this.comp[i]=n}}catch(i){console.error(i)}finally{this._isReceiving=!1}}}};function ay(l,e){let t=e!==l;if(!t&&l&&e){if(Array.isArray(l)&&Array.isArray(e))t=!0;else if(typeof l=="object"&&typeof e=="object"){for(let i of Object.keys(l))if(l[i]!==e[i]){t=!0;break}}}return t}function ly(l){if(l.__autoPropertySyncHandler)return l.__autoPropertySyncHandler;let e=Ip.getOrCreateSyncer(l);return e?.init(l),l.__autoPropertySyncHandler=e,e}var Ga=function(l){return function(e,t){let i=null,n=l?e[l]:void 0,r=e,s=r.__internalAwake;kp&&console.log(t);let o=t+"k__BackingField";r.__internalAwake=function(){if(this[o]!==void 0)return;this[o]=this[t],s.call(this),i=Ip.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,t)?.set===void 0&&Object.defineProperty(this,t,{set:function(d){let a=this[o];this[o]=d,ay(d,a)&&n?.call(this,d,a)!==!1&&ly(this)?.notifyChanged(t,d)},get:function(){return this[o]},configurable:!0,enumerable:!0}),i?.init(this)}}};var An=class extends M{url;allowDrop=!0;_loader;_prevLoadedEnvironment;_prevEnvironment=null;_prevBackground=null;onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.isInXR||(this.context.scene.environment=this._prevEnvironment,this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents()}async setSkybox(e){if(!e)return;if(!e?.endsWith(".hdr")&&!e.endsWith(".exr")&&console.warn("Potentially invalid skybox url",this.url,"on",this.name),!this._loader){let n=e.endsWith(".exr");this._loader=n?new dy:new cy}let t=await this._loader.loadAsync(e);if(!t||!this.enabled)return;this.url=e,t.mapping=hy,this._prevBackground=this.context.scene.background,this._prevEnvironment=this.context.scene.environment,console.log("Set skybox",this.url),this.context.scene.environment=t,this.context.scene.background=t,this._prevLoadedEnvironment=t;let i=e.lastIndexOf("/");t.name=e.substring(i>=0?i+1:0)}dragOverEvent;dropEvent;registerDropEvents(){this.dragOverEvent||(this.dragOverEvent=e=>{if(!!this.allowDrop&&!!e.dataTransfer)for(let t of e.dataTransfer.types)t==="text/uri-list"&&e.preventDefault()},this.dropEvent=e=>{if(!!this.allowDrop&&(e.preventDefault(),!!e.dataTransfer)){for(let t of e.dataTransfer.types)if(t==="text/uri-list"){let i=e.dataTransfer.getData(t);console.log(t,i);let n=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(i)?.groups?.name;if(n||(n=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(i)?.groups?.name),console.log(n),n){let r="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+n+"_1k.exr";this.setSkybox(r)}else console.warn("Could not resolve skybox name from dropped url",i)}}},this.context.domElement.addEventListener("dragover",this.dragOverEvent),this.context.domElement.addEventListener("drop",this.dropEvent))}unregisterDropEvents(){!this.dragOverEvent||(this.context.domElement.removeEventListener("dragover",this.dragOverEvent),this.context.domElement.removeEventListener("drop",this.dropEvent))}};k([Ga("setSkybox"),A()],An.prototype,"url",2),k([A()],An.prototype,"allowDrop",2);import*as vs from"three";import{Object3D as uy}from"three";var od=class extends M{target=null;followFactor=.1;rotateFactor=.1;flipForward=!1;_firstUpdate=!0;onEnable(){let e=O.getComponentInChildren(this.gameObject,ne);e&&e.cam&&(e.gameObject.position.set(0,0,0),e.cam.position.set(0,0,0),e.gameObject.quaternion.identity(),e.cam.quaternion.setFromEuler(new vs.Euler(0,Math.PI,0)))}onBeforeRender(){this.followFactor<=0||this.updateNow(!1)}updateNow(e){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){let t=q(this.target),i=this._firstUpdate||e?1:Q.clamp01(this.context.time.deltaTime*this.followFactor);this.worldPosition=this.worldPosition.lerp(t,i)}if(this.rotateFactor>0){let t=ve(this.target);this.flipForward&&t.multiply(od._invertForward);let i=this._firstUpdate||e?1:Q.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(t,i)}this._firstUpdate=!1}}},Ei=od;z(Ei,"_invertForward",new vs.Quaternion().setFromAxisAngle(new vs.Vector3(0,1,0),Math.PI)),k([A(uy)],Ei.prototype,"target",2);import{Layers as Dp}from"three";var Va=N("debugspatialtrigger"),Mp=new Dp,Lp=new Dp;function py(l,e){return Mp.mask=l,Lp.mask=e,Mp.test(Lp)}var wt=class extends M{triggerMask=0;onEnter;onStay;onExit;start(){Va&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(let e of Yi.triggers)py(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){let t=this.lastIntersected[e];this.currentIntersected.indexOf(t)<0&&(this.onExitTrigger(t),this.lastIntersected.splice(e,1))}for(let e of this.currentIntersected)this.lastIntersected.indexOf(e)<0&&this.onEnterTrigger(e),this.onStayTrigger(e);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}currentIntersected=[];lastIntersected=[];onEnterTrigger(e){Va&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),this.onEnter?.invoke(this,e)}onExitTrigger(e){Va&&console.log("EXIT TRIGGER",this.name,e.name,this,e),e.raiseOnExitEvent(this),this.onExit?.invoke(this,e)}onStayTrigger(e){e.raiseOnStayEvent(this),this.onStay?.invoke(this,e)}};k([A()],wt.prototype,"triggerMask",2),k([A(Oe)],wt.prototype,"onEnter",2),k([A(Oe)],wt.prototype,"onStay",2),k([A(Oe)],wt.prototype,"onExit",2);var vo=class extends M{triggerMask;boxHelper;start(){Va&&console.log(this.name,this.triggerMask,this)}onEnable(){vo.triggers.push(this),this.boxHelper||(this.boxHelper=O.addNewComponent(this.gameObject,lt),this.boxHelper?.showHelper())}onDisable(){vo.triggers.splice(vo.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){O.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof wt&&t.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){O.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof wt&&t.onStayTrigger(this)},!1)}raiseOnExitEvent(e){O.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof wt&&t.onExitTrigger(this)},!1)}},Yi=vo;z(Yi,"triggers",[]),k([A()],Yi.prototype,"triggerMask",2);import*as Bt from"three";var ys=class extends M{cam=null;_firstPersonMode=!1;get firstPersonMode(){return!0}set firstPersonMode(e){}enableFirstPersonMode(){this._firstPersonMode=!0,this.updateUI(),this.cam&&(this.firstPersonFollow&&(this.firstPersonFollow.enabled=!0,this.firstPersonFollow.updateNow(!0)),this.orbit&&(this.orbit.enabled=!1))}enableThirdPersonMode(){this._firstPersonMode=!1,this.updateUI(),this.firstPersonFollow&&(this.firstPersonFollow.enabled=!1),this.cam&&(ie(this.cam.cam,this._orbitStartPos),Ae(this.cam.cam,this._orbitStartRot),ie(this.cam.gameObject,this._orbitStartPos2),Ae(this.cam.gameObject,this._orbitStartRot2),this.orbit&&(this.orbit.enabled=!0,this.orbit.setFromTargetPosition()))}orbit=null;firstPersonFollow=null;spectatorUIDomElement=null;_avatar=null;eventSub_WebXRRequestStartEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;awake(){O.setActive(this.gameObject,!1);let e="#spectator-camera-ui";if(this.spectatorUIDomElement=this.context.domElement.querySelector(e),this.spectatorUIDomElement||console.warn("Could not find spectator camera UI element",e),this.spectatorUIDomElement?.classList.add("hidden"),!this.isSupportedPlatform()){console.log("Disable spectator cam",window.navigator.userAgent,this);return}if(this.cam=O.getComponent(this.gameObject,ne),!this.cam){console.error("Spectator camera needs camera component",this);return}this.cam&&(this.cam.enabled=!0,this._orbitStartPos.copy(q(this.cam.cam)),this._orbitStartRot.copy(ve(this.cam.cam)),this._orbitStartPos2.copy(q(this.cam.gameObject)),this._orbitStartRot2.copy(ve(this.cam.gameObject))),this.eventSub_WebXRRequestStartEvent=this.onXRSessionRequestStart.bind(this),this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),$.addEventListener("requestVRSession",this.eventSub_WebXRRequestStartEvent),$.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),$.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.context.domElement.querySelector("button#toggle-spectator-view")?.addEventListener("click",this.toggleView.bind(this)),this.updateUI()}onDestroy(){$.removeEventListener("requestVRSession",this.eventSub_WebXRStartEvent),$.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),$.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}toggleView(){this.firstPersonMode=!this.firstPersonMode}updateUI(){let e=this.context.domElement.querySelector("button#toggle-spectator-view");if(!!e&&(e.disabled=!0,e.firstChild&&(this._sessionHasStarted?e.firstChild.textContent=this.firstPersonMode?"\u{1F441}\uFE0F":"\u{1F4F7}":e.firstChild.textContent="Waiting for VR session"),e.children?.length>1)){let t=e.children[1];t.style.display=this._sessionHasStarted?"block":"none",this.firstPersonMode?t.textContent="First-Person View. See what the person in VR sees":t.textContent="Third-Person View. Freely move the camera around"}}isSupportedPlatform(){let e=window.navigator.userAgent,t=/Windows|MacOS/.test(e),i=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return t&&!i}onXRSessionRequestStart(e){this._sessionHasStarted=!1,this.spectatorUIDomElement?.classList.remove("hidden"),O.setActive(this.gameObject,!0),this.cam&&this.cam.cam&&(ie(this.cam.cam,this._orbitStartPos),Ae(this.cam.cam,this._orbitStartRot),ie(this.cam.gameObject,this._orbitStartPos2),Ae(this.cam.gameObject,this._orbitStartRot2)),this.firstPersonMode?this.enableFirstPersonMode():this.enableThirdPersonMode()}onXRSessionStart(e){this._sessionHasStarted=!0,this.updateUI()}onXRSessionEnded(e){this._sessionHasStarted=!1,this.spectatorUIDomElement?.classList.add("hidden"),O.setActive(this.gameObject,!1)}_sessionHasStarted=!1;_isFirstStart=!0;_firstPersonIsSetup=!1;_orbitStartPos=new Bt.Vector3;_orbitStartRot=new Bt.Quaternion;_orbitStartPos2=new Bt.Vector3;_orbitStartRot2=new Bt.Quaternion;onAfterRender(){if(!this.cam)return;if(this.firstPersonMode&&!this._firstPersonIsSetup&&(!this._avatar||this._avatar?.destroyed)){for(let o of fe.instances)if(o.avatar&&"isLocalAvatar"in o.avatar&&o.avatar?.isLocalAvatar){this._avatar=o;let c=o.avatar.head;if(!c)continue;this.setupFollowMode(c)}}let e=this.context.renderer,t=e.xr.enabled;if(!e.xr.isPresenting)return;let i=e.getRenderTarget(),n=null;if(!i){if(!e.state.bindFramebuffer||!e.state.bindXRFramebuffer)return;n=e._framebuffer,e.state.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender(),e.setClearColor(new Bt.Color(1,1,1)),e.setRenderTarget(null),e.xr.enabled=!1;let r=this.cam?.cam;this.context.updateAspect(r);let s=e.xr.isPresenting;e.xr.isPresenting=!1,e.setSize(this.context.domWidth,this.context.domHeight),e.render(this.context.scene,r),e.xr.isPresenting=s,e.xr.enabled=t,i?e.setRenderTarget(i):e.state.bindXRFramebuffer(n),this.resetAvatarFlags()}setupFollowMode(e,t=!0){if(!e||!this.cam||this._firstPersonIsSetup)return;this._firstPersonIsSetup=!0;let i=e.add(new Bt.Object3D);i.add(new Bt.AxesHelper),this.firstPersonFollow=O.addNewComponent(this.cam.gameObject,Ei),this.firstPersonFollow.target=i,this.firstPersonFollow.followFactor=12,this.firstPersonFollow.rotateFactor=5,t&&(this.firstPersonFollow.flipForward=!0);let n=this.context.mainCamera;n&&(this.cam.cam.near=n.near,this.cam.cam.far=n.far,this.cam.cam.updateProjectionMatrix()),this.orbit&&(this.orbit.enabled=!1)}setAvatarFlagsBeforeRender(){for(let e of fe.instances)if(e.avatar&&"isLocalAvatar"in e.avatar){let t=this.firstPersonMode&&this._firstPersonIsSetup&&e.avatar.isLocalAvatar?8:16,i=e.avatar.flags;if(!i)continue;for(let n of i)n.UpdateVisible(t)}}resetAvatarFlags(){for(let e of fe.instances)if(e.avatar&&"flags"in e.avatar){let t=e.avatar.flags;if(!t)continue;for(let i of t)e.avatar?.isLocalAvatar?i.UpdateVisible(8):i.UpdateVisible(16)}}};var Es=class extends M{anchor=null;connectedBody=null;connectedAnchor=null;spring=10;damper=.2;rb=null;awake(){if(this.rb=O.getComponent(this.gameObject,ce),!this.connectedBody||!this.connectedBody.body||!this.rb||!this.rb.body)return;this.connectedBody.body.mass=Math.min(this.rb.body.mass*.99,this.connectedBody.body.mass);let e=new ia(this.rb.body,this.connectedBody.body,{restLength:.01,stiffness:this.spring*.5,damping:this.damper});this.context.physics.addPostStepListener(t=>{e.applyForce()})}update(){}};import*as _t from"three";import{Material as fy,Texture as my}from"three";var ur=class{texture;triangles;uv;vertices;_geometry};k([A(my)],ur.prototype,"texture",2);var Wa=class{static getOrCreateGeometry(e){if(e._geometry)return e._geometry;let t=new _t.BufferGeometry;e._geometry=t;let i=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let r=0;r<e.triangles.length;r+=1){let s=e.triangles[r];i[r*3]=-e.vertices[s].x,i[r*3+1]=e.vertices[s].y,i[r*3+2]=0;let o=e.uv[s];n[r*2]=o.x,n[r*2+1]=1-o.y}return t.setAttribute("position",new _t.BufferAttribute(i,3)),t.setAttribute("uv",new _t.BufferAttribute(n,2)),t}},Zi=class extends M{drawMode=0;size={x:1,y:1};color;sharedMaterial;get sprite(){return this._sprite}set sprite(e){e!==this._sprite&&(this._sprite=e,this.updateSprite())}_sprite;_currentSprite;awake(){this._currentSprite=void 0}start(){this.drawMode===2&&console.warn("Tiled draw mode is not supported yet",this),this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(){if(!!this.__didAwake&&!!this.sprite&&!!this.sharedMaterial){if(this._currentSprite)this._currentSprite.geometry=Wa.getOrCreateGeometry(this.sprite),this._currentSprite.material.map=this.sprite.texture;else{let e=new _t.MeshBasicMaterial({color:16777215,side:_t.DoubleSide});if(!e)return;if(this.color&&(e.color||(e.color=new _t.Color),e.color.copy(this.color),e.opacity=this.color.alpha),e.alphaTest=.5,this.sprite.texture&&!e.wireframe){let t=this.sprite.texture;e.map=t}this._currentSprite=new _t.Mesh(Wa.getOrCreateGeometry(this.sprite),e)}this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite))}}};k([A()],Zi.prototype,"drawMode",2),k([A(we)],Zi.prototype,"color",2),k([A(fy)],Zi.prototype,"sharedMaterial",2);var xt=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedCameraModel(e,t){return(t||new xt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+4),(t||new xt).__init(e.readInt32(e.position())+e.position(),e)}userId(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}guid(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}dontSave(){let e=this.bb.__offset(this.bb_pos,8);return e?!!this.bb.readInt8(this.bb_pos+e):!1}pos(e){let t=this.bb.__offset(this.bb_pos,10);return t?(e||new Ce).__init(this.bb_pos+t,this.bb):null}rot(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new Ce).__init(this.bb_pos+t,this.bb):null}static startSyncedCameraModel(e){e.startObject(5)}static addUserId(e,t){e.addFieldOffset(0,t,0)}static addGuid(e,t){e.addFieldOffset(1,t,0)}static addDontSave(e,t){e.addFieldInt8(2,+t,0)}static addPos(e,t){e.addFieldStruct(3,t,0)}static addRot(e,t){e.addFieldStruct(4,t,0)}static endSyncedCameraModel(e){return e.endObject()}static finishSyncedCameraModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedCameraModelBuffer(e,t){e.finish(t,void 0,!0)}};import{Object3D as gy}from"three";var Ua="SCAM";Hr(Ua,xt.getRootAsSyncedCameraModel);var Tt=new ft,ad=class{userId;guid;constructor(e,t){this.guid=t,this.userId=e}send(e,t){let i=e.cam?.cam;if(i){Tt.clear();let n=Tt.createString(this.guid),r=Tt.createString(this.userId);xt.startSyncedCameraModel(Tt),xt.addGuid(Tt,n),xt.addUserId(Tt,r);let s=q(i),o=jo(i);xt.addPos(Tt,Ce.createVec3(Tt,s.x,s.y,s.z)),xt.addRot(Tt,Ce.createVec3(Tt,o.x,o.y,o.z));let c=xt.endSyncedCameraModel(Tt);Tt.finish(c,Ua),t.sendBinary(Tt.asUint8Array())}}},kn=class extends M{getUserCamera(e){let t=this.userToCamMap[e];return t?this.remoteCams[t].obj:null}cam=null;cameraPrefab=null;_lastWorldPosition;_lastWorldQuaternion;_model=null;_needsUpdate=!0;_lastUpdateTime=0;remoteCams={};userToCamMap={};_camTimeoutInSeconds=10;_receiveCallback=null;async awake(){this._lastWorldPosition=this.worldPosition.clone(),this._lastWorldQuaternion=this.worldQuaternion.clone(),this.cameraPrefab&&("uri"in this.cameraPrefab&&(this.cameraPrefab=await this.cameraPrefab.instantiate(this.gameObject)),this.cameraPrefab&&"isObject3D"in this.cameraPrefab&&(this.cameraPrefab.visible=!1))}start(){this.cam||(console.warn("Missing camera, fallback to main camera",this),this.cam=this.context.mainCameraComponent??null)}onEnable(){this._receiveCallback=this.context.connection.beginListenBinrary(Ua,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(Ua,this._receiveCallback)}update(){for(let i in this.remoteCams){let n=this.remoteCams[i],r=this.context.time.realtimeSinceStartup-n.lastUpdate;if(!n||r>this._camTimeoutInSeconds){console.log("Remote cam timeout",n,r),n?.obj&&O.destroy(n.obj),delete this.remoteCams[i],n&&delete this.userToCamMap[n.userId];continue}}if($.IsInWebXR)return;if(this.cam===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new ad(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));let e=q(this.cam.cam),t=ve(this.cam.cam);(e.distanceTo(this._lastWorldPosition)>.001||t.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(e),this._lastWorldQuaternion.copy(t),!((!this._needsUpdate||this.context.time.frameCount%2!==0)&&!(this.context.time.realtimeSinceStartup-this._lastUpdateTime>this._camTimeoutInSeconds*.5))&&(this._lastUpdateTime=this.context.time.realtimeSinceStartup,this._needsUpdate=!1,this._model.send(this,this.context.connection))}onReceivedRemoteCameraInfoBin(e){let t=e.guid();if(!t)return;let i=e.userId();if(!i||!this.context.connection.userIsInRoom(i)||!this.cameraPrefab)return;let n=this.remoteCams[t];if(!n)if("isObject3D"in this.cameraPrefab){let c=new ye;c.context=this.context;let d=O.instantiate(this.cameraPrefab,c);n=this.remoteCams[t]={obj:d,lastUpdate:this.context.time.realtimeSinceStartup,userId:i},n.obj.visible=!0,this.gameObject.add(d),this.userToCamMap[i]=t;let a=O.getOrAddComponent(d,fe);a.connectionId=i,a.avatar=d}else return;let r=n.obj;n.lastUpdate=this.context.time.realtimeSinceStartup,he.markDirty(r);let s=e.pos();s&&Cr(r,s.x(),s.y(),s.z());let o=e.rot();o&&Bo(r,o.x(),o.y(),o.z())}};k([A(ne)],kn.prototype,"cam",2),k([A([gy,tt])],kn.prototype,"cameraPrefab",2);var ld="view",Hp=N("debugsyncedroom"),ei=class extends M{roomName;urlParameterName;joinRandomRoom=!0;requireRoomParameter=!1;autoRejoin=!0;_roomPrefix;awake(){this._roomPrefix===void 0&&(this._roomPrefix=this.roomName,this.roomName="")}onEnable(){let e=N(ld);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}this.tryJoinRoom()}onDisable(){this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}tryJoinRoom(e=0){let t=!1;if(this.urlParameterName){let i=N(this.urlParameterName);if(i&&typeof i=="string"){t=!0;let n=sh(i);this.roomName=n}else if(this.joinRandomRoom&&(console.log("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),e<1))return this.tryJoinRoom(e+1)}else this.joinRandomRoom&&(this.roomName===null||this.roomName===void 0||this.roomName.length<=0)&&(console.log("generate room name"),this.roomName=this.generateRoomName());return this.requireRoomParameter&&!t?(Hp&&console.log('No required room parameter "'+this.urlParameterName+'" in url - will not connect to networking backend.'),!1):!this.roomName||this.roomName.length<=0?(Hp&&console.error('Missing room name on "'+this.name+'". Make sure this is correctly configured in Unity',this.context.connection.isDebugEnabled?this:""),!1):(this.context.connection.isConnected||this.context.connection.connect(),this._roomPrefix&&(this.roomName=this._roomPrefix+this.roomName),this.context.connection.joinRoom(this.roomName),!0)}_lastPingTime=0;_lastRoomTime=-1;update(){this.context.connection.isConnected&&(this.context.time.time-this._lastPingTime>3&&(this._lastPingTime=this.context.time.time,this.context.connection.send("ping",{time:this.context.time.time})),this.context.connection.isInRoom&&(this._lastRoomTime=this.context.time.time)),this._lastRoomTime>0&&this.context.time.time-this._lastRoomTime>.3&&(this._lastRoomTime=-1,this.autoRejoin?(console.log("Disconnected from networking backend - attempt reconnecting now"),this.tryJoinRoom()):console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you)"))}get currentRoomName(){let e=N(ld);return e||N(this.urlParameterName)}setRandomRoomUrlParameter(){let e=_l(),t=this.generateRoomName();N(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),ih(t,e)}generateRoomName(){return rh()+"_"+nh(100,999)}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){let e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(ld,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}};k([A()],ei.prototype,"roomName",2),k([A()],ei.prototype,"urlParameterName",2),k([A()],ei.prototype,"joinRandomRoom",2),k([A()],ei.prototype,"requireRoomParameter",2),k([A()],ei.prototype,"autoRejoin",2);function jp(){let l=N("testwindowcount")||0;l&&l>0&&by(l)}function by(l){if(N("testwindow"))return null;let e=new URL(window.location.href);Rr(e.searchParams,Kr,1),Rr(e.searchParams,"testwindow",1);let t=e.toString(),i=[];window.onbeforeunload=()=>{for(let c of i)c.close()};let n=.05,r=128,s=0,o=0;for(let c=0;c<l;c++){s*r+r*.01>=window.innerWidth&&(o+=1,s=0);let d=s*(r*(1+n))+window.screenLeft,a=o*(r*(1+n))+window.screenTop+90+60*o;s+=1;let h=window.open(t,"test window "+c,`popup=yes width=${r} height=${r} top=${a} left=${d}`);if(!h){console.warn("Failed to open window");continue}i.push(h),h.onload=()=>{h.onbeforeunload=()=>{for(let u=0;u<i.length;u++){let g=i[u];g!==h&&g.close()}i.length=0}}}return i}import{Vector3 as yy}from"three";var ws=class extends M{awake(){jp()}},_s=class extends M{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinrary(Jr,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new qa(this.context.connection.connectionId+"_simulatedTransform_"+e,this))}}builder=null;models=null;update(){if(!!this.context.connection.isConnected){if(this.useFlatbuffers){if(!this.context.connection.connectionId||this.context.time.frameCount%this.interval!==0)return;this.builder===null&&(this.builder=new ft(1024));let e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();let i=Dc(this.context.connection.connectionId,this);this.context.connection.sendBinary(i)}}else if(this.models)for(let e=0;e<this.models.length;e++){let t=this.models[e];t.dontSave=!0,t.update(this,null),this.context.connection.send("TestSimulateUserData-"+e,t)}}}},qa=class{guid;fast=!1;position;rotation;velocity=void 0;dontSave;isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}constructor(e,t){this.guid=e,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(t,null)}update(e,t){let i=e.worldPosition;this.position.x=i.x,this.position.y=i.y,this.position.z=i.z;let n=e.worldQuaternion;if(this.rotation.x=n.x,this.rotation.y=n.y,this.rotation.z=n.z,this.rotation.w=n.w,this.fast=!1,t){let r=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=r.x,this.velocity.y=r.y,this.velocity.z=r.z}}};z(qa,"temp",new yy);import{MathUtils as Ey}from"three";import{TransformControls as wy}from"three/examples/jsm/controls/TransformControls";import{OrbitControls as _y}from"three/examples/jsm/controls/OrbitControls";var pr=class extends M{isGizmo=!0;control;orbit;awake(){this.isGizmo&&!di||!this.context.mainCamera||(this.control=new wy(this.context.mainCamera,this.context.renderer.domElement),this.control.visible=!0,this.control.enabled=!0,this.control.getRaycaster().layers.set(2),this.control.size=.6,this.control.traverse(e=>{let t=e;if(t.layers.set(2),t){let i=t.material;i&&(i.opacity=.3)}}))}start(){if(this.context.mainCamera){let e=O.getComponentInParent(this.context.mainCamera,_y)??void 0;this.orbit=e}}changeEventListener;windowKeyDownListener;windowKeyUpListener;onEnable(){this.control&&(this.context.scene.add(this.control),this.control.attach(this.gameObject)),this.changeEventListener=this.onControlChangedEvent.bind(this),this.control?.addEventListener("dragging-changed",this.changeEventListener),this.attachWindowEvents()}onDisable(){this.control?.removeFromParent(),this.changeEventListener&&this.control?.removeEventListener("dragging-changed",this.changeEventListener)}onControlChangedEvent(e){let t=this.orbit;if(t&&(t.enabled=!e.value),e.value){let i=O.getComponentInParent(this.gameObject,Qe);i&&i.requestOwnership()}}attachWindowEvents(){let e=this.control;!e||(this.windowKeyDownListener||(this.windowKeyDownListener=t=>{switch(t.keyCode){case 81:e.setSpace(e.space==="local"?"world":"local");break;case 16:e.setTranslationSnap(100),e.setRotationSnap(Ey.degToRad(15)),e.setScaleSnap(.25);break;case 87:e.setMode("translate");break;case 69:e.setMode("rotate");break;case 82:e.setMode("scale");break;case 187:case 107:e.setSize(e.size+.1);break;case 189:case 109:e.setSize(Math.max(e.size-.1,.1));break;case 88:e.showX=!e.showX;break;case 89:e.showY=!e.showY;break;case 90:e.showZ=!e.showZ;break;case 32:e.enabled=!e.enabled;break}}),this.windowKeyUpListener||(this.windowKeyUpListener=t=>{switch(t.keyCode){case 16:e.setTranslationSnap(null),e.setRotationSnap(null),e.setScaleSnap(null);break}}),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener))}};k([A()],pr.prototype,"isGizmo",2);import{LinearToneMapping as Bp,ACESFilmicToneMapping as xy,ReinhardToneMapping as Ty}from"three";var xs=class{overrideState=!1;value=0},wi=class{active=!1;parameters},Mn=class extends wi{mode;get isToneMapping(){return!0}},Ln=class extends wi{postExposure};function Ry(l){return"mode"in l?Mn:"postExposure"in l?Ln:wi}var In=class{components;apply(e){if(!!this.components){for(let t of this.components)if(t instanceof Mn){let i=t;if(!t.active){e.renderer.toneMapping=Bp;continue}switch(i.mode?.value??0){case 0:e.renderer.toneMapping=Bp;break;case 1:e.renderer.toneMapping=Ty;break;case 2:e.renderer.toneMapping=xy;break}}else if(t instanceof Ln){let i=t;console.log(i.postExposure);let n=Math.pow(2,i.postExposure?.value??0);e.renderer.toneMappingExposure=i.postExposure?.overrideState?n:1}}}};k([A([l=>Ry(l),wi])],In.prototype,"components",2);var fr=class extends M{sharedProfile;onEnable(){this.sharedProfile?.apply(this.context)}};k([A(In)],fr.prototype,"sharedProfile",2);import*as Fp from"three";var mr=class{guid;dontSave=!0;userId;point={x:0,y:0,z:0};source={x:0,y:0,z:0};target;update(e,t,i,n=void 0){this.userId=e.connection.connectionId,this.point.x=t.x,this.point.y=t.y,this.point.z=t.z,this.source.x=i.x,this.source.y=i.y,this.source.z=i.z,this.target=n}},Ts=class extends M{prefab=null;_grabModels=[];_grabModelsUpdateTime=[];_addOrUpdateSub=null;_endSub=null;_freeSub=null;_instances={};awake(){this.prefab&&(this.prefab.visible=!1)}onEnable(){this._addOrUpdateSub=this.context.connection.beginListen("xr-grab-visual-start-or-update",this.onRemoteGrabStartOrUpdate.bind(this)),this._endSub=this.context.connection.beginListen("xr-grab-visual-end",this.onRemoteGrabEnd.bind(this)),this._freeSub=dt.AddEventListener("WillFree",this.onAttachedObjectFree.bind(this))}onDisable(){this.context.connection.stopListening("xr-grab-visual-start-or-update",this._addOrUpdateSub),this.context.connection.stopListening("xr-grab-visual-end",this._endSub),dt.RemoveEventListener("WillFree",this._freeSub)}addOrUpdateGrab(e){this.context.connection.send("xr-grab-visual-start-or-update",e,2)}endGrab(e){this.context.connection.send("xr-grab-visual-end",e,2)}onRemoteGrabStartOrUpdate(e){if(!this.prefab)return;let t=this._instances[e.guid];if(!t){let i=O.instantiate(this.prefab);if(i.visible=!0,this._instances[e.guid]={instance:i,model:e},e.userId){let n=O.getComponentsInChildren(i,ht);if(n?.length>0)for(let r of n)r.assignUserColor(e.userId)}return}t.model=e}onRemoteGrabEnd(e){if(!e)return;let t=e.guid;this._instances[t]&&(O.destroy(this._instances[t].instance),delete this._instances[t])}onAttachedObjectFree(e){if(this._grabModels.length<=0)return;let t=this._grabModels[0];this.updateModel(t,e),this.endGrab(t)}onBeforeRender(){if(this.updateRendering(),!!this.prefab&&(this.prefab.visible=!1,this.context.time.frameCount%10===0))for(let e=0;e<dt.Current.length;e++){let t=dt.Current[e];if(!t.controller||!t.selected)continue;this._grabModels.length<=e&&(this._grabModels.push(new mr),this._grabModelsUpdateTime.push(0)),this._grabModelsUpdateTime[e]=this.context.time.time;let i=this._grabModels[e];this.updateModel(i,t),this.addOrUpdateGrab(i)}}updateModel(e,t){if(!t.controller||!t.selected)return;e.guid=t.grabUUID;let i=t.selected.guid;e.update(this.context,t.grabPoint,t.controller.worldPosition,i)}temp=new Fp.Vector3;updateRendering(){let e=this.context.time.deltaTime/.5;for(let t in this._instances){let{instance:i,model:n}=this._instances[t];if(!i||!n)continue;let{point:r}=n,s=q(i);this.temp.set(r.x,r.y,r.z),s.lerp(this.temp,e),ie(i,s)}}};import{Object3D as Cy}from"three";var _i=class extends M{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=O.getComponentInParent(this.gameObject,Se)}update(){if(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)return;if(this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(let t of this.eyes)t&&(t.visible=this.eyesOpen)}}};k([A(Cy)],_i.prototype,"eyes",2),k([A()],_i.prototype,"lastBlinkTime",2),k([A()],_i.prototype,"blinkLength",2),k([A()],_i.prototype,"eyesOpen",2);import*as Xa from"three";import{Object3D as cd}from"three";var dd=class extends M{head=null;eyes=null;target=null;brain=null;awake(){this.brain||(this.brain=O.getComponentInParent(this.gameObject,Wi)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=O.addNewComponent(this.gameObject,Wi)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new Xa.Vector3;currentTargetPoint=new Xa.Vector3;update(){let e=this.target;if(e&&this.head){let t=this.eyes;if(t){let i=q(e);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);let n=q(this.head),r=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(r.length()<.1)return;let s=dd.forward;if(s.set(0,0,1),s.applyQuaternion(ve(this.head)),s.dot(r)>.45)for(let c=0;c<t.length;c++)t[c].lookAt(this.currentTargetPoint)}}}},xi=dd;z(xi,"forward",new Xa.Vector3(0,0,1)),k([A(cd)],xi.prototype,"head",2),k([A(cd)],xi.prototype,"eyes",2),k([A(cd)],xi.prototype,"target",2);import{Object3D as Np}from"three";var Sy=N("debugmouth"),Dn=class extends M{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){this.voip=O.findObjectOfType(Ke,this.context),console.log(this)}update(){if(!this.voip||this.context.time.frameCount%10!==0)return;let e=this.marker?.connectionId??null;e||Sy&&(e=null);let t=this.voip.getFrequency(e);t!=null&&this.updateLips(t)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>50){this.lastMouthChangeTime=this.context.time.time;let 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;let t=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,t)}}}setMouthShapeActive(e,t){if(!!e){e!=this.idle?this.idle.map(i=>i.visible=!1):this.talking.map(i=>i.visible=!1);for(let i=0;i<e.length;i++){let n=e[i];n&&(n.visible=i===t,n.scale.set(1,1,1))}}}};k([A(Np)],Dn.prototype,"idle",2),k([A(Np)],Dn.prototype,"talking",2);var Rs=class extends M{voip=null;marker=null;_startPosition=null;awake(){this.voip=O.findObjectOfType(Ke,this.context),this.marker=O.getComponentInParent(this.gameObject,fe)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;let e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());let i=t/100;this.gameObject.position.y=this._startPosition.y+i*.07}};var Py=N("logstats"),Cs=class extends M{onEnable(){console.log(this),Py&&this.startCoroutine(this.run(),4)}*run(){for(;this.enabled;){let e=this.context.renderer.info;console.log(e.memory,e.render,e.programs),yield}}};import*as Vp from"three";var gr=class{guid},br=class{signal;reaction;$serializedTypes={signal:gr,reaction:Oe}},Ji=class extends M{events;start(){console.log(this)}invoke(e){if(!this.events||!Array.isArray(this.events))return;let t=typeof e=="object"?e.guid:e;for(let i of this.events)if(i.signal.guid===t)try{if(i.reaction){if(!i.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",i,this);continue}}else{console.warn("Missing reaction for signal",i,this);continue}i.reaction.invoke()}catch(n){console.error(n)}}};k([A(br)],Ji.prototype,"events",2);import*as re from"three";import{Quaternion as Oy,Vector3 as Ay}from"three";var Qa=N("debugtimeline"),Ss=class{director;track;get muted(){return this.track.muted}set muted(e){e!==this.track.muted&&(this.track.muted=e,this.onMuteChanged?.call(this))}*forEachClip(e=!1){if(!!this.track?.clips)if(e)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(let t of this.track.clips)yield t}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,i,n=!0){if(t<0||t>=i.length)return 0;let r=i[t];if(n||e>=r.start&&e<=r.end){let s=1,o=!1;return r.easeInDuration>0&&(s*=Math.min((e-r.start)/r.easeInDuration,1)),r.easeOutDuration>0&&!o&&(s*=Math.min((r.end-e)/r.easeOutDuration,1)),s}return 0}},hd=class{clip;rootPositionOffset;rootQuaternionOffset;get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}rootStartPosition;rootEndPosition;rootStartQuaternion;rootEndQuaternion;constructor(e){let t=e.getClip();this.clip=t;let i=e.getRoot(),n=i.name+".position",r=i.name+".quaternion";Qa&&console.log(t.name,t.tracks,n);for(let s of t.tracks)if(!(s.times.length<=0)){if(s.name.endsWith(n))this.rootStartPosition=new re.Vector3().fromArray(s.values,0),this.rootEndPosition=new re.Vector3().fromArray(s.values,s.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),Qa&&console.log(this.rootPositionOffset);else if(s.name.endsWith(r)&&(this.rootStartQuaternion=new re.Quaternion().fromArray(s.values,0),this.rootEndQuaternion=new re.Quaternion().fromArray(s.values,s.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),Qa)){let o=new re.Euler().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",o)}}}},Hn=class extends Ss{models=[];trackOffset;target;mixer;clips=[];actions=[];_actionOffsets=[];_didBind=!1;createHooks(e,t){if(t.tracks?.length<=0){console.warn("No tracks in AnimationClip",t);return}let i=t.tracks[0].name.split("."),n=i[i.length-2],r=n+".position",s=n+".quaternion",o=!1,c=!1;for(let d of t.tracks)d.name.endsWith(r)?(o=!0,this.createPositionInterpolant(t,e,d)):d.name.endsWith(s)&&(c=!0,this.createRotationInterpolant(t,e,d));if(!o){let d=t.tracks[0].name.lastIndexOf("."),a=t.tracks[0].name.substring(0,d)+".position",h=new re.VectorKeyframeTrack(a,[0,t.duration],[0,0,0,0,0,0]);t.tracks.push(h),this.createPositionInterpolant(t,e,h)}if(!c){let d=t.tracks[0].name.lastIndexOf("."),a=t.tracks[0].name.substring(0,d)+".quaternion",h=new re.QuaternionKeyframeTrack(a,[0,t.duration],[0,0,0,1,0,0,0,1]);t.tracks.push(h),this.createRotationInterpolant(t,e,h)}}bind(){if(!this._didBind){this._didBind=!0,Qa&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(let e of this.actions){let t=new hd(e);this._actionOffsets.push(t)}for(let e of this.models){let t=e.asset,i=t.position,n=t.rotation;i.x!==void 0&&(i.isVector3||(t.position=new Ay(i.x,i.y,i.z)),n.isQuaternion||(t.rotation=new Oy(n.x,n.y,n.z,n.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){let e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new re.Vector3(e.x,e.y,e.z)));let t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new re.Quaternion(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new re.Vector3;_totalOffsetRotation=new re.Quaternion;_totalOffsetPosition2=new re.Vector3;_totalOffsetRotation2=new re.Quaternion;_summedPos=new re.Vector3;_tempPos=new re.Vector3;_summedRot=new re.Quaternion;_tempRot=new re.Quaternion;evaluate(e){if(this.track.muted||!this.mixer)return;this.bind(),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,i=0,n=!1;for(let r=0;r<this.clips.length;r++){let s=this.models[r],o=this.actions[r],c=s.asset;o.weight=0;let d=e>=s.start&&e<=s.end,a=s.postExtrapolationMode,h=d;if(!h&&!n&&s.end<e&&s.postExtrapolationMode!==0){let u=r<this.clips.length-1?this.models[r+1]:null;(!u||u.start>e)&&(h=!0,n=!0)}if(h){let u=1;u*=this.evaluateWeight(e,r,this.models,h);let g=this.getClipTime(e,s),E=0,b=c.duration;if(d){if(c.loop)for(E+=Math.floor(g/(b+1e-6));g>b;)g-=b}else if(!d)switch(a){case 2:g%=b;break;case 3:let p=Math.floor(g/b)%2!==0;g%=b,p&&(g=b-g);break}o.time=g,o.timeScale=0;let y=u*this.director.weight;if(o.weight=y,o.clampWhenFinished=!0,o.isRunning()||o.play(),this._useclipOffsets){let m=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,p=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-u),t+=1;let f=this._summedPos.set(0,0,0),v=this._tempPos.set(0,0,0),w=this._summedRot.identity(),x=this._tempRot.identity(),T=c.rotation,R=new re.Quaternion;R.slerp(T,u);let C=this._actionOffsets[r];if(C.hasOffsets)for(let P=0;P<E;P++)C.rootPositionOffset?v.copy(C.rootPositionOffset):v.set(0,0,0),v.applyQuaternion(w).applyQuaternion(R),C.rootQuaternionOffset&&(x.copy(C.rootQuaternionOffset),w.multiply(x)),f.add(v);p.multiply(R),p.multiply(w),f.add(c.position),m.add(f)}}}this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,i),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,i)),this.mixer.update(e)}createRotationInterpolant(e,t,i){let n=i.createInterpolant.bind(i),r=new re.Quaternion;this.ensureTrackOffsets();let s=this.trackOffset?.rotation;i.createInterpolant=()=>{let o=n(),c=o.evaluate.bind(o);return o.evaluate=d=>{let a=c(d);return r.set(a[0],a[1],a[2],a[3]),r.premultiply(this._totalOffsetRotation),s&&r.premultiply(s),a[0]=r.x,a[1]=r.y,a[2]=r.z,a[3]=r.w,a},o}}createPositionInterpolant(e,t,i){let n=i.createInterpolant.bind(i),r=new re.Vector3;this.ensureTrackOffsets();let s=this.trackOffset?.rotation,o=this.trackOffset?.position,c;i.createInterpolant=()=>{let d=n(),a=d.evaluate.bind(d);return d.evaluate=h=>{let u=a(h);return r.set(u[0],u[1],u[2]),t.removeStartOffset&&(c===void 0?(c=null,c=this._actionOffsets.find(g=>g.clip===e)?.rootStartPosition?.clone()):c?.isVector3&&r.sub(c)),r.applyQuaternion(this._totalOffsetRotation),r.add(this._totalOffsetPosition),s&&r.applyQuaternion(s),o&&(r.x-=o.x,r.y+=o.y,r.z+=o.z),u[0]=r.x,u[1]=r.y,u[2]=r.z,u},d}}},jn=class extends Ss{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;getAudioFilePath(e){let t=this.director.sourceId;return Ao(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){let i=this.models[t];this.audio[t].setVolume(e?i.asset.volume:0)}}addModel(e){let t=this.getAudioFilePath(e.asset.clip),i=new re.Audio(this.listener);i.setVolume(e.asset.volume);let n=new re.AudioLoader;console.log(t,this.director.sourceId),n.load(t,r=>{i.setBuffer(r),i.loop=e.asset.loop,this.audio.push(i),this.models.push(e)})}onDisable(){for(let e of this.audio)e.isPlaying&&e.stop()}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){let t=this.audio[e];t?.isPlaying&&t.stop()}}evaluate(e){if(!this.track.muted){for(let t=0;t<this.models.length;t++){let i=this.models[t],n=this.audio[t];if(e>=i.start&&e<=i.end){if(this.director.isPaused&&(n.isPlaying&&n.stop(),this.lastTime===e))continue;n.isPlaying||(n.offset=i.clipIn+(e-i.start)*i.timeScale,n.play());let r=i.asset.volume;i.easeInDuration>0&&(r*=Math.min((e-i.start)/i.easeInDuration,1)),i.easeOutDuration>0&&(r*=Math.min((i.end-e)/i.easeOutDuration,1)),n.setVolume(r*this.director.weight)}else n.isPlaying&&n.stop()}this.lastTime=e}}},Ki=class extends Ss{models=[];didTrigger=[];receivers=[];evaluate(e){if(!(this.receivers.length<=0)&&!this.track.muted)for(let t=0;t<this.models.length;t++){let i=this.models[t],n=this.didTrigger[t],r=i.time-e;if(i.retroActive?r<0:r<0&&Math.abs(r)<.1){if(!n){this.didTrigger[t]=!0;for(let o of this.receivers)!o||o.invoke(i.asset)}}else i.emitOnce||(this.didTrigger[t]=!1)}}},yo=class extends Ss{models=[];timelines=[];resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){let n=this.models[t].asset;if(typeof n.sourceObject=="string"){let r=n.sourceObject;yo.resolved[r]?n.sourceObject=yo.resolved[r]:(n.sourceObject=O.findByGuid(r,e.scene),yo.resolved[r]=n.sourceObject)}if(n.sourceObject){let r=O.getComponent(n.sourceObject,en);this.timelines.push(r),r&&n.updateDirector&&(r.playOnAwake=!1)}else{this.models.splice(t,1);continue}}}_previousActiveModel=null;evaluate(e){this._previousActiveModel=null;for(let t=0;t<this.models.length;t++){let i=this.models[t],n=i.asset;if(e>=i.start&&e<=i.end){this._previousActiveModel=i;let r=this.getClipTime(e,i);if(n.controlActivation){let s=n.sourceObject;s.visible=!0}if(n.updateDirector){let s=this.timelines[t];s&&(s.isPlaying&&s.pause(),s.time=r,s.evaluate())}}else{let r=this._previousActiveModel?.asset;if(n.controlActivation){let s=n.sourceObject;r?.sourceObject!==s&&(s.visible=!1)}}}}},$i=yo;z($i,"resolved",{});var Gp=N("debugtimeline");var Ya=class extends M{static registerCreateTrack(e,t){this.createTrackFunctions[e]=t}playableAsset;playOnAwake;extrapolationMode=1;get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(e){this._time=e}get duration(){return this._duration}set duration(e){this._duration=e}get weight(){return this._weight}set weight(e){this._weight=e}_visibilityChangeEvt;_clonedPlayableAsset=!1;awake(){Gp&&console.log(this,this.playableAsset?.tracks),this.rebuildGraph(),this.playOnAwake?this.play():this.evaluate(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,this.playableAsset?.tracks,Array.isArray(this.playableAsset?.tracks),this)}onEnable(){for(let e of this._audioTracks)e.onEnable?.();for(let e of this._customTracks)e.onEnable?.();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(){this.stop();for(let e of this._audioTracks)e.onDisable?.();for(let e of this._customTracks)e.onDisable?.();this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){for(let e of this._audioTracks)e.onDestroy?.()}rebuildGraph(){!this.isValid()||(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}play(){!this.isValid()||(this._isPaused=!1,!this._isPlaying&&(this._isPlaying=!0,this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate())))}pause(){this._isPaused=!0}stop(){this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.evaluate()),this._isPlaying=!1,this._isPaused=!1,this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null}evaluate(){if(!this.isValid())return;let e=this._time;switch(this.extrapolationMode){case 0:e=Math.min(e,this._duration);break;case 1:e%=this._duration;break;case 2:if(e>this._duration){this.stop();return}break}this.internalEvaluate(e)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(let e of this._allTracks)for(let t of e)yield t}get audioTracks(){return this._audioTracks}_guidsMap;resolveGuids(e){this._guidsMap=e}_isPlaying=!1;_internalUpdateRoutine;_isPaused=!1;_time=0;_duration=0;_weight=1;_animationTracks=[];_audioTracks=[];_signalTracks=[];_controlTracks=[];_customTracks=[];_allTracks=[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks];*internalUpdate(){for(;this._isPlaying;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime,this.evaluate()),yield}internalEvaluate(e){for(let t of this.playableAsset.tracks)if(!t.muted)switch(t.type){case"ActivationTrack":for(let i=0;i<t.outputs.length;i++){let n=t.outputs[i];if(typeof n=="object"){let r=!1;for(let o of t.clips)o.start<=e&&e<=o.end&&(r=!0);let s=n;s.visible!==void 0&&(s.visible=r)}}break}for(let t of this._animationTracks)t.evaluate(e);for(let t of this._audioTracks)t.evaluate(e);for(let t of this._signalTracks)t.evaluate(e);for(let t of this._controlTracks)t.evaluate(e);for(let t of this._customTracks)t.evaluate(e)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Vs(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;let e=this.findRoot(this.gameObject);for(let t of this.playableAsset.tracks)for(let i=t.outputs.length-1;i>=0;i--){let n=t.outputs[i];if(typeof n=="string"){this._guidsMap&&this._guidsMap[n]&&(n=this._guidsMap[n]);let r=O.findByGuid(n,e);r===null||typeof r!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(Gp&&console.log("Resolved binding",n,"to",r),t.outputs[i]=r)}else if(n===null){if(t.outputs.splice(i,1),Ya.createTrackFunctions[t.type])continue;t.type!=="AudioTrack"&&t.type!=="ControlTrack"&&t.type!=="MarkerTrack"&&console.warn("Missing binding",n,t.name,t.type,this.name,this.playableAsset.name)}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(let e of this.playableAsset.tracks)if(e.muted!==!0)for(let t of e.clips)t.end>this._duration&&(this._duration=t.end)}}setupAndCreateTrackHandlers(){if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let e=[];for(let t of this.playableAsset.tracks){let i=t.type,n=Ya.createTrackFunctions[i];if(n!=null){let r=n(this,t);if(typeof r.evaluate=="function"){r.director=this,r.track=t,this._customTracks.push(r);continue}}if(t.type==="AnimationTrack"){if(t.clips.length<=0)continue;for(let r=t.outputs.length-1;r>=0;r--){let s=t.outputs[r];typeof s.enabled=="boolean"&&(s.enabled=!1);let o=s?.gameObject?.animations;if(o){let c=new Hn;c.trackOffset=t.trackOffset,c.director=this,c.track=t;for(let d=0;d<t.clips.length;d++){let a=t.clips[d],h=a.asset;if(!h){console.error("MISSING anim model?","clip#"+d,a,t,this.playableAsset,this.name);continue}let u=h.clip,g=u;if((typeof g=="string"||typeof g=="number")&&(g=o.find(b=>b.name===u)),!g){console.warn("Could not find animationClip for model",a,t.name,this.name,this.playableAsset?.name);continue}c.mixer||(c.mixer=new Vp.AnimationMixer(s.gameObject)),c.clips.push(g),c.mixer.uncacheAction(g),c.createHooks(a.asset,g);let E=c.mixer.clipAction(g);c.actions.push(E),c.models.push(a)}this._animationTracks.push(c)}}}else if(t.type==="AudioTrack"){if(t.clips.length<=0)continue;e.push(t)}else if(t.type==="MarkerTrack"){let r=new Ki;r.director=this,r.track=t;for(let s of t.markers)switch(s.type){case"SignalEmitter":r.models.push(s),r.didTrigger.push(!1);break}if(r!==null&&r.models.length>0){let s=O.getComponent(this.gameObject,Ji);s&&(r.receivers.push(s),this._signalTracks.push(r))}}else if(t.type==="SignalTrack"){let r=new Ki;r.director=this,r.track=t;for(let s of t.markers)r.models.push(s),r.didTrigger.push(!1);for(let s of t.outputs)r.receivers.push(s);this._signalTracks.push(r)}else if(t.type==="ControlTrack"){let r=new $i;r.director=this,r.track=t;for(let s of t.clips)r.models.push(s);r.resolveSourceObjects(this.context),this._controlTracks.push(r)}}ue.registerWaitForAllowAudio(()=>{let t=O.findObjectOfType(Jt,this.context);if(!!t)for(let i of e){let n=new jn;n.director=this,n.track=i,n.listener=t.listener;for(let r=0;r<i.clips.length;r++){let s=i.clips[r];n.addModel(s)}this._audioTracks.push(n)}})}setAudioTracksAllowPlaying(e){for(let t of this._audioTracks)t.onAllowAudioChanged(e)}},en=Ya;z(en,"createTrackFunctions",{});import*as Wp from"three-mesh-ui";var ti=class{used=!1;Use(){this.used=!0}StopPropagation(){this.event?.stopImmediatePropagation()}inputSource;object;isDown;isUp;isPressed;isClicked;event;constructor(e){this.event=e}};import{Object3D as Iy}from"three";var My=N("debugeventsystem"),Ti=class extends M{static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Ti.systems.length<=0&&Ti.systems.push(...O.findObjectsOfType(Ti,e)));for(let i of Ti.systems)if(i.context===e)return;let t=new Iy;O.addNewComponent(t,Ti),e.scene.add(t)}static ensureUpdateMeshUI(e,t){ii.update(e,t)}static markUIDirty(e){ii.markDirty()}static get instance(){return this.systems[0]}orbitControl=null;orbitControlWasEnabled=!1;raycaster=[];constructor(){super(),Ti.systems.push(this)}onDestroy(){Ti.systems.splice(Ti.systems.indexOf(this),1)}start(){}register(e){e&&this.raycaster&&!this.raycaster.includes(e)&&this.raycaster?.push(e)}unregister(e){let t=this.raycaster?.indexOf(e);t!==void 0&&t!==-1&&this.raycaster?.splice(t,1)}onEnable(){oe.addEventListener("select-start",(t,i)=>{if(!i.grab)return;ii.resetLastSelected();let n=new ti;n.inputSource=t,n.isDown=t.selectionDown,n.isUp=t.selectionUp,n.isPressed=t.selectionPressed,n.isClicked=!1,i.grab&&!this.handleEvents(i.grab,n)&&(i.grab=null)});let e=new je;oe.addEventListener("select-end",(t,i)=>{if(!i.grab)return;let n=new ti;n.inputSource=t,n.isDown=t.selectionDown,n.isUp=t.selectionUp,n.isPressed=t.selectionPressed,n.isClicked=t.selectionClick,this.handleEvents(i.grab,n)}),oe.addEventListener("update",t=>{e.ray=t.getRay();let i=this.performRaycast(e);if(!i)return;let n=new ti;n.inputSource=t,this.handleIntersections(i,n)}),this.context.pre_update_callbacks.push(this.onBeforeUpdate.bind(this)),this.context.input.addEventListener("pointerDown",this.onPointerDown.bind(this))}onDisable(){}onPointerDown(){this.onBeforeUpdate()}lastPointerEvent=null;objectsHoveredThisFrame=[];objectsHoveredLastFrame=[];raisedPointerDownEvents=[];_didMove=!1;onBeforeUpdate(){if(this.objectsHoveredThisFrame.length=0,this.resetMeshUIStates(),$.IsInWebXR||this.context.input.isKeyPressed(18))return;if(!this._didMove){let r=this.context.input.getPointerPositionRC(0);if(r&&r.x===0&&r.y===0)return;this._didMove=!0}let e=this.performRaycast(null),t=new ti(this.context.input.getPointerEvent(0));if(t.inputSource=this.context.input,t.isClicked=this.context.input.mouseClick,t.isDown=this.context.input.mouseDown,t.isUp=this.context.input.mouseUp,t.isPressed=this.context.input.mousePressed,this.lastPointerEvent=t,!e)return;let i=null,n=null;this.context.input.mouseDown&&this.currentActiveMeshUIComponents.length>0&&this.context.mainCameraComponent&&(i=O.getComponent(this.context.mainCameraComponent.gameObject,gt)??null,i&&(n=i.enabled,i.enabled=!1)),this.handleIntersections(e,t),i&&(this.orbitControl=i,this.orbitControl?.enabled?(this.orbitControlWasEnabled=this.orbitControl.enabled,this.orbitControl.enabled=!1):this.orbitControl&&!this.context.input.mousePressed&&(this.orbitControl.enabled=this.orbitControlWasEnabled,this.orbitControl=null))}_tempComponentsArray=[];onBeforeRender(){if(this.lastPointerEvent)this.lastPointerEvent.used=!1;else return;if(this.lastPointerEvent.isUp){for(let t of this.raisedPointerDownEvents)t.onPointerUp&&t.onPointerUp(this.lastPointerEvent);this.raisedPointerDownEvents.length=0}for(let t of this.objectsHoveredLastFrame)if(this.objectsHoveredThisFrame.indexOf(t)<0){this._tempComponentsArray.length=0;let i=O.getComponentsInParent(t,M,this._tempComponentsArray);this.lastPointerEvent.object=t;for(let n=0;n<i.length;n++){let r=i[n];if(!r.gameObject||r.destroyed)continue;let s=r;s.onPointerExit&&s.onPointerExit(this.lastPointerEvent)}}let e=this.objectsHoveredLastFrame;this.objectsHoveredLastFrame=this.objectsHoveredThisFrame,this.objectsHoveredThisFrame=e}_sortedHits=[];performRaycast(e){if(!this.raycaster)return null;this._sortedHits.length=0;for(let t of this.raycaster){if(!t.activeAndEnabled)continue;let i=t.performRaycast(e);i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}handleIntersections(e,t){if(!e||e.length<=0)return!1;e=this.sortCandidates(e);for(let i of e){let{object:n}=i;if(this.handleEvents(n,t))return!0}return!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){let i=e[t],n=i.object;if(n.material&&n.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(let t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventsArray=[];handleEvents(e,t){if(!this.testIsVisible(e))return t.isClicked&&My&&console.log("not allowed",e),!1;t.object=e,this.lastPointerEvent=t;let i=e.parent,n=!1,r=t.isClicked??!1,s=null;if(i&&i.isUI){let o=(t.isPressed||t.isClicked)??!1;if(i.shadowComponentOwner){let c=i.shadowComponentOwner.gameObject;if(c){if(s=this.tryFindCanvasGroup(c),s?.blocksRaycasts===!1)return!1;if(s?.interactable===!1)return!0;let d=this.handleMeshUIIntersection(e,o);e=c,n=!0}}if(!n&&this.handleMeshUiObjectWithoutShadowDom(i,o))return!0}if(this.objectsHoveredThisFrame.push(e),s===null||s.interactable){let o=this.objectsHoveredLastFrame.indexOf(e)>=0;this.handleEventsArray.length=0;let c=O.getComponentsInParent(e,M,this.handleEventsArray);for(let d=0;d<c.length;d++){if(t.used)return!0;if(c[d].destroyed)continue;let a=c[d];a.interactable!==!1&&(a.onPointerEnter&&(o||a.onPointerEnter(t)),t.isDown&&a.onPointerDown&&!this.raisedPointerDownEvents.includes(a)&&(a.onPointerDown(t),this.raisedPointerDownEvents.push(a)),t.isUp&&a.onPointerUp&&a.onPointerUp(t),t.isClicked&&a.onPointerClick&&a.onPointerClick(t))}}return!0}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){let i=ii.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&ii.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){let t=this.currentActiveMeshUIComponents[e];ii.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?O.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}tryFindCanvasGroup(e){if(!e)return null;let t=O.foreachComponent(e,i=>{let n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}},Ze=Ti;z(Ze,"didSearchEventSystem",!1),z(Ze,"systems",[]);var ii=class{static markDirty(){this.needsUpdate=!0}static update(e,t){for(let i of this.lastUpdateFrame)if(i.context===t){if(t.time.frameCount===i.frame)return;i.frame=t.time.frameCount,(this.needsUpdate||t.time.frameCount<30)&&(this.needsUpdate=!1,e.update());return}this.lastUpdateFrame=[{context:t,frame:t.time.frameCount}],e.update()}static updateState(e,t){let i=null;if(e&&(i=this.findBlockInParent(e),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;t?(this.lastSelected=i,i.states.pressed&&i.setState("pressed")):i.states.hovered&&i.setState("hovered"),this.needsUpdate=!0}return i}static resetLastSelected(){let e=this.lastSelected;!e||(this.lastSelected=null,this.resetState(e))}static resetState(e){if(!e)return;e.interactable===!1?e.states.disabled&&e.setState("disabled"):e===this.lastSelected&&e.states.selected?e.setState("selected"):e.setState("normal"),this.needsUpdate=!0}static findBlockInParent(e){return e?e.isBlock&&Object.keys(e.states).length>0?e:this.findBlockInParent(e.parent):null}};z(ii,"lastSelected",null),z(ii,"lastUpdateFrame",[]),z(ii,"needsUpdate",!1);import{AxesHelper as Ly}from"three";var Ps="./include";Wp.Block.prototype.interactable={get(){return this.interactive},set(l){this.interactable=l}};var Ue=class extends M{isRoot(){return this.Root?.gameObject===this.gameObject}markDirty(){Ze.markUIDirty(this.context)}shadowComponent=null;_controlsChildLayout=!0;get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}_root=void 0;get Root(){return this._root===void 0&&(this._root=O.getComponentInParent(this.gameObject,tn)),this._root}_parentComponent=void 0;onEnable(){super.onEnable()}addShadowComponent(e,t){this.removeShadowComponent();let i=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=O.getComponentInParent(i,Ue),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have a UI element outside a Canvas?`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e.shadowComponentOwner=this;let n=this.raycastTarget;if(e.traverse(r=>{r.shadowComponentOwner===void 0&&(r.shadowComponentOwner=this),n===!1&&r.layers.set(2)}),this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{let r=this._parentComponent.shadowComponent;r&&r?.add(e)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),di&&e.add(new Ly(.5)),this.onAfterAddedToScene()}set(e){}traverseOwnedShadowComponents(e,t,i){if(!!e&&e.shadowComponentOwner===t){i(e);for(let n of e.children)this.traverseOwnedShadowComponents(n,t,i)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}},tn=class extends Ue{awake(){super.awake()}};import{Color as jy,Texture as Xp}from"three";import*as pd from"three-mesh-ui";import{Matrix4 as Dy,Object3D as Hy,Vector2 as Up,Vector3 as ud}from"three";var qp=N("debugui"),Os=class{width;height},vr=class{x;y;width;height},ut=class extends Ue{offset=.01;get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}_anchoredPosition;get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new ud),this._anchoredPosition}rect;sizeDelta;anchoredPosition3D;pivot;lastMatrix;rectBlock;_transformNeedsUpdate=!1;awake(){super.awake(),this.lastMatrix=new Dy,this.rectBlock=new Hy,this.rectBlock.position.z=.1,this.rectBlock.name=this.name,this._anchoredPosition||(this._anchoredPosition=new ud),qr(this,"_anchoredPosition",()=>{this._transformNeedsUpdate=!0})}onEnable(){super.onEnable(),this.addShadowComponent(this.rectBlock),this.applyTransform()}onDisable(){super.onDisable(),this.removeShadowComponent()}applyTransform(){let e=this.shadowComponent;!e||(this._transformNeedsUpdate=!1,this.isRoot()?e.rotation.y=Math.PI:(e.position.copy(this.gameObject.position),e.position.x*=-1,e.position.z*=-1,e.position.z-=this.offset,e.quaternion.copy(this.gameObject.quaternion),e.rotation.x*=-1,e.rotation.z*=-1,e.scale.copy(this.gameObject.scale)),this.applyAnchoring(e.position),this.lastMatrix.copy(this.gameObject.matrix))}markDirty(){this._transformNeedsUpdate=!0}onBeforeRender(){(this._transformNeedsUpdate||this.lastMatrix.equals(this.gameObject.matrix)===!1)&&(qp&&console.log("updating",this.name),this.applyTransform()),Ze.ensureUpdateMeshUI(pd,this.context)}applyAnchoring(e){if(this.pivot&&this.sizeDelta){let t=this.pivot.x*2-1,i=this.pivot.y*2-1;i-=this.anchoredPosition.y*.05;let n=this.sizeDelta.x*t,r=this.sizeDelta.y*i;e.x-=n*.5,e.y-=r*.5}}getBasicOptions(){let e={width:this.rect.width,height:this.rect.height,offset:this.offset,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}_createdBlocks=[];createNewBlock(e){e={...this.getBasicOptions(),...e},qp&&console.log(this.name,e);let t=new pd.Block(e);return this._createdBlocks.push(t),t}};k([A(vr)],ut.prototype,"rect",2),k([A(Up)],ut.prototype,"sizeDelta",2),k([A(ud)],ut.prototype,"anchoredPosition3D",2),k([A(Up)],ut.prototype,"pivot",2);var Rt=class extends Ue{get color(){return this._color||(this._color=new we(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new we(1,1,1,1)),this._color.copy(e))}onColorChanged(){let e=this.color;this.setOptions({backgroundColor:e,backgroundOpacity:e.alpha,borderOpacity:e.alpha})}get m_Color(){return this._color}raycastTarget=!0;uiObject=null;_color=null;_rect=null;get rectTransform(){return this._rect||(this._rect=this.gameObject.getComponent(ut)),this._rect}setState(e){this.makePanel(),this.uiObject&&this.uiObject.setState(e)}setupState(e){this.makePanel(),this.uiObject&&this.uiObject.setupState(e)}setOptions(e){this.makePanel(),this.uiObject&&(this.uiObject.set(e),(e.backgroundColor!==void 0||e.backgroundOpacity!==void 0)&&this.uiObject.updateBackgroundMaterial?.call(this.uiObject))}awake(){super.awake(),this.makePanel(),qr(this,"_color",()=>up(this,this.onColorChanged))}onEnable(){super.onEnable(),this.uiObject&&(this.rectTransform.shadowComponent?.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}_currentlyCreatingPanel=!1;makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;let e={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:1};this.onBeforeCreate(e),this.onCreate(e),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}async setTexture(e){!e||(this.setOptions({backgroundOpacity:0}),e&&this.setOptions({backgroundTexture:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}))}onAfterAddedToScene(){this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}};k([A(we)],Rt.prototype,"color",1),k([A()],Rt.prototype,"raycastTarget",2);var nn=class extends Rt{onAfterCreated(){this.uiObject&&(this.uiObject.scale.y*=-1)}};var Za=class{texture;rect};k([A(Xp)],Za.prototype,"texture",2);var rn=class extends nn{sprite;isBuiltinSprite(){switch(this.sprite?.texture?.name){case"InputFieldBackground":case"UISprite":case"Background":return!0}return!1}onBeforeCreate(e){this.isBuiltinSprite()&&(e.borderRadius=5,e.borderColor=new jy(.4,.4,.4),e.borderOpacity=this.color.alpha,e.borderWidth=.3)}onAfterCreated(){super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture)}};k([A(Za)],rn.prototype,"sprite",2);var yr=class extends nn{mainTexture;onAfterCreated(){super.onAfterCreated(),this.setTexture(this.mainTexture)}};k([A(Xp)],yr.prototype,"mainTexture",2);var As=N("debugbutton");var Ft=class extends M{onClick;_isHovered=!1;onPointerEnter(e){As&&console.log("Button Enter",this.animationTriggers?.highlightedTrigger,this.animator),this._isHovered=!0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&this._image?.setState("hovered")}onPointerExit(){As&&console.log("Button Exit",this.animationTriggers?.highlightedTrigger,this.animator),this._isHovered=!1,this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState("normal")}onPointerDown(e){As&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&this._image?.setState("pressed")}onPointerUp(e){As&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState(this._isHovered?"hovered":"normal")}onPointerClick(e){As&&console.trace("Button Click",this.onClick),this.onClick?.invoke()}colors;transition;animationTriggers;animator;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}_interactable=!0;set_interactable(e){this.interactable=e}awake(){super.awake(),As&&console.log(this),this.init()}start(){this._image?.setInteractable(this.interactable)}onEnable(){super.onEnable()}_requestedAnimatorTrigger;*setAnimatorTriggerAtEndOfFrame(e){this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&this.animator?.SetTrigger(e)}_isInit=!1;_image;init(){this._isInit||(this._isInit=!0,this._image=O.getComponent(this.gameObject,rn),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){e.setInteractable(this.interactable);let t=this.getFinalColor(e.color,this.colors?.normalColor),i={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(i);let n=this.getFinalColor(e.color,this.colors?.highlightedColor),r={state:"hovered",attributes:{backgroundColor:n,backgroundOpacity:n.alpha}};e.setupState(r);let s=this.getFinalColor(e.color,this.colors?.pressedColor),o={state:"pressed",attributes:{backgroundColor:s,backgroundOpacity:s.alpha}};e.setupState(o);let c=this.getFinalColor(e.color,this.colors?.selectedColor),d={state:"selected",attributes:{backgroundColor:c,backgroundOpacity:c.alpha}};e.setupState(d);let a=this.getFinalColor(e.color,this.colors?.disabledColor),h={state:"disabled",attributes:{backgroundColor:a,backgroundOpacity:a.alpha}};e.setupState(h)}getFinalColor(e,t){return t?e.clone().multiply(t):e.clone()}};k([A(Oe)],Ft.prototype,"onClick",2),k([A()],Ft.prototype,"colors",2),k([A()],Ft.prototype,"transition",2),k([A()],Ft.prototype,"animationTriggers",2),k([A(bt)],Ft.prototype,"animator",2),k([A()],Ft.prototype,"interactable",1);var fd=class extends tn{set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop}_renderOnTop=!1;set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}_depthWrite=!1;set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}_doubleSided=!0;set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}_castShadows=!0;set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}_receiveShadows=!0;get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}_renderMode=-1;_rootCanvas;set rootCanvas(e){this._rootCanvas instanceof fd||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}awake(){this.shadowComponent=this.gameObject,super.awake()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this.onRenderSettingsChanged()}previousAspect=-1;onBeforeRender(){this.isScreenSpace&&this.context.mainCameraComponent&&this.context.mainCameraComponent.aspect!==this.previousAspect&&(this.previousAspect=this.context.mainCameraComponent.aspect,this.updateRenderMode())}_updateRenderSettingsRoutine;onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),3))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.updateRenderMode(),Ur(this.shadowComponent,this);for(let e of this.gameObject.getComponentsInChildren(Ue))Ur(e.shadowComponent,this)}}_activeRenderMode=-1;get isScreenSpace(){return this._activeRenderMode===1||this._activeRenderMode===0}updateRenderMode(){if(this.renderMode!==this._activeRenderMode)switch(this.renderMode){case 0:case 1:let e=this.context.mainCameraComponent;if(!e)return;let t=this.gameObject;e.gameObject?.add(t);let n=e.farClipPlane;t.position.x=0,t.position.y=0,t.position.z=-n;let r=Math.tan(Q.toRadians(e.fieldOfView)*n)*(e.aspect*1.333333),s=r*(this.context.domHeight/this.context.domWidth);t.scale.x=-r,t.scale.y=s;break;case 2:break}}},Je=fd;k([A()],Je.prototype,"renderOnTop",1),k([A()],Je.prototype,"depthWrite",1),k([A()],Je.prototype,"doubleSided",1),k([A()],Je.prototype,"castShadows",1),k([A()],Je.prototype,"receiveShadows",1),k([A()],Je.prototype,"renderMode",1),k([A(Je)],Je.prototype,"rootCanvas",1);var sn=class extends M{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}_alpha=1;interactable=!0;blocksRaycasts=!0;_isDirty=!1;markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),3))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){for(let e of O.getComponentsInChildren(this.gameObject,Rt,this._buffer)){let t=e.color;t.alpha=this._alpha,e.color=t}}};k([A()],sn.prototype,"alpha",1),k([A()],sn.prototype,"interactable",2),k([A()],sn.prototype,"blocksRaycasts",2);import*as Qp from"three-mesh-ui";import{Color as B}from"three";var By=N("debugtext");var Le=class extends Rt{canvas;alignment=0;verticalOverflow=0;horizontalOverflow=0;lineSpacing=1;supportRichText=!1;font;fontStyle=0;get text(){return this._text}set text(e){if(this._text=e,!this._textMeshUi&&this._text.length>0&&this.context.time.frame>0&&this.createText(e,this.getTextOpts(),this.supportRichText),this._textMeshUi){if(this._textMeshUi.length>1){this.requestRebuild();return}this._textMeshUi[0].set({content:e}),this.markDirty()}}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){if(this._fontSize=e,this._textMeshUi){if(this._textMeshUi.length>1){this.requestRebuild();return}this._textMeshUi[0].set({content:e}),this.markDirty()}}onColorChanged(){if(this._textMeshUi){if(this._textMeshUi.length>1){this.requestRebuild();return}let e=this.color;this._textMeshUi[0].set({fontColor:e,fontOpacity:e.alpha}),this.markDirty()}}_isWaitingForRebuild=!1;requestRebuild(){this._isWaitingForRebuild||(this._isWaitingForRebuild=!0,this.startCoroutine(this.rebuildDelayedRoutine(),0))}*rebuildDelayedRoutine(){if(this._isWaitingForRebuild=!1,this._textMeshUi){for(let e of this._textMeshUi)e.removeFromParent();this._textMeshUi.length=0}this.createText(this.text,this.getTextOpts(),this.supportRichText),this.markDirty()}onCreate(e){By&&console.log(this);let t=this.verticalOverflow==0&&this.horizontalOverflow==0;t&&(this.context.renderer.localClippingEnabled=!0);let i=this.rectTransform;this._textContainer=this.uiObject=this.createBlock(i,t,null,!0),this.createText(this.text,this.getTextOpts(),this.supportRichText),this.uiObject,this.uiObject=this.createBlock(i,t,this.uiObject,!1)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}_text="";_fontSize=12;_textMeshUi=null;_textContainer=null;getTextOpts(){let e={content:this.text,fontColor:this.color,fontOpacity:this.color.alpha,fontSize:this.fontSize,fontKerning:"normal"};return this.font=this.font?.toLocaleLowerCase(),this.setFont(e,this.fontStyle),e}onEnable(){super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&(this.uiObject.onAfterUpdate=this.updateWidth.bind(this))}createBlock(e,t,i,n=!1){let r={};r.hiddenOverflow=t,r.interLine=(this.lineSpacing-1)*this.fontSize*1.333,this.getAlignment(r,n);let s=e.createNewBlock(r);return i&&(Array.isArray(i)?s.add(...i):s.add(i)),s}getAlignment(e,t=!1){switch(t||(e.contentDirection="row"),this.alignment){default:case 0:case 1:case 2:e.justifyContent="start";break;case 3:case 4:case 5:e.justifyContent="center";break;case 6:case 7:case 8:e.justifyContent="end";break}switch(this.alignment){case 0:case 3:case 6:e.alignContent=t?"left":"top";break;case 1:case 4:case 7:e.alignContent="center";break;case 2:case 5:case 8:e.alignContent=t?"right":"bottom";break}return e}updateWidth(){this.horizontalOverflow===1&&setTimeout(()=>{if(!this._textMeshUi)return;let e=this._textMeshUi[0].parent;if(!!e&&e.lines){let t=e.lines.reduce((i,n)=>i+n.width,0);t+=e.getFontSize()*5,t+=e.padding*2||0,t+=this.fontSize*1.5,e.set({width:t}),this.ensureShadowComponentOwner()}},1)}ensureShadowComponentOwner(){this.shadowComponent&&this.shadowComponent.traverse(e=>{e.shadowComponentOwner===void 0&&(e.shadowComponentOwner=this)})}createText(e,t,i){if(!(!e||e.length<=0))if(this._textMeshUi||(this._textMeshUi=[]),i){let n=this.getNextTag(e);if(n)n.startIndex>0&&this.createText(e.substring(0,n.startIndex),t,!1);else return this.createText(e,t,!1);let r=[];for(;n;){let s=this.getNextTag(e,n.endIndex);if(s){let o=this.getText(e,n,s);this.handleTag(n,t,r),this.createText(o,t,!1)}else{let o=e.substring(n.endIndex);this.handleTag(n,t,r),this.createText(o,t,!1)}n=s}}else{let n={...t};n.content=e;let r=new Qp.Text(n);this._textMeshUi.push(r),this._textContainer&&this._textContainer.add(r)}}_didHandleTextRenderOnTop=!1;handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;let e=[],t=this.canvas,i={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let n=!1;if(this._textMeshUi)for(let r=0;r<this._textMeshUi.length;r++){if(e[r]===!0)continue;n=!0;let s=this._textMeshUi[r];!s.textContent||(Ur(s,i),e[r]=!0)}if(!n)break;yield}}handleTag(e,t,i){if(e.isEndTag){if(i.length>0){let n=i.pop();if(n)for(let r in n.previousValues){let s=n.previousValues[r];t[r]=s}}}else if(e.type.includes("color")){let n=new Eo(e,{fontColor:t.fontColor});if(i.push(n),e.type.length>6){let r=e.type.substring(6);t.fontColor=Fy(r)}else t.fontColor=new B(1,1,1)}else if(e.type=="b"){let n=new Eo(e,{fontFamily:t.fontFamily,fontTexture:t.fontTexture});i.push(n),this.setFont(t,1)}else if(e.type=="i"){let n=new Eo(e,{fontFamily:t.fontFamily,fontTexture:t.fontTexture});i.push(n),this.setFont(t,2)}}getText(e,t,i){return e.substring(t.endIndex,i.startIndex)}getNextTag(e,t=0){let i=e.indexOf("<",t),n=e.indexOf(">",i);if(i>=0&&n>=0){let r=e.substring(i+1,n);return{type:r,startIndex:i,endIndex:n+1,isEndTag:r.startsWith("/")}}return null}setFont(e,t){let i=this.getFontName(t),n=i;n?.endsWith("-msdf.json")||(n+="-msdf.json"),e.fontFamily=n;let r=i;r?.endsWith(".png")||(r+=".png"),e.fontTexture=r}getFontName(e){return this.font?this.font:null}};k([A(Je)],Le.prototype,"canvas",2),k([A()],Le.prototype,"alignment",2),k([A()],Le.prototype,"verticalOverflow",2),k([A()],Le.prototype,"horizontalOverflow",2),k([A()],Le.prototype,"lineSpacing",2),k([A()],Le.prototype,"supportRichText",2),k([A()],Le.prototype,"font",2),k([A()],Le.prototype,"fontStyle",2),k([A()],Le.prototype,"text",1),k([A()],Le.prototype,"fontSize",1);var Eo=class{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}};function Fy(l){if(l.startsWith("#")){let t=l.substring(1);var e=parseInt(t,16);let i=e>>16&255,n=e>>8&255,r=e&255;return new B(i/255,n/255,r/255)}switch(l){case"black":return new B(0,0,0);case"white":return new B(1,1,1);case"red":return new B(1,0,0);case"lime":return new B(0,1,0);case"blue":return new B(0,0,1);case"yellow":return new B(1,1,0);case"cyan":return new B(0,1,1);case"magenta":return new B(1,0,1);case"silver":return new B(.75,.75,.75);case"gray":return new B(.5,.5,.5);case"maroon":return new B(.5,0,0);case"olive":return new B(.5,.5,0);case"green":return new B(0,.5,0);case"purple":return new B(.5,0,.5);case"teal":return new B(0,.5,.5);case"navy":return new B(0,0,.5);case"darkred":return new B(.54,0,0);case"brown":return new B(.55,.27,0);case"firebrick":return new B(.69,.13,.13);case"crimson":return new B(.86,.08,.24);case"tomato":return new B(1,.39,.28);case"coral":return new B(1,.49,.31);case"indianred":return new B(.6,.31,.51);case"lightcoral":return new B(.94,.5,.5);case"darkorange":return new B(1,.55,0);case"orange":return new B(1,.65,0);case"gold":return new B(1,.84,0);case"darkgoldenrod":return new B(.72,.53,.04);case"goldenrod":return new B(.85,.65,.13);case"palegoldenrod":return new B(.93,.87,.67);case"darkkhaki":return new B(.74,.7,.42);case"khaki":return new B(.94,.9,.55);case"yellowgreen":return new B(.6,.8,.19);case"darkolivegreen":return new B(.33,.42,.18);case"olivedrab":return new B(.42,.56,.14);case"lawngreen":return new B(.49,.99,0);case"chartreuse":return new B(.5,1,0);case"greenyellow":return new B(.68,1,.18);case"darkgreen":return new B(0,.39,0);case"forestgreen":return new B(.13,.55,.13);case"limegreen":return new B(.19,.8,.19);case"lightgreen":return new B(.56,.93,.56);case"palegreen":return new B(.59,.98,.59);case"darkseagreen":return new B(.56,.74,.56);case"mediumspringgreen":return new B(0,.98,.6);case"springgreen":return new B(0,1,.5);case"seagreen":return new B(.18,.31,.31);case"mediumaquamarine":return new B(.4,.8,.66);case"mediumseagreen":return new B(.24,.7,.44);case"lightseagreen":return new B(.13,.7,.67);case"darkslategray":return new B(.18,.31,.31);case"darkcyan":return new B(0,.55,.55);case"aqua":return new B(0,1,1);case"lightcyan":return new B(.8,1,1);case"darkturquoise":return new B(0,.81,.82);case"turquoise":return new B(0,.82,.82);case"mediumturquoise":return new B(.28,.82,.8);case"paleturquoise":return new B(.68,1,.93);case"aquamarine":return new B(.5,1,.83);case"powderblue":return new B(.69,.88,.9);case"cadetblue":return new B(.37,.62,.63);case"steelblue":return new B(.27,.51,.71);case"cornflowerblue":return new B(.39,.58,.93);case"deepskyblue":return new B(0,.7,1);case"dodgerblue":return new B(.12,.56,1);case"lightblue":return new B(.68,.85,.9);case"skyblue":return new B(.53,.81,.92);case"lightskyblue":return new B(.53,.81,.98);case"midnightblue":return new B(.18,.18,.31);case"darkblue":return new B(0,0,.55);case"mediumblue":return new B(0,0,.82);case"royalblue":return new B(.25,.41,.88);case"blueviolet":return new B(.54,.17,.89);case"indigo":return new B(.29,0,.51);case"darkslateblue":return new B(.28,.24,.55);case"slateblue":return new B(.42,.35,.8);case"mediumslateblue":return new B(.48,.41,.9);case"mediumpurple":return new B(.58,.44,.86);case"darkmagenta":return new B(.55,0,.55);case"darkviolet":return new B(.58,0,.83);case"darkorchid":return new B(.6,.2,.8);case"mediumorchid":return new B(.73,.33,.83);case"thistle":return new B(.84,.75,.85);case"plum":return new B(.87,.63,.87);case"violet":return new B(.93,.51,.93);case"fuchsia":return new B(1,0,1);case"orchid":return new B(.85,.44,.84);case"mediumvioletred":return new B(.78,.08,.52);case"palevioletred":return new B(.86,.44,.58);case"hotpink":return new B(1,.4,.71);case"deeppink":return new B(1,.08,.58);case"lightpink":return new B(1,.71,.76);case"pink":return new B(1,.75,.78);case"antiquewhite":return new B(.98,.92,.84);case"beige":return new B(.96,.96,.86);case"bisque":return new B(1,.89,.77);case"blanchedalmond":return new B(1,.92,.82);case"wheat":return new B(.96,.87,.87);case"cornsilk":return new B(1,.97,.86);case"lemonchiffon":return new B(1,.98,.8);case"lightgoldenrodyellow":return new B(.98,.98,.82);case"lightyellow":return new B(1,1,.8);case"saddlebrown":return new B(.55,.27,.07);case"sienna":return new B(.63,.32,.18);case"chocolate":return new B(.82,.41,.12);case"peru":return new B(.82,.52,.25);case"sandybrown":return new B(.96,.64,.38);case"burlywood":return new B(.87,.72,.53);case"tan":return new B(.82,.71,.55);case"rosybrown":return new B(.74,.56,.56);case"moccasin":return new B(1,.89,.71);case"navajowhite":return new B(1,.87,.68);case"peachpuff":return new B(1,.85,.73);case"mistyrose":return new B(1,.89,.88);case"lavenderblush":return new B(1,.94,.93);case"linen":return new B(.98,.94,.9);case"oldlace":return new B(.99,.96,.9);case"papayawhip":return new B(1,.94,.84);case"seashell":return new B(1,.96,.93);case"mintcream":return new B(.98,1,.98);case"slategray":return new B(.44,.5,.56);case"lightslategray":return new B(.47,.53,.6);case"lightsteelblue":return new B(.69,.77,.87);case"lavender":return new B(.9,.9,.98);case"floralwhite":return new B(1,.98,.98);case"aliceblue":return new B(.94,.97,1);case"ghostwhite":return new B(.97,.97,1);case"honeydew":return new B(.94,1,.94);case"ivory":return new B(1,1,.94);case"azure":return new B(.94,1,1);case"snow":return new B(1,.98,.98);case"dimgray":return new B(.4,.4,.4);case"darkgray":return new B(.66,.66,.66);case"lightgray":return new B(.83,.83,.83);case"gainsboro":return new B(.86,.86,.86);case"whitesmoke":return new B(.96,.96,.96)}return new B(1,1,1)}var Er=N("debuginputfield"),Y=class extends M{get text(){return this.textComponent?.text??""}get isFocused(){return Y.active===this}textComponent;placeholder;onValueChanged;onEndEdit;inputEventFn;start(){Er&&console.log(this.name,this)}onEnable(){Y.htmlField||(Y.htmlField=document.createElement("input"),Y.htmlField.classList.add("ar"),document.body.appendChild(Y.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),Y.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&O.setActive(this.placeholder.gameObject,!1)}onDisable(){Y.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected()}onPointerClick(e){Er&&console.log("CLICK",e,Y.active),Y.activeTime=this.context.time.time,Y.active!==this&&this.startCoroutine(this.activeLoop(),2),this.selectInputField()}*activeLoop(){for(this.onSelected();Y.active===this&&!(this.context.input.getPointerUp(0)&&this.context.time.time-Y.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(Y.active!==this&&(Er&&console.log("Select",this.name,this,Y.htmlField,this.context.isInXR,this.context.AROverlayElement,this.textComponent?.text,Y.htmlField?.value),Y.active?.onDeselected(),Y.active=this,this.placeholder&&O.setActive(this.placeholder.gameObject,!1),Y.htmlField)){if(Y.htmlField.value=this.textComponent?.text||"",Er&&console.log("set input field value",Y.htmlField.value),this.context.isInXR){let e=this.context.AROverlayElement;e&&(Y.htmlField.style.width="0px",Y.htmlField.style.height="0px",e.append(Y.htmlField))}this.selectInputField()}}onDeselected(){Y.active===this&&(Y.active=null,Er&&console.log("Deselect",this.name,this),Y.htmlField&&(Y.htmlField.blur(),document.body.append(Y.htmlField),Y.htmlField.style.width="",Y.htmlField.style.height=""),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&O.setActive(this.placeholder.gameObject,!0),this.onEndEdit?.invoke())}onInput(e){if(Y.active===this){if(Er&&console.log(e.code,e,Y.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}Y.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&O.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&Y.htmlField){if(this.textComponent.text!==Y.htmlField.value){Er&&console.log("VALUE CHANGED");let e=this.textComponent.text,t=Y.htmlField.value;this.onValueChanged?.invoke(t,e)}this.textComponent.text=Y.htmlField.value}}selectInputField(){Y.htmlField&&(Y.htmlField.setSelectionRange(Y.htmlField.value.length,Y.htmlField.value.length),Y.htmlField.focus())}},Ct=Y;z(Ct,"active",null),z(Ct,"activeTime",-1),z(Ct,"htmlField",null),k([A(Le)],Ct.prototype,"textComponent",2),k([A(Le)],Ct.prototype,"placeholder",2),k([A(Oe)],Ct.prototype,"onValueChanged",2),k([A(Oe)],Ct.prototype,"onEndEdit",2);import*as Yp from"three-mesh-ui";import*as wo from"three";var Zp=(o=>(o[o.fr=0]="fr",o[o.ru=1]="ru",o[o.de=2]="de",o[o.es=3]="es",o[o.el=4]="el",o[o.nord=5]="nord",o[o.eng=6]="eng",o))(Zp||{}),ks=class extends Ue{font;text;keymap;padding;margin;fontSize;borderRadius;colors={keyboardBack:8750469,panelBack:2500134,button:3552822,hovered:1842204,selected:1088605};awake(){super.awake();let e=Zp[this.keymap||6];this.makeKeyboard(e)}onEnable(){this.addShadowComponent(this.keyboard)}onDisable(){this.removeShadowComponent()}keyboard=null;_lastKeyPressed;_lastKeyPressedStartTime=0;_lastKeyPressedTime=0;makeKeyboard(e){!e&&!navigator.language&&(e="en");let t=this.font?this.font:"arial",i=this.gameObject.getComponent(ut);if(!i){console.error("Missing rect transform, please add this component inside a canvas");return}let n={...i.getBasicOptions(),margin:this.margin||0,padding:this.padding||0,language:e,fontFamily:Ps+"/"+t+"-msdf.json",fontTexture:Ps+"/"+t+".png",fontSize:this.fontSize||6,backgroundColor:new wo.Color(this.colors.keyboardBack),backspaceTexture:Ps+"/backspace.png",shiftTexture:Ps+"/shift.png",enterTexture:Ps+"/enter.png",borderRadius:this.borderRadius||0,autoLayout:!1},r=this.gameObject.scale;n.width*=this.gameObject.scale.x,n.height*=this.gameObject.scale.y,n.fontSize*=Math.max(r.x,r.y),this.keyboard=new Yp.Keyboard(n),this.gameObject.scale.set(1,1,1),this.keyboard.keys.forEach(s=>{s.setupState({state:"normal",attributes:{offset:.003,backgroundColor:new wo.Color(this.colors.button),backgroundOpacity:1}}),s.setState("normal"),s.setupState({state:"hovered",attributes:{offset:.3,backgroundColor:new wo.Color(this.colors.hovered),backgroundOpacity:1}}),s.setupState({state:"pressed",attributes:{offset:.1,backgroundColor:new wo.Color(this.colors.selected),backgroundOpacity:1},onSet:()=>{let o=s.info.input,c=s.info.command;if(this._lastKeyPressed!==o)this._lastKeyPressedStartTime=this.context.time.time;else if(this.context.time.time-this._lastKeyPressedTime>.05)this._lastKeyPressedStartTime=this.context.time.time;else if(this.context.time.time-this._lastKeyPressedStartTime<.5||c=="switch"||c=="shift"||c=="switch-set"){this._lastKeyPressedTime=this.context.time.time;return}if(this._lastKeyPressedTime=this.context.time.time,this._lastKeyPressed=o,c)switch(c){case"switch":this.keyboard.setNextPanel();break;case"switch-set":this.keyboard.setNextCharset();break;case"enter":this.tryAppend(`
135
- `);break;case"space":this.tryAppend(" ");break;case"backspace":if(!this.text?.text?.length)break;this.text?.text&&(this.text.text=this.text.text.substring(0,this.text.text.length-1)||"");break;case"shift":this.keyboard.toggleCase();break}else s.info.input!==void 0&&this.tryAppend(s.info.input)}})})}tryAppend(e){this.text&&(this.text.text+=e,this.markDirty())}};var on=class extends M{reverseArrangement=!1},Is=class extends on{},Ms=class extends on{},Ls=class extends on{};var wr=class extends M{awake(){Ze.createIfNoneExists(this.context)}onEnable(){Ze.instance?.register(this)}onDisable(){Ze.instance?.unregister(this)}performRaycast(e=null){return null}},Ri=class extends wr{targets=null;raycastHits=[];start(){this.targets=[this.gameObject]}performRaycast(e=null){return this.targets?(e??=new je,e.targets=this.targets,e.results=this.raycastHits,this.context.physics.raycast(e)):null}},Ds=class extends Ri{eventCamera=null;ignoreReversedGraphics=!1;rootRaycaster=null};import*as Jp from"three";import{HTMLMesh as Ny}from"three/examples/jsm/interactive/HTMLMesh.js";import{InteractiveGroup as zy}from"three/examples/jsm/interactive/InteractiveGroup.js";var Hs=class extends M{id=null;keepAspect=!1;start(){if(!this.id||!this.context.mainCamera)return;let e=document.getElementById(this.id);if(!e){console.warn('Could not find element with id "'+this.id+'"');return}e.style.display="block",e.style.visibility="hidden";let t=new zy(this.context.renderer,this.context.mainCamera);this.gameObject.add(t);let i=new Ny(e);t.add(i),i.visible=!1,console.log(i);let n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;let r=jo(this.gameObject).clone();Bo(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();let s=new Jp.Box3;s.setFromObject(t),this.setWorldRotation(r.x,r.y,r.z);let o=s.max.x-s.min.x,c=s.max.y-s.min.y;if(this.keepAspect){let a=o/c;o>c?i.scale.set(1/o,1/c/a,1):i.scale.set(1/o*a,1/c,1)}else i.scale.set(1/o,1/c,1);let d=this.gameObject.scale;i.scale.multiply(d)},1)}};var Ja=class extends M{toggleKey=80;update(){this.context.input.isKeyDown(80)&&this.context.domElement.classList.toggle("presentation-mode")}};import*as $p from"three";import{Raycaster as Wy,Vector3 as Uy}from"three";import*as $a from"three";import{MeshLine as Gy,MeshLineMaterial as Vy}from"three.meshline";var md=class{id=0;points=[];line=new Gy;material;mesh;constructor(e,t){if(t&&(this.material=t.material),this.material||(this.material=this.defaultLineMaterial),t){let i=t.options;i&&Object.assign(this.material,i)}this.mesh=new $a.Mesh(this.line,this.material),e.add(this.mesh)}appendPoint(e){let t=md.wp;t.set(e.x,e.y,e.z);let i=this.mesh?.parent;return i&&(t=i.worldToLocal(t),e.x=t.x,e.y=t.y,e.z=t.z),this.points.push(e.x,e.y,e.z),this.line.setPoints(this.points),e}defaultLineMaterial=new Vy({color:10066329,lineWidth:.01})},js=md;z(js,"wp",new $a.Vector3);var _r=class extends M{startLine(e,t){let i=Math.random()*Number.MAX_SAFE_INTEGER;return this.internalStartLine(e,i,!0,t)}updateLine(e,t){let i=this.inFlight[e.id];if(!i)return;t.point&&(t.point=i.appendPoint(t.point));let n=this.buffer[e.id];n&&(t.point&&n.push(t.point.x,t.point.y,t.point.z),n.length>5&&(this.sendLineUpdate(i,!1,void 0,n),n.length=0))}endLine(e,t=!0){let i=this.inFlight[e.id];if(!i)return;this.finished.push(i),delete this.inFlight[e.id],t&&this.sendLineUpdate(i,!0,0);let n=this.buffer[e.id];if(n){delete this.buffer[e.id];let r=n;r.length=0,this.freeBuffer.push(r)}return i}getLine(e){return this.inFlight[e.id]}finished=[];inFlight=[];buffer={};freeBuffer=new Array;awake(){this.context.connection.beginListen("line-start",e=>{this.onEnsureLine(e.id,e.parentGuid)}),this.context.connection.beginListen("line-update",e=>{let t=this.onEnsureLine(e.guid,e.parentGuid);t&&e.points&&(e.startIndex<=0?t.points=e.points:e.startIndex>=t.points.length&&t.points.push(...e.points),t.line.setPoints(t.points),t.material.lineWidth=e.width,t.material.color.fromArray(e.color),e.finished===!0&&this.endLine({id:t.id},!1))})}onEnsureLine(e,t){if(this.inFlight[e])return this.inFlight[e];let i=O.findByGuid(t,this.context.scene);if(!!i)return this.internalStartLine(i,e,!1),this.inFlight[e]}internalStartLine(e,t,i=!0,n){let r=new js(e??this.context.scene,n);r.id=t,this.inFlight[t]=r,i&&this.sendLineStart(r);let s;return this.freeBuffer.length<=0?s=new Array:s=this.freeBuffer.pop(),this.buffer[t]=s,{id:t}}sendLineStart(e){let t=e.mesh.parent;this.context.connection.send("line-start",{id:e.id,parentGuid:t?t.guid:void 0})}sendLineUpdate(e,t,i,n){if(e){let r={parentGuid:e.mesh.parent.guid,guid:e.id,points:n?[...n]:e.points,width:e.material.lineWidth,color:e.material.color.toArray(),startIndex:i!==void 0?i:e.points.length,finished:t};this.context.connection.send("line-update",r)}}};import{MeshLineMaterial as qy}from"three.meshline";var Ka=class{isDrawing;lastHit;currentHandle;maxDistance;prevDistance;lastParent;constructor(){this.isDrawing=!1,this.lastHit=new Uy,this.currentHandle=null,this.maxDistance=0,this.prevDistance=0,this.lastParent=null}},el=class extends M{lines;colliders;alignToSurface=!0;addToPaintedObject=!0;orbit;start(){this.lines||(this.lines=O.getComponent(this.gameObject,_r),this.lines||(this.lines=O.addNewComponent(this.gameObject,_r))),this.orbit=O.findObjectOfType(gt,this.context)??void 0,this._states.mouse=new Ka;let e={};oe.addEventListener("select-start",(t,i)=>{e[t.controller.uuid]=!0}),oe.addEventListener("update",(t,i)=>{if(e[t.controller.uuid]===!0){let n=t.getRay();this.updateLine(t.controller.uuid,n,!0,!1,!1)}}),oe.addEventListener("select-end",(t,i)=>{e[t.controller.uuid]=!1;let n=t.getRay();this.updateLine(t.controller.uuid,n,!0,!0,!1)})}_states={};update(){this.orbit&&this._states.mouse&&this.orbit&&(this.orbit.enabled=!this._states.mouse.isDrawing);let e=this.context.input.getPointerPressedCount()>1,t=this.context.input.getPointerPositionRC(0);el._raycaster.setFromCamera(t,this.context.mainCamera);let i=el._raycaster.ray;this.updateLine("mouse",i,this.context.input.getPointerPressed(0),this.context.input.getPointerUp(0),e||this.context.input.isKeyPressed(18))}updateLine(e,t,i,n,r=!1){let s=this._states[e];if(s||(this._states[e]=new Ka,s=this._states[e]),n)s.isDrawing=!1,s.currentHandle&&(this.lines.endLine(s.currentHandle),s.currentHandle=null);else if(i){if(r)return s;let o=this.getHit(t),c=null,d=s.prevDistance;if(o)s.currentHandle||(s.maxDistance=o.distance),c=o.point,c.add(o.face.normal.multiplyScalar(.01)),s.prevDistance=o.distance;else if(s.maxDistance>0){let a=s.maxDistance;if(!s.currentHandle&&s.lastHit){let h=q(this.context.mainCamera);a=s.lastHit.distanceTo(h)}c=t.origin.add(t.direction.multiplyScalar(s.maxDistance)),s.prevDistance=s.maxDistance}if(c){if(!s.currentHandle){let a=s.lastParent??this.gameObject;this.addToPaintedObject&&o&&(a=o.object),s.lastParent=a,s.currentHandle=this.lines.startLine(a,{material:this.createRandomMaterial()})}if(this.alignToSurface&&(s.prevDistance>s.maxDistance||Math.abs(d-s.prevDistance)>.2)){let a=s.maxDistance;c=t.origin.add(t.direction.multiplyScalar(a)),s.prevDistance=a}if(s.lastHit&&s.lastHit.distanceTo(c)<s.prevDistance*.01)return s;this.lines.updateLine(s.currentHandle,{point:c}),s.lastHit.copy(c)}s.isDrawing=s.currentHandle!==null}return s}_raycastOptions=new je;getHit(e){(!this.colliders||this.colliders.length===0)&&(this.colliders=[this.gameObject]),this._raycastOptions.targets=this.colliders,this._raycastOptions.ray=e;let t=this.context.physics.raycast(this._raycastOptions);if(t.length>0){for(let i of t)if(!!O.isActiveInHierarchy(i.object))return i}return null}createRandomMaterial(){let e;return this.context.connection.connectionId?e=ht.colorFromHashCode(ht.hashCode(this.context.connection.connectionId)):e=new $p.Color("hsl("+(Math.random()*100).toFixed(0)+", 80%, 30%)"),new qy({color:e,lineWidth:Q.lerp(.005,.01,Math.random())})}},_o=el;z(_o,"_raycaster",new Wy);import{Object3D as Xy}from"three";var xo=class extends M{asset;joinedRoomFunction;awake(){this.watchTabVisible(),this.joinedRoomFunction=this.onUserJoined.bind(this)}onEnable(){this.context.connection.beginListen("joined-room",this.joinedRoomFunction)}onDisable(){this.context.connection.stopListening("joined-room",this.joinedRoomFunction)}async onUserJoined(e){let t=await this.asset?.instantiateSynced({parent:this.gameObject},!0);if(t){let i=O.getComponent(t,Ci);i&&(i.owner=this.context.connection.connectionId)}}watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=Ci.all.length-1;t>=0;t--){let i=Ci.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};k([A(tt)],xo.prototype,"asset",2);var Nt=class extends M{static get all(){return Nt._all}static get local(){return Nt._local}static isLocalPlayer(e){return e instanceof Xy?O.getComponentInParent(e,Nt)?.isLocalPlayer??!1:e instanceof st?O.getComponentInParent(e.gameObject,Nt)?.isLocalPlayer??!1:!1}owner;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}awake(){this.isLocalPlayer&&Nt.local.push(this),Nt.all.push(this),this.context.connection.beginListen("user-left-room",e=>{if(e.userId===this.owner){this.doDestroy();return}})}start(){if(!this.owner||!this.context.connection.userIsInRoom(this.owner)){this.doDestroy();return}}doDestroy(){Sr(this.gameObject,this.context.connection)}onDestroy(){if(Nt.all.splice(Nt.all.indexOf(this),1),this.isLocalPlayer){let e=Nt._local.indexOf(this);e>=0&&Nt._local.splice(e,1)}}},Ci=Nt;z(Ci,"_all",[]),z(Ci,"_local",[]),k([Ga(),A()],Ci.prototype,"owner",2);D.add("AlignmentConstraint",zr);D.add("Animation",Zt);D.add("AnimationCurve",ir);D.add("Animator",bt);D.add("AnimatorController",Yt);D.add("AudioListener",Jt);D.add("AudioSource",ue);D.add("AvatarModel",nr);D.add("AvatarLoader",Fi);D.add("AxesHelper",Ni);D.add("BasicIKConstraint",Wr);D.add("BoxHelperComponent",lt);D.add("Camera",ne);D.add("Collider",pi);D.add("SphereCollider",En);D.add("BoxCollider",wn);D.add("InstantiateOptions",ye);D.add("UnityObject",Qr);D.add("DeleteBox",rr);D.add("Deletable",Yr);D.add("DeviceFlag",sr);D.add("DragControls",Et);D.add("DropListener",Cn);D.add("Duplicatable",bi);D.add("CallInfo",vi);D.add("EventListEvent",cr);D.add("EventList",Oe);D.add("EventTrigger",ns);D.add("FlyControls",rs);D.add("BoxGizmo",qi);D.add("GltfExportBox",os);D.add("GltfExport",jt);D.add("GridHelper",Xi);D.add("GroundProjectedEnv",Qi);D.add("Interactable",kt);D.add("UsageMarker",It);D.add("Light",Ye);D.add("LODModel",yi);D.add("LODGroup",Pn);D.add("LookAtConstraint",ji);D.add("MeshCollider",ls);D.add("NavMesh",cs);D.add("NavMeshAgent",ds);D.add("NestedGltf",dr);D.add("Networking",pt);D.add("OffsetConstraint",hs);D.add("OrbitControls",gt);D.add("ParticleSystemRenderer",hr);D.add("ParticleSystem",gs);D.add("MainModule",ps);D.add("EmissionModule",fs);D.add("ShapeModule",ms);D.add("PlayerColor",ht);D.add("FieldWithDefault",Ir);D.add("Renderer",Te);D.add("MeshRenderer",er);D.add("SkinnedMeshRenderer",Mr);D.add("InstancingUtil",he);D.add("RendererLightmap",Di);D.add("Rigidbody",ce);D.add("ScreenCapture",bs);D.add("ShadowCatcher",On);D.add("RemoteSkybox",An);D.add("SmoothFollow",Ei);D.add("SpatialTriggerReceiver",wt);D.add("SpatialTrigger",Yi);D.add("SpectatorCamera",ys);D.add("SpringJoint",Es);D.add("Sprite",ur);D.add("SpriteRenderer",Zi);D.add("SyncedCamera",kn);D.add("SyncedRoom",ei);D.add("SyncedTransform",Qe);D.add("TestRunner",ws);D.add("TestSimulateUserData",_s);D.add("TransformGizmo",pr);D.add("VideoPlayer",nt);D.add("Voip",Ke);D.add("VolumeParameter",xs);D.add("VolumeComponent",wi);D.add("ToneMapping",Mn);D.add("ColorAdjustments",Ln);D.add("VolumeProfile",In);D.add("Volume",fr);D.add("WebARSessionRoot",Dt);D.add("WebXR",$);D.add("WebAR",Rn);D.add("AvatarMarker",fe);D.add("WebXRAvatar",Lt);D.add("TeleportTarget",or);D.add("WebXRController",oe);D.add("AttachedObject",dt);D.add("XRGrabModel",mr);D.add("XRGrabRendering",Ts);D.add("XRRig",Tn);D.add("VRUserState",Ht);D.add("WebXRSync",Ui);D.add("XRState",vt);D.add("XRFlag",Se);D.add("AvatarBlink_Simple",_i);D.add("AvatarEyeLook_Rotation",xi);D.add("Avatar_POI",_e);D.add("Avatar_Brain_LookAt",Wi);D.add("Avatar_MouthShapes",Dn);D.add("Avatar_MustacheShake",Rs);D.add("LogStats",Cs);D.add("RGBAColor",we);D.add("PlayableDirector",en);D.add("SignalAsset",gr);D.add("SignalReceiverEvent",br);D.add("SignalReceiver",Ji);D.add("AnimationTrackHandler",Hn);D.add("AudioTrackHandler",jn);D.add("SignalTrackHandler",Ki);D.add("ControlTrackHandler",$i);D.add("BaseUIComponent",Ue);D.add("UIRootComponent",tn);D.add("Button",Ft);D.add("Canvas",Je);D.add("CanvasGroup",sn);D.add("EventSystem",Ze);D.add("Graphic",Rt);D.add("MaskableGraphic",nn);D.add("Image",rn);D.add("RawImage",yr);D.add("InputField",Ct);D.add("Keyboard",ks);D.add("LayoutGroup",on);D.add("VerticalLayoutGroup",Is);D.add("HorizontalLayoutGroup",Ms);D.add("GridLayoutGroup",Ls);D.add("PointerEventData",ti);D.add("Raycaster",wr);D.add("ObjectRaycaster",Ri);D.add("GraphicRaycaster",Ds);D.add("Size",Os);D.add("Rect",vr);D.add("RectTransform",ut);D.add("SpatialHtml",Hs);D.add("Text",Le);D.add("PresentationMode",Ja);D.add("LinesDrawer",_o);D.add("LineInstanceHandler",js);D.add("LinesManager",_r);D.add("PlayerSync",xo);D.add("PlayerState",Ci);import*as Kp from"three";import{Color as Qy,Object3D as Yy}from"three";var bd=class extends Bi{constructor(){super([Qy,we])}onDeserialize(e){if(e!=null)return e.a!==void 0?new we(e.r,e.g,e.b,e.a):e.alpha!==void 0?new we(e.r,e.g,e.b,e.alpha):new Kp.Color(e.r,e.g,e.b)}onSerialize(e){if(e!=null)return e.a!==void 0?{r:e.r,g:e.g,b:e.b,a:e.a}:{r:e.r,g:e.g,b:e.b}}},Bj=new bd,vd=class extends Bi{constructor(){super(Yy)}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){let i=t.objectToNode[e.uuid];return Ie&&console.log(i,e.name,e.uuid),{node:i}}}onDeserialize(e,t){if(e){if(e.node!==void 0&&t.nodeToObject){let i=t.nodeToObject[e.node];return Ie&&console.log("Deserialized object reference?",e,i,t?.nodeToObject),i||console.warn("Did not find node: "+e.node,t.nodeToObject,t.object),i}else if(e.guid){if(!t.context){console.error("Missing context");return}let i,n=t.gltf?.scene;return n&&(i=O.findByGuid(e.guid,n)),i||(i=O.findByGuid(e.guid,t.context.scene)),i?Ie&&console.log("Deserialized object reference?",e,i,t?.nodeToObject):console.warn("could not resolve reference",e,t.target,t.path,t.context.scene),i}}}},Zy=new vd,yd=class extends Bi{constructor(){super([st,M])}onSerialize(e,t){if(e?.guid)return{guid:e.guid}}onDeserialize(e,t){if(e?.guid){Ie&&console.log(e.guid,t.root,t.object,t.target);let i=this.findObjectForGuid(e.guid,t.root);if(i)return i;if(t.context)return this.findObjectForGuid(e.guid,t.context?.scene)}}findObjectForGuid(e,t){return O.foreachComponent(t,i=>{if(e===i.gameObject.guid)return i.gameObject;if(i.guid===e)return i})}},gd=new yd,Ed=class extends Bi{constructor(){super([Oe])}onSerialize(e,t){console.log("TODO: SERIALIZE EVENT")}onDeserialize(e,t){if(e&&e.type==="EventList"){Ie&&console.log("DESERIALIZE EVENT",e);let i=new Array;for(let s of e.calls){Ie&&console.log(s);let o=gd.findObjectForGuid(s.target,t.root);!o&&t.context?.scene&&(o=gd.findObjectForGuid(s.target,t.context?.scene));let c=s.method?.length>0;if(o&&c){let u=()=>console.warn(`Could not find method ${s.method} on object ${o.name}`,o,typeof o[s.method]);if(typeof o[s.method]!="function"){let g=!1;s.method.startsWith("set_")&&s.method.length>4&&(s.method=s.method.substring(4),o[s.method]!==void 0&&(g=!0)),g||u()}}let d,a=s.argument;s.argument!==void 0?(typeof a=="object"&&(a=Zy.onDeserialize(s.argument,t),a||(a=gd.onDeserialize(s.argument,t))),d=new vi(c?(...u)=>h(...u):void 0,s.enabled)):d=new vi(c?(...u)=>h(...u):void 0,s.enabled);let h=(...u)=>{let g=o[s.method];typeof g=="function"?a!==void 0?g?.call(o,a):g?.call(o,...u):o[s.method]=a};if(d.method||(d.__debuginfo=t.object?.name),!o||!d.method){let u=t.object?"Current object: "+t.object.name+", "+t.object.guid:null;o?console.warn('EventList method not found: "'+s.method+'" on',o):console.warn("EventList is missing target - will be ignored",s.target,u,e)}else i.push(d)}let n=new Oe(i);Ie&&console.log(n);let r=t.target;return r!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,r),n}}},Fj=new Ed;var ef=Ie;function Tp(l,e){let i=Oc(l,e);return i!==void 0?i:null}async function Ca(l,e,t,i=null,n){if(!t)return;let r=[],s=i;typeof s=="number"&&(s=new We(i));let o=new Fr(t.scene);o.gltfId=e,o.context=l,o.gltf=t,o.nodeToObject=n?.nodeToObjectMap;let c=[];if(t.scenes)for(let d of t.scenes)await _d(o,d,c,r);if(t.children)for(let d of t.children)await _d(o,d,c,r);l.new_scripts_pre_setup_callbacks.push(()=>{for(let d of c)$y(d,o);if(s){wd(t,s);for(let d of t.scenes)wd(d,s)}})}function wd(l,e){if(e!==null&&!!l){if(l.guid=e.generateUUID(),l&&l.userData&&l.userData.components)for(let t of l.userData.components)t!==null&&(t.guid=e.generateUUID());if(l.children)for(let t of l.children)wd(t,e)}}var To=[];async function _d(l,e,t,i){if(!e)return;let n=e.userData;if(n){let r=n.builtin_components;if(r&&r.length>0)for(let s of r)try{if(s===null)continue;let o=D.get(s.name);if(o!=null){let c=new o;c.sourceId=l.gltfId,lo(c,s),ko(c,e,!1),t.push({instance:c,compData:s,obj:e})}else ef&&console.debug("unknown component: "+s.name),To.includes(s.name)||To.push(s.name)}catch(o){console.error(s.name+" - "+o.message,o)}if(To.length>0){let s=To.join(", ");console.warn("unknown components: "+s),To.length=0}}if(e.children)for(let r of e.children)await _d(l,r,t,i)}function $y(l,e){let{instance:t,compData:i,obj:n}=l;e.object=n,e.target=t;let r=!0;r=ao(t,i,e)===!0,ef&&console.debug("add "+i.name,i,t)}import*as me from"three";import*as tf from"three";var Ky=new tf.FileLoader;async function xd(l){return new Promise((e,t)=>{Ky.load(l,e,void 0,t)})}import{Vector4 as Bn,FileLoader as tE,DataTexture as Pd,RGBAFormat as iE,Color as nE}from"three";var Ro=new Uint8Array(4);Ro[0]=255;Ro[1]=255;Ro[2]=255;Ro[3]=255;var sf=new Pd(Ro,1,1,iE);function of(l,e=1){let t="alpha"in l,i=e*e,n=new Uint8Array(4*i),r=Math.floor(l.r*255),s=Math.floor(l.g*255),o=Math.floor(l.b*255);for(let d=0;d<i;d++){let a=d*4;n[a+0]=r,n[a+1]=s,n[a+2]=o,t?n[a+3]=Math.floor(l.alpha*255):n[a+3]=255}let c=new Pd(n,e,e);return c.needsUpdate=!0,c}function af(l,e,t,i=1,n=3){let o=i*n,c=[l,e,t],d=c.length,a=new Uint8Array(4*d*o),h=new nE;for(let g=0;g<n;g++){let E=Math.floor(g/n*d),b=Q.clamp(E+1,0,d-1),y=c[E],m=c[b],p=g/n*d%1;h.lerpColors(y,m,p);let f=Math.floor(h.r*255),v=Math.floor(h.g*255),w=Math.floor(h.b*255);for(let x=0;x<i;x++){let T=(g*i+x)*4;a[T+0]=f,a[T+1]=v,a[T+2]=w,a[T+3]=255}}let u=new Pd(a,i,n);return u.needsUpdate=!0,u}var Rd=class{stage;code;constructor(e,t){this.stage=e,this.code=t}},Cd=class{loaded=new Map;async loadShader(e){let t=await xd(e);return JSON.parse(t)}async load(e,t){if(this.loaded.has(t))return new Promise((r,s)=>{let o=this.loaded.get(t);o?r(o):s("Shader not found")});let i=await xd(t),n=new Rd(e,i);return this.loaded.set(t,n),n}},Kj=new Cd;function Co(l,e){let t=l.elements;e||(e=[]),e.length=0;for(let i=0;i<16;i+=4){let n=t[i],r=t[i+1],s=t[i+2],o=t[i+3],c=new Bn(n,r,s,o);e.push(c)}return e}var Td=[],nf=[];function Od(l,e){if(Td.length===0)for(let t=0;t<27;t++)Td.push(0);e||(e=Td);for(let t=0;t<27;t++)nf[t]=e[t];e=nf,l.unity_SHAr={value:new Bn(e[9],e[3],e[6],e[0])},l.unity_SHBr={value:new Bn(e[12],e[15],e[18],e[21])},l.unity_SHAg={value:new Bn(e[10],e[4],e[7],e[1])},l.unity_SHBg={value:new Bn(e[13],e[16],e[19],e[22])},l.unity_SHAb={value:new Bn(e[11],e[5],e[8],e[2])},l.unity_SHBb={value:new Bn(e[14],e[17],e[20],e[23])},l.unity_SHC={value:new Bn(e[24],e[25],e[26],1)}}var Sd=class{vertexShader;fragmentShader;technique;constructor(e,t,i){this.vertexShader=e,this.fragmentShader=t,this.technique=i}};async function lf(l,e){if(!l)return console.error("Can not find technique: no shader data"),null;let t=l.programs[e],i=t.vertexShader,n=t.fragmentShader;if(i!==void 0&&n!==void 0){let r=l.shaders[i],s=l.shaders[n];if(r.uri&&s.uri||r.code&&s.code){if(!r.code&&r.uri&&await rf(r),!s.code&&s.uri&&await rf(s),!r.code||!s.code)return null;let o=l.techniques[e];return new Sd(r.code,s.code,o)}}return console.error("Shader technique not found",e),null}async function rf(l){let e=l.uri;if(!!e)if(e.endsWith(".glsl")){let i=await new tE().loadAsync(e);l.code=i.toString()}else l.code=rE(l.uri)}function rE(l){return decodeURIComponent(Array.prototype.map.call(atob(l),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}import{RawShaderMaterial as oE}from"three";var an=N("debugshaders"),Bs="NEEDLE_techniques_webgl";var Ad=class{objectToWorldMatrix=new me.Matrix4;worldToObjectMatrix=new me.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),Co(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),Co(this.worldToObjectMatrix,this.worldToObject)}};var pe=class extends oE{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);constructor(e,...t){super(...t),this.identifier=e,an&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName]&&this.waitForLighting(),(this.depthTextureUniform||this.opaqueTextureUniform)&&Z.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();let e=Z.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&Z.Current.pre_render_callbacks.splice(e,1)}async waitForLighting(){let e=Z.Current;if(!e){console.error("Missing context");return}let t=await e.rendererData.getSceneLightingData(this.identifier);if(!t||!t.array){console.warn("Missing lighting data for custom shader, getSceneLightingData did not return anything");return}an&&console.log(t);let i=t.array,n=t.texture;this.uniforms.unity_SpecCube0={value:n},Od(this.uniforms,i);let r=Math.sqrt(Math.PI*.5);this.uniforms.unity_SpecCube0_HDR={value:new me.Vector4(r,r,r,r)},an&&console.log("Set environment lighting",this.uniforms)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";_rendererData=new Ad;get depthTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&Z.Current.setRequireColor(!0),this.depthTextureUniform&&Z.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,r,s){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,r)}onUpdateUniforms(e,t){let i=Z.Current;e&&(pe.viewProjection&&this.uniforms[this._viewProjectionName]&&(pe.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),Co(pe.viewProjection,pe._viewProjectionValues)),pe.viewMatrix&&this.uniforms[this._viewMatrixName]&&(pe.viewMatrix.copy(e.matrixWorldInverse),Co(pe.viewMatrix,pe._viewMatrixValues)),this.uniforms[pe._worldSpaceCameraPosName]&&pe._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=i.rendererData.timeVec4);let n=i?.mainLight;if(n){let o=n.getWorldPosition(pe._mainLightPosition);this.uniforms._MainLightPosition={value:o.normalize()},pe._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:pe._mainLightColor};let c=n.intensity;pe._lightData.z=c,this.uniforms.unity_LightData={value:pe._lightData}}if(e&&(pe.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=pe._viewProjectionValues),pe.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=pe._viewMatrixValues),this.uniforms[pe._worldSpaceCameraPosName]&&(this.uniforms[pe._worldSpaceCameraPosName]={value:pe._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){let o=this.uniforms._ProjectionParams.value;o.x=1,o.y=i.mainCameraComponent.nearClipPlane,o.z=i.mainCameraComponent.farClipPlane,o.w=1/o.z,this.uniforms._ProjectionParams.value=o}if(this.uniforms._ZBufferParams){let o=this.uniforms._ZBufferParams.value,c=i.mainCameraComponent;o.x=1-c.farClipPlane/c.nearClipPlane,o.y=c.farClipPlane/c.nearClipPlane,o.z=o.x/c.farClipPlane,o.w=o.y/c.farClipPlane,this.uniforms._ZBufferParams.value=o}if(this.uniforms._ScreenParams){let o=this.uniforms._ScreenParams.value;o.x=i.domWidth,o.y=i.domHeight,o.z=1+1/o.x,o.w=1+1/o.y,this.uniforms._ScreenParams.value=o}}let r=this.depthTextureUniform;r&&(r.value=i.depthTexture);let s=this.opaqueTextureUniform;if(s&&(s.value=i.opaqueColorTexture),t){let o=this._rendererData;o.updateFrom(t),this.uniforms[this._worldToObjectName].value=o.worldToObject,this.uniforms[this._objToWorldName].value=o.objectToWorld}this.uniformsNeedUpdate=!0}},zt=pe;z(zt,"viewProjection",new me.Matrix4),z(zt,"_viewProjectionValues",[]),z(zt,"viewMatrix",new me.Matrix4),z(zt,"_viewMatrixValues",[]),z(zt,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),z(zt,"_worldSpaceCameraPos",new me.Vector3),z(zt,"_mainLightColor",new me.Vector4),z(zt,"_mainLightPosition",new me.Vector3),z(zt,"_lightData",new me.Vector4);var tl=class{get name(){return Bs}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){let t=this.parser.json.materials[e];if(!t)return an&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Bs])return an&&console.log("material "+e+" does not use NEEDLE_techniques_webgl"),null;let i=t.extensions[Bs].technique;if(i<0)return null;let n=this.parser.json.extensions[Bs];if(!n)return null;an&&console.log(n);let r=n.techniques[i];return r?new Promise(async(s,o)=>{let c=await lf(n,r.program),d=c?.fragmentShader,a=c?.vertexShader;if(!d||!a)return o();an&&console.log("loadMaterial",t,c);let h={},u=r.uniforms;for(let y in u){let m=y;switch(m){case"_TimeParameters":let p=new me.Vector4;h[m]={value:p};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":h[m]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":h[m]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":h[m]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":h[m]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":h[m]={value:null};break}}let g=!1;if(t.extensions&&t.extensions[Bs]){let y=t.extensions[Bs];if(y.technique===i){an&&console.log(t.name,"Material Properties",y);for(let m in y.values){let p=y.values[m];if(typeof p=="string"){if(p.startsWith("textures/")){let f=p.substring(9),v=Number.parseInt(f);if(v>=0){let w=await this.parser.getDependency("texture",v);w&&(w.encoding=me.LinearEncoding,w.needsUpdate=!0),h[m]={value:w};continue}}switch(m){case"alphaMode":p==="BLEND"&&(g=!0);continue}}if(Array.isArray(p)&&p.length===4){h[m]={value:new me.Vector4(p[0],p[1],p[2],p[3])};continue}h[m]={value:p}}}}let E=new zt(this.identifier,{name:t.name??"",uniforms:h,vertexShader:a,fragmentShader:d,lights:!1});switch(h._Cull?.value){case 0:E.side=me.DoubleSide;break;case 1:E.side=me.BackSide;break;case 2:E.side=me.FrontSide;break;default:E.side=me.FrontSide;break}E.transparent=g,g&&(E.depthWrite=!1),Od(h),E.onUpdateUniforms();for(let y in u){let m=y,p=u[y].type;if(h[m]?.value===void 0)switch(p){case 35678:h[m]={value:sf},console.warn("Missing/unassigned texture, fallback to white: "+m);break;default:console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+m,u[y]);break}}an&&console.log(E.uuid,h),s(E)}):null}};import{EXRLoader as aE}from"three/examples/jsm/loaders/EXRLoader";var cf=N("debugexr"),il=class{constructor(e){this.parser=e,this.name="EXT_texture_exr"}loadTexture(e){let t=this.name,i=this.parser,r=i.json.textures[e];if(cf&&console.log("EXT_texture_exr.loadTexture",e,r),!r.extensions||!r.extensions[t])return null;let s=r.extensions[t],o=new aE(i.options.manager);return cf&&console.log("EXT_texture_exr.loadTexture",s,o),i.loadTextureImage(e,s.source,o)}};var df="NEEDLE_gameobject_data",nl=class{get name(){return df}parser;constructor(e){this.parser=e}afterRoot(e){let t=[];for(let i=0;i<this.parser.json.nodes.length;i++){let n=this.parser.json.nodes[i];if(n&&n.extensions){let r=n.extensions[df];if(r){let s=this.findAndApplyExtensionData(i,r);t.push(s)}}}return Promise.all(t).then(()=>{})}async findAndApplyExtensionData(e,t){let i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){e.userData.layer=t.layers,e.userData.tag=t.tag,e.userData.hideFlags=t.hideFlags,e.userData.static=t.static,e.visible=t.activeSelf,e.guid=t.guid}};import{FloatType as lE,HalfFloatType as cE,sRGBEncoding as dE}from"three";var hf="NEEDLE_lightmaps",hE=N("debuglightmapsextension"),So=(i=>(i[i.Lightmap=0]="Lightmap",i[i.Skybox=1]="Skybox",i[i.Reflection=2]="Reflection",i))(So||{}),rl=class{get name(){return hf}parser;registry;source;constructor(e,t,i){this.parser=e,this.registry=t,this.source=i}afterRoot(e){let t=this.parser.json.extensions;if(t){let i=t[hf];if(i){let n=i.textures;return n.length?(hE&&console.log(i),new Promise(async(r,s)=>{let o=[];for(let c of n)if(c.pointer){let d=Br(this.parser,c.pointer).then(a=>{let h=a;h?.isTexture&&(this.registry?(c.type!==0&&(h.encoding=dE),(h.type==lE||h.type==cE)&&(h.flipY=!0),this.registry.registerTexture(this.source,c.type,h,c.index)):console.log(So[c.type],c.pointer,h))});o.push(d)}await Promise.all(o),r()})):null}}return null}};import{AmbientLight as mE,Color as uf,HemisphereLight as gE}from"three";import{Vector4 as uE,EquirectangularReflectionMapping as sl,sRGBEncoding as ol,WebGLCubeRenderTarget as pE}from"three";import{LightProbeGenerator as fE}from"three/examples/jsm/lights/LightProbeGenerator.js";var kd=N("debugenvlight"),Md=(n=>(n[n.Skybox=0]="Skybox",n[n.Trilight=1]="Trilight",n[n.Flat=3]="Flat",n[n.Custom=4]="Custom",n))(Md||{});var al=class{context;constructor(e){this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}sceneLightSettings;preUpdate(){let e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}_timevec4=new uE;get timeVec4(){return this._timevec4}get environmentIntensity(){return this.sceneLightSettings?this.sceneLightSettings.ambientIntensity:1}registerSceneLightSettings(e){this.sceneLightSettings=e}registerReflection(e,t){let i=new Id(this.context,t,1);this._lighting[e]=i}getReflection(e){return this._lighting[e]}enableReflection(e){switch(kd&&console.log(this.sceneLightSettings?Md[this.sceneLightSettings.ambientMode]:"Unknown ambient mode"),this.sceneLightSettings?.ambientMode){case 0:case 4:let t=this.getReflection(e);if(t&&t.Source){let i=this.context.scene,n=t.Source;n.encoding=ol,n.mapping=sl,i.environment=n;return}break}if(this.sceneLightSettings?.environmentReflectionSource===1)switch(this.sceneLightSettings?.ambientMode){case 1:if(this.sceneLightSettings.ambientTrilight){let t=this.sceneLightSettings.ambientTrilight,i=af(t[0],t[1],t[2],64,64);i.encoding=ol,i.mapping=sl,this.context.scene.environment=i}else console.error("Missing ambient trilight",this.sceneLightSettings.sourceId);return;case 3:if(this.sceneLightSettings.ambientLight){let t=of(this.sceneLightSettings.ambientLight,64);t.encoding=ol,t.mapping=sl,this.context.scene.environment=t}else console.error("Missing ambientlight",this.sceneLightSettings.sourceId);return;default:return}}disableReflection(){let e=this.context.scene;e.environment=null}async getSceneLightingData(e){return kd&&console.log("GET SCENE LIGHT DATA"),this._waitPromise?this._waitPromise:(this._waitPromise=new Promise((t,i)=>{let n=setInterval(async()=>{let r=this.getReflection(e);r&&(clearInterval(n),t(r.getSphericalHarmonicsArray(this.sceneLightSettings?.ambientIntensity??1)))},10)}),this._waitPromise)}_waitPromise;_lighting={}},Id=class{get Source(){return this._source}get Array(){return this._sphericalHarmonicsArray}_context;_source;_sphericalHarmonics=null;_sphericalHarmonicsArray;_ambientScale=1;_lightProbe;constructor(e,t,i=1){this._context=e,this._source=t,this._ambientScale=i,t.mapping=sl,t.encoding=ol}getSphericalHarmonicsArray(e=1){if(this._sphericalHarmonicsArray?.length&&this._source)return{array:this._sphericalHarmonicsArray,texture:this._source,lightProbe:this._lightProbe};try{let t=this._source,i=null;if(t){kd&&console.log("GENERATING LIGHT PROBE",t);let n=Math.min(t.image.width,512);i=new pE(n).fromEquirectangularTexture(this._context.renderer,t),this._source=i.texture}if(this._sphericalHarmonicsArray=[],i){let n=fE.fromCubeRenderTarget(this._context.renderer,i);this._lightProbe=n;let r=this._ambientScale*(e*e*Math.PI*.5)-1;this._sphericalHarmonics=n.sh,this._sphericalHarmonicsArray=this._sphericalHarmonics.toArray();let s=e/(Math.PI*.5);for(let o=0;o<this._sphericalHarmonicsArray.length;o++)this._sphericalHarmonicsArray[o]*=s;if(n.sh.scale(r),this._source)return{array:this._sphericalHarmonicsArray,texture:this._source,lightProbe:n}}}catch(t){console.error(t)}return null}};var pf="NEEDLE_lighting_settings",Po=N("debugenvlight"),ll=class{get name(){return pf}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}afterRoot(e){let t=this.parser.json.extensions;if(t){let i=t[pf];if(i){Po&&console.log(i);let n=O.addNewComponent(e.scene,Ld,!1);n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new uf().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(r=>new uf().fromArray(r))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource,this.context&&this.context.rendererData.registerSceneLightSettings(n)}}return null}},Ld=class extends M{ambientMode=0;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=0;_hasReflection=!1;_ambientLightObj;_lightProbeObj;awake(){if(this.sourceId){let e=this.environmentReflectionSource===0?1:2,t=this.context.lightmaps.tryGet(this.sourceId,e,0);this._hasReflection=t!=null,t&&this.context.rendererData.registerReflection(this.sourceId,t)}Po&&window.addEventListener("keydown",e=>{switch(e.key){case"l":this.enabled=!this.enabled;break}})}onEnable(){let e=this.context.mainCameraComponent?.sourceId===this.sourceId;if(Po&&console.log("enable",this.sourceId,e,this,this.context.mainCameraComponent?.sourceId),this.ambientMode==3)this.ambientLight&&(this._ambientLightObj=new mE(this.ambientLight,Math.PI*this.ambientIntensity)),this._ambientLightObj&&this.gameObject.add(this._ambientLightObj),this._lightProbeObj&&this._lightProbeObj.removeFromParent();else if(this.ambientMode===1){if(this.ambientTrilight){let t=this.ambientTrilight[0],i=this.ambientTrilight[this.ambientTrilight.length-1],n=new gE(i,t,this.ambientIntensity);this.gameObject.add(n)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._lightProbeObj?this.enabled&&this.destroyed&&this._lightProbeObj&&this.scene.add(this._lightProbeObj):this.sourceId&&this.context.rendererData.getSceneLightingData(this.sourceId).then(t=>{Po&&console.log(t),t&&(this._lightProbeObj=t.lightProbe,this.enabled&&!this.destroyed&&this._lightProbeObj&&this.scene.add(this._lightProbeObj))});this.sourceId&&this.context.rendererData.enableReflection(this.sourceId)}onDisable(){Po&&console.log("disable",this.sourceId,this),this._lightProbeObj&&this._lightProbeObj.removeFromParent(),this.sourceId&&this.context.rendererData.disableReflection()}};function Hd(l){let e=new ss;return l.register(t=>(e.parser=t,e)),e}var Dd=class{resolvePath(e){return e.includes("/extensions/builtin_components/")&&(e=e.replace("/extensions/builtin_components/","/userData/components/")),e}};function jd(l,e,t){l.register(n=>new nl(n)),l.register(n=>new va(n)),l.register(n=>new rl(n,e.lightmaps,t)),l.register(n=>new ll(n,t,e)),l.register(n=>new tl(n,t)),l.register(n=>new $n(n,t)),l.register(n=>new Hi(n,t,e)),l.register(n=>new il(n));let i=l.setAnimationPointerResolver;typeof i=="function"&&i.bind(l)(new Dd)}var bE=N("printGltf");var Fn=class{context;loader;path;gltf;constructor(e,t,i,n){this.context=e,this.path=t,this.loader=i,this.gltf=n}},ff={};function Fs(l,e){if(ff[l])for(let t of ff[l])t(e)}async function gf(l,e,t,i,n){bE&&console.log(t),await l.assets.registerGltf(t),await Ca(l,e,t,i,n)}function Vr(l,e,t,i){typeof t!="string"&&console.warn("Parse gltf binary without path, this might lead to errors in resolving extensions. Please provide the source path of the gltf/glb file",t,typeof t);let n=new mf;jd(n,l,t);let s=Hd(n);return new Promise((o,c)=>{try{Kn(n,l),Fs(0,new Fn(l,t,n)),n.parse(e,t,async d=>{Fs(1,new Fn(l,t,n,d)),await gf(l,t,d,i,s),Fs(10,new Fn(l,t,n,d)),o(d)},d=>{console.error("failed loading "+t,d),o(void 0)})}catch(d){console.error(d),c(d)}})}function lr(l,e,t,i=!1,n){let r=new mf;jd(r,l,e);let o=Hd(r);return new Promise((c,d)=>{try{Kn(r,l),Fs(0,new Fn(l,e,r)),r.load(e,async a=>{Fs(1,new Fn(l,e,r,a)),await gf(l,e,a,t,o),Fs(10,new Fn(l,e,r,a)),c(a)},a=>{n?.call(r,a)},a=>{console.error("failed loading "+e,a),c(void 0)})}catch(a){console.error(a),d(a)}})}import*as Nn from"three";function cl(l,e,t){let i=O.getComponentInChildren(l,Et);if(i||(i=O.addNewComponent(l,Et,!1),i.guid=e.generateUUID()),i&&!O.getComponent(i.gameObject,Qe)){let r=O.addNewComponent(i.gameObject,Qe,!1);r.guid=e.generateUUID()}if(i&&!O.getComponentInParent(i.gameObject,Ri)){let r=O.addNewComponent(i.gameObject,Ri,!1);r.guid=e.generateUUID()}if(t&&t.animations?.length>0){let r=t.animations[0],s=O.addNewComponent(l,Zt,!1);s.animations=[r]}let n=!1;l.traverse(r=>{!r||r.isSkinnedMesh===!0&&(n||console.log("Disabling frustum culling for skinned meshes",t),n=!0,r.frustumCulled=!1)})}var Bd=class{guid;file_name;file_hash;file_size;position;seed;sender;serverUrl;parentGuid;boundsSize;constructor(e,t,i,n,r,s,o,c){this.seed=t,this.guid=i,this.file_name=n,this.file_hash=r,this.file_size=s,this.position=o,this.sender=e,this.serverUrl=c}};async function vp(l,e,t){let i=l.name;return i.endsWith(".gltf")||i.endsWith(".glb")?new Promise((n,r)=>{let s=new FileReader;s.readAsDataURL(l),s.onloadend=async o=>{let c=s.result,d=Wo(),a=new We(d),h=await lr(e,c,a,!0);if(h&&h.scene){let u=h.scene;if(!u.guid){let g=new We(d);u.guid=g.generateUUID()}t&&yE(e.connection,l,d,u,t),cl(u,a,h),n(h)}}}):(console.warn("Unsupported file type: "+i),console.log(l),null)}async function yp(l,e){return new Promise(async(t,i)=>{let n=Wo(),r=new We(n),s=await lr(e,l.toString(),r,!0);if(s&&s.scene){let o=s.scene;cl(o,r,s),t(s)}else console.warn("Unsupported file type: "+l.toString())})}function bf(l){l.connection.beginListen("file-spawned",async e=>{if(e.sender!==l.connection.connectionId){console.log("received file event",e),EE(e,l);let t=null;try{t=await Ra(e.file_name,e.file_hash,e.file_size,e.serverUrl)}finally{wE(e,l)}if(t){let i=new We(e.seed),n=await Vr(l,t,null,i);if(n&&n.scene){let r=n.scene;if(cl(r,i,n),e.parentGuid){let s=O.findByGuid(e.parentGuid,l.scene);"add"in s&&s.add(r)}r.parent||l.scene.add(r),e.position!==null&&r.position.copy(e.position)}}else console.error("download didnt return file")}})}async function yE(l,e,t,i,n){if(!l.connectionId){console.error("Can not upload file - no connection id");return}if(!i.guid){console.error("Can not upload file - no guid",i,i.guid);return}let r=await sp(e,n);if(!r)return;if(!r.filename){console.error("Can not send upload event - no filename",e.name);return}if(!r.hash){console.error("Can not send upload event - no hash",e.name);return}let s=new Bd(l.connectionId,t,i.guid,r.filename,r.hash,e.size,i.position,r.url??n);i.parent&&(s.parentGuid=i.parent.guid),l.send("file-spawned",s)}var Fd={};function EE(l,e){let t=new Nn.BoxGeometry,i=new Nn.Mesh(t,new Nn.MeshBasicMaterial({color:65280})),n=new Nn.BoxHelper(i,5592405);if(Fd[l.guid]=n,e.scene.add(n),l.parentGuid){let r=O.findByGuid(l.parentGuid,e.scene);r&&r.add(n)}l.position&&n.position.copy(l.position)}function wE(l,e){let t=l.guid,i=Fd[t];i&&(delete Fd[t],i.removeFromParent())}import*as vf from"three";var cF=N("debugassets");var dl=class{constructor(){window.addEventListener("unhandledrejection",e=>{if(e.defaultPrevented)return;let t=e?.reason?.path;if(t){let i=t[0];i&&i.tagName==="IMG"&&(console.warn(`Could not load image:
136
- `+i.src),e.preventDefault())}})}texturesLoader=new vf.TextureLoader;textures={};texturesLoading={};async loadTexture(e){if(this.textures[e])return this.textures[e];if(this.texturesLoading[e])return await this.texturesLoading[e];let t=this.texturesLoader.loadAsync(e);this.texturesLoading[e]=t;let i=await t;return delete this.texturesLoading[e],this.textures[e]=i,i}getTexture(e){return this._textures.get(e)||null}findTexture(e){for(let t of this._textures.values())if(t.name===e)return t;return null}findMesh(e){for(let t of this._meshes.values())if(t.name===e)return t;return null}findMaterial(e){for(let t of this._materials.values())if(t.name===e)return t;return null}async registerGltf(e){}registerAsset(e){}_materials=new Map;_meshes=new Map;_textures=new Map};import*as Ef from"three/examples/jsm/libs/stats.module";import*as Si from"three";var yf=!!N("debuglightmaps"),hl=class{_context;_lightmaps=new Map;constructor(e){this._context=e}registerTexture(e,t,i,n){yf&&console.log("Registering lightmap",e,So[t],i),this._lightmaps.has(e)||this._lightmaps.set(e,new Map);let r=this._lightmaps.get(e),s=r?.get(t)??[];s.length<n&&(s.length=n+1),s[n]=i,r?.set(t,s)}tryGetLightmap(e,t=0){return this.tryGet(e,0,t)}tryGetSkybox(e){return this.tryGet(e,1,0)}tryGetReflection(e){return this.tryGet(e,2,0)}tryGet(e,t,i){if(!e)return yf&&console.warn("Missing source id"),null;let n=this._lightmaps.get(e)?.get(t)??null;return!n?.length||n.length<=i?null:n[i]}};Si.ShaderChunk.lights_fragment_maps=Si.ShaderChunk.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vUv2 );",`
134
+ `)}}}applyShadowMaterial(){let e=O.getComponent(this.gameObject,Te);if(e)if(e.material?.type!=="ShadowMaterial"){let t=new ly;t.color=this.shadowColor,t.opacity=this.shadowColor.alpha,this.applyMaterialOptions(t),e.material=t}else{let t=e.material;t.color=this.shadowColor,t.opacity=this.shadowColor.alpha,this.applyMaterialOptions(t)}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}};k([A()],kn.prototype,"mode",2),k([A(we)],kn.prototype,"shadowColor",2);import{RGBELoader as uy}from"three/examples/jsm/loaders/RGBELoader.js";import{EXRLoader as py}from"three/examples/jsm/loaders/EXRLoader";import{EquirectangularRefractionMapping as fy}from"three";var Bp=N("debugautosync"),cd=class{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];let t=new dd(e);return this._syncers[e.guid]=t,t}},Fp=new cd,dd=class{comp;constructor(e){this.comp=e}hasChanges=!1;changedProperties={};data={};_boundEvent;get networkingKey(){return this.comp.constructor.name}_isReceiving=!1;_isInit=!1;init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,this._boundEvent=this.onHandleSending.bind(this),this.comp.context.post_render_callbacks.push(this._boundEvent),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving.bind(this));let t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}notifyChanged(e,t){this._isReceiving||(this.hasChanges=!0,this.changedProperties[e]=t)}onHandleSending(){if(!this.hasChanges)return;this.hasChanges=!1;let e=this.comp.context.connection;if(!e||!e.isConnected){for(let t in this.changedProperties)delete this.changedProperties[t];return}for(let t in this.data)delete this.data[t];this.data.guid=this.comp.guid;for(let t in this.changedProperties){let i=this.changedProperties[t];delete this.changedProperties[t],this.data[t]=i}e.send(this.networkingKey,this.data)}onHandleReceiving(e){if(!this._isInit||!this.comp)return;let t=e.guid;if(!(t&&t!==this.comp.guid)){Bp&&console.log("RECEIVED",this.comp.name,this.comp.guid,e);try{this._isReceiving=!0;for(let i in e){if(i==="guid")continue;let n=e[i];this.comp[i]=n}}catch(i){console.error(i)}finally{this._isReceiving=!1}}}};function dy(l,e){let t=e!==l;if(!t&&l&&e){if(Array.isArray(l)&&Array.isArray(e))t=!0;else if(typeof l=="object"&&typeof e=="object"){for(let i of Object.keys(l))if(l[i]!==e[i]){t=!0;break}}}return t}function hy(l){if(l.__autoPropertySyncHandler)return l.__autoPropertySyncHandler;let e=Fp.getOrCreateSyncer(l);return e?.init(l),l.__autoPropertySyncHandler=e,e}var Va=function(l){return function(e,t){let i=null,n=l?e[l]:void 0,r=e,o=r.__internalAwake;Bp&&console.log(t);let s=t+"k__BackingField";r.__internalAwake=function(){if(this[s]!==void 0)return;this[s]=this[t],o.call(this),i=Fp.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,t)?.set===void 0&&Object.defineProperty(this,t,{set:function(d){let a=this[s];this[s]=d,dy(d,a)&&n?.call(this,d,a)!==!1&&hy(this)?.notifyChanged(t,d)},get:function(){return this[s]},configurable:!0,enumerable:!0}),i?.init(this)}}};var In=class extends M{url;allowDrop=!0;_loader;_prevLoadedEnvironment;_prevEnvironment=null;_prevBackground=null;onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.isInXR||(this.context.scene.environment=this._prevEnvironment,this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents()}async setSkybox(e){if(!e)return;if(!e?.endsWith(".hdr")&&!e.endsWith(".exr")&&console.warn("Potentially invalid skybox url",this.url,"on",this.name),!this._loader){let n=e.endsWith(".exr");this._loader=n?new py:new uy}let t=await this._loader.loadAsync(e);if(!t||!this.enabled)return;this.url=e,t.mapping=fy,this._prevBackground=this.context.scene.background,this._prevEnvironment=this.context.scene.environment,console.log("Set skybox",this.url),this.context.scene.environment=t,this.context.scene.background=t,this._prevLoadedEnvironment=t;let i=e.lastIndexOf("/");t.name=e.substring(i>=0?i+1:0)}dragOverEvent;dropEvent;registerDropEvents(){this.dragOverEvent||(this.dragOverEvent=e=>{if(!!this.allowDrop&&!!e.dataTransfer)for(let t of e.dataTransfer.types)t==="text/uri-list"&&e.preventDefault()},this.dropEvent=e=>{if(!!this.allowDrop&&(e.preventDefault(),!!e.dataTransfer)){for(let t of e.dataTransfer.types)if(t==="text/uri-list"){let i=e.dataTransfer.getData(t);console.log(t,i);let n=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(i)?.groups?.name;if(n||(n=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(i)?.groups?.name),console.log(n),n){let r="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+n+"_1k.exr";this.setSkybox(r)}else console.warn("Could not resolve skybox name from dropped url",i)}}},this.context.domElement.addEventListener("dragover",this.dragOverEvent),this.context.domElement.addEventListener("drop",this.dropEvent))}unregisterDropEvents(){!this.dragOverEvent||(this.context.domElement.removeEventListener("dragover",this.dragOverEvent),this.context.domElement.removeEventListener("drop",this.dropEvent))}};k([Va("setSkybox"),A()],In.prototype,"url",2),k([A()],In.prototype,"allowDrop",2);import*as xo from"three";import{Object3D as my}from"three";var hd=class extends M{target=null;followFactor=.1;rotateFactor=.1;flipForward=!1;_firstUpdate=!0;onEnable(){let e=O.getComponentInChildren(this.gameObject,ne);e&&e.cam&&(e.gameObject.position.set(0,0,0),e.cam.position.set(0,0,0),e.gameObject.quaternion.identity(),e.cam.quaternion.setFromEuler(new xo.Euler(0,Math.PI,0)))}onBeforeRender(){this.followFactor<=0||this.updateNow(!1)}updateNow(e){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){let t=q(this.target),i=this._firstUpdate||e?1:Q.clamp01(this.context.time.deltaTime*this.followFactor);this.worldPosition=this.worldPosition.lerp(t,i)}if(this.rotateFactor>0){let t=ve(this.target);this.flipForward&&t.multiply(hd._invertForward);let i=this._firstUpdate||e?1:Q.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(t,i)}this._firstUpdate=!1}}},wi=hd;z(wi,"_invertForward",new xo.Quaternion().setFromAxisAngle(new xo.Vector3(0,1,0),Math.PI)),k([A(my)],wi.prototype,"target",2);import{Layers as Gp}from"three";var Wa=N("debugspatialtrigger"),Np=new Gp,zp=new Gp;function gy(l,e){return Np.mask=l,zp.mask=e,Np.test(zp)}var wt=class extends M{triggerMask=0;onEnter;onStay;onExit;start(){Wa&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(let e of Zi.triggers)gy(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){let t=this.lastIntersected[e];this.currentIntersected.indexOf(t)<0&&(this.onExitTrigger(t),this.lastIntersected.splice(e,1))}for(let e of this.currentIntersected)this.lastIntersected.indexOf(e)<0&&this.onEnterTrigger(e),this.onStayTrigger(e);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}currentIntersected=[];lastIntersected=[];onEnterTrigger(e){Wa&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),this.onEnter?.invoke(this,e)}onExitTrigger(e){Wa&&console.log("EXIT TRIGGER",this.name,e.name,this,e),e.raiseOnExitEvent(this),this.onExit?.invoke(this,e)}onStayTrigger(e){e.raiseOnStayEvent(this),this.onStay?.invoke(this,e)}};k([A()],wt.prototype,"triggerMask",2),k([A(Oe)],wt.prototype,"onEnter",2),k([A(Oe)],wt.prototype,"onStay",2),k([A(Oe)],wt.prototype,"onExit",2);var ws=class extends M{triggerMask;boxHelper;start(){Wa&&console.log(this.name,this.triggerMask,this)}onEnable(){ws.triggers.push(this),this.boxHelper||(this.boxHelper=O.addNewComponent(this.gameObject,lt),this.boxHelper?.showHelper())}onDisable(){ws.triggers.splice(ws.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){O.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof wt&&t.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){O.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof wt&&t.onStayTrigger(this)},!1)}raiseOnExitEvent(e){O.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof wt&&t.onExitTrigger(this)},!1)}},Zi=ws;z(Zi,"triggers",[]),k([A()],Zi.prototype,"triggerMask",2);import*as Bt from"three";var To=class extends M{cam=null;_firstPersonMode=!1;get firstPersonMode(){return!0}set firstPersonMode(e){}enableFirstPersonMode(){this._firstPersonMode=!0,this.updateUI(),this.cam&&(this.firstPersonFollow&&(this.firstPersonFollow.enabled=!0,this.firstPersonFollow.updateNow(!0)),this.orbit&&(this.orbit.enabled=!1))}enableThirdPersonMode(){this._firstPersonMode=!1,this.updateUI(),this.firstPersonFollow&&(this.firstPersonFollow.enabled=!1),this.cam&&(ie(this.cam.cam,this._orbitStartPos),Ae(this.cam.cam,this._orbitStartRot),ie(this.cam.gameObject,this._orbitStartPos2),Ae(this.cam.gameObject,this._orbitStartRot2),this.orbit&&(this.orbit.enabled=!0,this.orbit.setFromTargetPosition()))}orbit=null;firstPersonFollow=null;spectatorUIDomElement=null;_avatar=null;eventSub_WebXRRequestStartEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;awake(){O.setActive(this.gameObject,!1);let e="#spectator-camera-ui";if(this.spectatorUIDomElement=this.context.domElement.querySelector(e),this.spectatorUIDomElement||console.warn("Could not find spectator camera UI element",e),this.spectatorUIDomElement?.classList.add("hidden"),!this.isSupportedPlatform()){console.log("Disable spectator cam",window.navigator.userAgent,this);return}if(this.cam=O.getComponent(this.gameObject,ne),!this.cam){console.error("Spectator camera needs camera component",this);return}this.cam&&(this.cam.enabled=!0,this._orbitStartPos.copy(q(this.cam.cam)),this._orbitStartRot.copy(ve(this.cam.cam)),this._orbitStartPos2.copy(q(this.cam.gameObject)),this._orbitStartRot2.copy(ve(this.cam.gameObject))),this.eventSub_WebXRRequestStartEvent=this.onXRSessionRequestStart.bind(this),this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),$.addEventListener("requestVRSession",this.eventSub_WebXRRequestStartEvent),$.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),$.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.context.domElement.querySelector("button#toggle-spectator-view")?.addEventListener("click",this.toggleView.bind(this)),this.updateUI()}onDestroy(){$.removeEventListener("requestVRSession",this.eventSub_WebXRStartEvent),$.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),$.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}toggleView(){this.firstPersonMode=!this.firstPersonMode}updateUI(){let e=this.context.domElement.querySelector("button#toggle-spectator-view");if(!!e&&(e.disabled=!0,e.firstChild&&(this._sessionHasStarted?e.firstChild.textContent=this.firstPersonMode?"\u{1F441}\uFE0F":"\u{1F4F7}":e.firstChild.textContent="Waiting for VR session"),e.children?.length>1)){let t=e.children[1];t.style.display=this._sessionHasStarted?"block":"none",this.firstPersonMode?t.textContent="First-Person View. See what the person in VR sees":t.textContent="Third-Person View. Freely move the camera around"}}isSupportedPlatform(){let e=window.navigator.userAgent,t=/Windows|MacOS/.test(e),i=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return t&&!i}onXRSessionRequestStart(e){this._sessionHasStarted=!1,this.spectatorUIDomElement?.classList.remove("hidden"),O.setActive(this.gameObject,!0),this.cam&&this.cam.cam&&(ie(this.cam.cam,this._orbitStartPos),Ae(this.cam.cam,this._orbitStartRot),ie(this.cam.gameObject,this._orbitStartPos2),Ae(this.cam.gameObject,this._orbitStartRot2)),this.firstPersonMode?this.enableFirstPersonMode():this.enableThirdPersonMode()}onXRSessionStart(e){this._sessionHasStarted=!0,this.updateUI()}onXRSessionEnded(e){this._sessionHasStarted=!1,this.spectatorUIDomElement?.classList.add("hidden"),O.setActive(this.gameObject,!1)}_sessionHasStarted=!1;_isFirstStart=!0;_firstPersonIsSetup=!1;_orbitStartPos=new Bt.Vector3;_orbitStartRot=new Bt.Quaternion;_orbitStartPos2=new Bt.Vector3;_orbitStartRot2=new Bt.Quaternion;onAfterRender(){if(!this.cam)return;if(this.firstPersonMode&&!this._firstPersonIsSetup&&(!this._avatar||this._avatar?.destroyed)){for(let s of fe.instances)if(s.avatar&&"isLocalAvatar"in s.avatar&&s.avatar?.isLocalAvatar){this._avatar=s;let c=s.avatar.head;if(!c)continue;this.setupFollowMode(c)}}let e=this.context.renderer,t=e.xr.enabled;if(!e.xr.isPresenting)return;let i=e.getRenderTarget(),n=null;if(!i){if(!e.state.bindFramebuffer||!e.state.bindXRFramebuffer)return;n=e._framebuffer,e.state.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender(),e.setClearColor(new Bt.Color(1,1,1)),e.setRenderTarget(null),e.xr.enabled=!1;let r=this.cam?.cam;this.context.updateAspect(r);let o=e.xr.isPresenting;e.xr.isPresenting=!1,e.setSize(this.context.domWidth,this.context.domHeight),e.render(this.context.scene,r),e.xr.isPresenting=o,e.xr.enabled=t,i?e.setRenderTarget(i):e.state.bindXRFramebuffer(n),this.resetAvatarFlags()}setupFollowMode(e,t=!0){if(!e||!this.cam||this._firstPersonIsSetup)return;this._firstPersonIsSetup=!0;let i=e.add(new Bt.Object3D);i.add(new Bt.AxesHelper),this.firstPersonFollow=O.addNewComponent(this.cam.gameObject,wi),this.firstPersonFollow.target=i,this.firstPersonFollow.followFactor=12,this.firstPersonFollow.rotateFactor=5,t&&(this.firstPersonFollow.flipForward=!0);let n=this.context.mainCamera;n&&(this.cam.cam.near=n.near,this.cam.cam.far=n.far,this.cam.cam.updateProjectionMatrix()),this.orbit&&(this.orbit.enabled=!1)}setAvatarFlagsBeforeRender(){for(let e of fe.instances)if(e.avatar&&"isLocalAvatar"in e.avatar){let t=this.firstPersonMode&&this._firstPersonIsSetup&&e.avatar.isLocalAvatar?8:16,i=e.avatar.flags;if(!i)continue;for(let n of i)n.UpdateVisible(t)}}resetAvatarFlags(){for(let e of fe.instances)if(e.avatar&&"flags"in e.avatar){let t=e.avatar.flags;if(!t)continue;for(let i of t)e.avatar?.isLocalAvatar?i.UpdateVisible(8):i.UpdateVisible(16)}}};var Ro=class extends M{anchor=null;connectedBody=null;connectedAnchor=null;spring=10;damper=.2;rb=null;awake(){if(this.rb=O.getComponent(this.gameObject,ce),!this.connectedBody||!this.connectedBody.body||!this.rb||!this.rb.body)return;this.connectedBody.body.mass=Math.min(this.rb.body.mass*.99,this.connectedBody.body.mass);let e=new na(this.rb.body,this.connectedBody.body,{restLength:.01,stiffness:this.spring*.5,damping:this.damper});this.context.physics.addPostStepListener(t=>{e.applyForce()})}update(){}};import*as _t from"three";import{Material as by,Texture as vy}from"three";var fr=class{texture;triangles;uv;vertices;_geometry};k([A(vy)],fr.prototype,"texture",2);var Ua=class{static getOrCreateGeometry(e){if(e._geometry)return e._geometry;let t=new _t.BufferGeometry;e._geometry=t;let i=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let r=0;r<e.triangles.length;r+=1){let o=e.triangles[r];i[r*3]=-e.vertices[o].x,i[r*3+1]=e.vertices[o].y,i[r*3+2]=0;let s=e.uv[o];n[r*2]=s.x,n[r*2+1]=1-s.y}return t.setAttribute("position",new _t.BufferAttribute(i,3)),t.setAttribute("uv",new _t.BufferAttribute(n,2)),t}},Ji=class extends M{drawMode=0;size={x:1,y:1};color;sharedMaterial;get sprite(){return this._sprite}set sprite(e){e!==this._sprite&&(this._sprite=e,this.updateSprite())}_sprite;_currentSprite;awake(){this._currentSprite=void 0}start(){this.drawMode===2&&console.warn("Tiled draw mode is not supported yet",this),this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(){if(!!this.__didAwake&&!!this.sprite&&!!this.sharedMaterial){if(this._currentSprite)this._currentSprite.geometry=Ua.getOrCreateGeometry(this.sprite),this._currentSprite.material.map=this.sprite.texture;else{let e=new _t.MeshBasicMaterial({color:16777215,side:_t.DoubleSide});if(!e)return;if(this.color&&(e.color||(e.color=new _t.Color),e.color.copy(this.color),e.opacity=this.color.alpha),e.alphaTest=.5,this.sprite.texture&&!e.wireframe){let t=this.sprite.texture;e.map=t}this._currentSprite=new _t.Mesh(Ua.getOrCreateGeometry(this.sprite),e)}this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite))}}};k([A()],Ji.prototype,"drawMode",2),k([A(we)],Ji.prototype,"color",2),k([A(by)],Ji.prototype,"sharedMaterial",2);var xt=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedCameraModel(e,t){return(t||new xt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+4),(t||new xt).__init(e.readInt32(e.position())+e.position(),e)}userId(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}guid(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}dontSave(){let e=this.bb.__offset(this.bb_pos,8);return e?!!this.bb.readInt8(this.bb_pos+e):!1}pos(e){let t=this.bb.__offset(this.bb_pos,10);return t?(e||new Ce).__init(this.bb_pos+t,this.bb):null}rot(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new Ce).__init(this.bb_pos+t,this.bb):null}static startSyncedCameraModel(e){e.startObject(5)}static addUserId(e,t){e.addFieldOffset(0,t,0)}static addGuid(e,t){e.addFieldOffset(1,t,0)}static addDontSave(e,t){e.addFieldInt8(2,+t,0)}static addPos(e,t){e.addFieldStruct(3,t,0)}static addRot(e,t){e.addFieldStruct(4,t,0)}static endSyncedCameraModel(e){return e.endObject()}static finishSyncedCameraModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedCameraModelBuffer(e,t){e.finish(t,void 0,!0)}};import{Object3D as yy}from"three";var qa="SCAM";Nr(qa,xt.getRootAsSyncedCameraModel);var Tt=new ft,ud=class{userId;guid;constructor(e,t){this.guid=t,this.userId=e}send(e,t){let i=e.cam?.cam;if(i){Tt.clear();let n=Tt.createString(this.guid),r=Tt.createString(this.userId);xt.startSyncedCameraModel(Tt),xt.addGuid(Tt,n),xt.addUserId(Tt,r);let o=q(i),s=Ns(i);xt.addPos(Tt,Ce.createVec3(Tt,o.x,o.y,o.z)),xt.addRot(Tt,Ce.createVec3(Tt,s.x,s.y,s.z));let c=xt.endSyncedCameraModel(Tt);Tt.finish(c,qa),t.sendBinary(Tt.asUint8Array())}}},Mn=class extends M{getUserCamera(e){let t=this.userToCamMap[e];return t?this.remoteCams[t].obj:null}cam=null;cameraPrefab=null;_lastWorldPosition;_lastWorldQuaternion;_model=null;_needsUpdate=!0;_lastUpdateTime=0;remoteCams={};userToCamMap={};_camTimeoutInSeconds=10;_receiveCallback=null;async awake(){this._lastWorldPosition=this.worldPosition.clone(),this._lastWorldQuaternion=this.worldQuaternion.clone(),this.cameraPrefab&&("uri"in this.cameraPrefab&&(this.cameraPrefab=await this.cameraPrefab.instantiate(this.gameObject)),this.cameraPrefab&&"isObject3D"in this.cameraPrefab&&(this.cameraPrefab.visible=!1))}start(){this.cam||(console.warn("Missing camera, fallback to main camera",this),this.cam=this.context.mainCameraComponent??null)}onEnable(){this._receiveCallback=this.context.connection.beginListenBinrary(qa,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(qa,this._receiveCallback)}update(){for(let i in this.remoteCams){let n=this.remoteCams[i],r=this.context.time.realtimeSinceStartup-n.lastUpdate;if(!n||r>this._camTimeoutInSeconds){console.log("Remote cam timeout",n,r),n?.obj&&O.destroy(n.obj),delete this.remoteCams[i],n&&delete this.userToCamMap[n.userId];continue}}if($.IsInWebXR)return;if(this.cam===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new ud(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));let e=q(this.cam.cam),t=ve(this.cam.cam);(e.distanceTo(this._lastWorldPosition)>.001||t.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(e),this._lastWorldQuaternion.copy(t),!((!this._needsUpdate||this.context.time.frameCount%2!==0)&&!(this.context.time.realtimeSinceStartup-this._lastUpdateTime>this._camTimeoutInSeconds*.5))&&(this._lastUpdateTime=this.context.time.realtimeSinceStartup,this._needsUpdate=!1,this._model.send(this,this.context.connection))}onReceivedRemoteCameraInfoBin(e){let t=e.guid();if(!t)return;let i=e.userId();if(!i||!this.context.connection.userIsInRoom(i)||!this.cameraPrefab)return;let n=this.remoteCams[t];if(!n)if("isObject3D"in this.cameraPrefab){let c=new ye;c.context=this.context;let d=O.instantiate(this.cameraPrefab,c);n=this.remoteCams[t]={obj:d,lastUpdate:this.context.time.realtimeSinceStartup,userId:i},n.obj.visible=!0,this.gameObject.add(d),this.userToCamMap[i]=t;let a=O.getOrAddComponent(d,fe);a.connectionId=i,a.avatar=d}else return;let r=n.obj;n.lastUpdate=this.context.time.realtimeSinceStartup,he.markDirty(r);let o=e.pos();o&&Ar(r,o.x(),o.y(),o.z());let s=e.rot();s&&zs(r,s.x(),s.y(),s.z())}};k([A(ne)],Mn.prototype,"cam",2),k([A([yy,tt])],Mn.prototype,"cameraPrefab",2);var pd="view",Vp=N("debugsyncedroom"),ti=class extends M{roomName;urlParameterName;joinRandomRoom=!0;requireRoomParameter=!1;autoRejoin=!0;_roomPrefix;awake(){this._roomPrefix===void 0&&(this._roomPrefix=this.roomName,this.roomName="")}onEnable(){let e=N(pd);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}this.tryJoinRoom()}onDisable(){this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}tryJoinRoom(e=0){let t=!1;if(this.urlParameterName){let i=N(this.urlParameterName);if(i&&typeof i=="string"){t=!0;let n=hh(i);this.roomName=n}else if(this.joinRandomRoom&&(console.log("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),e<1))return this.tryJoinRoom(e+1)}else this.joinRandomRoom&&(this.roomName===null||this.roomName===void 0||this.roomName.length<=0)&&(console.log("generate room name"),this.roomName=this.generateRoomName());return this.requireRoomParameter&&!t?(Vp&&console.log('No required room parameter "'+this.urlParameterName+'" in url - will not connect to networking backend.'),!1):!this.roomName||this.roomName.length<=0?(Vp&&console.error('Missing room name on "'+this.name+'". Make sure this is correctly configured in Unity',this.context.connection.isDebugEnabled?this:""),!1):(this.context.connection.isConnected||this.context.connection.connect(),this._roomPrefix&&(this.roomName=this._roomPrefix+this.roomName),this.context.connection.joinRoom(this.roomName),!0)}_lastPingTime=0;_lastRoomTime=-1;update(){this.context.connection.isConnected&&(this.context.time.time-this._lastPingTime>3&&(this._lastPingTime=this.context.time.time,this.context.connection.send("ping",{time:this.context.time.time})),this.context.connection.isInRoom&&(this._lastRoomTime=this.context.time.time)),this._lastRoomTime>0&&this.context.time.time-this._lastRoomTime>.3&&(this._lastRoomTime=-1,this.autoRejoin?(console.log("Disconnected from networking backend - attempt reconnecting now"),this.tryJoinRoom()):console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you)"))}get currentRoomName(){let e=N(pd);return e||N(this.urlParameterName)}setRandomRoomUrlParameter(){let e=_l(),t=this.generateRoomName();N(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),lh(t,e)}generateRoomName(){return dh()+"_"+ch(100,999)}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){let e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(pd,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}};k([A()],ti.prototype,"roomName",2),k([A()],ti.prototype,"urlParameterName",2),k([A()],ti.prototype,"joinRandomRoom",2),k([A()],ti.prototype,"requireRoomParameter",2),k([A()],ti.prototype,"autoRejoin",2);function Wp(){let l=N("testwindowcount")||0;l&&l>0&&Ey(l)}function Ey(l){if(N("testwindow"))return null;let e=new URL(window.location.href);Or(e.searchParams,no,1),Or(e.searchParams,"testwindow",1);let t=e.toString(),i=[];window.onbeforeunload=()=>{for(let c of i)c.close()};let n=.05,r=128,o=0,s=0;for(let c=0;c<l;c++){o*r+r*.01>=window.innerWidth&&(s+=1,o=0);let d=o*(r*(1+n))+window.screenLeft,a=s*(r*(1+n))+window.screenTop+90+60*s;o+=1;let h=window.open(t,"test window "+c,`popup=yes width=${r} height=${r} top=${a} left=${d}`);if(!h){console.warn("Failed to open window");continue}i.push(h),h.onload=()=>{h.onbeforeunload=()=>{for(let u=0;u<i.length;u++){let f=i[u];f!==h&&f.close()}i.length=0}}}return i}import{Vector3 as _y}from"three";var Co=class extends M{awake(){Wp()}},So=class extends M{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinrary(to,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new Xa(this.context.connection.connectionId+"_simulatedTransform_"+e,this))}}builder=null;models=null;update(){if(!!this.context.connection.isConnected){if(this.useFlatbuffers){if(!this.context.connection.connectionId||this.context.time.frameCount%this.interval!==0)return;this.builder===null&&(this.builder=new ft(1024));let e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();let i=Nc(this.context.connection.connectionId,this);this.context.connection.sendBinary(i)}}else if(this.models)for(let e=0;e<this.models.length;e++){let t=this.models[e];t.dontSave=!0,t.update(this,null),this.context.connection.send("TestSimulateUserData-"+e,t)}}}},Xa=class{guid;fast=!1;position;rotation;velocity=void 0;dontSave;isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}constructor(e,t){this.guid=e,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(t,null)}update(e,t){let i=e.worldPosition;this.position.x=i.x,this.position.y=i.y,this.position.z=i.z;let n=e.worldQuaternion;if(this.rotation.x=n.x,this.rotation.y=n.y,this.rotation.z=n.z,this.rotation.w=n.w,this.fast=!1,t){let r=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=r.x,this.velocity.y=r.y,this.velocity.z=r.z}}};z(Xa,"temp",new _y);import{MathUtils as xy}from"three";import{TransformControls as Ty}from"three/examples/jsm/controls/TransformControls";import{OrbitControls as Ry}from"three/examples/jsm/controls/OrbitControls";var mr=class extends M{isGizmo=!0;control;orbit;awake(){this.isGizmo&&!hi||!this.context.mainCamera||(this.control=new Ty(this.context.mainCamera,this.context.renderer.domElement),this.control.visible=!0,this.control.enabled=!0,this.control.getRaycaster().layers.set(2),this.control.size=.6,this.control.traverse(e=>{let t=e;if(t.layers.set(2),t){let i=t.material;i&&(i.opacity=.3)}}))}start(){if(this.context.mainCamera){let e=O.getComponentInParent(this.context.mainCamera,Ry)??void 0;this.orbit=e}}changeEventListener;windowKeyDownListener;windowKeyUpListener;onEnable(){this.control&&(this.context.scene.add(this.control),this.control.attach(this.gameObject)),this.changeEventListener=this.onControlChangedEvent.bind(this),this.control?.addEventListener("dragging-changed",this.changeEventListener),this.attachWindowEvents()}onDisable(){this.control?.removeFromParent(),this.changeEventListener&&this.control?.removeEventListener("dragging-changed",this.changeEventListener)}onControlChangedEvent(e){let t=this.orbit;if(t&&(t.enabled=!e.value),e.value){let i=O.getComponentInParent(this.gameObject,Qe);i&&i.requestOwnership()}}attachWindowEvents(){let e=this.control;!e||(this.windowKeyDownListener||(this.windowKeyDownListener=t=>{switch(t.keyCode){case 81:e.setSpace(e.space==="local"?"world":"local");break;case 16:e.setTranslationSnap(100),e.setRotationSnap(xy.degToRad(15)),e.setScaleSnap(.25);break;case 87:e.setMode("translate");break;case 69:e.setMode("rotate");break;case 82:e.setMode("scale");break;case 187:case 107:e.setSize(e.size+.1);break;case 189:case 109:e.setSize(Math.max(e.size-.1,.1));break;case 88:e.showX=!e.showX;break;case 89:e.showY=!e.showY;break;case 90:e.showZ=!e.showZ;break;case 32:e.enabled=!e.enabled;break}}),this.windowKeyUpListener||(this.windowKeyUpListener=t=>{switch(t.keyCode){case 16:e.setTranslationSnap(null),e.setRotationSnap(null),e.setScaleSnap(null);break}}),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener))}};k([A()],mr.prototype,"isGizmo",2);import{LinearToneMapping as Up,ACESFilmicToneMapping as Cy,ReinhardToneMapping as Sy}from"three";var Po=class{overrideState=!1;value=0},_i=class{active=!1;parameters},Dn=class extends _i{mode;get isToneMapping(){return!0}},Hn=class extends _i{postExposure};function Py(l){return"mode"in l?Dn:"postExposure"in l?Hn:_i}var Ln=class{components;apply(e){if(!!this.components){for(let t of this.components)if(t instanceof Dn){let i=t;if(!t.active){e.renderer.toneMapping=Up;continue}switch(i.mode?.value??0){case 0:e.renderer.toneMapping=Up;break;case 1:e.renderer.toneMapping=Sy;break;case 2:e.renderer.toneMapping=Cy;break}}else if(t instanceof Hn){let i=t;console.log(i.postExposure);let n=Math.pow(2,i.postExposure?.value??0);e.renderer.toneMappingExposure=i.postExposure?.overrideState?n:1}}}};k([A([l=>Py(l),_i])],Ln.prototype,"components",2);var gr=class extends M{sharedProfile;onEnable(){this.sharedProfile?.apply(this.context)}};k([A(Ln)],gr.prototype,"sharedProfile",2);import*as qp from"three";var br=class{guid;dontSave=!0;userId;point={x:0,y:0,z:0};source={x:0,y:0,z:0};target;update(e,t,i,n=void 0){this.userId=e.connection.connectionId,this.point.x=t.x,this.point.y=t.y,this.point.z=t.z,this.source.x=i.x,this.source.y=i.y,this.source.z=i.z,this.target=n}},Oo=class extends M{prefab=null;_grabModels=[];_grabModelsUpdateTime=[];_addOrUpdateSub=null;_endSub=null;_freeSub=null;_instances={};awake(){this.prefab&&(this.prefab.visible=!1)}onEnable(){this._addOrUpdateSub=this.context.connection.beginListen("xr-grab-visual-start-or-update",this.onRemoteGrabStartOrUpdate.bind(this)),this._endSub=this.context.connection.beginListen("xr-grab-visual-end",this.onRemoteGrabEnd.bind(this)),this._freeSub=dt.AddEventListener("WillFree",this.onAttachedObjectFree.bind(this))}onDisable(){this.context.connection.stopListening("xr-grab-visual-start-or-update",this._addOrUpdateSub),this.context.connection.stopListening("xr-grab-visual-end",this._endSub),dt.RemoveEventListener("WillFree",this._freeSub)}addOrUpdateGrab(e){this.context.connection.send("xr-grab-visual-start-or-update",e,2)}endGrab(e){this.context.connection.send("xr-grab-visual-end",e,2)}onRemoteGrabStartOrUpdate(e){if(!this.prefab)return;let t=this._instances[e.guid];if(!t){let i=O.instantiate(this.prefab);if(i.visible=!0,this._instances[e.guid]={instance:i,model:e},e.userId){let n=O.getComponentsInChildren(i,ht);if(n?.length>0)for(let r of n)r.assignUserColor(e.userId)}return}t.model=e}onRemoteGrabEnd(e){if(!e)return;let t=e.guid;this._instances[t]&&(O.destroy(this._instances[t].instance),delete this._instances[t])}onAttachedObjectFree(e){if(this._grabModels.length<=0)return;let t=this._grabModels[0];this.updateModel(t,e),this.endGrab(t)}onBeforeRender(){if(this.updateRendering(),!!this.prefab&&(this.prefab.visible=!1,this.context.time.frameCount%10===0))for(let e=0;e<dt.Current.length;e++){let t=dt.Current[e];if(!t.controller||!t.selected)continue;this._grabModels.length<=e&&(this._grabModels.push(new br),this._grabModelsUpdateTime.push(0)),this._grabModelsUpdateTime[e]=this.context.time.time;let i=this._grabModels[e];this.updateModel(i,t),this.addOrUpdateGrab(i)}}updateModel(e,t){if(!t.controller||!t.selected)return;e.guid=t.grabUUID;let i=t.selected.guid;e.update(this.context,t.grabPoint,t.controller.worldPosition,i)}temp=new qp.Vector3;updateRendering(){let e=this.context.time.deltaTime/.5;for(let t in this._instances){let{instance:i,model:n}=this._instances[t];if(!i||!n)continue;let{point:r}=n,o=q(i);this.temp.set(r.x,r.y,r.z),o.lerp(this.temp,e),ie(i,o)}}};import{Object3D as Oy}from"three";var xi=class extends M{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=O.getComponentInParent(this.gameObject,Se)}update(){if(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)return;if(this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(let t of this.eyes)t&&(t.visible=this.eyesOpen)}}};k([A(Oy)],xi.prototype,"eyes",2),k([A()],xi.prototype,"lastBlinkTime",2),k([A()],xi.prototype,"blinkLength",2),k([A()],xi.prototype,"eyesOpen",2);import*as Qa from"three";import{Object3D as fd}from"three";var md=class extends M{head=null;eyes=null;target=null;brain=null;awake(){this.brain||(this.brain=O.getComponentInParent(this.gameObject,Ui)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=O.addNewComponent(this.gameObject,Ui)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new Qa.Vector3;currentTargetPoint=new Qa.Vector3;update(){let e=this.target;if(e&&this.head){let t=this.eyes;if(t){let i=q(e);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);let n=q(this.head),r=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(r.length()<.1)return;let o=md.forward;if(o.set(0,0,1),o.applyQuaternion(ve(this.head)),o.dot(r)>.45)for(let c=0;c<t.length;c++)t[c].lookAt(this.currentTargetPoint)}}}},Ti=md;z(Ti,"forward",new Qa.Vector3(0,0,1)),k([A(fd)],Ti.prototype,"head",2),k([A(fd)],Ti.prototype,"eyes",2),k([A(fd)],Ti.prototype,"target",2);import{Object3D as Xp}from"three";var Ay=N("debugmouth"),jn=class extends M{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){this.voip=O.findObjectOfType(Ke,this.context),console.log(this)}update(){if(!this.voip||this.context.time.frameCount%10!==0)return;let e=this.marker?.connectionId??null;e||Ay&&(e=null);let t=this.voip.getFrequency(e);t!=null&&this.updateLips(t)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>50){this.lastMouthChangeTime=this.context.time.time;let 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;let t=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,t)}}}setMouthShapeActive(e,t){if(!!e){e!=this.idle?this.idle.map(i=>i.visible=!1):this.talking.map(i=>i.visible=!1);for(let i=0;i<e.length;i++){let n=e[i];n&&(n.visible=i===t,n.scale.set(1,1,1))}}}};k([A(Xp)],jn.prototype,"idle",2),k([A(Xp)],jn.prototype,"talking",2);var Ao=class extends M{voip=null;marker=null;_startPosition=null;awake(){this.voip=O.findObjectOfType(Ke,this.context),this.marker=O.getComponentInParent(this.gameObject,fe)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;let e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());let i=t/100;this.gameObject.position.y=this._startPosition.y+i*.07}};var ky=N("logstats"),ko=class extends M{onEnable(){console.log(this),ky&&this.startCoroutine(this.run(),4)}*run(){for(;this.enabled;){let e=this.context.renderer.info;console.log(e.memory,e.render,e.programs),yield}}};import*as Zp from"three";var vr=class{guid},yr=class{signal;reaction;$serializedTypes={signal:vr,reaction:Oe}},$i=class extends M{events;start(){console.log(this)}invoke(e){if(!this.events||!Array.isArray(this.events))return;let t=typeof e=="object"?e.guid:e;for(let i of this.events)if(i.signal.guid===t)try{if(i.reaction){if(!i.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",i,this);continue}}else{console.warn("Missing reaction for signal",i,this);continue}i.reaction.invoke()}catch(n){console.error(n)}}};k([A(yr)],$i.prototype,"events",2);import*as re from"three";import{Quaternion as Iy,Vector3 as My}from"three";var Io=N("debugtimeline"),Mo=class{director;track;get muted(){return this.track.muted}set muted(e){e!==this.track.muted&&(this.track.muted=e,this.onMuteChanged?.call(this))}*forEachClip(e=!1){if(!!this.track?.clips)if(e)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(let t of this.track.clips)yield t}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,i,n=!0){if(t<0||t>=i.length)return 0;let r=i[t];if(n||e>=r.start&&e<=r.end){let o=1,s=!1;return r.easeInDuration>0&&(o*=Math.min((e-r.start)/r.easeInDuration,1)),r.easeOutDuration>0&&!s&&(o*=Math.min((r.end-e)/r.easeOutDuration,1)),o}return 0}},gd=class{clip;rootPositionOffset;rootQuaternionOffset;get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}rootStartPosition;rootEndPosition;rootStartQuaternion;rootEndQuaternion;constructor(e){let t=e.getClip();this.clip=t;let i=e.getRoot(),n=i.name+".position",r=i.name+".quaternion";Io&&console.log(t.name,t.tracks,n);for(let o of t.tracks)if(!(o.times.length<=0)){if(o.name.endsWith(n))this.rootStartPosition=new re.Vector3().fromArray(o.values,0),this.rootEndPosition=new re.Vector3().fromArray(o.values,o.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),Io&&console.log(this.rootPositionOffset);else if(o.name.endsWith(r)&&(this.rootStartQuaternion=new re.Quaternion().fromArray(o.values,0),this.rootEndQuaternion=new re.Quaternion().fromArray(o.values,o.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),Io)){let s=new re.Euler().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",s)}}}},Bn=class extends Mo{models=[];trackOffset;target;mixer;clips=[];actions=[];_actionOffsets=[];_didBind=!1;createHooks(e,t){if(t.tracks?.length<=0){console.warn("No tracks in AnimationClip",t);return}let i=t.tracks[0].name.split("."),n=i[i.length-2],r=n+".position",o=n+".quaternion",s=!1,c=!1;for(let d of t.tracks)d.name.endsWith(r)?(s=!0,this.createPositionInterpolant(t,e,d)):d.name.endsWith(o)&&(c=!0,this.createRotationInterpolant(t,e,d));if(!s||!c){let d=this.mixer?.getRoot(),a=t.tracks[0],h=a.name.lastIndexOf("."),u=a.name.substring(0,h),f=u.substring(u.lastIndexOf(".")+1),E=d.getObjectByName(f);if(E)if(s){if(!c){let b=t.tracks[0].name.substring(0,h)+".quaternion";Io&&console.warn("Create quaternion track",f,E);let y=E.quaternion,g=new re.QuaternionKeyframeTrack(b,[0,t.duration],[y.x,y.y,y.z,y.w,y.x,y.y,y.z,y.w]);t.tracks.push(g),this.createRotationInterpolant(t,e,g)}}else{let b=u+".position";Io&&console.warn("Create position track",f,E);let y=E.position,g=new re.VectorKeyframeTrack(b,[0,t.duration],[y.x,y.y,y.z,y.x,y.y,y.z]);t.tracks.push(g),this.createPositionInterpolant(t,e,g)}}}bind(){if(!this._didBind){this._didBind=!0,Io&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(let e of this.actions){let t=new gd(e);this._actionOffsets.push(t)}for(let e of this.models){let t=e.asset,i=t.position,n=t.rotation;i.x!==void 0&&(i.isVector3||(t.position=new My(i.x,i.y,i.z)),n.isQuaternion||(t.rotation=new Iy(n.x,n.y,n.z,n.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){let e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new re.Vector3(e.x,e.y,e.z)));let t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new re.Quaternion(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new re.Vector3;_totalOffsetRotation=new re.Quaternion;_totalOffsetPosition2=new re.Vector3;_totalOffsetRotation2=new re.Quaternion;_summedPos=new re.Vector3;_tempPos=new re.Vector3;_summedRot=new re.Quaternion;_tempRot=new re.Quaternion;evaluate(e){if(this.track.muted||!this.mixer)return;this.bind(),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,i=0,n=!1;for(let r=0;r<this.clips.length;r++){let o=this.models[r],s=this.actions[r],c=o.asset;s.weight=0;let d=e>=o.start&&e<=o.end,a=o.postExtrapolationMode,h=d;if(!h&&!n&&o.end<e&&o.postExtrapolationMode!==0){let u=r<this.clips.length-1?this.models[r+1]:null;(!u||u.start>e)&&(h=!0,n=!0)}if(h){let u=1;u*=this.evaluateWeight(e,r,this.models,h);let f=this.getClipTime(e,o),E=0,b=c.duration;if(d){if(c.loop)for(E+=Math.floor(f/(b+1e-6));f>b;)f-=b}else if(!d)switch(a){case 2:f%=b;break;case 3:let p=Math.floor(f/b)%2!==0;f%=b,p&&(f=b-f);break}s.time=f,s.timeScale=0;let y=u*this.director.weight;if(s.weight=y,s.clampWhenFinished=!0,s.isRunning()||s.play(),this._useclipOffsets){let g=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,p=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-u),t+=1;let m=this._summedPos.set(0,0,0),v=this._tempPos.set(0,0,0),w=this._summedRot.identity(),x=this._tempRot.identity(),T=c.rotation,R=new re.Quaternion;R.slerp(T,u);let C=this._actionOffsets[r];if(C.hasOffsets)for(let P=0;P<E;P++)C.rootPositionOffset?v.copy(C.rootPositionOffset):v.set(0,0,0),v.applyQuaternion(w).applyQuaternion(R),C.rootQuaternionOffset&&(x.copy(C.rootQuaternionOffset),w.multiply(x)),m.add(v);p.multiply(R),p.multiply(w),m.add(c.position),g.add(m)}}}this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,i),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,i)),this.mixer.update(e)}createRotationInterpolant(e,t,i){let n=i.createInterpolant.bind(i),r=new re.Quaternion;this.ensureTrackOffsets();let o=this.trackOffset?.rotation;i.createInterpolant=()=>{let s=n(),c=s.evaluate.bind(s);return s.evaluate=d=>{let a=c(d);return r.set(a[0],a[1],a[2],a[3]),r.premultiply(this._totalOffsetRotation),o&&r.premultiply(o),a[0]=r.x,a[1]=r.y,a[2]=r.z,a[3]=r.w,a},s}}createPositionInterpolant(e,t,i){let n=i.createInterpolant.bind(i),r=new re.Vector3;this.ensureTrackOffsets();let o=this.trackOffset?.rotation,s=this.trackOffset?.position,c;i.createInterpolant=()=>{let d=n(),a=d.evaluate.bind(d);return d.evaluate=h=>{let u=a(h);return r.set(u[0],u[1],u[2]),t.removeStartOffset&&(c===void 0?(c=null,c=this._actionOffsets.find(f=>f.clip===e)?.rootStartPosition?.clone()):c?.isVector3&&r.sub(c)),r.applyQuaternion(this._totalOffsetRotation),r.add(this._totalOffsetPosition),o&&r.applyQuaternion(o),s&&(r.x-=s.x,r.y+=s.y,r.z+=s.z),u[0]=r.x,u[1]=r.y,u[2]=r.z,u},d}}},Fn=class extends Mo{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;getAudioFilePath(e){let t=this.director.sourceId;return Ms(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){let i=this.models[t];this.audio[t].setVolume(e?i.asset.volume:0)}}addModel(e){let t=this.getAudioFilePath(e.asset.clip),i=new re.Audio(this.listener);i.setVolume(e.asset.volume);let n=new re.AudioLoader;console.log(t,this.director.sourceId),n.load(t,r=>{i.setBuffer(r),i.loop=e.asset.loop,this.audio.push(i),this.models.push(e)})}onDisable(){for(let e of this.audio)e.isPlaying&&e.stop()}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){let t=this.audio[e];t?.isPlaying&&t.stop()}}evaluate(e){if(!this.track.muted){for(let t=0;t<this.models.length;t++){let i=this.models[t],n=this.audio[t];if(e>=i.start&&e<=i.end){if(this.director.isPaused&&(n.isPlaying&&n.stop(),this.lastTime===e))continue;n.isPlaying||(n.offset=i.clipIn+(e-i.start)*i.timeScale,n.play());let r=i.asset.volume;i.easeInDuration>0&&(r*=Math.min((e-i.start)/i.easeInDuration,1)),i.easeOutDuration>0&&(r*=Math.min((i.end-e)/i.easeOutDuration,1)),n.setVolume(r*this.director.weight)}else n.isPlaying&&n.stop()}this.lastTime=e}}},en=class extends Mo{models=[];didTrigger=[];receivers=[];evaluate(e){if(!(this.receivers.length<=0)&&!this.track.muted)for(let t=0;t<this.models.length;t++){let i=this.models[t],n=this.didTrigger[t],r=i.time-e;if(i.retroActive?r<0:r<0&&Math.abs(r)<.1){if(!n){this.didTrigger[t]=!0;for(let s of this.receivers)!s||s.invoke(i.asset)}}else i.emitOnce||(this.didTrigger[t]=!1)}}},_s=class extends Mo{models=[];timelines=[];resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){let n=this.models[t].asset;if(typeof n.sourceObject=="string"){let r=n.sourceObject;_s.resolved[r]?n.sourceObject=_s.resolved[r]:(n.sourceObject=O.findByGuid(r,e.scene),_s.resolved[r]=n.sourceObject)}if(n.sourceObject){let r=O.getComponent(n.sourceObject,tn);this.timelines.push(r),r&&n.updateDirector&&(r.playOnAwake=!1)}else{this.models.splice(t,1);continue}}}_previousActiveModel=null;evaluate(e){this._previousActiveModel=null;for(let t=0;t<this.models.length;t++){let i=this.models[t],n=i.asset;if(e>=i.start&&e<=i.end){this._previousActiveModel=i;let r=this.getClipTime(e,i);if(n.controlActivation){let o=n.sourceObject;o.visible=!0}if(n.updateDirector){let o=this.timelines[t];o&&(o.isPlaying&&o.pause(),o.time=r,o.evaluate())}}else{let r=this._previousActiveModel?.asset;if(n.controlActivation){let o=n.sourceObject;r?.sourceObject!==o&&(o.visible=!1)}}}}},Ki=_s;z(Ki,"resolved",{});var Yp=N("debugtimeline");var Ya=class extends M{static registerCreateTrack(e,t){this.createTrackFunctions[e]=t}playableAsset;playOnAwake;extrapolationMode=1;get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(e){this._time=e}get duration(){return this._duration}set duration(e){this._duration=e}get weight(){return this._weight}set weight(e){this._weight=e}_visibilityChangeEvt;_clonedPlayableAsset=!1;awake(){Yp&&console.log(this,this.playableAsset?.tracks),this.rebuildGraph(),this.playOnAwake?this.play():this.evaluate(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,this.playableAsset?.tracks,Array.isArray(this.playableAsset?.tracks),this)}onEnable(){for(let e of this._audioTracks)e.onEnable?.();for(let e of this._customTracks)e.onEnable?.();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(){this.stop();for(let e of this._audioTracks)e.onDisable?.();for(let e of this._customTracks)e.onDisable?.();this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){for(let e of this._audioTracks)e.onDestroy?.()}rebuildGraph(){!this.isValid()||(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}play(){!this.isValid()||(this._isPaused=!1,!this._isPlaying&&(this._isPlaying=!0,this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate())))}pause(){this._isPaused=!0}stop(){this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.evaluate()),this._isPlaying=!1,this._isPaused=!1,this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null}evaluate(){if(!this.isValid())return;let e=this._time;switch(this.extrapolationMode){case 0:e=Math.min(e,this._duration);break;case 1:e%=this._duration;break;case 2:if(e>this._duration){this.stop();return}break}this.internalEvaluate(e)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(let e of this._allTracks)for(let t of e)yield t}get audioTracks(){return this._audioTracks}_guidsMap;resolveGuids(e){this._guidsMap=e}_isPlaying=!1;_internalUpdateRoutine;_isPaused=!1;_time=0;_duration=0;_weight=1;_animationTracks=[];_audioTracks=[];_signalTracks=[];_controlTracks=[];_customTracks=[];_allTracks=[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks];*internalUpdate(){for(;this._isPlaying;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime,this.evaluate()),yield}internalEvaluate(e){for(let t of this.playableAsset.tracks)if(!t.muted)switch(t.type){case"ActivationTrack":for(let i=0;i<t.outputs.length;i++){let n=t.outputs[i];if(typeof n=="object"){let r=!1;for(let s of t.clips)s.start<=e&&e<=s.end&&(r=!0);let o=n;o.visible!==void 0&&(o.visible=r)}}break}for(let t of this._animationTracks)t.evaluate(e);for(let t of this._audioTracks)t.evaluate(e);for(let t of this._signalTracks)t.evaluate(e);for(let t of this._controlTracks)t.evaluate(e);for(let t of this._customTracks)t.evaluate(e)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Qo(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;let e=this.findRoot(this.gameObject);for(let t of this.playableAsset.tracks)for(let i=t.outputs.length-1;i>=0;i--){let n=t.outputs[i];if(typeof n=="string"){this._guidsMap&&this._guidsMap[n]&&(n=this._guidsMap[n]);let r=O.findByGuid(n,e);r===null||typeof r!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(Yp&&console.log("Resolved binding",n,"to",r),t.outputs[i]=r)}else if(n===null){if(t.outputs.splice(i,1),Ya.createTrackFunctions[t.type])continue;t.type!=="AudioTrack"&&t.type!=="ControlTrack"&&t.type!=="MarkerTrack"&&console.warn("Missing binding",n,t.name,t.type,this.name,this.playableAsset.name)}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(let e of this.playableAsset.tracks)if(e.muted!==!0)for(let t of e.clips)t.end>this._duration&&(this._duration=t.end)}}setupAndCreateTrackHandlers(){if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let e=[];for(let t of this.playableAsset.tracks){let i=t.type,n=Ya.createTrackFunctions[i];if(n!=null){let r=n(this,t);if(typeof r.evaluate=="function"){r.director=this,r.track=t,this._customTracks.push(r);continue}}if(t.type==="AnimationTrack"){if(t.clips.length<=0)continue;for(let r=t.outputs.length-1;r>=0;r--){let o=t.outputs[r];typeof o.enabled=="boolean"&&(o.enabled=!1);let s=o?.gameObject?.animations;if(s){let c=new Bn;c.trackOffset=t.trackOffset,c.director=this,c.track=t;for(let d=0;d<t.clips.length;d++){let a=t.clips[d],h=a.asset;if(!h){console.error("MISSING anim model?","clip#"+d,a,t,this.playableAsset,this.name);continue}let u=h.clip,f=u;if((typeof f=="string"||typeof f=="number")&&(f=s.find(b=>b.name===u)),!f){console.warn("Could not find animationClip for model",a,t.name,this.name,this.playableAsset?.name);continue}c.mixer||(c.mixer=new Zp.AnimationMixer(o.gameObject)),c.clips.push(f),c.mixer.uncacheAction(f),c.createHooks(a.asset,f);let E=c.mixer.clipAction(f);c.actions.push(E),c.models.push(a)}this._animationTracks.push(c)}}}else if(t.type==="AudioTrack"){if(t.clips.length<=0)continue;e.push(t)}else if(t.type==="MarkerTrack"){let r=new en;r.director=this,r.track=t;for(let o of t.markers)switch(o.type){case"SignalEmitter":r.models.push(o),r.didTrigger.push(!1);break}if(r!==null&&r.models.length>0){let o=O.getComponent(this.gameObject,$i);o&&(r.receivers.push(o),this._signalTracks.push(r))}}else if(t.type==="SignalTrack"){let r=new en;r.director=this,r.track=t;for(let o of t.markers)r.models.push(o),r.didTrigger.push(!1);for(let o of t.outputs)r.receivers.push(o);this._signalTracks.push(r)}else if(t.type==="ControlTrack"){let r=new Ki;r.director=this,r.track=t;for(let o of t.clips)r.models.push(o);r.resolveSourceObjects(this.context),this._controlTracks.push(r)}}ue.registerWaitForAllowAudio(()=>{let t=O.findObjectOfType($t,this.context);if(!!t)for(let i of e){let n=new Fn;n.director=this,n.track=i,n.listener=t.listener;for(let r=0;r<i.clips.length;r++){let o=i.clips[r];n.addModel(o)}this._audioTracks.push(n)}})}setAudioTracksAllowPlaying(e){for(let t of this._audioTracks)t.onAllowAudioChanged(e)}},tn=Ya;z(tn,"createTrackFunctions",{});import*as Jp from"three-mesh-ui";var ii=class{used=!1;Use(){this.used=!0}StopPropagation(){this.event?.stopImmediatePropagation()}inputSource;object;isDown;isUp;isPressed;isClicked;event;constructor(e){this.event=e}};import{Object3D as Dy}from"three";var Hy=N("debugeventsystem"),Ri=class extends M{static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Ri.systems.length<=0&&Ri.systems.push(...O.findObjectsOfType(Ri,e)));for(let i of Ri.systems)if(i.context===e)return;let t=new Dy;O.addNewComponent(t,Ri),e.scene.add(t)}static ensureUpdateMeshUI(e,t){ni.update(e,t)}static markUIDirty(e){ni.markDirty()}static get instance(){return this.systems[0]}orbitControl=null;orbitControlWasEnabled=!1;raycaster=[];constructor(){super(),Ri.systems.push(this)}onDestroy(){Ri.systems.splice(Ri.systems.indexOf(this),1)}start(){}register(e){e&&this.raycaster&&!this.raycaster.includes(e)&&this.raycaster?.push(e)}unregister(e){let t=this.raycaster?.indexOf(e);t!==void 0&&t!==-1&&this.raycaster?.splice(t,1)}onEnable(){se.addEventListener("select-start",(t,i)=>{if(!i.grab)return;ni.resetLastSelected();let n=new ii;n.inputSource=t,n.isDown=t.selectionDown,n.isUp=t.selectionUp,n.isPressed=t.selectionPressed,n.isClicked=!1,i.grab&&!this.handleEvents(i.grab,n)&&(i.grab=null)});let e=new je;se.addEventListener("select-end",(t,i)=>{if(!i.grab)return;let n=new ii;n.inputSource=t,n.isDown=t.selectionDown,n.isUp=t.selectionUp,n.isPressed=t.selectionPressed,n.isClicked=t.selectionClick,this.handleEvents(i.grab,n)}),se.addEventListener("update",t=>{e.ray=t.getRay();let i=this.performRaycast(e);if(!i)return;let n=new ii;n.inputSource=t,this.handleIntersections(i,n)}),this.context.pre_update_callbacks.push(this.onBeforeUpdate.bind(this)),this.context.input.addEventListener("pointerDown",this.onPointerDown.bind(this))}onDisable(){}onPointerDown(){this.onBeforeUpdate()}lastPointerEvent=null;objectsHoveredThisFrame=[];objectsHoveredLastFrame=[];raisedPointerDownEvents=[];_didMove=!1;onBeforeUpdate(){if(this.objectsHoveredThisFrame.length=0,this.resetMeshUIStates(),$.IsInWebXR||this.context.input.isKeyPressed(18))return;if(!this._didMove){let r=this.context.input.getPointerPositionRC(0);if(r&&r.x===0&&r.y===0)return;this._didMove=!0}let e=this.performRaycast(null),t=new ii(this.context.input.getPointerEvent(0));if(t.inputSource=this.context.input,t.isClicked=this.context.input.mouseClick,t.isDown=this.context.input.mouseDown,t.isUp=this.context.input.mouseUp,t.isPressed=this.context.input.mousePressed,this.lastPointerEvent=t,!e)return;let i=null,n=null;this.context.input.mouseDown&&this.currentActiveMeshUIComponents.length>0&&this.context.mainCameraComponent&&(i=O.getComponent(this.context.mainCameraComponent.gameObject,gt)??null,i&&(n=i.enabled,i.enabled=!1)),this.handleIntersections(e,t),i&&(this.orbitControl=i,this.orbitControl?.enabled?(this.orbitControlWasEnabled=this.orbitControl.enabled,this.orbitControl.enabled=!1):this.orbitControl&&!this.context.input.mousePressed&&(this.orbitControl.enabled=this.orbitControlWasEnabled,this.orbitControl=null))}_tempComponentsArray=[];onBeforeRender(){if(this.lastPointerEvent)this.lastPointerEvent.used=!1;else return;if(this.lastPointerEvent.isUp){for(let t of this.raisedPointerDownEvents)t.onPointerUp&&t.onPointerUp(this.lastPointerEvent);this.raisedPointerDownEvents.length=0}for(let t of this.objectsHoveredLastFrame)if(this.objectsHoveredThisFrame.indexOf(t)<0){this._tempComponentsArray.length=0;let i=O.getComponentsInParent(t,M,this._tempComponentsArray);this.lastPointerEvent.object=t;for(let n=0;n<i.length;n++){let r=i[n];if(!r.gameObject||r.destroyed)continue;let o=r;o.onPointerExit&&o.onPointerExit(this.lastPointerEvent)}}let e=this.objectsHoveredLastFrame;this.objectsHoveredLastFrame=this.objectsHoveredThisFrame,this.objectsHoveredThisFrame=e}_sortedHits=[];performRaycast(e){if(!this.raycaster)return null;this._sortedHits.length=0;for(let t of this.raycaster){if(!t.activeAndEnabled)continue;let i=t.performRaycast(e);i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}handleIntersections(e,t){if(!e||e.length<=0)return!1;e=this.sortCandidates(e);for(let i of e){let{object:n}=i;if(this.handleEvents(n,t))return!0}return!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){let i=e[t],n=i.object;if(n.material&&n.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(let t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventsArray=[];handleEvents(e,t){if(!this.testIsVisible(e))return t.isClicked&&Hy&&console.log("not allowed",e),!1;t.object=e,this.lastPointerEvent=t;let i=e.parent,n=!1,r=t.isClicked??!1,o=null;if(i&&i.isUI){let s=(t.isPressed||t.isClicked)??!1;if(i.shadowComponentOwner){let c=i.shadowComponentOwner.gameObject;if(c){if(o=this.tryFindCanvasGroup(c),o?.blocksRaycasts===!1)return!1;if(o?.interactable===!1)return!0;let d=this.handleMeshUIIntersection(e,s);e=c,n=!0}}if(!n&&this.handleMeshUiObjectWithoutShadowDom(i,s))return!0}if(this.objectsHoveredThisFrame.push(e),o===null||o.interactable){let s=this.objectsHoveredLastFrame.indexOf(e)>=0;this.handleEventsArray.length=0;let c=O.getComponentsInParent(e,M,this.handleEventsArray);for(let d=0;d<c.length;d++){if(t.used)return!0;if(c[d].destroyed)continue;let a=c[d];a.interactable!==!1&&(a.onPointerEnter&&(s||a.onPointerEnter(t)),t.isDown&&a.onPointerDown&&!this.raisedPointerDownEvents.includes(a)&&(a.onPointerDown(t),this.raisedPointerDownEvents.push(a)),t.isUp&&a.onPointerUp&&a.onPointerUp(t),t.isClicked&&a.onPointerClick&&a.onPointerClick(t))}}return!0}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){let i=ni.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&ni.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){let t=this.currentActiveMeshUIComponents[e];ni.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?O.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}tryFindCanvasGroup(e){if(!e)return null;let t=O.foreachComponent(e,i=>{let n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}},Ze=Ri;z(Ze,"didSearchEventSystem",!1),z(Ze,"systems",[]);var ni=class{static markDirty(){this.needsUpdate=!0}static update(e,t){for(let i of this.lastUpdateFrame)if(i.context===t){if(t.time.frameCount===i.frame)return;i.frame=t.time.frameCount,(this.needsUpdate||t.time.frameCount<30)&&(this.needsUpdate=!1,e.update());return}this.lastUpdateFrame=[{context:t,frame:t.time.frameCount}],e.update()}static updateState(e,t){let i=null;if(e&&(i=this.findBlockInParent(e),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;t?(this.lastSelected=i,i.states.pressed&&i.setState("pressed")):i.states.hovered&&i.setState("hovered"),this.needsUpdate=!0}return i}static resetLastSelected(){let e=this.lastSelected;!e||(this.lastSelected=null,this.resetState(e))}static resetState(e){if(!e)return;e.interactable===!1?e.states.disabled&&e.setState("disabled"):e===this.lastSelected&&e.states.selected?e.setState("selected"):e.setState("normal"),this.needsUpdate=!0}static findBlockInParent(e){return e?e.isBlock&&Object.keys(e.states).length>0?e:this.findBlockInParent(e.parent):null}};z(ni,"lastSelected",null),z(ni,"lastUpdateFrame",[]),z(ni,"needsUpdate",!1);import{AxesHelper as jy}from"three";var Lo="./include";Jp.Block.prototype.interactable={get(){return this.interactive},set(l){this.interactable=l}};var Ue=class extends M{isRoot(){return this.Root?.gameObject===this.gameObject}markDirty(){Ze.markUIDirty(this.context)}shadowComponent=null;_controlsChildLayout=!0;get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}_root=void 0;get Root(){return this._root===void 0&&(this._root=O.getComponentInParent(this.gameObject,nn)),this._root}_parentComponent=void 0;onEnable(){super.onEnable()}addShadowComponent(e,t){this.removeShadowComponent();let i=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=O.getComponentInParent(i,Ue),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have a UI element outside a Canvas?`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e.shadowComponentOwner=this;let n=this.raycastTarget;if(e.traverse(r=>{r.shadowComponentOwner===void 0&&(r.shadowComponentOwner=this),n===!1&&r.layers.set(2)}),this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{let r=this._parentComponent.shadowComponent;r&&r?.add(e)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),hi&&e.add(new jy(.5)),this.onAfterAddedToScene()}set(e){}traverseOwnedShadowComponents(e,t,i){if(!!e&&e.shadowComponentOwner===t){i(e);for(let n of e.children)this.traverseOwnedShadowComponents(n,t,i)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}},nn=class extends Ue{awake(){super.awake()}};import{Color as Ny,Texture as ef}from"three";import*as vd from"three-mesh-ui";import{Matrix4 as By,Object3D as Fy,Vector2 as $p,Vector3 as bd}from"three";var Kp=N("debugui"),Do=class{width;height},Er=class{x;y;width;height},ut=class extends Ue{offset=.01;get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}_anchoredPosition;get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new bd),this._anchoredPosition}rect;sizeDelta;anchoredPosition3D;pivot;lastMatrix;rectBlock;_transformNeedsUpdate=!1;awake(){super.awake(),this.lastMatrix=new By,this.rectBlock=new Fy,this.rectBlock.position.z=.1,this.rectBlock.name=this.name,this._anchoredPosition||(this._anchoredPosition=new bd),Zr(this,"_anchoredPosition",()=>{this._transformNeedsUpdate=!0})}onEnable(){super.onEnable(),this.addShadowComponent(this.rectBlock),this.applyTransform()}onDisable(){super.onDisable(),this.removeShadowComponent()}applyTransform(){let e=this.shadowComponent;!e||(this._transformNeedsUpdate=!1,this.isRoot()?e.rotation.y=Math.PI:(e.position.copy(this.gameObject.position),e.position.x*=-1,e.position.z*=-1,e.position.z-=this.offset,e.quaternion.copy(this.gameObject.quaternion),e.rotation.x*=-1,e.rotation.z*=-1,e.scale.copy(this.gameObject.scale)),this.applyAnchoring(e.position),this.lastMatrix.copy(this.gameObject.matrix))}markDirty(){this._transformNeedsUpdate=!0}onBeforeRender(){(this._transformNeedsUpdate||this.lastMatrix.equals(this.gameObject.matrix)===!1)&&(Kp&&console.log("updating",this.name),this.applyTransform()),Ze.ensureUpdateMeshUI(vd,this.context)}applyAnchoring(e){if(this.pivot&&this.sizeDelta){let t=this.pivot.x*2-1,i=this.pivot.y*2-1;i-=this.anchoredPosition.y*.05;let n=this.sizeDelta.x*t,r=this.sizeDelta.y*i;e.x-=n*.5,e.y-=r*.5}}getBasicOptions(){let e={width:this.rect.width,height:this.rect.height,offset:this.offset,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}_createdBlocks=[];createNewBlock(e){e={...this.getBasicOptions(),...e},Kp&&console.log(this.name,e);let t=new vd.Block(e);return this._createdBlocks.push(t),t}};k([A(Er)],ut.prototype,"rect",2),k([A($p)],ut.prototype,"sizeDelta",2),k([A(bd)],ut.prototype,"anchoredPosition3D",2),k([A($p)],ut.prototype,"pivot",2);var Rt=class extends Ue{get color(){return this._color||(this._color=new we(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new we(1,1,1,1)),this._color.copy(e))}onColorChanged(){let e=this.color;this.setOptions({backgroundColor:e,backgroundOpacity:e.alpha,borderOpacity:e.alpha})}get m_Color(){return this._color}raycastTarget=!0;uiObject=null;_color=null;_rect=null;get rectTransform(){return this._rect||(this._rect=this.gameObject.getComponent(ut)),this._rect}setState(e){this.makePanel(),this.uiObject&&this.uiObject.setState(e)}setupState(e){this.makePanel(),this.uiObject&&this.uiObject.setupState(e)}setOptions(e){this.makePanel(),this.uiObject&&(this.uiObject.set(e),(e.backgroundColor!==void 0||e.backgroundOpacity!==void 0)&&this.uiObject.updateBackgroundMaterial?.call(this.uiObject))}awake(){super.awake(),this.makePanel(),Zr(this,"_color",()=>yp(this,this.onColorChanged))}onEnable(){super.onEnable(),this.uiObject&&(this.rectTransform.shadowComponent?.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}_currentlyCreatingPanel=!1;makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;let e={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:1};this.onBeforeCreate(e),this.onCreate(e),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}async setTexture(e){!e||(this.setOptions({backgroundOpacity:0}),e&&this.setOptions({backgroundTexture:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}))}onAfterAddedToScene(){this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}};k([A(we)],Rt.prototype,"color",1),k([A()],Rt.prototype,"raycastTarget",2);var rn=class extends Rt{onAfterCreated(){this.uiObject&&(this.uiObject.scale.y*=-1)}};var Za=class{texture;rect};k([A(ef)],Za.prototype,"texture",2);var on=class extends rn{sprite;isBuiltinSprite(){switch(this.sprite?.texture?.name){case"InputFieldBackground":case"UISprite":case"Background":return!0}return!1}onBeforeCreate(e){this.isBuiltinSprite()&&(e.borderRadius=5,e.borderColor=new Ny(.4,.4,.4),e.borderOpacity=this.color.alpha,e.borderWidth=.3)}onAfterCreated(){super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture)}};k([A(Za)],on.prototype,"sprite",2);var wr=class extends rn{mainTexture;onAfterCreated(){super.onAfterCreated(),this.setTexture(this.mainTexture)}};k([A(ef)],wr.prototype,"mainTexture",2);var Ho=N("debugbutton");var Ft=class extends M{onClick;_isHovered=!1;onPointerEnter(e){Ho&&console.log("Button Enter",this.animationTriggers?.highlightedTrigger,this.animator),this._isHovered=!0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&this._image?.setState("hovered")}onPointerExit(){Ho&&console.log("Button Exit",this.animationTriggers?.highlightedTrigger,this.animator),this._isHovered=!1,this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState("normal")}onPointerDown(e){Ho&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&this._image?.setState("pressed")}onPointerUp(e){Ho&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState(this._isHovered?"hovered":"normal")}onPointerClick(e){Ho&&console.trace("Button Click",this.onClick),this.onClick?.invoke()}colors;transition;animationTriggers;animator;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}_interactable=!0;set_interactable(e){this.interactable=e}awake(){super.awake(),Ho&&console.log(this),this.init()}start(){this._image?.setInteractable(this.interactable)}onEnable(){super.onEnable()}_requestedAnimatorTrigger;*setAnimatorTriggerAtEndOfFrame(e){this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&this.animator?.SetTrigger(e)}_isInit=!1;_image;init(){this._isInit||(this._isInit=!0,this._image=O.getComponent(this.gameObject,on),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){e.setInteractable(this.interactable);let t=this.getFinalColor(e.color,this.colors?.normalColor),i={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(i);let n=this.getFinalColor(e.color,this.colors?.highlightedColor),r={state:"hovered",attributes:{backgroundColor:n,backgroundOpacity:n.alpha}};e.setupState(r);let o=this.getFinalColor(e.color,this.colors?.pressedColor),s={state:"pressed",attributes:{backgroundColor:o,backgroundOpacity:o.alpha}};e.setupState(s);let c=this.getFinalColor(e.color,this.colors?.selectedColor),d={state:"selected",attributes:{backgroundColor:c,backgroundOpacity:c.alpha}};e.setupState(d);let a=this.getFinalColor(e.color,this.colors?.disabledColor),h={state:"disabled",attributes:{backgroundColor:a,backgroundOpacity:a.alpha}};e.setupState(h)}getFinalColor(e,t){return t?e.clone().multiply(t):e.clone()}};k([A(Oe)],Ft.prototype,"onClick",2),k([A()],Ft.prototype,"colors",2),k([A()],Ft.prototype,"transition",2),k([A()],Ft.prototype,"animationTriggers",2),k([A(bt)],Ft.prototype,"animator",2),k([A()],Ft.prototype,"interactable",1);var yd=class extends nn{set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop}_renderOnTop=!1;set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}_depthWrite=!1;set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}_doubleSided=!0;set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}_castShadows=!0;set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}_receiveShadows=!0;get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}_renderMode=-1;_rootCanvas;set rootCanvas(e){this._rootCanvas instanceof yd||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}awake(){this.shadowComponent=this.gameObject,super.awake()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this.onRenderSettingsChanged()}previousAspect=-1;onBeforeRender(){this.isScreenSpace&&this.context.mainCameraComponent&&this.context.mainCameraComponent.aspect!==this.previousAspect&&(this.previousAspect=this.context.mainCameraComponent.aspect,this.updateRenderMode())}_updateRenderSettingsRoutine;onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),3))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.updateRenderMode(),Yr(this.shadowComponent,this);for(let e of this.gameObject.getComponentsInChildren(Ue))Yr(e.shadowComponent,this)}}_activeRenderMode=-1;get isScreenSpace(){return this._activeRenderMode===1||this._activeRenderMode===0}updateRenderMode(){if(this.renderMode!==this._activeRenderMode)switch(this.renderMode){case 0:case 1:let e=this.context.mainCameraComponent;if(!e)return;let t=this.gameObject;e.gameObject?.add(t);let n=e.farClipPlane;t.position.x=0,t.position.y=0,t.position.z=-n;let r=Math.tan(Q.toRadians(e.fieldOfView)*n)*(e.aspect*1.333333),o=r*(this.context.domHeight/this.context.domWidth);t.scale.x=-r,t.scale.y=o;break;case 2:break}}},Je=yd;k([A()],Je.prototype,"renderOnTop",1),k([A()],Je.prototype,"depthWrite",1),k([A()],Je.prototype,"doubleSided",1),k([A()],Je.prototype,"castShadows",1),k([A()],Je.prototype,"receiveShadows",1),k([A()],Je.prototype,"renderMode",1),k([A(Je)],Je.prototype,"rootCanvas",1);var sn=class extends M{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}_alpha=1;interactable=!0;blocksRaycasts=!0;_isDirty=!1;markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),3))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){for(let e of O.getComponentsInChildren(this.gameObject,Rt,this._buffer)){let t=e.color;t.alpha=this._alpha,e.color=t}}};k([A()],sn.prototype,"alpha",1),k([A()],sn.prototype,"interactable",2),k([A()],sn.prototype,"blocksRaycasts",2);import*as tf from"three-mesh-ui";import{Color as B}from"three";var zy=N("debugtext");var Le=class extends Rt{canvas;alignment=0;verticalOverflow=0;horizontalOverflow=0;lineSpacing=1;supportRichText=!1;font;fontStyle=0;get text(){return this._text}set text(e){if(this._text=e,!this._textMeshUi&&this._text.length>0&&this.context.time.frame>0&&this.createText(e,this.getTextOpts(),this.supportRichText),this._textMeshUi){if(this._textMeshUi.length>1){this.requestRebuild();return}this._textMeshUi[0].set({content:e}),this.markDirty()}}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){if(this._fontSize=e,this._textMeshUi){if(this._textMeshUi.length>1){this.requestRebuild();return}this._textMeshUi[0].set({content:e}),this.markDirty()}}onColorChanged(){if(this._textMeshUi){if(this._textMeshUi.length>1){this.requestRebuild();return}let e=this.color;this._textMeshUi[0].set({fontColor:e,fontOpacity:e.alpha}),this.markDirty()}}_isWaitingForRebuild=!1;requestRebuild(){this._isWaitingForRebuild||(this._isWaitingForRebuild=!0,this.startCoroutine(this.rebuildDelayedRoutine(),0))}*rebuildDelayedRoutine(){if(this._isWaitingForRebuild=!1,this._textMeshUi){for(let e of this._textMeshUi)e.removeFromParent();this._textMeshUi.length=0}this.createText(this.text,this.getTextOpts(),this.supportRichText),this.markDirty()}onCreate(e){zy&&console.log(this);let t=this.verticalOverflow==0&&this.horizontalOverflow==0;t&&(this.context.renderer.localClippingEnabled=!0);let i=this.rectTransform;this._textContainer=this.uiObject=this.createBlock(i,t,null,!0),this.createText(this.text,this.getTextOpts(),this.supportRichText),this.uiObject,this.uiObject=this.createBlock(i,t,this.uiObject,!1)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}_text="";_fontSize=12;_textMeshUi=null;_textContainer=null;getTextOpts(){let e={content:this.text,fontColor:this.color,fontOpacity:this.color.alpha,fontSize:this.fontSize,fontKerning:"normal"};return this.font=this.font?.toLocaleLowerCase(),this.setFont(e,this.fontStyle),e}onEnable(){super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&(this.uiObject.onAfterUpdate=this.updateWidth.bind(this))}createBlock(e,t,i,n=!1){let r={};r.hiddenOverflow=t,r.interLine=(this.lineSpacing-1)*this.fontSize*1.333,this.getAlignment(r,n);let o=e.createNewBlock(r);return i&&(Array.isArray(i)?o.add(...i):o.add(i)),o}getAlignment(e,t=!1){switch(t||(e.contentDirection="row"),this.alignment){default:case 0:case 1:case 2:e.justifyContent="start";break;case 3:case 4:case 5:e.justifyContent="center";break;case 6:case 7:case 8:e.justifyContent="end";break}switch(this.alignment){case 0:case 3:case 6:e.alignContent=t?"left":"top";break;case 1:case 4:case 7:e.alignContent="center";break;case 2:case 5:case 8:e.alignContent=t?"right":"bottom";break}return e}updateWidth(){this.horizontalOverflow===1&&setTimeout(()=>{if(!this._textMeshUi)return;let e=this._textMeshUi[0].parent;if(!!e&&e.lines){let t=e.lines.reduce((i,n)=>i+n.width,0);t+=e.getFontSize()*5,t+=e.padding*2||0,t+=this.fontSize*1.5,e.set({width:t}),this.ensureShadowComponentOwner()}},1)}ensureShadowComponentOwner(){this.shadowComponent&&this.shadowComponent.traverse(e=>{e.shadowComponentOwner===void 0&&(e.shadowComponentOwner=this)})}createText(e,t,i){if(!(!e||e.length<=0))if(this._textMeshUi||(this._textMeshUi=[]),i){let n=this.getNextTag(e);if(n)n.startIndex>0&&this.createText(e.substring(0,n.startIndex),t,!1);else return this.createText(e,t,!1);let r=[];for(;n;){let o=this.getNextTag(e,n.endIndex);if(o){let s=this.getText(e,n,o);this.handleTag(n,t,r),this.createText(s,t,!1)}else{let s=e.substring(n.endIndex);this.handleTag(n,t,r),this.createText(s,t,!1)}n=o}}else{let n={...t};n.content=e;let r=new tf.Text(n);this._textMeshUi.push(r),this._textContainer&&this._textContainer.add(r)}}_didHandleTextRenderOnTop=!1;handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;let e=[],t=this.canvas,i={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let n=!1;if(this._textMeshUi)for(let r=0;r<this._textMeshUi.length;r++){if(e[r]===!0)continue;n=!0;let o=this._textMeshUi[r];!o.textContent||(Yr(o,i),e[r]=!0)}if(!n)break;yield}}handleTag(e,t,i){if(e.isEndTag){if(i.length>0){let n=i.pop();if(n)for(let r in n.previousValues){let o=n.previousValues[r];t[r]=o}}}else if(e.type.includes("color")){let n=new xs(e,{fontColor:t.fontColor});if(i.push(n),e.type.length>6){let r=e.type.substring(6);t.fontColor=Gy(r)}else t.fontColor=new B(1,1,1)}else if(e.type=="b"){let n=new xs(e,{fontFamily:t.fontFamily,fontTexture:t.fontTexture});i.push(n),this.setFont(t,1)}else if(e.type=="i"){let n=new xs(e,{fontFamily:t.fontFamily,fontTexture:t.fontTexture});i.push(n),this.setFont(t,2)}}getText(e,t,i){return e.substring(t.endIndex,i.startIndex)}getNextTag(e,t=0){let i=e.indexOf("<",t),n=e.indexOf(">",i);if(i>=0&&n>=0){let r=e.substring(i+1,n);return{type:r,startIndex:i,endIndex:n+1,isEndTag:r.startsWith("/")}}return null}setFont(e,t){let i=this.getFontName(t),n=i;n?.endsWith("-msdf.json")||(n+="-msdf.json"),e.fontFamily=n;let r=i;r?.endsWith(".png")||(r+=".png"),e.fontTexture=r}getFontName(e){return this.font?this.font:null}};k([A(Je)],Le.prototype,"canvas",2),k([A()],Le.prototype,"alignment",2),k([A()],Le.prototype,"verticalOverflow",2),k([A()],Le.prototype,"horizontalOverflow",2),k([A()],Le.prototype,"lineSpacing",2),k([A()],Le.prototype,"supportRichText",2),k([A()],Le.prototype,"font",2),k([A()],Le.prototype,"fontStyle",2),k([A()],Le.prototype,"text",1),k([A()],Le.prototype,"fontSize",1);var xs=class{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}};function Gy(l){if(l.startsWith("#")){let t=l.substring(1);var e=parseInt(t,16);let i=e>>16&255,n=e>>8&255,r=e&255;return new B(i/255,n/255,r/255)}switch(l){case"black":return new B(0,0,0);case"white":return new B(1,1,1);case"red":return new B(1,0,0);case"lime":return new B(0,1,0);case"blue":return new B(0,0,1);case"yellow":return new B(1,1,0);case"cyan":return new B(0,1,1);case"magenta":return new B(1,0,1);case"silver":return new B(.75,.75,.75);case"gray":return new B(.5,.5,.5);case"maroon":return new B(.5,0,0);case"olive":return new B(.5,.5,0);case"green":return new B(0,.5,0);case"purple":return new B(.5,0,.5);case"teal":return new B(0,.5,.5);case"navy":return new B(0,0,.5);case"darkred":return new B(.54,0,0);case"brown":return new B(.55,.27,0);case"firebrick":return new B(.69,.13,.13);case"crimson":return new B(.86,.08,.24);case"tomato":return new B(1,.39,.28);case"coral":return new B(1,.49,.31);case"indianred":return new B(.6,.31,.51);case"lightcoral":return new B(.94,.5,.5);case"darkorange":return new B(1,.55,0);case"orange":return new B(1,.65,0);case"gold":return new B(1,.84,0);case"darkgoldenrod":return new B(.72,.53,.04);case"goldenrod":return new B(.85,.65,.13);case"palegoldenrod":return new B(.93,.87,.67);case"darkkhaki":return new B(.74,.7,.42);case"khaki":return new B(.94,.9,.55);case"yellowgreen":return new B(.6,.8,.19);case"darkolivegreen":return new B(.33,.42,.18);case"olivedrab":return new B(.42,.56,.14);case"lawngreen":return new B(.49,.99,0);case"chartreuse":return new B(.5,1,0);case"greenyellow":return new B(.68,1,.18);case"darkgreen":return new B(0,.39,0);case"forestgreen":return new B(.13,.55,.13);case"limegreen":return new B(.19,.8,.19);case"lightgreen":return new B(.56,.93,.56);case"palegreen":return new B(.59,.98,.59);case"darkseagreen":return new B(.56,.74,.56);case"mediumspringgreen":return new B(0,.98,.6);case"springgreen":return new B(0,1,.5);case"seagreen":return new B(.18,.31,.31);case"mediumaquamarine":return new B(.4,.8,.66);case"mediumseagreen":return new B(.24,.7,.44);case"lightseagreen":return new B(.13,.7,.67);case"darkslategray":return new B(.18,.31,.31);case"darkcyan":return new B(0,.55,.55);case"aqua":return new B(0,1,1);case"lightcyan":return new B(.8,1,1);case"darkturquoise":return new B(0,.81,.82);case"turquoise":return new B(0,.82,.82);case"mediumturquoise":return new B(.28,.82,.8);case"paleturquoise":return new B(.68,1,.93);case"aquamarine":return new B(.5,1,.83);case"powderblue":return new B(.69,.88,.9);case"cadetblue":return new B(.37,.62,.63);case"steelblue":return new B(.27,.51,.71);case"cornflowerblue":return new B(.39,.58,.93);case"deepskyblue":return new B(0,.7,1);case"dodgerblue":return new B(.12,.56,1);case"lightblue":return new B(.68,.85,.9);case"skyblue":return new B(.53,.81,.92);case"lightskyblue":return new B(.53,.81,.98);case"midnightblue":return new B(.18,.18,.31);case"darkblue":return new B(0,0,.55);case"mediumblue":return new B(0,0,.82);case"royalblue":return new B(.25,.41,.88);case"blueviolet":return new B(.54,.17,.89);case"indigo":return new B(.29,0,.51);case"darkslateblue":return new B(.28,.24,.55);case"slateblue":return new B(.42,.35,.8);case"mediumslateblue":return new B(.48,.41,.9);case"mediumpurple":return new B(.58,.44,.86);case"darkmagenta":return new B(.55,0,.55);case"darkviolet":return new B(.58,0,.83);case"darkorchid":return new B(.6,.2,.8);case"mediumorchid":return new B(.73,.33,.83);case"thistle":return new B(.84,.75,.85);case"plum":return new B(.87,.63,.87);case"violet":return new B(.93,.51,.93);case"fuchsia":return new B(1,0,1);case"orchid":return new B(.85,.44,.84);case"mediumvioletred":return new B(.78,.08,.52);case"palevioletred":return new B(.86,.44,.58);case"hotpink":return new B(1,.4,.71);case"deeppink":return new B(1,.08,.58);case"lightpink":return new B(1,.71,.76);case"pink":return new B(1,.75,.78);case"antiquewhite":return new B(.98,.92,.84);case"beige":return new B(.96,.96,.86);case"bisque":return new B(1,.89,.77);case"blanchedalmond":return new B(1,.92,.82);case"wheat":return new B(.96,.87,.87);case"cornsilk":return new B(1,.97,.86);case"lemonchiffon":return new B(1,.98,.8);case"lightgoldenrodyellow":return new B(.98,.98,.82);case"lightyellow":return new B(1,1,.8);case"saddlebrown":return new B(.55,.27,.07);case"sienna":return new B(.63,.32,.18);case"chocolate":return new B(.82,.41,.12);case"peru":return new B(.82,.52,.25);case"sandybrown":return new B(.96,.64,.38);case"burlywood":return new B(.87,.72,.53);case"tan":return new B(.82,.71,.55);case"rosybrown":return new B(.74,.56,.56);case"moccasin":return new B(1,.89,.71);case"navajowhite":return new B(1,.87,.68);case"peachpuff":return new B(1,.85,.73);case"mistyrose":return new B(1,.89,.88);case"lavenderblush":return new B(1,.94,.93);case"linen":return new B(.98,.94,.9);case"oldlace":return new B(.99,.96,.9);case"papayawhip":return new B(1,.94,.84);case"seashell":return new B(1,.96,.93);case"mintcream":return new B(.98,1,.98);case"slategray":return new B(.44,.5,.56);case"lightslategray":return new B(.47,.53,.6);case"lightsteelblue":return new B(.69,.77,.87);case"lavender":return new B(.9,.9,.98);case"floralwhite":return new B(1,.98,.98);case"aliceblue":return new B(.94,.97,1);case"ghostwhite":return new B(.97,.97,1);case"honeydew":return new B(.94,1,.94);case"ivory":return new B(1,1,.94);case"azure":return new B(.94,1,1);case"snow":return new B(1,.98,.98);case"dimgray":return new B(.4,.4,.4);case"darkgray":return new B(.66,.66,.66);case"lightgray":return new B(.83,.83,.83);case"gainsboro":return new B(.86,.86,.86);case"whitesmoke":return new B(.96,.96,.96)}return new B(1,1,1)}var _r=N("debuginputfield"),Y=class extends M{get text(){return this.textComponent?.text??""}get isFocused(){return Y.active===this}textComponent;placeholder;onValueChanged;onEndEdit;inputEventFn;start(){_r&&console.log(this.name,this)}onEnable(){Y.htmlField||(Y.htmlField=document.createElement("input"),Y.htmlField.classList.add("ar"),document.body.appendChild(Y.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),Y.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&O.setActive(this.placeholder.gameObject,!1)}onDisable(){Y.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected()}onPointerClick(e){_r&&console.log("CLICK",e,Y.active),Y.activeTime=this.context.time.time,Y.active!==this&&this.startCoroutine(this.activeLoop(),2),this.selectInputField()}*activeLoop(){for(this.onSelected();Y.active===this&&!(this.context.input.getPointerUp(0)&&this.context.time.time-Y.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(Y.active!==this&&(_r&&console.log("Select",this.name,this,Y.htmlField,this.context.isInXR,this.context.AROverlayElement,this.textComponent?.text,Y.htmlField?.value),Y.active?.onDeselected(),Y.active=this,this.placeholder&&O.setActive(this.placeholder.gameObject,!1),Y.htmlField)){if(Y.htmlField.value=this.textComponent?.text||"",_r&&console.log("set input field value",Y.htmlField.value),this.context.isInXR){let e=this.context.AROverlayElement;e&&(Y.htmlField.style.width="0px",Y.htmlField.style.height="0px",e.append(Y.htmlField))}this.selectInputField()}}onDeselected(){Y.active===this&&(Y.active=null,_r&&console.log("Deselect",this.name,this),Y.htmlField&&(Y.htmlField.blur(),document.body.append(Y.htmlField),Y.htmlField.style.width="",Y.htmlField.style.height=""),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&O.setActive(this.placeholder.gameObject,!0),this.onEndEdit?.invoke())}onInput(e){if(Y.active===this){if(_r&&console.log(e.code,e,Y.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}Y.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&O.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&Y.htmlField){if(this.textComponent.text!==Y.htmlField.value){_r&&console.log("VALUE CHANGED");let e=this.textComponent.text,t=Y.htmlField.value;this.onValueChanged?.invoke(t,e)}this.textComponent.text=Y.htmlField.value}}selectInputField(){Y.htmlField&&(Y.htmlField.setSelectionRange(Y.htmlField.value.length,Y.htmlField.value.length),Y.htmlField.focus())}},Ct=Y;z(Ct,"active",null),z(Ct,"activeTime",-1),z(Ct,"htmlField",null),k([A(Le)],Ct.prototype,"textComponent",2),k([A(Le)],Ct.prototype,"placeholder",2),k([A(Oe)],Ct.prototype,"onValueChanged",2),k([A(Oe)],Ct.prototype,"onEndEdit",2);import*as nf from"three-mesh-ui";import*as Ts from"three";var rf=(s=>(s[s.fr=0]="fr",s[s.ru=1]="ru",s[s.de=2]="de",s[s.es=3]="es",s[s.el=4]="el",s[s.nord=5]="nord",s[s.eng=6]="eng",s))(rf||{}),jo=class extends Ue{font;text;keymap;padding;margin;fontSize;borderRadius;colors={keyboardBack:8750469,panelBack:2500134,button:3552822,hovered:1842204,selected:1088605};awake(){super.awake();let e=rf[this.keymap||6];this.makeKeyboard(e)}onEnable(){this.addShadowComponent(this.keyboard)}onDisable(){this.removeShadowComponent()}keyboard=null;_lastKeyPressed;_lastKeyPressedStartTime=0;_lastKeyPressedTime=0;makeKeyboard(e){!e&&!navigator.language&&(e="en");let t=this.font?this.font:"arial",i=this.gameObject.getComponent(ut);if(!i){console.error("Missing rect transform, please add this component inside a canvas");return}let n={...i.getBasicOptions(),margin:this.margin||0,padding:this.padding||0,language:e,fontFamily:Lo+"/"+t+"-msdf.json",fontTexture:Lo+"/"+t+".png",fontSize:this.fontSize||6,backgroundColor:new Ts.Color(this.colors.keyboardBack),backspaceTexture:Lo+"/backspace.png",shiftTexture:Lo+"/shift.png",enterTexture:Lo+"/enter.png",borderRadius:this.borderRadius||0,autoLayout:!1},r=this.gameObject.scale;n.width*=this.gameObject.scale.x,n.height*=this.gameObject.scale.y,n.fontSize*=Math.max(r.x,r.y),this.keyboard=new nf.Keyboard(n),this.gameObject.scale.set(1,1,1),this.keyboard.keys.forEach(o=>{o.setupState({state:"normal",attributes:{offset:.003,backgroundColor:new Ts.Color(this.colors.button),backgroundOpacity:1}}),o.setState("normal"),o.setupState({state:"hovered",attributes:{offset:.3,backgroundColor:new Ts.Color(this.colors.hovered),backgroundOpacity:1}}),o.setupState({state:"pressed",attributes:{offset:.1,backgroundColor:new Ts.Color(this.colors.selected),backgroundOpacity:1},onSet:()=>{let s=o.info.input,c=o.info.command;if(this._lastKeyPressed!==s)this._lastKeyPressedStartTime=this.context.time.time;else if(this.context.time.time-this._lastKeyPressedTime>.05)this._lastKeyPressedStartTime=this.context.time.time;else if(this.context.time.time-this._lastKeyPressedStartTime<.5||c=="switch"||c=="shift"||c=="switch-set"){this._lastKeyPressedTime=this.context.time.time;return}if(this._lastKeyPressedTime=this.context.time.time,this._lastKeyPressed=s,c)switch(c){case"switch":this.keyboard.setNextPanel();break;case"switch-set":this.keyboard.setNextCharset();break;case"enter":this.tryAppend(`
135
+ `);break;case"space":this.tryAppend(" ");break;case"backspace":if(!this.text?.text?.length)break;this.text?.text&&(this.text.text=this.text.text.substring(0,this.text.text.length-1)||"");break;case"shift":this.keyboard.toggleCase();break}else o.info.input!==void 0&&this.tryAppend(o.info.input)}})})}tryAppend(e){this.text&&(this.text.text+=e,this.markDirty())}};var an=class extends M{reverseArrangement=!1},Bo=class extends an{},Fo=class extends an{},No=class extends an{};var xr=class extends M{awake(){Ze.createIfNoneExists(this.context)}onEnable(){Ze.instance?.register(this)}onDisable(){Ze.instance?.unregister(this)}performRaycast(e=null){return null}},Ci=class extends xr{targets=null;raycastHits=[];start(){this.targets=[this.gameObject]}performRaycast(e=null){return this.targets?(e??=new je,e.targets=this.targets,e.results=this.raycastHits,this.context.physics.raycast(e)):null}},zo=class extends Ci{eventCamera=null;ignoreReversedGraphics=!1;rootRaycaster=null};import*as of from"three";import{HTMLMesh as Vy}from"three/examples/jsm/interactive/HTMLMesh.js";import{InteractiveGroup as Wy}from"three/examples/jsm/interactive/InteractiveGroup.js";var Go=class extends M{id=null;keepAspect=!1;start(){if(!this.id||!this.context.mainCamera)return;let e=document.getElementById(this.id);if(!e){console.warn('Could not find element with id "'+this.id+'"');return}e.style.display="block",e.style.visibility="hidden";let t=new Wy(this.context.renderer,this.context.mainCamera);this.gameObject.add(t);let i=new Vy(e);t.add(i),i.visible=!1,console.log(i);let n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;let r=Ns(this.gameObject).clone();zs(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();let o=new of.Box3;o.setFromObject(t),this.setWorldRotation(r.x,r.y,r.z);let s=o.max.x-o.min.x,c=o.max.y-o.min.y;if(this.keepAspect){let a=s/c;s>c?i.scale.set(1/s,1/c/a,1):i.scale.set(1/s*a,1/c,1)}else i.scale.set(1/s,1/c,1);let d=this.gameObject.scale;i.scale.multiply(d)},1)}};var Ja=class extends M{toggleKey=80;update(){this.context.input.isKeyDown(80)&&this.context.domElement.classList.toggle("presentation-mode")}};import*as sf from"three";import{Raycaster as Xy,Vector3 as Qy}from"three";import*as $a from"three";import{MeshLine as Uy,MeshLineMaterial as qy}from"three.meshline";var Ed=class{id=0;points=[];line=new Uy;material;mesh;constructor(e,t){if(t&&(this.material=t.material),this.material||(this.material=this.defaultLineMaterial),t){let i=t.options;i&&Object.assign(this.material,i)}this.mesh=new $a.Mesh(this.line,this.material),e.add(this.mesh)}appendPoint(e){let t=Ed.wp;t.set(e.x,e.y,e.z);let i=this.mesh?.parent;return i&&(t=i.worldToLocal(t),e.x=t.x,e.y=t.y,e.z=t.z),this.points.push(e.x,e.y,e.z),this.line.setPoints(this.points),e}defaultLineMaterial=new qy({color:10066329,lineWidth:.01})},Vo=Ed;z(Vo,"wp",new $a.Vector3);var Tr=class extends M{startLine(e,t){let i=Math.random()*Number.MAX_SAFE_INTEGER;return this.internalStartLine(e,i,!0,t)}updateLine(e,t){let i=this.inFlight[e.id];if(!i)return;t.point&&(t.point=i.appendPoint(t.point));let n=this.buffer[e.id];n&&(t.point&&n.push(t.point.x,t.point.y,t.point.z),n.length>5&&(this.sendLineUpdate(i,!1,void 0,n),n.length=0))}endLine(e,t=!0){let i=this.inFlight[e.id];if(!i)return;this.finished.push(i),delete this.inFlight[e.id],t&&this.sendLineUpdate(i,!0,0);let n=this.buffer[e.id];if(n){delete this.buffer[e.id];let r=n;r.length=0,this.freeBuffer.push(r)}return i}getLine(e){return this.inFlight[e.id]}finished=[];inFlight=[];buffer={};freeBuffer=new Array;awake(){this.context.connection.beginListen("line-start",e=>{this.onEnsureLine(e.id,e.parentGuid)}),this.context.connection.beginListen("line-update",e=>{let t=this.onEnsureLine(e.guid,e.parentGuid);t&&e.points&&(e.startIndex<=0?t.points=e.points:e.startIndex>=t.points.length&&t.points.push(...e.points),t.line.setPoints(t.points),t.material.lineWidth=e.width,t.material.color.fromArray(e.color),e.finished===!0&&this.endLine({id:t.id},!1))})}onEnsureLine(e,t){if(this.inFlight[e])return this.inFlight[e];let i=O.findByGuid(t,this.context.scene);if(!!i)return this.internalStartLine(i,e,!1),this.inFlight[e]}internalStartLine(e,t,i=!0,n){let r=new Vo(e??this.context.scene,n);r.id=t,this.inFlight[t]=r,i&&this.sendLineStart(r);let o;return this.freeBuffer.length<=0?o=new Array:o=this.freeBuffer.pop(),this.buffer[t]=o,{id:t}}sendLineStart(e){let t=e.mesh.parent;this.context.connection.send("line-start",{id:e.id,parentGuid:t?t.guid:void 0})}sendLineUpdate(e,t,i,n){if(e){let r={parentGuid:e.mesh.parent.guid,guid:e.id,points:n?[...n]:e.points,width:e.material.lineWidth,color:e.material.color.toArray(),startIndex:i!==void 0?i:e.points.length,finished:t};this.context.connection.send("line-update",r)}}};import{MeshLineMaterial as Yy}from"three.meshline";var Ka=class{isDrawing;lastHit;currentHandle;maxDistance;prevDistance;lastParent;constructor(){this.isDrawing=!1,this.lastHit=new Qy,this.currentHandle=null,this.maxDistance=0,this.prevDistance=0,this.lastParent=null}},el=class extends M{lines;colliders;alignToSurface=!0;addToPaintedObject=!0;orbit;start(){this.lines||(this.lines=O.getComponent(this.gameObject,Tr),this.lines||(this.lines=O.addNewComponent(this.gameObject,Tr))),this.orbit=O.findObjectOfType(gt,this.context)??void 0,this._states.mouse=new Ka;let e={};se.addEventListener("select-start",(t,i)=>{e[t.controller.uuid]=!0}),se.addEventListener("update",(t,i)=>{if(e[t.controller.uuid]===!0){let n=t.getRay();this.updateLine(t.controller.uuid,n,!0,!1,!1)}}),se.addEventListener("select-end",(t,i)=>{e[t.controller.uuid]=!1;let n=t.getRay();this.updateLine(t.controller.uuid,n,!0,!0,!1)})}_states={};update(){this.orbit&&this._states.mouse&&this.orbit&&(this.orbit.enabled=!this._states.mouse.isDrawing);let e=this.context.input.getPointerPressedCount()>1,t=this.context.input.getPointerPositionRC(0);el._raycaster.setFromCamera(t,this.context.mainCamera);let i=el._raycaster.ray;this.updateLine("mouse",i,this.context.input.getPointerPressed(0),this.context.input.getPointerUp(0),e||this.context.input.isKeyPressed(18))}updateLine(e,t,i,n,r=!1){let o=this._states[e];if(o||(this._states[e]=new Ka,o=this._states[e]),n)o.isDrawing=!1,o.currentHandle&&(this.lines.endLine(o.currentHandle),o.currentHandle=null);else if(i){if(r)return o;let s=this.getHit(t),c=null,d=o.prevDistance;if(s)o.currentHandle||(o.maxDistance=s.distance),c=s.point,c.add(s.face.normal.multiplyScalar(.01)),o.prevDistance=s.distance;else if(o.maxDistance>0){let a=o.maxDistance;if(!o.currentHandle&&o.lastHit){let h=q(this.context.mainCamera);a=o.lastHit.distanceTo(h)}c=t.origin.add(t.direction.multiplyScalar(o.maxDistance)),o.prevDistance=o.maxDistance}if(c){if(!o.currentHandle){let a=o.lastParent??this.gameObject;this.addToPaintedObject&&s&&(a=s.object),o.lastParent=a,o.currentHandle=this.lines.startLine(a,{material:this.createRandomMaterial()})}if(this.alignToSurface&&(o.prevDistance>o.maxDistance||Math.abs(d-o.prevDistance)>.2)){let a=o.maxDistance;c=t.origin.add(t.direction.multiplyScalar(a)),o.prevDistance=a}if(o.lastHit&&o.lastHit.distanceTo(c)<o.prevDistance*.01)return o;this.lines.updateLine(o.currentHandle,{point:c}),o.lastHit.copy(c)}o.isDrawing=o.currentHandle!==null}return o}_raycastOptions=new je;getHit(e){(!this.colliders||this.colliders.length===0)&&(this.colliders=[this.gameObject]),this._raycastOptions.targets=this.colliders,this._raycastOptions.ray=e;let t=this.context.physics.raycast(this._raycastOptions);if(t.length>0){for(let i of t)if(!!O.isActiveInHierarchy(i.object))return i}return null}createRandomMaterial(){let e;return this.context.connection.connectionId?e=ht.colorFromHashCode(ht.hashCode(this.context.connection.connectionId)):e=new sf.Color("hsl("+(Math.random()*100).toFixed(0)+", 80%, 30%)"),new Yy({color:e,lineWidth:Q.lerp(.005,.01,Math.random())})}},Rs=el;z(Rs,"_raycaster",new Xy);import{Object3D as Zy}from"three";var Cs=class extends M{asset;joinedRoomFunction;awake(){this.watchTabVisible(),this.joinedRoomFunction=this.onUserJoined.bind(this)}onEnable(){this.context.connection.beginListen("joined-room",this.joinedRoomFunction)}onDisable(){this.context.connection.stopListening("joined-room",this.joinedRoomFunction)}async onUserJoined(e){let t=await this.asset?.instantiateSynced({parent:this.gameObject},!0);if(t){let i=O.getComponent(t,Si);i&&(i.owner=this.context.connection.connectionId)}}watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=Si.all.length-1;t>=0;t--){let i=Si.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};k([A(tt)],Cs.prototype,"asset",2);var Nt=class extends M{static get all(){return Nt._all}static get local(){return Nt._local}static isLocalPlayer(e){return e instanceof Zy?O.getComponentInParent(e,Nt)?.isLocalPlayer??!1:e instanceof ot?O.getComponentInParent(e.gameObject,Nt)?.isLocalPlayer??!1:!1}owner;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}awake(){this.isLocalPlayer&&Nt.local.push(this),Nt.all.push(this),this.context.connection.beginListen("user-left-room",e=>{if(e.userId===this.owner){this.doDestroy();return}})}start(){if(!this.owner||!this.context.connection.userIsInRoom(this.owner)){this.doDestroy();return}}doDestroy(){kr(this.gameObject,this.context.connection)}onDestroy(){if(Nt.all.splice(Nt.all.indexOf(this),1),this.isLocalPlayer){let e=Nt._local.indexOf(this);e>=0&&Nt._local.splice(e,1)}}},Si=Nt;z(Si,"_all",[]),z(Si,"_local",[]),k([Va(),A()],Si.prototype,"owner",2);D.add("AlignmentConstraint",Ur);D.add("Animation",Jt);D.add("AnimationCurve",rr);D.add("Animator",bt);D.add("AnimatorController",Zt);D.add("AudioListener",$t);D.add("AudioSource",ue);D.add("AvatarModel",or);D.add("AvatarLoader",Ni);D.add("AxesHelper",zi);D.add("BasicIKConstraint",Qr);D.add("BoxHelperComponent",lt);D.add("Camera",ne);D.add("Collider",fi);D.add("SphereCollider",_n);D.add("BoxCollider",xn);D.add("InstantiateOptions",ye);D.add("UnityObject",$r);D.add("DeleteBox",sr);D.add("Deletable",Kr);D.add("DeviceFlag",ar);D.add("DragControls",Et);D.add("DropListener",Pn);D.add("Duplicatable",vi);D.add("CallInfo",yi);D.add("EventListEvent",hr);D.add("EventList",Oe);D.add("EventTrigger",ao);D.add("FlyControls",lo);D.add("BoxGizmo",Xi);D.add("GltfExportBox",ho);D.add("GltfExport",jt);D.add("GridHelper",Qi);D.add("GroundProjectedEnv",Yi);D.add("Interactable",kt);D.add("UsageMarker",It);D.add("Light",Ye);D.add("LODModel",Ei);D.add("LODGroup",An);D.add("LookAtConstraint",Bi);D.add("MeshCollider",po);D.add("NavMesh",fo);D.add("NavMeshAgent",mo);D.add("NestedGltf",ur);D.add("Networking",pt);D.add("OffsetConstraint",go);D.add("OrbitControls",gt);D.add("ParticleSystemRenderer",pr);D.add("ParticleSystem",wo);D.add("MainModule",vo);D.add("EmissionModule",yo);D.add("ShapeModule",Eo);D.add("PlayerColor",ht);D.add("FieldWithDefault",Hr);D.add("Renderer",Te);D.add("MeshRenderer",ir);D.add("SkinnedMeshRenderer",jr);D.add("InstancingUtil",he);D.add("RendererLightmap",Hi);D.add("Rigidbody",ce);D.add("ScreenCapture",_o);D.add("ShadowCatcher",kn);D.add("RemoteSkybox",In);D.add("SmoothFollow",wi);D.add("SpatialTriggerReceiver",wt);D.add("SpatialTrigger",Zi);D.add("SpectatorCamera",To);D.add("SpringJoint",Ro);D.add("Sprite",fr);D.add("SpriteRenderer",Ji);D.add("SyncedCamera",Mn);D.add("SyncedRoom",ti);D.add("SyncedTransform",Qe);D.add("TestRunner",Co);D.add("TestSimulateUserData",So);D.add("TransformGizmo",mr);D.add("VideoPlayer",nt);D.add("Voip",Ke);D.add("VolumeParameter",Po);D.add("VolumeComponent",_i);D.add("ToneMapping",Dn);D.add("ColorAdjustments",Hn);D.add("VolumeProfile",Ln);D.add("Volume",gr);D.add("WebARSessionRoot",Dt);D.add("WebXR",$);D.add("WebAR",Sn);D.add("AvatarMarker",fe);D.add("WebXRAvatar",Lt);D.add("TeleportTarget",lr);D.add("WebXRController",se);D.add("AttachedObject",dt);D.add("XRGrabModel",br);D.add("XRGrabRendering",Oo);D.add("XRRig",Cn);D.add("VRUserState",Ht);D.add("WebXRSync",qi);D.add("XRState",vt);D.add("XRFlag",Se);D.add("AvatarBlink_Simple",xi);D.add("AvatarEyeLook_Rotation",Ti);D.add("Avatar_POI",_e);D.add("Avatar_Brain_LookAt",Ui);D.add("Avatar_MouthShapes",jn);D.add("Avatar_MustacheShake",Ao);D.add("LogStats",ko);D.add("RGBAColor",we);D.add("PlayableDirector",tn);D.add("SignalAsset",vr);D.add("SignalReceiverEvent",yr);D.add("SignalReceiver",$i);D.add("AnimationTrackHandler",Bn);D.add("AudioTrackHandler",Fn);D.add("SignalTrackHandler",en);D.add("ControlTrackHandler",Ki);D.add("BaseUIComponent",Ue);D.add("UIRootComponent",nn);D.add("Button",Ft);D.add("Canvas",Je);D.add("CanvasGroup",sn);D.add("EventSystem",Ze);D.add("Graphic",Rt);D.add("MaskableGraphic",rn);D.add("Image",on);D.add("RawImage",wr);D.add("InputField",Ct);D.add("Keyboard",jo);D.add("LayoutGroup",an);D.add("VerticalLayoutGroup",Bo);D.add("HorizontalLayoutGroup",Fo);D.add("GridLayoutGroup",No);D.add("PointerEventData",ii);D.add("Raycaster",xr);D.add("ObjectRaycaster",Ci);D.add("GraphicRaycaster",zo);D.add("Size",Do);D.add("Rect",Er);D.add("RectTransform",ut);D.add("SpatialHtml",Go);D.add("Text",Le);D.add("PresentationMode",Ja);D.add("LinesDrawer",Rs);D.add("LineInstanceHandler",Vo);D.add("LinesManager",Tr);D.add("PlayerSync",Cs);D.add("PlayerState",Si);import*as af from"three";import{Color as Jy,Object3D as $y}from"three";var _d=class extends Fi{constructor(){super([Jy,we])}onDeserialize(e){if(e!=null)return e.a!==void 0?new we(e.r,e.g,e.b,e.a):e.alpha!==void 0?new we(e.r,e.g,e.b,e.alpha):new af.Color(e.r,e.g,e.b)}onSerialize(e){if(e!=null)return e.a!==void 0?{r:e.r,g:e.g,b:e.b,a:e.a}:{r:e.r,g:e.g,b:e.b}}},Gj=new _d,xd=class extends Fi{constructor(){super($y)}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){let i=t.objectToNode[e.uuid];return Ie&&console.log(i,e.name,e.uuid),{node:i}}}onDeserialize(e,t){if(e){if(e.node!==void 0&&t.nodeToObject){let i=t.nodeToObject[e.node];return Ie&&console.log("Deserialized object reference?",e,i,t?.nodeToObject),i||console.warn("Did not find node: "+e.node,t.nodeToObject,t.object),i}else if(e.guid){if(!t.context){console.error("Missing context");return}let i,n=t.gltf?.scene;return n&&(i=O.findByGuid(e.guid,n)),i||(i=O.findByGuid(e.guid,t.context.scene)),i?Ie&&console.log("Deserialized object reference?",e,i,t?.nodeToObject):console.warn("could not resolve reference",e,t.target,t.path,t.context.scene),i}}}},Ky=new xd,Td=class extends Fi{constructor(){super([ot,M])}onSerialize(e,t){if(e?.guid)return{guid:e.guid}}onDeserialize(e,t){if(e?.guid){Ie&&console.log(e.guid,t.root,t.object,t.target);let i=this.findObjectForGuid(e.guid,t.root);if(i)return i;if(t.context)return this.findObjectForGuid(e.guid,t.context?.scene)}}findObjectForGuid(e,t){return O.foreachComponent(t,i=>{if(e===i.gameObject.guid)return i.gameObject;if(i.guid===e)return i})}},wd=new Td,Rd=class extends Fi{constructor(){super([Oe])}onSerialize(e,t){console.log("TODO: SERIALIZE EVENT")}onDeserialize(e,t){if(e&&e.type==="EventList"){Ie&&console.log("DESERIALIZE EVENT",e);let i=new Array;for(let o of e.calls){Ie&&console.log(o);let s=wd.findObjectForGuid(o.target,t.root);!s&&t.context?.scene&&(s=wd.findObjectForGuid(o.target,t.context?.scene));let c=o.method?.length>0;if(s&&c){let u=()=>console.warn(`Could not find method ${o.method} on object ${s.name}`,s,typeof s[o.method]);if(typeof s[o.method]!="function"){let f=!1;o.method.startsWith("set_")&&o.method.length>4&&(o.method=o.method.substring(4),s[o.method]!==void 0&&(f=!0)),f||u()}}let d,a=o.argument;o.argument!==void 0?(typeof a=="object"&&(a=Ky.onDeserialize(o.argument,t),a||(a=wd.onDeserialize(o.argument,t))),d=new yi(c?(...u)=>h(...u):void 0,o.enabled)):d=new yi(c?(...u)=>h(...u):void 0,o.enabled);let h=(...u)=>{let f=s[o.method];typeof f=="function"?a!==void 0?f?.call(s,a):f?.call(s,...u):s[o.method]=a};if(d.method||(d.__debuginfo=t.object?.name),!s||!d.method){let u=t.object?"Current object: "+t.object.name+", "+t.object.guid:null;s?console.warn('EventList method not found: "'+o.method+'" on',s):console.warn("EventList is missing target - will be ignored",o.target,u,e)}else i.push(d)}let n=new Oe(i);Ie&&console.log(n);let r=t.target;return r!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,r),n}}},Vj=new Rd;var lf=Ie;function kp(l,e){let i=Lc(l,e);return i!==void 0?i:null}async function Sa(l,e,t,i=null,n){if(!t)return;let r=[],o=i;typeof o=="number"&&(o=new We(i));let s=new Vr(t.scene);s.gltfId=e,s.context=l,s.gltf=t,s.nodeToObject=n?.nodeToObjectMap;let c=[];if(t.scenes)for(let d of t.scenes)await Sd(s,d,c,r);if(t.children)for(let d of t.children)await Sd(s,d,c,r);l.new_scripts_pre_setup_callbacks.push(()=>{for(let d of c)tE(d,s);if(o){Cd(t,o);for(let d of t.scenes)Cd(d,o)}})}function Cd(l,e){if(e!==null&&!!l){if(l.guid=e.generateUUID(),l&&l.userData&&l.userData.components)for(let t of l.userData.components)t!==null&&(t.guid=e.generateUUID());if(l.children)for(let t of l.children)Cd(t,e)}}var Ss=[];async function Sd(l,e,t,i){if(!e)return;let n=e.userData;if(n){let r=n.builtin_components;if(r&&r.length>0)for(let o of r)try{if(o===null)continue;let s=D.get(o.name);if(s!=null){let c=new s;c.sourceId=l.gltfId,us(c,o),Ls(c,e,!1),t.push({instance:c,compData:o,obj:e})}else lf&&console.debug("unknown component: "+o.name),Ss.includes(o.name)||Ss.push(o.name)}catch(s){console.error(o.name+" - "+s.message,s)}if(Ss.length>0){let o=Ss.join(", ");console.warn("unknown components: "+o),Ss.length=0}}if(e.children)for(let r of e.children)await Sd(l,r,t,i)}function tE(l,e){let{instance:t,compData:i,obj:n}=l;e.object=n,e.target=t;let r=!0;r=hs(t,i,e)===!0,lf&&console.debug("add "+i.name,i,t)}import*as me from"three";import*as cf from"three";var iE=new cf.FileLoader;async function Pd(l){return new Promise((e,t)=>{iE.load(l,e,void 0,t)})}import{Vector4 as Nn,FileLoader as rE,DataTexture as Md,RGBAFormat as oE,Color as sE}from"three";var Ps=new Uint8Array(4);Ps[0]=255;Ps[1]=255;Ps[2]=255;Ps[3]=255;var uf=new Md(Ps,1,1,oE);function pf(l,e=1){let t="alpha"in l,i=e*e,n=new Uint8Array(4*i),r=Math.floor(l.r*255),o=Math.floor(l.g*255),s=Math.floor(l.b*255);for(let d=0;d<i;d++){let a=d*4;n[a+0]=r,n[a+1]=o,n[a+2]=s,t?n[a+3]=Math.floor(l.alpha*255):n[a+3]=255}let c=new Md(n,e,e);return c.needsUpdate=!0,c}function ff(l,e,t,i=1,n=3){let s=i*n,c=[l,e,t],d=c.length,a=new Uint8Array(4*d*s),h=new sE;for(let f=0;f<n;f++){let E=Math.floor(f/n*d),b=Q.clamp(E+1,0,d-1),y=c[E],g=c[b],p=f/n*d%1;h.lerpColors(y,g,p);let m=Math.floor(h.r*255),v=Math.floor(h.g*255),w=Math.floor(h.b*255);for(let x=0;x<i;x++){let T=(f*i+x)*4;a[T+0]=m,a[T+1]=v,a[T+2]=w,a[T+3]=255}}let u=new Md(a,i,n);return u.needsUpdate=!0,u}var Ad=class{stage;code;constructor(e,t){this.stage=e,this.code=t}},kd=class{loaded=new Map;async loadShader(e){let t=await Pd(e);return JSON.parse(t)}async load(e,t){if(this.loaded.has(t))return new Promise((r,o)=>{let s=this.loaded.get(t);s?r(s):o("Shader not found")});let i=await Pd(t),n=new Ad(e,i);return this.loaded.set(t,n),n}},nB=new kd;function Os(l,e){let t=l.elements;e||(e=[]),e.length=0;for(let i=0;i<16;i+=4){let n=t[i],r=t[i+1],o=t[i+2],s=t[i+3],c=new Nn(n,r,o,s);e.push(c)}return e}var Od=[],df=[];function Ld(l,e){if(Od.length===0)for(let t=0;t<27;t++)Od.push(0);e||(e=Od);for(let t=0;t<27;t++)df[t]=e[t];e=df,l.unity_SHAr={value:new Nn(e[9],e[3],e[6],e[0])},l.unity_SHBr={value:new Nn(e[12],e[15],e[18],e[21])},l.unity_SHAg={value:new Nn(e[10],e[4],e[7],e[1])},l.unity_SHBg={value:new Nn(e[13],e[16],e[19],e[22])},l.unity_SHAb={value:new Nn(e[11],e[5],e[8],e[2])},l.unity_SHBb={value:new Nn(e[14],e[17],e[20],e[23])},l.unity_SHC={value:new Nn(e[24],e[25],e[26],1)}}var Id=class{vertexShader;fragmentShader;technique;constructor(e,t,i){this.vertexShader=e,this.fragmentShader=t,this.technique=i}};async function mf(l,e){if(!l)return console.error("Can not find technique: no shader data"),null;let t=l.programs[e],i=t.vertexShader,n=t.fragmentShader;if(i!==void 0&&n!==void 0){let r=l.shaders[i],o=l.shaders[n];if(r.uri&&o.uri||r.code&&o.code){if(!r.code&&r.uri&&await hf(r),!o.code&&o.uri&&await hf(o),!r.code||!o.code)return null;let s=l.techniques[e];return new Id(r.code,o.code,s)}}return console.error("Shader technique not found",e),null}async function hf(l){let e=l.uri;if(!!e)if(e.endsWith(".glsl")){let i=await new rE().loadAsync(e);l.code=i.toString()}else l.code=aE(l.uri)}function aE(l){return decodeURIComponent(Array.prototype.map.call(atob(l),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}import{RawShaderMaterial as cE}from"three";var ln=N("debugshaders"),Wo="NEEDLE_techniques_webgl";var Dd=class{objectToWorldMatrix=new me.Matrix4;worldToObjectMatrix=new me.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),Os(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),Os(this.worldToObjectMatrix,this.worldToObject)}};var pe=class extends cE{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);constructor(e,...t){super(...t),this.identifier=e,ln&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName]&&this.waitForLighting(),(this.depthTextureUniform||this.opaqueTextureUniform)&&Z.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();let e=Z.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&Z.Current.pre_render_callbacks.splice(e,1)}async waitForLighting(){let e=Z.Current;if(!e){console.error("Missing context");return}let t=await e.rendererData.getSceneLightingData(this.identifier);if(!t||!t.array){console.warn("Missing lighting data for custom shader, getSceneLightingData did not return anything");return}ln&&console.log(t);let i=t.array,n=t.texture;this.uniforms.unity_SpecCube0={value:n},Ld(this.uniforms,i);let r=Math.sqrt(Math.PI*.5);this.uniforms.unity_SpecCube0_HDR={value:new me.Vector4(r,r,r,r)},ln&&console.log("Set environment lighting",this.uniforms)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";_rendererData=new Dd;get depthTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&Z.Current.setRequireColor(!0),this.depthTextureUniform&&Z.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,r,o){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,r)}onUpdateUniforms(e,t){let i=Z.Current;e&&(pe.viewProjection&&this.uniforms[this._viewProjectionName]&&(pe.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),Os(pe.viewProjection,pe._viewProjectionValues)),pe.viewMatrix&&this.uniforms[this._viewMatrixName]&&(pe.viewMatrix.copy(e.matrixWorldInverse),Os(pe.viewMatrix,pe._viewMatrixValues)),this.uniforms[pe._worldSpaceCameraPosName]&&pe._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=i.rendererData.timeVec4);let n=i?.mainLight;if(n){let s=n.getWorldPosition(pe._mainLightPosition);this.uniforms._MainLightPosition={value:s.normalize()},pe._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:pe._mainLightColor};let c=n.intensity;pe._lightData.z=c,this.uniforms.unity_LightData={value:pe._lightData}}if(e&&(pe.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=pe._viewProjectionValues),pe.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=pe._viewMatrixValues),this.uniforms[pe._worldSpaceCameraPosName]&&(this.uniforms[pe._worldSpaceCameraPosName]={value:pe._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){let s=this.uniforms._ProjectionParams.value;s.x=1,s.y=i.mainCameraComponent.nearClipPlane,s.z=i.mainCameraComponent.farClipPlane,s.w=1/s.z,this.uniforms._ProjectionParams.value=s}if(this.uniforms._ZBufferParams){let s=this.uniforms._ZBufferParams.value,c=i.mainCameraComponent;s.x=1-c.farClipPlane/c.nearClipPlane,s.y=c.farClipPlane/c.nearClipPlane,s.z=s.x/c.farClipPlane,s.w=s.y/c.farClipPlane,this.uniforms._ZBufferParams.value=s}if(this.uniforms._ScreenParams){let s=this.uniforms._ScreenParams.value;s.x=i.domWidth,s.y=i.domHeight,s.z=1+1/s.x,s.w=1+1/s.y,this.uniforms._ScreenParams.value=s}}let r=this.depthTextureUniform;r&&(r.value=i.depthTexture);let o=this.opaqueTextureUniform;if(o&&(o.value=i.opaqueColorTexture),t){let s=this._rendererData;s.updateFrom(t),this.uniforms[this._worldToObjectName].value=s.worldToObject,this.uniforms[this._objToWorldName].value=s.objectToWorld}this.uniformsNeedUpdate=!0}},zt=pe;z(zt,"viewProjection",new me.Matrix4),z(zt,"_viewProjectionValues",[]),z(zt,"viewMatrix",new me.Matrix4),z(zt,"_viewMatrixValues",[]),z(zt,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),z(zt,"_worldSpaceCameraPos",new me.Vector3),z(zt,"_mainLightColor",new me.Vector4),z(zt,"_mainLightPosition",new me.Vector3),z(zt,"_lightData",new me.Vector4);var tl=class{get name(){return Wo}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){let t=this.parser.json.materials[e];if(!t)return ln&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Wo])return ln&&console.log("material "+e+" does not use NEEDLE_techniques_webgl"),null;let i=t.extensions[Wo].technique;if(i<0)return null;let n=this.parser.json.extensions[Wo];if(!n)return null;ln&&console.log(n);let r=n.techniques[i];return r?new Promise(async(o,s)=>{let c=await mf(n,r.program),d=c?.fragmentShader,a=c?.vertexShader;if(!d||!a)return s();ln&&console.log("loadMaterial",t,c);let h={},u=r.uniforms;for(let y in u){let g=y;switch(g){case"_TimeParameters":let p=new me.Vector4;h[g]={value:p};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":h[g]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":h[g]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":h[g]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":h[g]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":h[g]={value:null};break}}let f=!1;if(t.extensions&&t.extensions[Wo]){let y=t.extensions[Wo];if(y.technique===i){ln&&console.log(t.name,"Material Properties",y);for(let g in y.values){let p=y.values[g];if(typeof p=="string"){if(p.startsWith("textures/")){let m=p.substring(9),v=Number.parseInt(m);if(v>=0){let w=await this.parser.getDependency("texture",v);w&&(w.encoding=me.LinearEncoding,w.needsUpdate=!0),h[g]={value:w};continue}}switch(g){case"alphaMode":p==="BLEND"&&(f=!0);continue}}if(Array.isArray(p)&&p.length===4){h[g]={value:new me.Vector4(p[0],p[1],p[2],p[3])};continue}h[g]={value:p}}}}let E=new zt(this.identifier,{name:t.name??"",uniforms:h,vertexShader:a,fragmentShader:d,lights:!1});switch(h._Cull?.value){case 0:E.side=me.DoubleSide;break;case 1:E.side=me.BackSide;break;case 2:E.side=me.FrontSide;break;default:E.side=me.FrontSide;break}E.transparent=f,f&&(E.depthWrite=!1),Ld(h),E.onUpdateUniforms();for(let y in u){let g=y,p=u[y].type;if(h[g]?.value===void 0)switch(p){case 35678:h[g]={value:uf},console.warn("Missing/unassigned texture, fallback to white: "+g);break;default:console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+g,u[y]);break}}ln&&console.log(E.uuid,h),o(E)}):null}};import{EXRLoader as dE}from"three/examples/jsm/loaders/EXRLoader";var Hd=N("debugexr"),il=class{constructor(e){this.parser=e,this.name="EXT_texture_exr",Hd&&console.log(e)}loadTexture(e){let t=this.name,i=this.parser,r=i.json.textures[e];if(Hd&&console.log("EXT_texture_exr.loadTexture",e,r),!r.extensions||!r.extensions[t])return null;let o=r.extensions[t],s=new dE(i.options.manager);return Hd&&console.log("EXT_texture_exr.loadTexture",o,s),i.loadTextureImage(e,o.source,s)}};var gf="NEEDLE_gameobject_data",nl=class{get name(){return gf}parser;constructor(e){this.parser=e}afterRoot(e){let t=[];for(let i=0;i<this.parser.json.nodes.length;i++){let n=this.parser.json.nodes[i];if(n&&n.extensions){let r=n.extensions[gf];if(r){let o=this.findAndApplyExtensionData(i,r);t.push(o)}}}return Promise.all(t).then(()=>{})}async findAndApplyExtensionData(e,t){let i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){e.userData.layer=t.layers,e.userData.tag=t.tag,e.userData.hideFlags=t.hideFlags,e.userData.static=t.static,e.visible=t.activeSelf,e.guid=t.guid}};import{FloatType as hE,HalfFloatType as uE,sRGBEncoding as pE}from"three";var bf="NEEDLE_lightmaps",fE=N("debuglightmapsextension"),As=(i=>(i[i.Lightmap=0]="Lightmap",i[i.Skybox=1]="Skybox",i[i.Reflection=2]="Reflection",i))(As||{}),rl=class{get name(){return bf}parser;registry;source;constructor(e,t,i){this.parser=e,this.registry=t,this.source=i}afterRoot(e){let t=this.parser.json.extensions;if(t){let i=t[bf];if(i){let n=i.textures;return n.length?(fE&&console.log(i),new Promise(async(r,o)=>{let s=[];for(let c of n)if(c.pointer){let d=Gr(this.parser,c.pointer).then(a=>{let h=a;h?.isTexture&&(this.registry?(c.type!==0&&(h.encoding=pE),(h.type==hE||h.type==uE)&&(h.flipY=!0),this.registry.registerTexture(this.source,c.type,h,c.index)):console.log(As[c.type],c.pointer,h))});s.push(d)}await Promise.all(s),r()})):null}}return null}};import{AmbientLight as vE,Color as vf,HemisphereLight as yE}from"three";import{Vector4 as mE,EquirectangularReflectionMapping as ol,sRGBEncoding as sl,WebGLCubeRenderTarget as gE}from"three";import{LightProbeGenerator as bE}from"three/examples/jsm/lights/LightProbeGenerator.js";var jd=N("debugenvlight"),Fd=(n=>(n[n.Skybox=0]="Skybox",n[n.Trilight=1]="Trilight",n[n.Flat=3]="Flat",n[n.Custom=4]="Custom",n))(Fd||{});var al=class{context;constructor(e){this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}sceneLightSettings;preUpdate(){let e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}_timevec4=new mE;get timeVec4(){return this._timevec4}get environmentIntensity(){return this.sceneLightSettings?this.sceneLightSettings.ambientIntensity:1}registerSceneLightSettings(e){this.sceneLightSettings=e}registerReflection(e,t){let i=new Bd(this.context,t,1);this._lighting[e]=i}getReflection(e){return this._lighting[e]}enableReflection(e){switch(jd&&console.log(this.sceneLightSettings?Fd[this.sceneLightSettings.ambientMode]:"Unknown ambient mode"),this.sceneLightSettings?.ambientMode){case 0:case 4:let t=this.getReflection(e);if(t&&t.Source){let i=this.context.scene,n=t.Source;n.encoding=sl,n.mapping=ol,i.environment=n;return}break}if(this.sceneLightSettings?.environmentReflectionSource===1)switch(this.sceneLightSettings?.ambientMode){case 1:if(this.sceneLightSettings.ambientTrilight){let t=this.sceneLightSettings.ambientTrilight,i=ff(t[0],t[1],t[2],64,64);i.encoding=sl,i.mapping=ol,this.context.scene.environment=i}else console.error("Missing ambient trilight",this.sceneLightSettings.sourceId);return;case 3:if(this.sceneLightSettings.ambientLight){let t=pf(this.sceneLightSettings.ambientLight,64);t.encoding=sl,t.mapping=ol,this.context.scene.environment=t}else console.error("Missing ambientlight",this.sceneLightSettings.sourceId);return;default:return}}disableReflection(){let e=this.context.scene;e.environment=null}async getSceneLightingData(e){return jd&&console.log("GET SCENE LIGHT DATA"),this._waitPromise?this._waitPromise:(this._waitPromise=new Promise((t,i)=>{let n=setInterval(async()=>{let r=this.getReflection(e);r&&(clearInterval(n),t(r.getSphericalHarmonicsArray(this.sceneLightSettings?.ambientIntensity??1)))},10)}),this._waitPromise)}_waitPromise;_lighting={}},Bd=class{get Source(){return this._source}get Array(){return this._sphericalHarmonicsArray}_context;_source;_sphericalHarmonics=null;_sphericalHarmonicsArray;_ambientScale=1;_lightProbe;constructor(e,t,i=1){this._context=e,this._source=t,this._ambientScale=i,t.mapping=ol,t.encoding=sl}getSphericalHarmonicsArray(e=1){if(this._sphericalHarmonicsArray?.length&&this._source)return{array:this._sphericalHarmonicsArray,texture:this._source,lightProbe:this._lightProbe};try{let t=this._source,i=null;if(t){jd&&console.log("GENERATING LIGHT PROBE",t);let n=Math.min(t.image.width,512);i=new gE(n).fromEquirectangularTexture(this._context.renderer,t),this._source=i.texture}if(this._sphericalHarmonicsArray=[],i){let n=bE.fromCubeRenderTarget(this._context.renderer,i);this._lightProbe=n;let r=this._ambientScale*(e*e*Math.PI*.5)-1;this._sphericalHarmonics=n.sh,this._sphericalHarmonicsArray=this._sphericalHarmonics.toArray();let o=e/(Math.PI*.5);for(let s=0;s<this._sphericalHarmonicsArray.length;s++)this._sphericalHarmonicsArray[s]*=o;if(n.sh.scale(r),this._source)return{array:this._sphericalHarmonicsArray,texture:this._source,lightProbe:n}}}catch(t){console.error(t)}return null}};var yf="NEEDLE_lighting_settings",ks=N("debugenvlight"),ll=class{get name(){return yf}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}afterRoot(e){let t=this.parser.json.extensions;if(t){let i=t[yf];if(i){ks&&console.log(i);let n=O.addNewComponent(e.scene,Nd,!1);n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new vf().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(r=>new vf().fromArray(r))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource,this.context&&this.context.rendererData.registerSceneLightSettings(n)}}return null}},Nd=class extends M{ambientMode=0;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=0;_hasReflection=!1;_ambientLightObj;_lightProbeObj;awake(){if(this.sourceId){let e=this.environmentReflectionSource===0?1:2,t=this.context.lightmaps.tryGet(this.sourceId,e,0);this._hasReflection=t!=null,t&&this.context.rendererData.registerReflection(this.sourceId,t)}ks&&window.addEventListener("keydown",e=>{switch(e.key){case"l":this.enabled=!this.enabled;break}})}onEnable(){let e=this.context.mainCameraComponent?.sourceId===this.sourceId;if(ks&&console.log("enable",this.sourceId,e,this,this.context.mainCameraComponent?.sourceId),this.ambientMode==3)this.ambientLight&&(this._ambientLightObj=new vE(this.ambientLight,Math.PI*this.ambientIntensity)),this._ambientLightObj&&this.gameObject.add(this._ambientLightObj),this._lightProbeObj&&this._lightProbeObj.removeFromParent();else if(this.ambientMode===1){if(this.ambientTrilight){let t=this.ambientTrilight[0],i=this.ambientTrilight[this.ambientTrilight.length-1],n=new yE(i,t,this.ambientIntensity);this.gameObject.add(n)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._lightProbeObj?this.enabled&&this.destroyed&&this._lightProbeObj&&this.scene.add(this._lightProbeObj):this.sourceId&&this.context.rendererData.getSceneLightingData(this.sourceId).then(t=>{ks&&console.log(t),t&&(this._lightProbeObj=t.lightProbe,this.enabled&&!this.destroyed&&this._lightProbeObj&&this.scene.add(this._lightProbeObj))});this.sourceId&&this.context.rendererData.enableReflection(this.sourceId)}onDisable(){ks&&console.log("disable",this.sourceId,this),this._lightProbeObj&&this._lightProbeObj.removeFromParent(),this.sourceId&&this.context.rendererData.disableReflection()}};function Gd(l){let e=new co;return l.register(t=>(e.parser=t,e)),e}var zd=class{resolvePath(e){return e.includes("/extensions/builtin_components/")&&(e=e.replace("/extensions/builtin_components/","/userData/components/")),e}};function Vd(l,e,t){l.register(n=>new nl(n)),l.register(n=>new ya(n)),l.register(n=>new rl(n,e.lightmaps,t)),l.register(n=>new ll(n,t,e)),l.register(n=>new tl(n,t)),l.register(n=>new er(n,t)),l.register(n=>new ji(n,t,e)),l.register(n=>new il(n));let i=l.setAnimationPointerResolver;typeof i=="function"&&i.bind(l)(new zd)}var EE=N("printGltf");var zn=class{context;loader;path;gltf;constructor(e,t,i,n){this.context=e,this.path=t,this.loader=i,this.gltf=n}},Ef={};function Uo(l,e){if(Ef[l])for(let t of Ef[l])t(e)}async function _f(l,e,t,i,n){EE&&console.log(t),await l.assets.registerGltf(t),await Sa(l,e,t,i,n)}function Xr(l,e,t,i){typeof t!="string"&&console.warn("Parse gltf binary without path, this might lead to errors in resolving extensions. Please provide the source path of the gltf/glb file",t,typeof t);let n=new wf;Vd(n,l,t);let o=Gd(n);return new Promise((s,c)=>{try{tr(n,l),Uo(0,new zn(l,t,n)),n.parse(e,t,async d=>{Uo(1,new zn(l,t,n,d)),await _f(l,t,d,i,o),Uo(10,new zn(l,t,n,d)),s(d)},d=>{console.error("failed loading "+t,d),s(void 0)})}catch(d){console.error(d),c(d)}})}function dr(l,e,t,i=!1,n){let r=new wf;Vd(r,l,e);let s=Gd(r);return new Promise((c,d)=>{try{tr(r,l),Uo(0,new zn(l,e,r)),r.load(e,async a=>{Uo(1,new zn(l,e,r,a)),await _f(l,e,a,t,s),Uo(10,new zn(l,e,r,a)),c(a)},a=>{n?.call(r,a)},a=>{console.error("failed loading "+e,a),c(void 0)})}catch(a){console.error(a),d(a)}})}import*as Gn from"three";function cl(l,e,t){let i=O.getComponentInChildren(l,Et);if(i||(i=O.addNewComponent(l,Et,!1),i.guid=e.generateUUID()),i&&!O.getComponent(i.gameObject,Qe)){let r=O.addNewComponent(i.gameObject,Qe,!1);r.guid=e.generateUUID()}if(i&&!O.getComponentInParent(i.gameObject,Ci)){let r=O.addNewComponent(i.gameObject,Ci,!1);r.guid=e.generateUUID()}if(t&&t.animations?.length>0){let r=t.animations[0],o=O.addNewComponent(l,Jt,!1);o.animations=[r]}let n=!1;l.traverse(r=>{!r||r.isSkinnedMesh===!0&&(n||console.log("Disabling frustum culling for skinned meshes",t),n=!0,r.frustumCulled=!1)})}var Wd=class{guid;file_name;file_hash;file_size;position;seed;sender;serverUrl;parentGuid;boundsSize;constructor(e,t,i,n,r,o,s,c){this.seed=t,this.guid=i,this.file_name=n,this.file_hash=r,this.file_size=o,this.position=s,this.sender=e,this.serverUrl=c}};async function Rp(l,e,t){let i=l.name;return i.endsWith(".gltf")||i.endsWith(".glb")?new Promise((n,r)=>{let o=new FileReader;o.readAsDataURL(l),o.onloadend=async s=>{let c=o.result,d=Us(),a=new We(d),h=await dr(e,c,a,!0);if(h&&h.scene){let u=h.scene;if(!u.guid){let f=new We(d);u.guid=f.generateUUID()}t&&_E(e.connection,l,d,u,t),cl(u,a,h),n(h)}}}):(console.warn("Unsupported file type: "+i),console.log(l),null)}async function Cp(l,e){return new Promise(async(t,i)=>{let n=Us(),r=new We(n),o=await dr(e,l.toString(),r,!0);if(o&&o.scene){let s=o.scene;cl(s,r,o),t(o)}else console.warn("Unsupported file type: "+l.toString())})}function xf(l){l.connection.beginListen("file-spawned",async e=>{if(e.sender!==l.connection.connectionId){console.log("received file event",e),xE(e,l);let t=null;try{t=await Ca(e.file_name,e.file_hash,e.file_size,e.serverUrl)}finally{TE(e,l)}if(t){let i=new We(e.seed),n=await Xr(l,t,null,i);if(n&&n.scene){let r=n.scene;if(cl(r,i,n),e.parentGuid){let o=O.findByGuid(e.parentGuid,l.scene);"add"in o&&o.add(r)}r.parent||l.scene.add(r),e.position!==null&&r.position.copy(e.position)}}else console.error("download didnt return file")}})}async function _E(l,e,t,i,n){if(!l.connectionId){console.error("Can not upload file - no connection id");return}if(!i.guid){console.error("Can not upload file - no guid",i,i.guid);return}let r=await up(e,n);if(!r)return;if(!r.filename){console.error("Can not send upload event - no filename",e.name);return}if(!r.hash){console.error("Can not send upload event - no hash",e.name);return}let o=new Wd(l.connectionId,t,i.guid,r.filename,r.hash,e.size,i.position,r.url??n);i.parent&&(o.parentGuid=i.parent.guid),l.send("file-spawned",o)}var Ud={};function xE(l,e){let t=new Gn.BoxGeometry,i=new Gn.Mesh(t,new Gn.MeshBasicMaterial({color:65280})),n=new Gn.BoxHelper(i,5592405);if(Ud[l.guid]=n,e.scene.add(n),l.parentGuid){let r=O.findByGuid(l.parentGuid,e.scene);r&&r.add(n)}l.position&&n.position.copy(l.position)}function TE(l,e){let t=l.guid,i=Ud[t];i&&(delete Ud[t],i.removeFromParent())}import*as Tf from"three";var pF=N("debugassets");var dl=class{constructor(){window.addEventListener("unhandledrejection",e=>{if(e.defaultPrevented)return;let t=e?.reason?.path;if(t){let i=t[0];i&&i.tagName==="IMG"&&(console.warn(`Could not load image:
136
+ `+i.src),e.preventDefault())}})}texturesLoader=new Tf.TextureLoader;textures={};texturesLoading={};async loadTexture(e){if(this.textures[e])return this.textures[e];if(this.texturesLoading[e])return await this.texturesLoading[e];let t=this.texturesLoader.loadAsync(e);this.texturesLoading[e]=t;let i=await t;return delete this.texturesLoading[e],this.textures[e]=i,i}getTexture(e){return this._textures.get(e)||null}findTexture(e){for(let t of this._textures.values())if(t.name===e)return t;return null}findMesh(e){for(let t of this._meshes.values())if(t.name===e)return t;return null}findMaterial(e){for(let t of this._materials.values())if(t.name===e)return t;return null}async registerGltf(e){}registerAsset(e){}_materials=new Map;_meshes=new Map;_textures=new Map};import*as Cf from"three/examples/jsm/libs/stats.module";import*as Pi from"three";var Rf=!!N("debuglightmaps"),hl=class{_context;_lightmaps=new Map;constructor(e){this._context=e}registerTexture(e,t,i,n){Rf&&console.log("Registering lightmap",e,As[t],i),this._lightmaps.has(e)||this._lightmaps.set(e,new Map);let r=this._lightmaps.get(e),o=r?.get(t)??[];o.length<n&&(o.length=n+1),o[n]=i,r?.set(t,o)}tryGetLightmap(e,t=0){return this.tryGet(e,0,t)}tryGetSkybox(e){return this.tryGet(e,1,0)}tryGetReflection(e){return this.tryGet(e,2,0)}tryGet(e,t,i){if(!e)return Rf&&console.warn("Missing source id"),null;let n=this._lightmaps.get(e)?.get(t)??null;return!n?.length||n.length<=i?null:n[i]}};Pi.ShaderChunk.lights_fragment_maps=Pi.ShaderChunk.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vUv2 );",`
137
137
 
138
138
  vec2 lUv = vUv2.xy * lightmapScaleOffset.xy + vec2(lightmapScaleOffset.z, (1. - (lightmapScaleOffset.y + lightmapScaleOffset.w)));
139
139
  vec4 lightMapTexel = texture2D( lightMap, lUv);
@@ -141,7 +141,7 @@ a=extmap-allow-mixed`)!==-1){var f=p.sdp.split(`
141
141
  lightMapTexel.rgb *= lightMapTexel.a * 8.; // no idea where that "8" comes from... heuristically derived
142
142
  lightMapTexel.a = 1.;
143
143
  lightMapTexel = conv_sRGBToLinear(lightMapTexel);
144
- `);Si.ShaderChunk.lightmap_pars_fragment=`
144
+ `);Pi.ShaderChunk.lightmap_pars_fragment=`
145
145
  #ifdef USE_LIGHTMAP
146
146
  uniform sampler2D lightMap;
147
147
  uniform float lightMapIntensity;
@@ -152,12 +152,12 @@ a=extmap-allow-mixed`)!==-1){var f=p.sdp.split(`
152
152
  return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );
153
153
  }
154
154
  #endif
155
- `;Si.ShaderChunk.lights_fragment_begin=Si.ShaderChunk.lights_fragment_begin.replace("irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );",`
155
+ `;Pi.ShaderChunk.lights_fragment_begin=Pi.ShaderChunk.lights_fragment_begin.replace("irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );",`
156
156
  #if defined(USE_LIGHTMAP)
157
157
  irradiance += 0.;
158
158
  #else
159
159
  irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
160
- #endif`);Si.UniformsLib.lightmap.lightmapScaleOffset={value:new Si.Vector4(1,1,0,0)};var CE=N("debugSetup"),SE=N("stats"),ul={};var St=class{static get Current(){return this._current}static set Current(e){this._current=e}name;alias;isManagedExternally=!1;domElement;get domWidth(){return this.domElement.clientWidth}get domHeight(){return this.domElement.clientHeight}get domX(){return this.domElement.offsetLeft}get domY(){return this.domElement.offsetTop}get isInXR(){return this.renderer.xr.isPresenting}get AROverlayElement(){let e=this.domElement;return typeof e.getAROverlayContainer=="function"?e.getAROverlayContainer():this.domElement}scene;renderer;composer=null;scripts=[];scripts_earlyUpdate=[];scripts_update=[];scripts_lateUpdate=[];scripts_onBeforeRender=[];scripts_onAfterRender=[];scripts_WithCorroutines=[];coroutines={};get mainCamera(){if(this.mainCameraComponent){let e=this.mainCameraComponent;return e.cam||e.buildCamera(),e.cam}return null}mainCameraComponent;post_setup_callbacks=[];pre_update_callbacks=[];pre_render_callbacks=[];post_render_callbacks=[];new_scripts=[];new_script_start=[];new_scripts_pre_setup_callbacks=[];new_scripts_post_setup_callbacks=[];application;time;input;physics;connection;assets;mainLight=null;rendererData;addressables;lightmaps;_sizeChanged=!1;_isCreated=!1;_stats=SE?Ef.default():null;constructor(e){if(this.name=e?.name||"",this.alias=e?.alias,this.domElement=e?.domElement||document.body,e?.renderer)this.renderer=e.renderer,this.isManagedExternally=!0;else{let i=N("postfx");this.renderer=new xE({antialias:!0}),this.renderer.toneMappingExposure=1,this.renderer.toneMapping=De.NoToneMapping,this.renderer.setClearColor(new De.Color("lightgrey"),0),this.renderer.antialias=!0,this.renderer.alpha=!1,this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=De.PCFSoftShadowMap,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputEncoding=De.sRGBEncoding,this.renderer.physicallyCorrectLights=!0,this.composer=i?new TE(this.renderer):null}this.scene=new De.Scene,this.application=new xa(this),this.time=new ca,this.input=new Uo(this),this.physics=new la(this),this.connection=new ma(this),this.assets=new dl,this.rendererData=new al(this),this.addressables=new Ha(this),this.lightmaps=new hl(this),window.addEventListener("resize",this.updateSize.bind(this)),new ResizeObserver(i=>this._sizeChanged=!0).observe(this.domElement)}updateSize(){if(!this.isManagedExternally&&!this.renderer.xr.isPresenting){this._sizeChanged=!1;let e=this.domWidth,t=this.domHeight,i=this.mainCamera;this.updateAspect(i),this.renderer.setSize(e,t),this.renderer.setPixelRatio(window.devicePixelRatio),this.composer&&(this.composer.setSize(e,t),this.composer.setPixelRatio(window.devicePixelRatio))}}updateAspect(e){if(!e)return;let t=this.domWidth,i=this.domHeight,n=e.aspect;e.aspect=t/i,n!==e.aspect&&e.updateProjectionMatrix()}onCreate(e,t){return this._isCreated?(console.warn("Context already created"),null):(this._isCreated=!0,this.internalOnCreate(e,t))}onDestroy(){!this._isCreated||(this._isCreated=!1,O.destroy(this.scene,!0),this.renderer?.setAnimationLoop(null),this.isManagedExternally||this.renderer?.dispose())}registerCoroutineUpdate(e,t,i){return this.coroutines[i]||(this.coroutines[i]=[]),this.coroutines[i].push({comp:e,main:t}),t}unregisterCoroutineUpdate(e,t){if(!this.coroutines[t])return;let i=this.coroutines[t].findIndex(n=>n.main===e);i>=0&&this.coroutines[t].splice(i,1)}stopAllCoroutinesFrom(e){for(let t in this.coroutines){let i=this.coroutines[t];for(let n=i.length-1;n>=0;n--)i[n].comp===e&&i.splice(n,1)}}_cameraStack=[];setCurrentCamera(e){if(!e)return;if(e.cam||e.buildCamera(),!e.cam){console.warn("Camera component is missing camera",e);return}let t=this._cameraStack.indexOf(e);t>=0&&this._cameraStack.splice(t,1),this._cameraStack.push(e),this.mainCameraComponent=e;let i=e.cam;i.isPerspectiveCamera&&this.updateAspect(i),this.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}_onBeforeRenderListeners={};addBeforeRenderListener(e,t){if(!this._onBeforeRenderListeners[e.uuid]){this._onBeforeRenderListeners[e.uuid]=[];let i=(n,r,s,o,c,d)=>{let a=this._onBeforeRenderListeners[e.uuid];if(!!a)for(let h=0;h<a.length;h++){let u=a[h];u(n,r,s,o,c,d)}};e.onBeforeRender=i}this._onBeforeRenderListeners[e.uuid].push(t)}removeBeforeRenderListener(e,t){if(this._onBeforeRenderListeners[e.uuid]){let i=this._onBeforeRenderListeners[e.uuid],n=i.indexOf(t);n>=0&&i.splice(n,1)}}_requireDepthTexture=!1;_requireColorTexture=!1;_renderTarget;_isRendering=!1;get isRendering(){return this._isRendering}setRequireDepth(e){this._requireDepthTexture=e}setRequireColor(e){this._requireColorTexture=e}get depthTexture(){return this._renderTarget?.depthTexture||null}get opaqueColorTexture(){return this._renderTarget?.texture||null}async internalOnCreate(e,t){let i=!0;try{St.Current=this,e&&await e(this,t)}catch(r){console.error(r),i=!1}if(!i)return;this.isManagedExternally||this.domElement.prepend(this.renderer.domElement),Ah(this),Oh(this),bf(this),St._current=this;for(let r=0;r<this.new_scripts.length;r++){let s=this.new_scripts[r];if(s.gameObject!==void 0&&s.gameObject!==null){s.gameObject.userData===void 0&&(s.gameObject.userData={}),s.gameObject.userData.components===void 0&&(s.gameObject.userData.components=[]);let o=s.gameObject.userData.components;o.includes(s)||o.push(s)}}if(this.post_setup_callbacks)for(let r=0;r<this.post_setup_callbacks.length;r++)St._current=this,await this.post_setup_callbacks[r](this);if(!this.mainCamera){St._current=this;let r=O.findObjectsOfType(ne,this),s=r.find(o=>o.tag=="MainCamera")??r.find(o=>!0);if(s)s.tag!=="MainCamera"&&console.warn('No mainCamera configured. Some components rely on a mainCamera object being present. When exporting your scene, make sure to set the mainCamera tag on your camera. Using "'+s.name+'" as mainCamera now.'),this.setCurrentCamera(s);else{console.error("No camera found");let o=Gu(this.scene);this.setCurrentCamera(o)}}St._current=this,Ai(this);let n=this.mainCameraComponent;if(n&&n.applyClearFlagsIfIsActiveCamera(),!this.isManagedExternally&&this.composer&&this.mainCamera){let r=new RE(this.scene,this.mainCamera);this.renderer.setSize(this.domWidth,this.domHeight),this.composer.addPass(r),this.composer.setSize(this.domWidth,this.domHeight)}this._sizeChanged=!0,this._stats&&(this._stats.showPanel(1),this.domElement.appendChild(this._stats.dom)),this.renderer.setAnimationLoop(this.render.bind(this)),CE&&Us(this.scene,!0)}render(e,t){for(this._stats?.begin(),St._current=this,this.time.update(),Ai(this),dh(),ch(this);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);let i=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(i)}if(this.pre_update_callbacks)for(let i in this.pre_update_callbacks)this.pre_update_callbacks[i]();for(let i=0;i<this.scripts_earlyUpdate.length;i++){let n=this.scripts_earlyUpdate[i];!n.activeAndEnabled||n.earlyUpdate!==void 0&&(St._current=this,n.earlyUpdate())}this.executeCoroutines(0);for(let i=0;i<this.scripts_update.length;i++){let n=this.scripts_update[i];!n.activeAndEnabled||n.update!==void 0&&(St._current=this,n.update())}this.executeCoroutines(1);for(let i=0;i<this.scripts_lateUpdate.length;i++){let n=this.scripts_lateUpdate[i];!n.activeAndEnabled||n.lateUpdate!==void 0&&(St._current=this,n.lateUpdate())}this.mainLight=null,this.executeCoroutines(2);try{let n=this.time.deltaTime/2;for(let r=0;r<2;r++)this.physics.step(n),this.executeCoroutines(10)}catch(i){console.error(i)}this.physics.postStep();for(let i=0;i<this.scripts_onBeforeRender.length;i++){let n=this.scripts_onBeforeRender[i];!n.activeAndEnabled||n.onBeforeRender!==void 0&&(St._current=this,n.onBeforeRender(t))}if(this.executeCoroutines(3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(let i in this.pre_render_callbacks)this.pre_render_callbacks[i]();this._isRendering=!0,this.renderRequiredTextures(),this.isManagedExternally||(this.composer?this.composer.render():this.mainCamera&&this.renderer.render(this.scene,this.mainCamera)),this._isRendering=!1;for(let i=0;i<this.scripts_onAfterRender.length;i++){let n=this.scripts_onAfterRender[i];!n.activeAndEnabled||n.onAfterRender!==void 0&&(St._current=this,n.onAfterRender())}if(this.executeCoroutines(4),this.post_render_callbacks)for(let i in this.post_render_callbacks)this.post_render_callbacks[i]();this.connection.sendBufferedMessagesNow(),this._stats?.end()}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new De.WebGLRenderTarget(this.domWidth,this.domHeight),this._requireDepthTexture){let i=new _E(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new De.Texture,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=De.NearestFilter,this._renderTarget.texture.magFilter=De.NearestFilter,this._renderTarget.texture.format=De.RGBAFormat)}let e=this._renderTarget;e.texture&&(e.texture.encoding=this.renderer.outputEncoding);let 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]){let i=this.coroutines[e];for(let n=0;n<i.length;n++){let r=i[n];if(!r.comp||r.comp.destroyed||!r.main){i.splice(n,1),--n;continue}let s=r.chained;if(s&&s.length>0){let a=s[s.length-1].next();if(a.done&&s.pop(),t(a)&&(r.chained||(r.chained=[]),r.chained.push(a.value)),!a.done)continue}let o=r.main.next();if(o.done===!0){i.splice(n,1),--n;continue}let c=o.value;if(t(c)){if(c.next().done)continue;r.chained||(r.chained=[]),r.chained.push(c)}}}function t(i){return!!(i&&i.next&&i.return)}}},Z=St;z(Z,"_current");var Ns="ar",PE="quit-ar",pl=class{get ARContainer(){return this.arContainer}constructor(){this.closeARCallback=this.onRequestedEndAR.bind(this)}arContainer=null;closeARCallback;currentSession=null;registeredCloseEventElements=[];_createdAROnlyElements=[];requestEndAR(){this.onRequestedEndAR()}onBegin(e,t){if(this.currentSession=t,this.arContainer=e,!this.arContainer)return;let i=e.getElementsByClassName(PE);if(!i||i.length<=0)console.warn("Missing quit AR elements"),this.createFallbackCloseARButton(this.arContainer);else for(let n=0;n<i.length;n++){let r=i[n];!r||(r.addEventListener("click",this.closeARCallback),this.registeredCloseEventElements.push(r))}}onEnd(){for(let e of this._createdAROnlyElements)e.remove&&e.remove()}findOrCreateARContainer(e){if(e.classList.contains(Ns))return e;if(e.children){for(let i of e.children)if(!(!i||!i.classList)&&i.classList.contains(Ns))return i}let t=document.createElement("div");return t.classList.add(Ns),e.appendChild(t)}onRequestedEndAR(){if(!!this.currentSession){this.currentSession.end(),this.currentSession=null;for(let 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 i=document.createElementNS("http://www.w3.org/2000/svg","path");i.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),i.setAttribute("stroke","#eee"),i.setAttribute("stroke-width","2px"),t.appendChild(i),this._createdAROnlyElements.push(i)}};var OE=N("debugloadingbar");function Nd(l){return l.index/l.count+l.progress.loaded/l.progress.total/l.count}var fl=class{loadingProgress=0;container;_progress=0;_allowCustomLoadingElement=!1;_loadingElement;_loadingTextContainer=null;_loadingBar=null;_messageContainer=null;_loadingElementOptions;constructor(e,t){this.container=e,this._loadingElementOptions=t}onLoadingBegin(e){if(!this._loadingElement){for(let t=0;t<this.container.children.length;t++){let i=this.container.children[t];if(i.classList.contains("loading")){if(!this._allowCustomLoadingElement){this.container.removeChild(i);continue}this._loadingElement=this.createLoadingElement();return}}this._loadingElement=this.createLoadingElement()}this._progress=0,this.loadingProgress=0,this._loadingElement.style.display="",this.container.appendChild(this._loadingElement),this.smoothProgressLoop(),this.setMessage(e??"")}onLoadingUpdate(e,t){this._loadingElement?.parentElement||this.onLoadingBegin(t);let i=0;typeof e=="number"?i=e:("index"in e&&(i=Nd(e)),!t&&"name"in e&&this.setMessage(e.name)),this.loadingProgress=i,t&&this.setMessage(t),this.updateDisplay()}onLoadingFinished(e){this.loadingProgress=1,this.setMessage(e??"")}setMessage(e){this._messageContainer&&(this._messageContainer.innerText=e)}_progressLoop;smoothProgressLoop(){if(this._progressLoop)return;let e=1/12;OE&&(e=.001);let t=1-.05;this._progressLoop=setInterval(()=>{if(this.loadingProgress>=1&&this._progress>=t){this._loadingElement&&(this._loadingElement.style.display="none",this._loadingElement.remove()),clearInterval(this._progressLoop),this._progressLoop=null;return}this._progress=Q.lerp(this._progress,this.loadingProgress,e*this.loadingProgress),this.updateDisplay()},e)}updateDisplay(){let e=this._progress,t=(e*100).toFixed(0)+"%";this._loadingBar&&(this._loadingBar.style.width=e*100+"%"),this._loadingTextContainer&&(this._loadingTextContainer.textContent=t)}createLoadingElement(e){this._loadingElement=e||document.createElement("div");let t=this._loadingElementOptions?.className??"loading";if(this._loadingElement.classList.add(t),this._loadingElementOptions?.additionalClasses)for(let o of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(o);e||(this._loadingElement.style.color="white",this._loadingElement.style.display="flex");let i=document.createElement("div"),n=20;i.style.display="flex",i.style.width=n+"%",i.style.height="2px",i.style.background="rgba(255,255,255,.1)",this._loadingElement.appendChild(i),this._loadingBar=document.createElement("div"),i.appendChild(this._loadingBar);let r=function(o){return Q.lerp(n*.5,100-n*.5,o)+"%"};this._loadingBar.style.background=`linear-gradient(90deg, #02022B ${r(0)}, #0BA398 ${r(.4)}, #99CC33 ${r(.5)}, #D7DB0A ${r(1)})`,this._loadingBar.style.backgroundAttachment="fixed",this._loadingBar.style.width="0%",this._loadingBar.style.height="100%",this._loadingTextContainer=document.createElement("div"),this._loadingTextContainer.style.display="flex",this._loadingTextContainer.style.justifyContent="center",this._loadingTextContainer.style.marginTop=".9em",this._loadingElement.appendChild(this._loadingTextContainer);let s=document.createElement("div");return this._messageContainer=s,s.style.display="flex",s.style.fontSize=".8em",s.style.paddingTop=".5em",s.style.color="rgba(255,255,255,.5)",this._loadingElement.appendChild(s),this._loadingElement}};var zd=class{id;context;previouslyAdded;previousSource;networkEvent;constructor(e,t){this.id=e,this.context=t,this.networkEvent="needle-engine-source-changed",this.id&&(this.networkEvent+="-"+this.id),this.context.connection.beginListen(this.networkEvent,i=>{this.onSourceChanged(i,!0)})}async onSourceChanged(e,t=!1,i=!1){this.previouslyAdded&&(t&&e===this.previousSource||O.destroySynced(this.previouslyAdded)),this.previouslyAdded=null,t||this.context.connection.send(this.networkEvent,e),this.previousSource=e,Z.Current=this.context;let n=await lr(this.context,e,this.getHashFromString(e));i||Ai(this.context);let r=n?.scene;r&&(this.previouslyAdded=r,this.context.scene.add(r))}getHashFromString(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}},AE="needle-engine",kE="vr",IE="desktop",ME=[Ns,kE,IE],Gd=class extends HTMLElement{get loadingProgress01(){return this._loadingProgress01}get loadingFinished(){return this.loadingProgress01>.999}getContext(){return new Promise((e,t)=>{if(this.context&&this.loadingFinished)e(this.context);else{let i=()=>{this.removeEventListener("loadfinished",i),this.context&&this.loadingFinished&&e(this.context)};this.addEventListener("loadfinished",i)}})}gameObject=O;GameObject=O;context=null;overlay_ar;_loadingProgress01=0;_watcher;_loadingView;constructor(){super(),this.overlay_ar=new pl}async connectedCallback(){this.onSetupDesktop();var e=new MutationObserver(this.onElementsChanged.bind(this));e.observe(this,{childList:!0});let t=()=>{let s=this.getAttribute("src");return s?.endsWith(".glb")||s?.endsWith(".gltf")?s:null},i="loadScene",n=t();n&&(i=n);let r=this.getAttribute("alias");if(this.context=new Z({name:i,domElement:this,alias:r}),this._watcher=new zd(this.getAttribute("id")??r??"",this.context),i&&i.length>0){if(!n)for(;Object.keys(ul).length<=0;){if(!this.isConnected)return;await oh(10)}let s=ul[i]??window[i],o=null;if((!s||n)&&(n&&(i=n),s=async c=>{let d=t();d&&this._watcher&&(o=d,await this._watcher.onSourceChanged(d,!0,!0))}),s){this.classList.add("loading"),console.log("Needle Engine: Begin loading",r??"");let c=this.dispatchEvent(new CustomEvent("loadstart",{detail:{context:this.context,alias:r},cancelable:!0}));!this._loadingView&&c&&(this._loadingView=new fl(this)),c&&this._loadingView?.onLoadingBegin("begin load");let d=(h,u)=>{this._loadingProgress01=Nd(h),c&&this._loadingView?.onLoadingUpdate(h,u),this.dispatchEvent(new CustomEvent("progress",{detail:{context:this.context,name:h.name,progress:h.progress,index:h.index,count:h.count,totalProgress01:this._loadingProgress01}}))};await this.context.onCreate(s,{progress:d});let a=t();a&&a!==o&&await this._watcher.onSourceChanged(a,!0,!0),this._loadingProgress01=1,c&&this._loadingView?.onLoadingFinished("create scene"),this.classList.remove("loading"),this.classList.add("loading-finished"),console.log("Needle Engine: finished loading",r??""),this.dispatchEvent(new CustomEvent("loadfinished",{detail:{context:this.context,src:r??i}})),this.onSetupDesktop()}else console.error('Could not find scene function named "'+i+'", it must be either in global scope or added to build_scene_functions',ul)}else console.error("Missing src attribute - please provide a function name",this)}disconnectedCallback(){this.context&&this.context.onDestroy()}static get observedAttributes(){return["src","loadfinished"]}attributeChangedCallback(e,t,i){switch(e){case"src":this._watcher?.onSourceChanged(i);break;case"loadfinished":typeof i=="string"&&i.length>0&&this.registerEventFromAttribute("loadfinished",i);break}}registerEventFromAttribute(e,t){if(typeof t=="string"&&t.length>0){let i=(0,eval)(t);typeof i=="function"&&this.addEventListener(e,n=>i?.call(globalThis,this.context,n))}}getAROverlayContainer(){return this.overlay_ar.findOrCreateARContainer(this)}getVROverlayContainer(){for(let e=0;e<this.children.length;e++){let t=this.children[e];if(t.classList.contains("vr"))return t}return null}onEnterAR(e,t){this.onSetupAR(),this.overlay_ar.onBegin(t,e),this.dispatchEvent(new CustomEvent("enter-ar",{detail:{session:e,context:this.context,htmlContainer:this.overlay_ar?.ARContainer}}))}onExitAR(e){this.overlay_ar.onEnd(),this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-ar",{detail:{session:e,context:this.context,htmlContainer:this.overlay_ar?.ARContainer}}))}onEnterVR(e){this.onSetupVR(),this.dispatchEvent(new CustomEvent("enter-vr",{detail:{session:e,context:this.context}}))}onExitVR(e){this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-vr",{detail:{session:e,context:this.context}}))}onElementsChanged(){}onSetupAR(){this.classList.add("ar-session-active"),this.classList.remove("desktop-session-active"),this.foreachHtmlElement(e=>this.setupElementsForMode(e,Ns))}onSetupVR(){this.classList.remove("ar-session-active"),this.classList.remove("desktop-session-active"),this.foreachHtmlElement(e=>this.setupElementsForMode(e,"vr"))}onSetupDesktop(){this.classList.remove("ar-session-active"),this.classList.add("desktop-session-active"),this.foreachHtmlElement(e=>this.setupElementsForMode(e,"desktop"))}setupElementsForMode(e,t,i=null){if(e===this.context?.renderer.domElement||e.id==="VRButton"||e.id==="ARButton")return;if(e.style.position="absolute",e.classList.contains(t))e.style.visibility="visible",e.style.display="block";else for(let r of ME)e.classList.contains(r)&&(e.style.visibility="hidden",e.style.display="none")}foreachHtmlElement(e){for(let t=0;t<this.children.length;t++){let i=this.children[t];i.style&&e(i)}}};window.customElements.define(AE,Gd);var Vd={};Kd(Vd,{AlignmentConstraint:()=>zr,Animation:()=>Zt,AnimationCurve:()=>ir,AnimationTrackHandler:()=>Hn,Animator:()=>bt,AnimatorController:()=>Yt,AttachedObject:()=>dt,AudioListener:()=>Jt,AudioSource:()=>ue,AudioTrackHandler:()=>jn,AvatarBlink_Simple:()=>_i,AvatarEyeLook_Rotation:()=>xi,AvatarLoader:()=>Fi,AvatarMarker:()=>fe,AvatarModel:()=>nr,Avatar_Brain_LookAt:()=>Wi,Avatar_MouthShapes:()=>Dn,Avatar_MustacheShake:()=>Rs,Avatar_POI:()=>_e,AxesHelper:()=>Ni,BaseUIComponent:()=>Ue,BasicIKConstraint:()=>Wr,BoxCollider:()=>wn,BoxGizmo:()=>qi,BoxHelperComponent:()=>lt,Button:()=>Ft,CallInfo:()=>vi,Camera:()=>ne,Canvas:()=>Je,CanvasGroup:()=>sn,Collider:()=>pi,ColorAdjustments:()=>Ln,ControlTrackHandler:()=>$i,Deletable:()=>Yr,DeleteBox:()=>rr,DeviceFlag:()=>sr,DragControls:()=>Et,DropListener:()=>Cn,Duplicatable:()=>bi,EmissionModule:()=>fs,EventList:()=>Oe,EventListEvent:()=>cr,EventSystem:()=>Ze,EventTrigger:()=>ns,FieldWithDefault:()=>Ir,FlyControls:()=>rs,GltfExport:()=>jt,GltfExportBox:()=>os,Graphic:()=>Rt,GraphicRaycaster:()=>Ds,GridHelper:()=>Xi,GridLayoutGroup:()=>Ls,GroundProjectedEnv:()=>Qi,HorizontalLayoutGroup:()=>Ms,Image:()=>rn,InputField:()=>Ct,InstancingUtil:()=>he,InstantiateOptions:()=>ye,Interactable:()=>kt,Keyboard:()=>ks,LODGroup:()=>Pn,LODModel:()=>yi,LayoutGroup:()=>on,Light:()=>Ye,LogStats:()=>Cs,LookAtConstraint:()=>ji,MainModule:()=>ps,MaskableGraphic:()=>nn,MeshCollider:()=>ls,MeshRenderer:()=>er,NavMesh:()=>cs,NavMeshAgent:()=>ds,NestedGltf:()=>dr,Networking:()=>pt,ObjectRaycaster:()=>Ri,OffsetConstraint:()=>hs,OrbitControls:()=>gt,ParticleSystem:()=>gs,ParticleSystemRenderer:()=>hr,PlayableDirector:()=>en,PlayerColor:()=>ht,PointerEventData:()=>ti,RGBAColor:()=>we,RawImage:()=>yr,Raycaster:()=>wr,Rect:()=>vr,RectTransform:()=>ut,RemoteSkybox:()=>An,Renderer:()=>Te,RendererLightmap:()=>Di,Rigidbody:()=>ce,ScreenCapture:()=>bs,ShadowCatcher:()=>On,ShapeModule:()=>ms,SignalAsset:()=>gr,SignalReceiver:()=>Ji,SignalReceiverEvent:()=>br,SignalTrackHandler:()=>Ki,Size:()=>Os,SkinnedMeshRenderer:()=>Mr,SmoothFollow:()=>Ei,SpatialHtml:()=>Hs,SpatialTrigger:()=>Yi,SpatialTriggerReceiver:()=>wt,SpectatorCamera:()=>ys,SphereCollider:()=>En,SpringJoint:()=>Es,Sprite:()=>ur,SpriteRenderer:()=>Zi,SyncedCamera:()=>kn,SyncedRoom:()=>ei,SyncedTransform:()=>Qe,TeleportTarget:()=>or,TestRunner:()=>ws,TestSimulateUserData:()=>_s,Text:()=>Le,ToneMapping:()=>Mn,TransformGizmo:()=>pr,UIRootComponent:()=>tn,UnityObject:()=>Qr,UsageMarker:()=>It,VRUserState:()=>Ht,VerticalLayoutGroup:()=>Is,VideoPlayer:()=>nt,Voip:()=>Ke,Volume:()=>fr,VolumeComponent:()=>wi,VolumeParameter:()=>xs,VolumeProfile:()=>In,WebAR:()=>Rn,WebARSessionRoot:()=>Dt,WebXR:()=>$,WebXRAvatar:()=>Lt,WebXRController:()=>oe,WebXRSync:()=>Ui,XRFlag:()=>Se,XRGrabModel:()=>mr,XRGrabRendering:()=>Ts,XRRig:()=>Tn,XRState:()=>vt});var Wd={Context:Z};globalThis.Needle=Wd;function wf(l){for(let e in l)Wd[e]=l[e]}wf(Hl);wf(Vd);for(let l of Object.getOwnPropertyNames(O))switch(l){case"prototype":case"constructor":case"length":case"name":continue;default:Wd[l]=O[l];break}export{zr as AlignmentConstraint,Zt as Animation,ir as AnimationCurve,Hn as AnimationTrackHandler,bt as Animator,Yt as AnimatorController,dt as AttachedObject,Jt as AudioListener,ue as AudioSource,jn as AudioTrackHandler,_i as AvatarBlink_Simple,xi as AvatarEyeLook_Rotation,Fi as AvatarLoader,fe as AvatarMarker,nr as AvatarModel,Wi as Avatar_Brain_LookAt,Dn as Avatar_MouthShapes,Rs as Avatar_MustacheShake,_e as Avatar_POI,Ni as AxesHelper,Ue as BaseUIComponent,Wr as BasicIKConstraint,M as Behaviour,wn as BoxCollider,qi as BoxGizmo,lt as BoxHelperComponent,Ft as Button,vi as CallInfo,ne as Camera,Je as Canvas,sn as CanvasGroup,pi as Collider,Ln as ColorAdjustments,$i as ControlTrackHandler,Yr as Deletable,rr as DeleteBox,sr as DeviceFlag,Et as DragControls,Cn as DropListener,bi as Duplicatable,fs as EmissionModule,Oe as EventList,cr as EventListEvent,Ze as EventSystem,ns as EventTrigger,Ir as FieldWithDefault,rs as FlyControls,O as GameObject,jt as GltfExport,os as GltfExportBox,Rt as Graphic,Ds as GraphicRaycaster,Xi as GridHelper,Ls as GridLayoutGroup,Qi as GroundProjectedEnv,Ms as HorizontalLayoutGroup,rn as Image,Ct as InputField,he as InstancingUtil,ye as InstantiateOptions,kt as Interactable,ks as Keyboard,Pn as LODGroup,yi as LODModel,on as LayoutGroup,Ye as Light,Cs as LogStats,ji as LookAtConstraint,ps as MainModule,nn as MaskableGraphic,ls as MeshCollider,er as MeshRenderer,cs as NavMesh,ds as NavMeshAgent,dr as NestedGltf,pt as Networking,Ri as ObjectRaycaster,hs as OffsetConstraint,gt as OrbitControls,gs as ParticleSystem,hr as ParticleSystemRenderer,en as PlayableDirector,ht as PlayerColor,ti as PointerEventData,we as RGBAColor,yr as RawImage,wr as Raycaster,vr as Rect,ut as RectTransform,An as RemoteSkybox,Te as Renderer,Di as RendererLightmap,ce as Rigidbody,bs as ScreenCapture,On as ShadowCatcher,ms as ShapeModule,gr as SignalAsset,Ji as SignalReceiver,br as SignalReceiverEvent,Ki as SignalTrackHandler,Os as Size,Mr as SkinnedMeshRenderer,Ei as SmoothFollow,Hs as SpatialHtml,Yi as SpatialTrigger,wt as SpatialTriggerReceiver,ys as SpectatorCamera,En as SphereCollider,Es as SpringJoint,ur as Sprite,Zi as SpriteRenderer,kn as SyncedCamera,ei as SyncedRoom,Qe as SyncedTransform,or as TeleportTarget,ws as TestRunner,_s as TestSimulateUserData,Le as Text,Mn as ToneMapping,pr as TransformGizmo,tn as UIRootComponent,Qr as UnityObject,It as UsageMarker,Ht as VRUserState,Is as VerticalLayoutGroup,nt as VideoPlayer,Ke as Voip,fr as Volume,wi as VolumeComponent,xs as VolumeParameter,In as VolumeProfile,Rn as WebAR,Dt as WebARSessionRoot,$ as WebXR,Lt as WebXRAvatar,oe as WebXRController,Ui as WebXRSync,Se as XRFlag,mr as XRGrabModel,Ts as XRGrabRendering,Tn as XRRig,vt as XRState,A as serializeable};
160
+ #endif`);Pi.UniformsLib.lightmap.lightmapScaleOffset={value:new Pi.Vector4(1,1,0,0)};var OE=N("debugSetup"),AE=N("stats"),ul={};var St=class{static get Current(){return this._current}static set Current(e){this._current=e}name;alias;isManagedExternally=!1;domElement;get domWidth(){return this.domElement.clientWidth}get domHeight(){return this.domElement.clientHeight}get domX(){return this.domElement.offsetLeft}get domY(){return this.domElement.offsetTop}get isInXR(){return this.renderer.xr.isPresenting}get AROverlayElement(){let e=this.domElement;return typeof e.getAROverlayContainer=="function"?e.getAROverlayContainer():this.domElement}scene;renderer;composer=null;scripts=[];scripts_earlyUpdate=[];scripts_update=[];scripts_lateUpdate=[];scripts_onBeforeRender=[];scripts_onAfterRender=[];scripts_WithCorroutines=[];coroutines={};get mainCamera(){if(this.mainCameraComponent){let e=this.mainCameraComponent;return e.cam||e.buildCamera(),e.cam}return null}mainCameraComponent;post_setup_callbacks=[];pre_update_callbacks=[];pre_render_callbacks=[];post_render_callbacks=[];new_scripts=[];new_script_start=[];new_scripts_pre_setup_callbacks=[];new_scripts_post_setup_callbacks=[];application;time;input;physics;connection;assets;mainLight=null;rendererData;addressables;lightmaps;_sizeChanged=!1;_isCreated=!1;_stats=AE?Cf.default():null;constructor(e){if(this.name=e?.name||"",this.alias=e?.alias,this.domElement=e?.domElement||document.body,e?.renderer)this.renderer=e.renderer,this.isManagedExternally=!0;else{let i=N("postfx");this.renderer=new CE({antialias:!0}),this.renderer.toneMappingExposure=1,this.renderer.toneMapping=De.NoToneMapping,this.renderer.setClearColor(new De.Color("lightgrey"),0),this.renderer.antialias=!0,this.renderer.alpha=!1,this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=De.PCFSoftShadowMap,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputEncoding=De.sRGBEncoding,this.renderer.physicallyCorrectLights=!0,this.composer=i?new SE(this.renderer):null}this.scene=new De.Scene,this.application=new Ta(this),this.time=new da,this.input=new qs(this),this.physics=new ca(this),this.connection=new ga(this),this.assets=new dl,this.rendererData=new al(this),this.addressables=new ja(this),this.lightmaps=new hl(this),window.addEventListener("resize",this.updateSize.bind(this)),new ResizeObserver(i=>this._sizeChanged=!0).observe(this.domElement)}updateSize(){if(!this.isManagedExternally&&!this.renderer.xr.isPresenting){this._sizeChanged=!1;let e=this.domWidth,t=this.domHeight,i=this.mainCamera;this.updateAspect(i),this.renderer.setSize(e,t),this.renderer.setPixelRatio(window.devicePixelRatio),this.composer&&(this.composer.setSize(e,t),this.composer.setPixelRatio(window.devicePixelRatio))}}updateAspect(e){if(!e)return;let t=this.domWidth,i=this.domHeight,n=e.aspect;e.aspect=t/i,n!==e.aspect&&e.updateProjectionMatrix()}onCreate(e,t){return this._isCreated?(console.warn("Context already created"),null):(this._isCreated=!0,this.internalOnCreate(e,t))}onDestroy(){!this._isCreated||(this._isCreated=!1,O.destroy(this.scene,!0),this.renderer?.setAnimationLoop(null),this.isManagedExternally||this.renderer?.dispose())}registerCoroutineUpdate(e,t,i){return this.coroutines[i]||(this.coroutines[i]=[]),this.coroutines[i].push({comp:e,main:t}),t}unregisterCoroutineUpdate(e,t){if(!this.coroutines[t])return;let i=this.coroutines[t].findIndex(n=>n.main===e);i>=0&&this.coroutines[t].splice(i,1)}stopAllCoroutinesFrom(e){for(let t in this.coroutines){let i=this.coroutines[t];for(let n=i.length-1;n>=0;n--)i[n].comp===e&&i.splice(n,1)}}_cameraStack=[];setCurrentCamera(e){if(!e)return;if(e.cam||e.buildCamera(),!e.cam){console.warn("Camera component is missing camera",e);return}let t=this._cameraStack.indexOf(e);t>=0&&this._cameraStack.splice(t,1),this._cameraStack.push(e),this.mainCameraComponent=e;let i=e.cam;i.isPerspectiveCamera&&this.updateAspect(i),this.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}_onBeforeRenderListeners={};addBeforeRenderListener(e,t){if(!this._onBeforeRenderListeners[e.uuid]){this._onBeforeRenderListeners[e.uuid]=[];let i=(n,r,o,s,c,d)=>{let a=this._onBeforeRenderListeners[e.uuid];if(!!a)for(let h=0;h<a.length;h++){let u=a[h];u(n,r,o,s,c,d)}};e.onBeforeRender=i}this._onBeforeRenderListeners[e.uuid].push(t)}removeBeforeRenderListener(e,t){if(this._onBeforeRenderListeners[e.uuid]){let i=this._onBeforeRenderListeners[e.uuid],n=i.indexOf(t);n>=0&&i.splice(n,1)}}_requireDepthTexture=!1;_requireColorTexture=!1;_renderTarget;_isRendering=!1;get isRendering(){return this._isRendering}setRequireDepth(e){this._requireDepthTexture=e}setRequireColor(e){this._requireColorTexture=e}get depthTexture(){return this._renderTarget?.depthTexture||null}get opaqueColorTexture(){return this._renderTarget?.texture||null}async internalOnCreate(e,t){let i=!0;try{St.Current=this,e&&await e(this,t)}catch(r){console.error(r),i=!1}if(!i)return;this.isManagedExternally||this.domElement.prepend(this.renderer.domElement),Hh(this),Dh(this),xf(this),St._current=this;for(let r=0;r<this.new_scripts.length;r++){let o=this.new_scripts[r];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=[]);let s=o.gameObject.userData.components;s.includes(o)||s.push(o)}}if(this.post_setup_callbacks)for(let r=0;r<this.post_setup_callbacks.length;r++)St._current=this,await this.post_setup_callbacks[r](this);if(!this.mainCamera){St._current=this;let r=O.findObjectsOfType(ne,this),o=r.find(s=>s.tag=="MainCamera")??r.find(s=>!0);if(o)o.tag!=="MainCamera"&&console.warn('No mainCamera configured. Some components rely on a mainCamera object being present. When exporting your scene, make sure to set the mainCamera tag on your camera. Using "'+o.name+'" as mainCamera now.'),this.setCurrentCamera(o);else{console.error("No camera found");let s=Yu(this.scene);this.setCurrentCamera(s)}}St._current=this,ki(this);let n=this.mainCameraComponent;if(n&&n.applyClearFlagsIfIsActiveCamera(),!this.isManagedExternally&&this.composer&&this.mainCamera){let r=new PE(this.scene,this.mainCamera);this.renderer.setSize(this.domWidth,this.domHeight),this.composer.addPass(r),this.composer.setSize(this.domWidth,this.domHeight)}this._sizeChanged=!0,this._stats&&(this._stats.showPanel(1),this.domElement.appendChild(this._stats.dom)),this.renderer.setAnimationLoop(this.render.bind(this)),OE&&Zo(this.scene,!0)}render(e,t){for(this._stats?.begin(),St._current=this,this.time.update(),ki(this),gh(),mh(this);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);let i=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(i)}if(this.pre_update_callbacks)for(let i in this.pre_update_callbacks)this.pre_update_callbacks[i]();for(let i=0;i<this.scripts_earlyUpdate.length;i++){let n=this.scripts_earlyUpdate[i];!n.activeAndEnabled||n.earlyUpdate!==void 0&&(St._current=this,n.earlyUpdate())}this.executeCoroutines(0);for(let i=0;i<this.scripts_update.length;i++){let n=this.scripts_update[i];!n.activeAndEnabled||n.update!==void 0&&(St._current=this,n.update())}this.executeCoroutines(1);for(let i=0;i<this.scripts_lateUpdate.length;i++){let n=this.scripts_lateUpdate[i];!n.activeAndEnabled||n.lateUpdate!==void 0&&(St._current=this,n.lateUpdate())}this.mainLight=null,this.executeCoroutines(2);try{let n=this.time.deltaTime/2;for(let r=0;r<2;r++)this.physics.step(n),this.executeCoroutines(10)}catch(i){console.error(i)}this.physics.postStep();for(let i=0;i<this.scripts_onBeforeRender.length;i++){let n=this.scripts_onBeforeRender[i];!n.activeAndEnabled||n.onBeforeRender!==void 0&&(St._current=this,n.onBeforeRender(t))}if(this.executeCoroutines(3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(let i in this.pre_render_callbacks)this.pre_render_callbacks[i]();this._isRendering=!0,this.renderRequiredTextures(),this.isManagedExternally||(this.composer?this.composer.render():this.mainCamera&&this.renderer.render(this.scene,this.mainCamera)),this._isRendering=!1;for(let i=0;i<this.scripts_onAfterRender.length;i++){let n=this.scripts_onAfterRender[i];!n.activeAndEnabled||n.onAfterRender!==void 0&&(St._current=this,n.onAfterRender())}if(this.executeCoroutines(4),this.post_render_callbacks)for(let i in this.post_render_callbacks)this.post_render_callbacks[i]();this.connection.sendBufferedMessagesNow(),this._stats?.end()}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new De.WebGLRenderTarget(this.domWidth,this.domHeight),this._requireDepthTexture){let i=new RE(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new De.Texture,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=De.NearestFilter,this._renderTarget.texture.magFilter=De.NearestFilter,this._renderTarget.texture.format=De.RGBAFormat)}let e=this._renderTarget;e.texture&&(e.texture.encoding=this.renderer.outputEncoding);let 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]){let i=this.coroutines[e];for(let n=0;n<i.length;n++){let r=i[n];if(!r.comp||r.comp.destroyed||!r.main||r.comp.enabled===!1){i.splice(n,1),--n;continue}let s=r.chained;if(s&&s.length>0){let h=s[s.length-1].next();if(h.done&&s.pop(),t(h)&&(r.chained||(r.chained=[]),r.chained.push(h.value)),!h.done)continue}let c=r.main.next();if(c.done===!0){i.splice(n,1),--n;continue}let d=c.value;if(t(d)){if(d.next().done)continue;r.chained||(r.chained=[]),r.chained.push(d)}}}function t(i){return!!(i&&i.next&&i.return)}}},Z=St;z(Z,"_current");var Rr="ar",kE="quit-ar",pl=class{get ARContainer(){return this.arContainer}constructor(){this.closeARCallback=this.onRequestedEndAR.bind(this)}arContainer=null;closeARCallback;currentSession=null;registeredCloseEventElements=[];_createdAROnlyElements=[];_reparentedObjects=[];requestEndAR(){this.onRequestedEndAR()}onBegin(e,t,i){this.currentSession=i,this.arContainer=t,e.domElement.querySelectorAll(`.${Rr}`).forEach(o=>{!o||o!==this.arContainer&&(this._reparentedObjects.push({el:o,previousParent:o.parentElement}),this.arContainer?.appendChild(o))});let r=t.getElementsByClassName(kE);if(!r||r.length<=0)console.warn("Missing quit AR elements"),this.createFallbackCloseARButton(this.arContainer);else for(let o=0;o<r.length;o++){let s=r[o];!s||(s.addEventListener("click",this.closeARCallback),this.registeredCloseEventElements.push(s))}}onEnd(e){for(let t of this._createdAROnlyElements)t.remove&&t.remove();for(let t of this._reparentedObjects){let i=t.el;t.previousParent?.appendChild(i)}this._reparentedObjects.length=0}findOrCreateARContainer(e){if(e.classList.contains(Rr))return e;if(e.children){for(let i of e.children)if(!(!i||!i.classList)&&i.classList.contains(Rr))return i}let t=document.createElement("div");return t.classList.add(Rr),e.appendChild(t)}onRequestedEndAR(){if(!!this.currentSession){this.currentSession.end(),this.currentSession=null;for(let 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 i=document.createElementNS("http://www.w3.org/2000/svg","path");i.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),i.setAttribute("stroke","#eee"),i.setAttribute("stroke-width","2px"),t.appendChild(i),this._createdAROnlyElements.push(i)}};var IE=N("debugloadingbar");function qd(l){return l.index/l.count+l.progress.loaded/l.progress.total/l.count}var fl=class{loadingProgress=0;container;_progress=0;_allowCustomLoadingElement=!1;_loadingElement;_loadingTextContainer=null;_loadingBar=null;_messageContainer=null;_loadingElementOptions;constructor(e,t){this.container=e,this._loadingElementOptions=t}onLoadingBegin(e){if(!this._loadingElement){for(let t=0;t<this.container.children.length;t++){let i=this.container.children[t];if(i.classList.contains("loading")){if(!this._allowCustomLoadingElement){this.container.removeChild(i);continue}this._loadingElement=this.createLoadingElement();return}}this._loadingElement=this.createLoadingElement()}this._progress=0,this.loadingProgress=0,this._loadingElement.style.display="",this.container.appendChild(this._loadingElement),this.smoothProgressLoop(),this.setMessage(e??"")}onLoadingUpdate(e,t){this._loadingElement?.parentElement||this.onLoadingBegin(t);let i=0;typeof e=="number"?i=e:("index"in e&&(i=qd(e)),!t&&"name"in e&&this.setMessage(e.name)),this.loadingProgress=i,t&&this.setMessage(t),this.updateDisplay()}onLoadingFinished(e){this.loadingProgress=1,this.setMessage(e??"")}setMessage(e){this._messageContainer&&(this._messageContainer.innerText=e)}_progressLoop;smoothProgressLoop(){if(this._progressLoop)return;let e=1/12;IE&&(e=.001);let t=1-.05;this._progressLoop=setInterval(()=>{if(this.loadingProgress>=1&&this._progress>=t){this._loadingElement&&(this._loadingElement.style.display="none",this._loadingElement.remove()),clearInterval(this._progressLoop),this._progressLoop=null;return}this._progress=Q.lerp(this._progress,this.loadingProgress,e*this.loadingProgress),this.updateDisplay()},e)}updateDisplay(){let e=this._progress,t=(e*100).toFixed(0)+"%";this._loadingBar&&(this._loadingBar.style.width=e*100+"%"),this._loadingTextContainer&&(this._loadingTextContainer.textContent=t)}createLoadingElement(e){this._loadingElement=e||document.createElement("div");let t=this._loadingElementOptions?.className??"loading";if(this._loadingElement.classList.add(t),this._loadingElementOptions?.additionalClasses)for(let s of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(s);e||(this._loadingElement.style.color="white",this._loadingElement.style.display="flex");let i=document.createElement("div"),n=20;i.style.display="flex",i.style.width=n+"%",i.style.height="2px",i.style.background="rgba(255,255,255,.1)",this._loadingElement.appendChild(i),this._loadingBar=document.createElement("div"),i.appendChild(this._loadingBar);let r=function(s){return Q.lerp(n*.5,100-n*.5,s)+"%"};this._loadingBar.style.background=`linear-gradient(90deg, #02022B ${r(0)}, #0BA398 ${r(.4)}, #99CC33 ${r(.5)}, #D7DB0A ${r(1)})`,this._loadingBar.style.backgroundAttachment="fixed",this._loadingBar.style.width="0%",this._loadingBar.style.height="100%",this._loadingTextContainer=document.createElement("div"),this._loadingTextContainer.style.display="flex",this._loadingTextContainer.style.justifyContent="center",this._loadingTextContainer.style.marginTop=".9em",this._loadingElement.appendChild(this._loadingTextContainer);let o=document.createElement("div");return this._messageContainer=o,o.style.display="flex",o.style.fontSize=".8em",o.style.paddingTop=".5em",o.style.color="rgba(255,255,255,.5)",this._loadingElement.appendChild(o),this._loadingElement}};var Cr=N("debugwebcomponent"),Xd=class{id;context;previouslyAdded;previousSource;networkEvent;constructor(e,t){this.id=e,this.context=t,this.networkEvent="needle-engine-source-changed",this.id&&(this.networkEvent+="-"+this.id),this.context.connection.beginListen(this.networkEvent,i=>{this.onSourceChanged(i,!0)})}async onSourceChanged(e,t=!1,i=!1){this.previouslyAdded&&(t&&e===this.previousSource||O.destroySynced(this.previouslyAdded)),this.previouslyAdded=null,t||this.context.connection.send(this.networkEvent,e),this.previousSource=e,Z.Current=this.context;let n=await dr(this.context,e,this.getHashFromString(e));i||ki(this.context);let r=n?.scene;r&&(this.previouslyAdded=r,this.context.scene.add(r))}getHashFromString(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}},ME="needle-engine",LE="vr",DE="desktop",HE=[Rr,LE,DE],Qd=class extends HTMLElement{get loadingProgress01(){return this._loadingProgress01}get loadingFinished(){return this.loadingProgress01>.999}getContext(){return new Promise((e,t)=>{if(this._context&&this.loadingFinished)e(this._context);else{let i=()=>{this.removeEventListener("loadfinished",i),this._context&&this.loadingFinished&&e(this._context)};this.addEventListener("loadfinished",i)}})}get Context(){return this._context}gameObject=O;GameObject=O;_context=null;_overlay_ar;_loadingProgress01=0;_watcher;_loadingView;constructor(){super(),this._overlay_ar=new pl}async connectedCallback(){this.onSetupDesktop();var e=new MutationObserver(this.onElementsChanged.bind(this));e.observe(this,{childList:!0});let t=()=>{let o=this.getAttribute("src");return o?.endsWith(".glb")||o?.endsWith(".gltf")?o:null},i="loadScene",n=t();n&&(i=n);let r=this.getAttribute("alias");if(this._context=new Z({name:i,domElement:this,alias:r}),this._watcher=new Xd(this.getAttribute("id")??r??"",this._context),i&&i.length>0){if(!n)for(;Object.keys(ul).length<=0;){if(!this.isConnected)return;await uh(10)}let o=ul[i]??window[i],s=null;if((!o||n)&&(n&&(i=n),o=async c=>{let d=t();d&&this._watcher&&(s=d,await this._watcher.onSourceChanged(d,!0,!0))}),o){this.classList.add("loading"),console.log("Needle Engine: Begin loading",r??"");let c=this.dispatchEvent(new CustomEvent("loadstart",{detail:{context:this._context,alias:r},cancelable:!0}));!this._loadingView&&c&&(this._loadingView=new fl(this)),c&&this._loadingView?.onLoadingBegin("begin load");let d=(h,u)=>{this._loadingProgress01=qd(h),c&&this._loadingView?.onLoadingUpdate(h,u),this.dispatchEvent(new CustomEvent("progress",{detail:{context:this._context,name:h.name,progress:h.progress,index:h.index,count:h.count,totalProgress01:this._loadingProgress01}}))};this.onBeforeBeginLoading(),await this._context.onCreate(o,{progress:d});let a=t();a&&a!==s&&await this._watcher.onSourceChanged(a,!0,!0),this._loadingProgress01=1,c&&this._loadingView?.onLoadingFinished("create scene"),this.classList.remove("loading"),this.classList.add("loading-finished"),console.log("Needle Engine: finished loading",r??""),this.dispatchEvent(new CustomEvent("loadfinished",{detail:{context:this._context,src:r??i}})),this.onSetupDesktop()}else console.error('Could not find scene function named "'+i+'", it must be either in global scope or added to build_scene_functions',ul)}else console.error("Missing src attribute - please provide a function name",this)}disconnectedCallback(){this._context&&this._context.onDestroy()}static get observedAttributes(){return["src","loadstart","progress","loadfinished","dracoDecoderPath","dracoDecoderType","ktx2DecoderPath"]}attributeChangedCallback(e,t,i){switch(e){case"src":this._watcher?.onSourceChanged(i);break;case"loadstart":case"progress":case"loadfinished":typeof i=="string"&&i.length>0&&(Cr&&console.log(e+" attribute changed",i),this.registerEventFromAttribute(e,i));break;case"dracoDecoderPath":Cr&&console.log("dracoDecoderPath",i),ac(i);break;case"dracoDecoderType":i==="wasm"||i==="js"?(Cr&&console.log("dracoDecoderType",i),lc(i)):console.error("Invalid dracoDecoderType",i,"expected js or wasm");break;case"ktx2DecoderPath":Cr&&console.log("ktx2DecoderPath",i),cc(i);break}}registerEventFromAttribute(e,t){if(typeof t=="string"&&t.length>0){let i=(0,eval)(t);typeof i=="function"&&this.addEventListener(e,n=>i?.call(globalThis,this._context,n))}}getAROverlayContainer(){return this._overlay_ar.findOrCreateARContainer(this)}getVROverlayContainer(){for(let e=0;e<this.children.length;e++){let t=this.children[e];if(t.classList.contains("vr"))return t}return null}onEnterAR(e,t){this.onSetupAR(),this._overlay_ar.onBegin(this._context,t,e),this.dispatchEvent(new CustomEvent("enter-ar",{detail:{session:e,context:this._context,htmlContainer:this._overlay_ar?.ARContainer}}))}onExitAR(e){this._overlay_ar.onEnd(this._context),this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-ar",{detail:{session:e,context:this._context,htmlContainer:this._overlay_ar?.ARContainer}}))}onEnterVR(e){this.onSetupVR(),this.dispatchEvent(new CustomEvent("enter-vr",{detail:{session:e,context:this._context}}))}onExitVR(e){this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-vr",{detail:{session:e,context:this._context}}))}onElementsChanged(){}onSetupAR(){this.classList.add("ar-session-active"),this.classList.remove("desktop-session-active"),this.foreachHtmlElement(e=>this.setupElementsForMode(e,Rr))}onSetupVR(){this.classList.remove("ar-session-active"),this.classList.remove("desktop-session-active"),this.foreachHtmlElement(e=>this.setupElementsForMode(e,"vr"))}onSetupDesktop(){this.classList.remove("ar-session-active"),this.classList.add("desktop-session-active"),this.foreachHtmlElement(e=>this.setupElementsForMode(e,"desktop"))}setupElementsForMode(e,t,i=null){if(e===this._context?.renderer.domElement||e.id==="VRButton"||e.id==="ARButton")return;if(e.style.position="absolute",e.classList.contains(t))e.style.visibility="visible",e.style.display==="none"&&(e.style.display="block");else for(let r of HE)e.classList.contains(r)&&(e.style.visibility="hidden",e.style.display="none")}foreachHtmlElement(e){for(let t=0;t<this.children.length;t++){let i=this.children[t];i.style&&e(i)}}onBeforeBeginLoading(){let e=this.getAttribute("dracoDecoderPath");e&&(Cr&&console.log("using custom draco decoder path",e),ac(e));let t=this.getAttribute("dracoDecoderType");t&&(Cr&&console.log("using custom draco decoder type",t),lc(t));let i=this.getAttribute("ktx2DecoderPath");i&&(Cr&&console.log("using custom ktx2 decoder path",i),cc(i))}};window.customElements.define(ME,Qd);var Yd={};oh(Yd,{AlignmentConstraint:()=>Ur,Animation:()=>Jt,AnimationCurve:()=>rr,AnimationTrackHandler:()=>Bn,Animator:()=>bt,AnimatorController:()=>Zt,AttachedObject:()=>dt,AudioListener:()=>$t,AudioSource:()=>ue,AudioTrackHandler:()=>Fn,AvatarBlink_Simple:()=>xi,AvatarEyeLook_Rotation:()=>Ti,AvatarLoader:()=>Ni,AvatarMarker:()=>fe,AvatarModel:()=>or,Avatar_Brain_LookAt:()=>Ui,Avatar_MouthShapes:()=>jn,Avatar_MustacheShake:()=>Ao,Avatar_POI:()=>_e,AxesHelper:()=>zi,BaseUIComponent:()=>Ue,BasicIKConstraint:()=>Qr,BoxCollider:()=>xn,BoxGizmo:()=>Xi,BoxHelperComponent:()=>lt,Button:()=>Ft,CallInfo:()=>yi,Camera:()=>ne,Canvas:()=>Je,CanvasGroup:()=>sn,Collider:()=>fi,ColorAdjustments:()=>Hn,ControlTrackHandler:()=>Ki,Deletable:()=>Kr,DeleteBox:()=>sr,DeviceFlag:()=>ar,DragControls:()=>Et,DropListener:()=>Pn,Duplicatable:()=>vi,EmissionModule:()=>yo,EventList:()=>Oe,EventListEvent:()=>hr,EventSystem:()=>Ze,EventTrigger:()=>ao,FieldWithDefault:()=>Hr,FlyControls:()=>lo,GltfExport:()=>jt,GltfExportBox:()=>ho,Graphic:()=>Rt,GraphicRaycaster:()=>zo,GridHelper:()=>Qi,GridLayoutGroup:()=>No,GroundProjectedEnv:()=>Yi,HorizontalLayoutGroup:()=>Fo,Image:()=>on,InputField:()=>Ct,InstancingUtil:()=>he,InstantiateOptions:()=>ye,Interactable:()=>kt,Keyboard:()=>jo,LODGroup:()=>An,LODModel:()=>Ei,LayoutGroup:()=>an,Light:()=>Ye,LogStats:()=>ko,LookAtConstraint:()=>Bi,MainModule:()=>vo,MaskableGraphic:()=>rn,MeshCollider:()=>po,MeshRenderer:()=>ir,NavMesh:()=>fo,NavMeshAgent:()=>mo,NestedGltf:()=>ur,Networking:()=>pt,ObjectRaycaster:()=>Ci,OffsetConstraint:()=>go,OrbitControls:()=>gt,ParticleSystem:()=>wo,ParticleSystemRenderer:()=>pr,PlayableDirector:()=>tn,PlayerColor:()=>ht,PointerEventData:()=>ii,RGBAColor:()=>we,RawImage:()=>wr,Raycaster:()=>xr,Rect:()=>Er,RectTransform:()=>ut,RemoteSkybox:()=>In,Renderer:()=>Te,RendererLightmap:()=>Hi,Rigidbody:()=>ce,ScreenCapture:()=>_o,ShadowCatcher:()=>kn,ShapeModule:()=>Eo,SignalAsset:()=>vr,SignalReceiver:()=>$i,SignalReceiverEvent:()=>yr,SignalTrackHandler:()=>en,Size:()=>Do,SkinnedMeshRenderer:()=>jr,SmoothFollow:()=>wi,SpatialHtml:()=>Go,SpatialTrigger:()=>Zi,SpatialTriggerReceiver:()=>wt,SpectatorCamera:()=>To,SphereCollider:()=>_n,SpringJoint:()=>Ro,Sprite:()=>fr,SpriteRenderer:()=>Ji,SyncedCamera:()=>Mn,SyncedRoom:()=>ti,SyncedTransform:()=>Qe,TeleportTarget:()=>lr,TestRunner:()=>Co,TestSimulateUserData:()=>So,Text:()=>Le,ToneMapping:()=>Dn,TransformGizmo:()=>mr,UIRootComponent:()=>nn,UnityObject:()=>$r,UsageMarker:()=>It,VRUserState:()=>Ht,VerticalLayoutGroup:()=>Bo,VideoPlayer:()=>nt,Voip:()=>Ke,Volume:()=>gr,VolumeComponent:()=>_i,VolumeParameter:()=>Po,VolumeProfile:()=>Ln,WebAR:()=>Sn,WebARSessionRoot:()=>Dt,WebXR:()=>$,WebXRAvatar:()=>Lt,WebXRController:()=>se,WebXRSync:()=>qi,XRFlag:()=>Se,XRGrabModel:()=>br,XRGrabRendering:()=>Oo,XRRig:()=>Cn,XRState:()=>vt});import*as jE from"three";var Zd={Context:Z};globalThis.Needle=Zd;function Sf(l){for(let e in l)Zd[e]=l[e]}Sf(jl);Sf(Yd);for(let l of Object.getOwnPropertyNames(O))switch(l){case"prototype":case"constructor":case"length":case"name":continue;default:Zd[l]=O[l];break}globalThis.THREE?console.warn("Threejs is already imported"):globalThis.THREE=jE;export{Ur as AlignmentConstraint,Jt as Animation,rr as AnimationCurve,Bn as AnimationTrackHandler,bt as Animator,Zt as AnimatorController,dt as AttachedObject,$t as AudioListener,ue as AudioSource,Fn as AudioTrackHandler,xi as AvatarBlink_Simple,Ti as AvatarEyeLook_Rotation,Ni as AvatarLoader,fe as AvatarMarker,or as AvatarModel,Ui as Avatar_Brain_LookAt,jn as Avatar_MouthShapes,Ao as Avatar_MustacheShake,_e as Avatar_POI,zi as AxesHelper,Ue as BaseUIComponent,Qr as BasicIKConstraint,M as Behaviour,xn as BoxCollider,Xi as BoxGizmo,lt as BoxHelperComponent,Ft as Button,yi as CallInfo,ne as Camera,Je as Canvas,sn as CanvasGroup,fi as Collider,Hn as ColorAdjustments,Ki as ControlTrackHandler,Kr as Deletable,sr as DeleteBox,ar as DeviceFlag,Et as DragControls,Pn as DropListener,vi as Duplicatable,yo as EmissionModule,Oe as EventList,hr as EventListEvent,Ze as EventSystem,ao as EventTrigger,Hr as FieldWithDefault,lo as FlyControls,O as GameObject,jt as GltfExport,ho as GltfExportBox,Rt as Graphic,zo as GraphicRaycaster,Qi as GridHelper,No as GridLayoutGroup,Yi as GroundProjectedEnv,Fo as HorizontalLayoutGroup,on as Image,Ct as InputField,he as InstancingUtil,ye as InstantiateOptions,kt as Interactable,jo as Keyboard,An as LODGroup,Ei as LODModel,an as LayoutGroup,Ye as Light,ko as LogStats,Bi as LookAtConstraint,vo as MainModule,rn as MaskableGraphic,po as MeshCollider,ir as MeshRenderer,fo as NavMesh,mo as NavMeshAgent,ur as NestedGltf,pt as Networking,Ci as ObjectRaycaster,go as OffsetConstraint,gt as OrbitControls,wo as ParticleSystem,pr as ParticleSystemRenderer,tn as PlayableDirector,ht as PlayerColor,ii as PointerEventData,we as RGBAColor,wr as RawImage,xr as Raycaster,Er as Rect,ut as RectTransform,In as RemoteSkybox,Te as Renderer,Hi as RendererLightmap,ce as Rigidbody,_o as ScreenCapture,kn as ShadowCatcher,Eo as ShapeModule,vr as SignalAsset,$i as SignalReceiver,yr as SignalReceiverEvent,en as SignalTrackHandler,Do as Size,jr as SkinnedMeshRenderer,wi as SmoothFollow,Go as SpatialHtml,Zi as SpatialTrigger,wt as SpatialTriggerReceiver,To as SpectatorCamera,_n as SphereCollider,Ro as SpringJoint,fr as Sprite,Ji as SpriteRenderer,Mn as SyncedCamera,ti as SyncedRoom,Qe as SyncedTransform,lr as TeleportTarget,Co as TestRunner,So as TestSimulateUserData,Le as Text,Dn as ToneMapping,mr as TransformGizmo,nn as UIRootComponent,$r as UnityObject,It as UsageMarker,Ht as VRUserState,Bo as VerticalLayoutGroup,nt as VideoPlayer,Ke as Voip,gr as Volume,_i as VolumeComponent,Po as VolumeParameter,Ln as VolumeProfile,Sn as WebAR,Dt as WebARSessionRoot,$ as WebXR,Lt as WebXRAvatar,se as WebXRController,qi as WebXRSync,Se as XRFlag,br as XRGrabModel,Oo as XRGrabRendering,Cn as XRRig,vt as XRState,A as serializeable};
161
161
  /*!
162
162
  * Determine if an object is a Buffer
163
163
  *