@needle-tools/engine 2.35.0-pre → 2.35.2-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.
Files changed (68) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/needle-engine.d.ts +202 -181
  3. package/dist/needle-engine.js +234 -3338
  4. package/dist/needle-engine.js.map +4 -4
  5. package/dist/needle-engine.min.js +41 -36
  6. package/dist/needle-engine.min.js.map +4 -4
  7. package/lib/engine/engine_components.d.ts +12 -11
  8. package/lib/engine/engine_components.js +48 -24
  9. package/lib/engine/engine_components.js.map +1 -1
  10. package/lib/engine/engine_element.js +2 -1
  11. package/lib/engine/engine_element.js.map +1 -1
  12. package/lib/engine/engine_element_loading.js +4 -1
  13. package/lib/engine/engine_element_loading.js.map +1 -1
  14. package/lib/engine/engine_gltf_builtin_components.d.ts +1 -0
  15. package/lib/engine/engine_gltf_builtin_components.js +5 -0
  16. package/lib/engine/engine_gltf_builtin_components.js.map +1 -1
  17. package/lib/engine/engine_networking.d.ts +5 -0
  18. package/lib/engine/engine_networking.js +6 -4
  19. package/lib/engine/engine_networking.js.map +1 -1
  20. package/lib/engine/engine_physics.d.ts +6 -1
  21. package/lib/engine/engine_physics.js +12 -2
  22. package/lib/engine/engine_physics.js.map +1 -1
  23. package/lib/engine/engine_types.d.ts +7 -2
  24. package/lib/engine/engine_types.js +6 -5
  25. package/lib/engine/engine_types.js.map +1 -1
  26. package/lib/engine-components/Collider.d.ts +3 -1
  27. package/lib/engine-components/Collider.js +11 -0
  28. package/lib/engine-components/Collider.js.map +1 -1
  29. package/lib/engine-components/Component.d.ts +7 -7
  30. package/lib/engine-components/Component.js +8 -8
  31. package/lib/engine-components/Component.js.map +1 -1
  32. package/lib/engine-components/Networking.d.ts +3 -1
  33. package/lib/engine-components/Networking.js +3 -0
  34. package/lib/engine-components/Networking.js.map +1 -1
  35. package/lib/engine-components/OrbitControls.js +16 -4
  36. package/lib/engine-components/OrbitControls.js.map +1 -1
  37. package/lib/engine-components/Renderer.d.ts +2 -1
  38. package/lib/engine-components/Renderer.js +11 -2
  39. package/lib/engine-components/Renderer.js.map +1 -1
  40. package/lib/engine-components/WebXR.js +5 -1
  41. package/lib/engine-components/WebXR.js.map +1 -1
  42. package/lib/engine-components/js-extensions/Object3D.js +13 -11
  43. package/lib/engine-components/js-extensions/Object3D.js.map +1 -1
  44. package/lib/engine-components/ui/EventSystem.js +2 -2
  45. package/lib/engine-components/ui/EventSystem.js.map +1 -1
  46. package/lib/engine-components/ui/RaycastUtils.js +0 -1
  47. package/lib/engine-components/ui/RaycastUtils.js.map +1 -1
  48. package/lib/needle-engine.d.ts +0 -1
  49. package/lib/needle-engine.js +0 -1
  50. package/lib/needle-engine.js.map +1 -1
  51. package/package.json +1 -1
  52. package/src/engine/engine_components.ts +50 -27
  53. package/src/engine/engine_element.ts +2 -1
  54. package/src/engine/engine_element_loading.ts +5 -1
  55. package/src/engine/engine_gltf_builtin_components.ts +4 -0
  56. package/src/engine/engine_networking.ts +12 -4
  57. package/src/engine/engine_physics.ts +34 -4
  58. package/src/engine/engine_types.ts +14 -6
  59. package/src/engine-components/Collider.ts +17 -2
  60. package/src/engine-components/Component.ts +21 -22
  61. package/src/engine-components/Networking.ts +6 -1
  62. package/src/engine-components/OrbitControls.ts +20 -7
  63. package/src/engine-components/Renderer.ts +13 -3
  64. package/src/engine-components/WebXR.ts +4 -1
  65. package/src/engine-components/js-extensions/Object3D.ts +17 -15
  66. package/src/engine-components/ui/EventSystem.ts +2 -2
  67. package/src/engine-components/ui/RaycastUtils.ts +0 -1
  68. package/src/needle-engine.ts +0 -1
@@ -1,21 +1,21 @@
1
- var Cf=Object.create;var Ko=Object.defineProperty;var ch=Object.getOwnPropertyDescriptor;var Rf=Object.getOwnPropertyNames;var Sf=Object.getPrototypeOf,Pf=Object.prototype.hasOwnProperty;var Of=(c,e,t)=>e in c?Ko(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t;var Cl=(c=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(c,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):c)(function(c){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+c+'" is not supported')});var Jo=(c,e)=>()=>(e||c((e={exports:{}}).exports,e),e.exports),dh=(c,e)=>{for(var t in e)Ko(c,t,{get:e[t],enumerable:!0})},kf=(c,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Rf(e))!Pf.call(c,n)&&n!==t&&Ko(c,n,{get:()=>e[n],enumerable:!(i=ch(e,n))||i.enumerable});return c};var Ls=(c,e,t)=>(t=c!=null?Cf(Sf(c)):{},kf(e||!c||!c.__esModule?Ko(t,"default",{value:c,enumerable:!0}):t,c));var k=(c,e,t,i)=>{for(var n=i>1?void 0:i?ch(e,t):e,r=c.length-1,o;r>=0;r--)(o=c[r])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&Ko(e,t,n),n};var z=(c,e,t)=>(Of(c,typeof e!="symbol"?e+"":e,t),t);var xa=Jo((Zu,gc)=>{parcelRequire=function(c,e,t,i){var n,r=typeof parcelRequire=="function"&&parcelRequire,o=typeof Cl=="function"&&Cl;function s(a,u){if(!e[a]){if(!c[a]){var h=typeof parcelRequire=="function"&&parcelRequire;if(!u&&h)return h(a,!0);if(r)return r(a,!0);if(o&&typeof a=="string")return o(a);var m=new Error("Cannot find module '"+a+"'");throw m.code="MODULE_NOT_FOUND",m}b.resolve=function(y){return c[a][1][y]||y},b.cache={};var E=e[a]=new s.Module(a);c[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=c,s.cache=e,s.parent=r,s.register=function(a,u){c[a]=[function(h,m){m.exports=u},{}]};for(var l=0;l<t.length;l++)try{s(t[l])}catch(a){n||(n=a)}if(t.length){var d=s(t[t.length-1]);typeof Zu=="object"&&typeof gc<"u"?gc.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(c,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,l=this._parts.length;s<l;s++)o.append(this._parts[s]);return o.getBlob()}return new Blob(this._parts)},e.exports.BufferBuilder=r},{}],kdPp:[function(c,e,t){var i=c("./bufferbuilder").BufferBuilder,n=c("./bufferbuilder").binaryFeatures,r={unpack:function(a){return new o(a).unpack()},pack:function(a){var u=new s;return u.pack(a),u.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 l(a){var u=a.charCodeAt(0);return u<=2047?"00":u<=65535?"000":u<=2097151?"0000":u<=67108863?"00000":"000000"}function d(a){return a.length>600?new Blob([a]).size:a.replace(/[^\u0000-\u007F]/g,l).length}e.exports=r,o.prototype.unpack=function(){var a,u=this.unpack_uint8();if(u<128)return u;if((224^u)<32)return(224^u)-32;if((a=160^u)<=15)return this.unpack_raw(a);if((a=176^u)<=15)return this.unpack_string(a);if((a=144^u)<=15)return this.unpack_array(a);if((a=128^u)<=15)return this.unpack_map(a);switch(u){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),u=256*(255&a[0])+(255&a[1]);return this.index+=2,u},o.prototype.unpack_uint32=function(){var a=this.read(4),u=256*(256*(256*a[0]+a[1])+a[2])+a[3];return this.index+=4,u},o.prototype.unpack_uint64=function(){var a=this.read(8),u=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,u},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 u=this.dataBuffer.slice(this.index,this.index+a);return this.index+=a,u},o.prototype.unpack_string=function(a){for(var u,h,m=this.read(a),E=0,b="";E<a;)(u=m[E])<128?(b+=String.fromCharCode(u),E++):(192^u)<32?(h=(192^u)<<6|63&m[E+1],b+=String.fromCharCode(h),E+=2):(h=(15&u)<<12|(63&m[E+1])<<6|63&m[E+2],b+=String.fromCharCode(h),E+=3);return this.index+=a,b},o.prototype.unpack_array=function(a){for(var u=new Array(a),h=0;h<a;h++)u[h]=this.unpack();return u},o.prototype.unpack_map=function(a){for(var u={},h=0;h<a;h++){var m=this.unpack(),E=this.unpack();u[m]=E}return u},o.prototype.unpack_float=function(){var a=this.unpack_uint32(),u=(a>>23&255)-127;return(a>>31===0?1:-1)*(8388607&a|8388608)*Math.pow(2,u-23)},o.prototype.unpack_double=function(){var a=this.unpack_uint32(),u=this.unpack_uint32(),h=(a>>20&2047)-1023;return(a>>31===0?1:-1)*((1048575&a|1048576)*Math.pow(2,h-20)+u*Math.pow(2,h-52))},o.prototype.read=function(a){var u=this.index;if(u+a<=this.length)return this.dataView.subarray(u,u+a);throw new Error("BinaryPackFailure: read index out of range")},s.prototype.getBuffer=function(){return this.bufferBuilder.getBuffer()},s.prototype.pack=function(a){var u=typeof a;if(u==="string")this.pack_string(a);else if(u==="number")Math.floor(a)===a?this.pack_integer(a):this.pack_double(a);else if(u==="boolean")a===!0?this.bufferBuilder.append(195):a===!1&&this.bufferBuilder.append(194);else if(u==="undefined")this.bufferBuilder.append(192);else{if(u!=="object")throw new Error('Type "'+u+'" not yet supported');if(a===null)this.bufferBuilder.append(192);else{var h=a.constructor;if(h==Array)this.pack_array(a);else if(h==Blob||h==File||a instanceof Blob||a instanceof File)this.pack_bin(a);else if(h==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(h==Object||h.toString().startsWith("class"))this.pack_object(a);else if(h==Date)this.pack_string(a.toString());else{if(typeof a.toBinaryPack!="function")throw new Error('Type "'+h.toString()+'" not yet supported');this.bufferBuilder.append(a.toBinaryPack())}}}this.bufferBuilder.flush()},s.prototype.pack_bin=function(a){var u=a.length||a.byteLength||a.size;if(u<=15)this.pack_uint8(160+u);else if(u<=65535)this.bufferBuilder.append(218),this.pack_uint16(u);else{if(!(u<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(219),this.pack_uint32(u)}this.bufferBuilder.append(a)},s.prototype.pack_string=function(a){var u=d(a);if(u<=15)this.pack_uint8(176+u);else if(u<=65535)this.bufferBuilder.append(216),this.pack_uint16(u);else{if(!(u<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(217),this.pack_uint32(u)}this.bufferBuilder.append(a)},s.prototype.pack_array=function(a){var u=a.length;if(u<=15)this.pack_uint8(144+u);else if(u<=65535)this.bufferBuilder.append(220),this.pack_uint16(u);else{if(!(u<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(221),this.pack_uint32(u)}for(var h=0;h<u;h++)this.pack(a[h])},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 u=0;a<0&&(u=1,a=-a);var h=Math.floor(Math.log(a)/Math.LN2),m=a/Math.pow(2,h)-1,E=Math.floor(m*Math.pow(2,52)),b=Math.pow(2,32),y=u<<31|h+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 u=Object.keys(a).length;if(u<=15)this.pack_uint8(128+u);else if(u<=65535)this.bufferBuilder.append(222),this.pack_uint16(u);else{if(!(u<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(223),this.pack_uint32(u)}for(var h in a)a.hasOwnProperty(h)&&(this.pack(h),this.pack(a[h]))},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 u=4294967295&a;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_uint64=function(a){var u=a/Math.pow(2,32),h=a%Math.pow(2,32);this.bufferBuilder.append((4278190080&u)>>>24),this.bufferBuilder.append((16711680&u)>>>16),this.bufferBuilder.append((65280&u)>>>8),this.bufferBuilder.append(255&u),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_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 u=Math.floor(a/Math.pow(2,32)),h=a%Math.pow(2,32);this.bufferBuilder.append((4278190080&u)>>>24),this.bufferBuilder.append((16711680&u)>>>16),this.bufferBuilder.append((65280&u)>>>8),this.bufferBuilder.append(255&u),this.bufferBuilder.append((4278190080&h)>>>24),this.bufferBuilder.append((16711680&h)>>>16),this.bufferBuilder.append((65280&h)>>>8),this.bufferBuilder.append(255&h)}},{"./bufferbuilder":"EgBh"}],iSxC:[function(c,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=s,t.wrapPeerConnectionEvent=l,t.disableLog=d,t.disableWarnings=a,t.log=u,t.deprecated=h,t.detectBrowser=m,t.compactObject=b,t.walkStats=y,t.filterStats=g;var r=!0,o=!0;function s(p,f,v){var w=p.match(f);return w&&w.length>=v&&parseInt(w[v],10)}function l(p,f,v){if(p.RTCPeerConnection){var w=p.RTCPeerConnection.prototype,x=w.addEventListener;w.addEventListener=function(C,R){if(C!==f)return x.apply(this,arguments);var P=function(S){var M=v(S);M&&(R.handleEvent?R.handleEvent(M):R(M))};return this._eventMap=this._eventMap||{},this._eventMap[f]||(this._eventMap[f]=new Map),this._eventMap[f].set(R,P),x.apply(this,[C,P])};var T=w.removeEventListener;w.removeEventListener=function(C,R){if(C!==f||!this._eventMap||!this._eventMap[f])return T.apply(this,arguments);if(!this._eventMap[f].has(R))return T.apply(this,arguments);var P=this._eventMap[f].get(R);return this._eventMap[f].delete(R),this._eventMap[f].size===0&&delete this._eventMap[f],Object.keys(this._eventMap).length===0&&delete this._eventMap,T.apply(this,[C,P])},Object.defineProperty(w,"on"+f,{get:function(){return this["_on"+f]},set:function(C){this["_on"+f]&&(this.removeEventListener(f,this["_on"+f]),delete this["_on"+f]),C&&this.addEventListener(f,this["_on"+f]=C)},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 u(){if((typeof window>"u"?"undefined":n(window))==="object"){if(r)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function h(p,f){o&&console.warn(p+" is deprecated, please use "+f+" instead.")}function m(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=s(v.userAgent,/Firefox\/(\d+)\./,1);else if(v.webkitGetUserMedia||p.isSecureContext===!1&&p.webkitRTCPeerConnection&&!p.RTCIceGatherer)f.browser="chrome",f.version=s(v.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(v.mediaDevices&&v.userAgent.match(/Edge\/(\d+).(\d+)$/))f.browser="edge",f.version=s(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=s(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 g(p,f,v){var w=v?"outbound-rtp":"inbound-rtp",x=new Map;if(f===null)return x;var T=[];return p.forEach(function(C){C.type==="track"&&C.trackIdentifier===f.id&&T.push(C)}),T.forEach(function(C){p.forEach(function(R){R.type===w&&R.trackId===C.id&&y(p,R,x)})}),x}},{}],s6SN:[function(c,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetUserMedia=l;var i=r(c("../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 u={},h=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var m in d)if(Object.prototype.hasOwnProperty.call(d,m)){var E=h?Object.getOwnPropertyDescriptor(d,m):null;E&&(E.get||E.set)?Object.defineProperty(u,m,E):u[m]=d[m]}return u.default=d,a&&a.set(d,u),u}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 l(d,a){var u=d&&d.navigator;if(u.mediaDevices){var h=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 f=o(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){g.optional=g.optional||[];var w={};typeof f.ideal=="number"?(w[v("min",p)]=f.ideal,g.optional.push(w),(w={})[v("max",p)]=f.ideal,g.optional.push(w)):(w[v("",p)]=f.ideal,g.optional.push(w))}f.exact!==void 0&&typeof f.exact!="number"?(g.mandatory=g.mandatory||{},g.mandatory[v("",p)]=f.exact):["min","max"].forEach(function(x){f[x]!==void 0&&(g.mandatory=g.mandatory||{},g.mandatory[v(x,p)]=f[x])})}}),y.advanced&&(g.optional=(g.optional||[]).concat(y.advanced)),g},m=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,C){T in x&&!(C in x)&&(x[C]=x[T],delete x[T])};p((y=JSON.parse(JSON.stringify(y))).audio,"autoGainControl","googAutoGainControl"),p(y.audio,"noiseSuppression","googNoiseSuppression"),y.audio=h(y.audio)}if(y&&o(y.video)==="object"){var f=y.video.facingMode;f=f&&(o(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")&&(!u.mediaDevices.getSupportedConstraints||!u.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 u.mediaDevices.enumerateDevices().then(function(x){var T=(x=x.filter(function(C){return C.kind==="videoinput"})).find(function(C){return v.some(function(R){return C.label.toLowerCase().includes(R)})});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=h(y.video),s("chrome: "+JSON.stringify(y)),g(y)});y.video=h(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(u.getUserMedia=function(y,g,p){m(y,function(f){u.webkitGetUserMedia(f,g,function(v){p&&p(E(v))})})}.bind(u),u.mediaDevices.getUserMedia){var b=u.mediaDevices.getUserMedia.bind(u.mediaDevices);u.mediaDevices.getUserMedia=function(y){return m(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(f){f.stop()}),new DOMException("","NotFoundError");return p},function(p){return Promise.reject(E(p))})})}}}}},{"../utils.js":"iSxC"}],VHa8:[function(c,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 l=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}},l&&(o.video.mandatory.maxWidth=l),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(c,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimMediaStream=a,t.shimOnTrack=u,t.shimGetSendersWithDtmf=h,t.shimGetStats=m,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(c("../utils.js")),n=c("./getusermedia"),r=c("./getdisplaymedia");function o(){if(typeof WeakMap!="function")return null;var f=new WeakMap;return o=function(){return f},f}function s(f){if(f&&f.__esModule)return f;if(f===null||typeof f!="object"&&typeof f!="function")return{default:f};var v=o();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 C=x?Object.getOwnPropertyDescriptor(f,T):null;C&&(C.get||C.set)?Object.defineProperty(w,T,C):w[T]=f[T]}return w.default=f,v&&v.set(f,w),w}function l(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 u(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 C;C=f.RTCPeerConnection.prototype.getReceivers?w.getReceivers().find(function(P){return P.track&&P.track.id===T.track.id}):{track:T.track};var R=new Event("track");R.track=T.track,R.receiver=C,R.transceiver={receiver:C},R.streams=[x.stream],w.dispatchEvent(R)}),x.stream.getTracks().forEach(function(T){var C;C=f.RTCPeerConnection.prototype.getReceivers?w.getReceivers().find(function(P){return P.track&&P.track.id===T.id}):{track:T};var R=new Event("track");R.track=T,R.receiver=C,R.transceiver={receiver:C},R.streams=[x.stream],w.dispatchEvent(R)})},this.addEventListener("addstream",this._ontrackpoly)),v.apply(this,arguments)}}}function h(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 M=w.apply(this,arguments);return M||(M=v(this,P),this._senders.push(M)),M};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(M){S._senders.push(v(S,M))})};var C=f.RTCPeerConnection.prototype.removeStream;f.RTCPeerConnection.prototype.removeStream=function(P){var S=this;this._senders=this._senders||[],C.apply(this,[P]),P.getTracks().forEach(function(M){var I=S._senders.find(function(j){return j.track===M});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 R=f.RTCPeerConnection.prototype.getSenders;f.RTCPeerConnection.prototype.getSenders=function(){var P=this,S=R.apply(this,[]);return S.forEach(function(M){return M._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 m(f){if(f.RTCPeerConnection){var v=f.RTCPeerConnection.prototype.getStats;f.RTCPeerConnection.prototype.getStats=function(){var w=this,[x,T,C]=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 R=function(S){var M={};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)}),M[j.id]=j}),M},P=function(S){return new Map(Object.keys(S).map(function(M){return[M,S[M]]}))};return arguments.length>=2?v.apply(this,[function(S){T(P(R(S)))},x]):new Promise(function(S,M){v.apply(w,[function(I){S(P(R(I)))},M])}).then(T,C)}}}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 C=this,R=v.apply(this,[]);return R.forEach(function(P){return P._pc=C}),R});var w=f.RTCPeerConnection.prototype.addTrack;w&&(f.RTCPeerConnection.prototype.addTrack=function(){var C=w.apply(this,arguments);return C._pc=this,C}),f.RTCRtpSender.prototype.getStats=function(){var C=this;return this._pc.getStats().then(function(R){return i.filterStats(R,C.track,!0)})}}if(!("getStats"in f.RTCRtpReceiver.prototype)){var x=f.RTCPeerConnection.prototype.getReceivers;x&&(f.RTCPeerConnection.prototype.getReceivers=function(){var C=this,R=x.apply(this,[]);return R.forEach(function(P){return P._pc=C}),R}),i.wrapPeerConnectionEvent(f,"track",function(C){return C.receiver._pc=C.srcElement,C}),f.RTCRtpReceiver.prototype.getStats=function(){var C=this;return this._pc.getStats().then(function(R){return i.filterStats(R,C.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 C,R,P,S=arguments[0];return this.getSenders().forEach(function(M){M.track===S&&(C?P=!0:C=M)}),this.getReceivers().forEach(function(M){return M.track===S&&(R?P=!0:R=M),M.track===S}),P||C&&R?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):C?C.getStats():R?R.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 C=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(function(R){return C._shimmedLocalStreams[R][0]})};var v=f.RTCPeerConnection.prototype.addTrack;f.RTCPeerConnection.prototype.addTrack=function(C,R){if(!R)return v.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var P=v.apply(this,arguments);return this._shimmedLocalStreams[R.id]?this._shimmedLocalStreams[R.id].indexOf(P)===-1&&this._shimmedLocalStreams[R.id].push(P):this._shimmedLocalStreams[R.id]=[R,P],P};var w=f.RTCPeerConnection.prototype.addStream;f.RTCPeerConnection.prototype.addStream=function(C){var R=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},C.getTracks().forEach(function(M){if(R.getSenders().find(function(I){return I.track===M}))throw new DOMException("Track already exists.","InvalidAccessError")});var P=this.getSenders();w.apply(this,arguments);var S=this.getSenders().filter(function(M){return P.indexOf(M)===-1});this._shimmedLocalStreams[C.id]=[C].concat(S)};var x=f.RTCPeerConnection.prototype.removeStream;f.RTCPeerConnection.prototype.removeStream=function(C){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[C.id],x.apply(this,arguments)};var T=f.RTCPeerConnection.prototype.removeTrack;f.RTCPeerConnection.prototype.removeTrack=function(C){var R=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},C&&Object.keys(this._shimmedLocalStreams).forEach(function(P){var S=R._shimmedLocalStreams[P].indexOf(C);S!==-1&&R._shimmedLocalStreams[P].splice(S,1),R._shimmedLocalStreams[P].length===1&&delete R._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,M=w.apply(this);return this._reverseStreams=this._reverseStreams||{},M.map(function(I){return S._reverseStreams[I.id]})};var x=f.RTCPeerConnection.prototype.addStream;f.RTCPeerConnection.prototype.addStream=function(S){var M=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},S.getTracks().forEach(function(j){if(M.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,M){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(W){return W===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(W){return W.track===S}))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var H=this._streams[M.id];if(H)H.addTrack(S),Promise.resolve().then(function(){I.dispatchEvent(new Event("negotiationneeded"))});else{var N=new f.MediaStream([S]);this._streams[M.id]=N,this._reverseStreams[N.id]=M,this.addStream(N)}return this.getSenders().find(function(W){return W.track===S})},["createOffer","createAnswer"].forEach(function(S){var M=f.RTCPeerConnection.prototype[S],I=l({},S,function(){var j=this,H=arguments;return arguments.length&&typeof arguments[0]=="function"?M.apply(this,[function(N){var W=P(j,N);H[0].apply(null,[W])},function(N){H[1]&&H[1].apply(null,N)},arguments[2]]):M.apply(this,arguments).then(function(N){return P(j,N)})});f.RTCPeerConnection.prototype[S]=I[S]});var C=f.RTCPeerConnection.prototype.setLocalDescription;f.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=(S=this,M=arguments[0],I=M.sdp,Object.keys(S._reverseStreams||[]).forEach(function(j){var H=S._reverseStreams[j],N=S._streams[H.id];I=I.replace(new RegExp(H.id,"g"),N.id)}),new RTCSessionDescription({type:M.type,sdp:I})),C.apply(this,arguments)):C.apply(this,arguments);var S,M,I};var R=Object.getOwnPropertyDescriptor(f.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(f.RTCPeerConnection.prototype,"localDescription",{get:function(){var S=R.get.apply(this);return S.type===""?S:P(this,S)}}),f.RTCPeerConnection.prototype.removeTrack=function(S){var M,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})&&(M=I._streams[j])}),M&&(M.getTracks().length===1?this.removeStream(this._reverseStreams[M.id]):M.removeTrack(S.track),this.dispatchEvent(new Event("negotiationneeded")))}}function P(S,M){var I=M.sdp;return Object.keys(S._reverseStreams||[]).forEach(function(j){var H=S._reverseStreams[j],N=S._streams[H.id];I=I.replace(new RegExp(N.id,"g"),H.id)}),new RTCSessionDescription({type:M.type,sdp:I})}}function g(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=l({},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(c,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterIceServers=o;var i=r(c("../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 l=n();if(l&&l.has(s))return l.get(s);var d={},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var u in s)if(Object.prototype.hasOwnProperty.call(s,u)){var h=a?Object.getOwnPropertyDescriptor(s,u):null;h&&(h.get||h.set)?Object.defineProperty(d,u,h):d[u]=s[u]}return d.default=s,l&&l.set(s,d),d}function o(s,l){var d=!1;return(s=JSON.parse(JSON.stringify(s))).filter(function(a){if(a&&(a.urls||a.url)){var u=a.urls||a.url;a.url&&!a.urls&&i.deprecated("RTCIceServer.url","RTCIceServer.urls");var h=typeof u=="string";return h&&(u=[u]),u=u.filter(function(m){if(m.indexOf("stun:")===0)return!1;var E=m.startsWith("turn")&&!m.startsWith("turn:[")&&m.includes("transport=udp");return E&&!d?(d=!0,!0):E&&!d}),delete a.url,a.urls=h?u[0]:u,!!u.length}})}},{"../utils":"iSxC"}],YHvh:[function(c,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 bf=Object.create;var Yr=Object.defineProperty;var Zd=Object.getOwnPropertyDescriptor;var vf=Object.getOwnPropertyNames;var yf=Object.getPrototypeOf,Ef=Object.prototype.hasOwnProperty;var wf=(l,e,t)=>e in l?Yr(l,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):l[e]=t;var pl=(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 Kr=(l,e)=>()=>(e||l((e={exports:{}}).exports,e),e.exports),$d=(l,e)=>{for(var t in e)Yr(l,t,{get:e[t],enumerable:!0})},_f=(l,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of vf(e))!Ef.call(l,n)&&n!==t&&Yr(l,n,{get:()=>e[n],enumerable:!(i=Zd(e,n))||i.enumerable});return l};var $o=(l,e,t)=>(t=l!=null?bf(yf(l)):{},_f(e||!l||!l.__esModule?Yr(t,"default",{value:l,enumerable:!0}):t,l));var k=(l,e,t,i)=>{for(var n=i>1?void 0:i?Zd(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&&Yr(e,t,n),n};var N=(l,e,t)=>(wf(l,typeof e!="symbol"?e+"":e,t),t);var Us=Kr((Vu,rc)=>{parcelRequire=function(l,e,t,i){var n,r=typeof parcelRequire=="function"&&parcelRequire,o=typeof pl=="function"&&pl;function s(a,u){if(!e[a]){if(!l[a]){var h=typeof parcelRequire=="function"&&parcelRequire;if(!u&&h)return h(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,u){l[a]=[function(h,f){f.exports=u},{}]};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 Vu=="object"&&typeof rc<"u"?rc.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 u=new s;return u.pack(a),u.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 u=a.charCodeAt(0);return u<=2047?"00":u<=65535?"000":u<=2097151?"0000":u<=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,u=this.unpack_uint8();if(u<128)return u;if((224^u)<32)return(224^u)-32;if((a=160^u)<=15)return this.unpack_raw(a);if((a=176^u)<=15)return this.unpack_string(a);if((a=144^u)<=15)return this.unpack_array(a);if((a=128^u)<=15)return this.unpack_map(a);switch(u){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),u=256*(255&a[0])+(255&a[1]);return this.index+=2,u},o.prototype.unpack_uint32=function(){var a=this.read(4),u=256*(256*(256*a[0]+a[1])+a[2])+a[3];return this.index+=4,u},o.prototype.unpack_uint64=function(){var a=this.read(8),u=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,u},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 u=this.dataBuffer.slice(this.index,this.index+a);return this.index+=a,u},o.prototype.unpack_string=function(a){for(var u,h,f=this.read(a),E=0,b="";E<a;)(u=f[E])<128?(b+=String.fromCharCode(u),E++):(192^u)<32?(h=(192^u)<<6|63&f[E+1],b+=String.fromCharCode(h),E+=2):(h=(15&u)<<12|(63&f[E+1])<<6|63&f[E+2],b+=String.fromCharCode(h),E+=3);return this.index+=a,b},o.prototype.unpack_array=function(a){for(var u=new Array(a),h=0;h<a;h++)u[h]=this.unpack();return u},o.prototype.unpack_map=function(a){for(var u={},h=0;h<a;h++){var f=this.unpack(),E=this.unpack();u[f]=E}return u},o.prototype.unpack_float=function(){var a=this.unpack_uint32(),u=(a>>23&255)-127;return(a>>31===0?1:-1)*(8388607&a|8388608)*Math.pow(2,u-23)},o.prototype.unpack_double=function(){var a=this.unpack_uint32(),u=this.unpack_uint32(),h=(a>>20&2047)-1023;return(a>>31===0?1:-1)*((1048575&a|1048576)*Math.pow(2,h-20)+u*Math.pow(2,h-52))},o.prototype.read=function(a){var u=this.index;if(u+a<=this.length)return this.dataView.subarray(u,u+a);throw new Error("BinaryPackFailure: read index out of range")},s.prototype.getBuffer=function(){return this.bufferBuilder.getBuffer()},s.prototype.pack=function(a){var u=typeof a;if(u==="string")this.pack_string(a);else if(u==="number")Math.floor(a)===a?this.pack_integer(a):this.pack_double(a);else if(u==="boolean")a===!0?this.bufferBuilder.append(195):a===!1&&this.bufferBuilder.append(194);else if(u==="undefined")this.bufferBuilder.append(192);else{if(u!=="object")throw new Error('Type "'+u+'" not yet supported');if(a===null)this.bufferBuilder.append(192);else{var h=a.constructor;if(h==Array)this.pack_array(a);else if(h==Blob||h==File||a instanceof Blob||a instanceof File)this.pack_bin(a);else if(h==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(h==Object||h.toString().startsWith("class"))this.pack_object(a);else if(h==Date)this.pack_string(a.toString());else{if(typeof a.toBinaryPack!="function")throw new Error('Type "'+h.toString()+'" not yet supported');this.bufferBuilder.append(a.toBinaryPack())}}}this.bufferBuilder.flush()},s.prototype.pack_bin=function(a){var u=a.length||a.byteLength||a.size;if(u<=15)this.pack_uint8(160+u);else if(u<=65535)this.bufferBuilder.append(218),this.pack_uint16(u);else{if(!(u<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(219),this.pack_uint32(u)}this.bufferBuilder.append(a)},s.prototype.pack_string=function(a){var u=d(a);if(u<=15)this.pack_uint8(176+u);else if(u<=65535)this.bufferBuilder.append(216),this.pack_uint16(u);else{if(!(u<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(217),this.pack_uint32(u)}this.bufferBuilder.append(a)},s.prototype.pack_array=function(a){var u=a.length;if(u<=15)this.pack_uint8(144+u);else if(u<=65535)this.bufferBuilder.append(220),this.pack_uint16(u);else{if(!(u<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(221),this.pack_uint32(u)}for(var h=0;h<u;h++)this.pack(a[h])},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 u=0;a<0&&(u=1,a=-a);var h=Math.floor(Math.log(a)/Math.LN2),f=a/Math.pow(2,h)-1,E=Math.floor(f*Math.pow(2,52)),b=Math.pow(2,32),y=u<<31|h+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 u=Object.keys(a).length;if(u<=15)this.pack_uint8(128+u);else if(u<=65535)this.bufferBuilder.append(222),this.pack_uint16(u);else{if(!(u<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(223),this.pack_uint32(u)}for(var h in a)a.hasOwnProperty(h)&&(this.pack(h),this.pack(a[h]))},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 u=4294967295&a;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_uint64=function(a){var u=a/Math.pow(2,32),h=a%Math.pow(2,32);this.bufferBuilder.append((4278190080&u)>>>24),this.bufferBuilder.append((16711680&u)>>>16),this.bufferBuilder.append((65280&u)>>>8),this.bufferBuilder.append(255&u),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_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 u=Math.floor(a/Math.pow(2,32)),h=a%Math.pow(2,32);this.bufferBuilder.append((4278190080&u)>>>24),this.bufferBuilder.append((16711680&u)>>>16),this.bufferBuilder.append((65280&u)>>>8),this.bufferBuilder.append(255&u),this.bufferBuilder.append((4278190080&h)>>>24),this.bufferBuilder.append((16711680&h)>>>16),this.bufferBuilder.append((65280&h)>>>8),this.bufferBuilder.append(255&h)}},{"./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=u,t.deprecated=h,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(C,R){if(C!==m)return x.apply(this,arguments);var P=function(S){var M=v(S);M&&(R.handleEvent?R.handleEvent(M):R(M))};return this._eventMap=this._eventMap||{},this._eventMap[m]||(this._eventMap[m]=new Map),this._eventMap[m].set(R,P),x.apply(this,[C,P])};var T=w.removeEventListener;w.removeEventListener=function(C,R){if(C!==m||!this._eventMap||!this._eventMap[m])return T.apply(this,arguments);if(!this._eventMap[m].has(R))return T.apply(this,arguments);var P=this._eventMap[m].get(R);return this._eventMap[m].delete(R),this._eventMap[m].size===0&&delete this._eventMap[m],Object.keys(this._eventMap).length===0&&delete this._eventMap,T.apply(this,[C,P])},Object.defineProperty(w,"on"+m,{get:function(){return this["_on"+m]},set:function(C){this["_on"+m]&&(this.removeEventListener(m,this["_on"+m]),delete this["_on"+m]),C&&this.addEventListener(m,this["_on"+m]=C)},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 u(){if((typeof window>"u"?"undefined":n(window))==="object"){if(r)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function h(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(C){C.type==="track"&&C.trackIdentifier===m.id&&T.push(C)}),T.forEach(function(C){p.forEach(function(R){R.type===w&&R.trackId===C.id&&y(p,R,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 u={},h=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var f in d)if(Object.prototype.hasOwnProperty.call(d,f)){var E=h?Object.getOwnPropertyDescriptor(d,f):null;E&&(E.get||E.set)?Object.defineProperty(u,f,E):u[f]=d[f]}return u.default=d,a&&a.set(d,u),u}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 u=d&&d.navigator;if(u.mediaDevices){var h=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,C){T in x&&!(C in x)&&(x[C]=x[T],delete x[T])};p((y=JSON.parse(JSON.stringify(y))).audio,"autoGainControl","googAutoGainControl"),p(y.audio,"noiseSuppression","googNoiseSuppression"),y.audio=h(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")&&(!u.mediaDevices.getSupportedConstraints||!u.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 u.mediaDevices.enumerateDevices().then(function(x){var T=(x=x.filter(function(C){return C.kind==="videoinput"})).find(function(C){return v.some(function(R){return C.label.toLowerCase().includes(R)})});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=h(y.video),s("chrome: "+JSON.stringify(y)),g(y)});y.video=h(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(u.getUserMedia=function(y,g,p){f(y,function(m){u.webkitGetUserMedia(m,g,function(v){p&&p(E(v))})})}.bind(u),u.mediaDevices.getUserMedia){var b=u.mediaDevices.getUserMedia.bind(u.mediaDevices);u.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=u,t.shimGetSendersWithDtmf=h,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 C=x?Object.getOwnPropertyDescriptor(m,T):null;C&&(C.get||C.set)?Object.defineProperty(w,T,C):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 u(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 C;C=m.RTCPeerConnection.prototype.getReceivers?w.getReceivers().find(function(P){return P.track&&P.track.id===T.track.id}):{track:T.track};var R=new Event("track");R.track=T.track,R.receiver=C,R.transceiver={receiver:C},R.streams=[x.stream],w.dispatchEvent(R)}),x.stream.getTracks().forEach(function(T){var C;C=m.RTCPeerConnection.prototype.getReceivers?w.getReceivers().find(function(P){return P.track&&P.track.id===T.id}):{track:T};var R=new Event("track");R.track=T,R.receiver=C,R.transceiver={receiver:C},R.streams=[x.stream],w.dispatchEvent(R)})},this.addEventListener("addstream",this._ontrackpoly)),v.apply(this,arguments)}}}function h(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 M=w.apply(this,arguments);return M||(M=v(this,P),this._senders.push(M)),M};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(M){S._senders.push(v(S,M))})};var C=m.RTCPeerConnection.prototype.removeStream;m.RTCPeerConnection.prototype.removeStream=function(P){var S=this;this._senders=this._senders||[],C.apply(this,[P]),P.getTracks().forEach(function(M){var I=S._senders.find(function(j){return j.track===M});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 R=m.RTCPeerConnection.prototype.getSenders;m.RTCPeerConnection.prototype.getSenders=function(){var P=this,S=R.apply(this,[]);return S.forEach(function(M){return M._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,C]=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 R=function(S){var M={};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(L){j[L]=I.stat(L)}),M[j.id]=j}),M},P=function(S){return new Map(Object.keys(S).map(function(M){return[M,S[M]]}))};return arguments.length>=2?v.apply(this,[function(S){T(P(R(S)))},x]):new Promise(function(S,M){v.apply(w,[function(I){S(P(R(I)))},M])}).then(T,C)}}}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 C=this,R=v.apply(this,[]);return R.forEach(function(P){return P._pc=C}),R});var w=m.RTCPeerConnection.prototype.addTrack;w&&(m.RTCPeerConnection.prototype.addTrack=function(){var C=w.apply(this,arguments);return C._pc=this,C}),m.RTCRtpSender.prototype.getStats=function(){var C=this;return this._pc.getStats().then(function(R){return i.filterStats(R,C.track,!0)})}}if(!("getStats"in m.RTCRtpReceiver.prototype)){var x=m.RTCPeerConnection.prototype.getReceivers;x&&(m.RTCPeerConnection.prototype.getReceivers=function(){var C=this,R=x.apply(this,[]);return R.forEach(function(P){return P._pc=C}),R}),i.wrapPeerConnectionEvent(m,"track",function(C){return C.receiver._pc=C.srcElement,C}),m.RTCRtpReceiver.prototype.getStats=function(){var C=this;return this._pc.getStats().then(function(R){return i.filterStats(R,C.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 C,R,P,S=arguments[0];return this.getSenders().forEach(function(M){M.track===S&&(C?P=!0:C=M)}),this.getReceivers().forEach(function(M){return M.track===S&&(R?P=!0:R=M),M.track===S}),P||C&&R?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):C?C.getStats():R?R.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 C=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(function(R){return C._shimmedLocalStreams[R][0]})};var v=m.RTCPeerConnection.prototype.addTrack;m.RTCPeerConnection.prototype.addTrack=function(C,R){if(!R)return v.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var P=v.apply(this,arguments);return this._shimmedLocalStreams[R.id]?this._shimmedLocalStreams[R.id].indexOf(P)===-1&&this._shimmedLocalStreams[R.id].push(P):this._shimmedLocalStreams[R.id]=[R,P],P};var w=m.RTCPeerConnection.prototype.addStream;m.RTCPeerConnection.prototype.addStream=function(C){var R=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},C.getTracks().forEach(function(M){if(R.getSenders().find(function(I){return I.track===M}))throw new DOMException("Track already exists.","InvalidAccessError")});var P=this.getSenders();w.apply(this,arguments);var S=this.getSenders().filter(function(M){return P.indexOf(M)===-1});this._shimmedLocalStreams[C.id]=[C].concat(S)};var x=m.RTCPeerConnection.prototype.removeStream;m.RTCPeerConnection.prototype.removeStream=function(C){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[C.id],x.apply(this,arguments)};var T=m.RTCPeerConnection.prototype.removeTrack;m.RTCPeerConnection.prototype.removeTrack=function(C){var R=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},C&&Object.keys(this._shimmedLocalStreams).forEach(function(P){var S=R._shimmedLocalStreams[P].indexOf(C);S!==-1&&R._shimmedLocalStreams[P].splice(S,1),R._shimmedLocalStreams[P].length===1&&delete R._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,M=w.apply(this);return this._reverseStreams=this._reverseStreams||{},M.map(function(I){return S._reverseStreams[I.id]})};var x=m.RTCPeerConnection.prototype.addStream;m.RTCPeerConnection.prototype.addStream=function(S){var M=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},S.getTracks().forEach(function(j){if(M.getSenders().find(function(L){return L.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,M){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(W){return W===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(W){return W.track===S}))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var L=this._streams[M.id];if(L)L.addTrack(S),Promise.resolve().then(function(){I.dispatchEvent(new Event("negotiationneeded"))});else{var F=new m.MediaStream([S]);this._streams[M.id]=F,this._reverseStreams[F.id]=M,this.addStream(F)}return this.getSenders().find(function(W){return W.track===S})},["createOffer","createAnswer"].forEach(function(S){var M=m.RTCPeerConnection.prototype[S],I=c({},S,function(){var j=this,L=arguments;return arguments.length&&typeof arguments[0]=="function"?M.apply(this,[function(F){var W=P(j,F);L[0].apply(null,[W])},function(F){L[1]&&L[1].apply(null,F)},arguments[2]]):M.apply(this,arguments).then(function(F){return P(j,F)})});m.RTCPeerConnection.prototype[S]=I[S]});var C=m.RTCPeerConnection.prototype.setLocalDescription;m.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=(S=this,M=arguments[0],I=M.sdp,Object.keys(S._reverseStreams||[]).forEach(function(j){var L=S._reverseStreams[j],F=S._streams[L.id];I=I.replace(new RegExp(L.id,"g"),F.id)}),new RTCSessionDescription({type:M.type,sdp:I})),C.apply(this,arguments)):C.apply(this,arguments);var S,M,I};var R=Object.getOwnPropertyDescriptor(m.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(m.RTCPeerConnection.prototype,"localDescription",{get:function(){var S=R.get.apply(this);return S.type===""?S:P(this,S)}}),m.RTCPeerConnection.prototype.removeTrack=function(S){var M,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(L){return S.track===L})&&(M=I._streams[j])}),M&&(M.getTracks().length===1?this.removeStream(this._reverseStreams[M.id]):M.removeTrack(S.track),this.dispatchEvent(new Event("negotiationneeded")))}}function P(S,M){var I=M.sdp;return Object.keys(S._reverseStreams||[]).forEach(function(j){var L=S._reverseStreams[j],F=S._streams[L.id];I=I.replace(new RegExp(F.id,"g"),L.id)}),new RTCSessionDescription({type:M.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 u in s)if(Object.prototype.hasOwnProperty.call(s,u)){var h=a?Object.getOwnPropertyDescriptor(s,u):null;h&&(h.get||h.set)?Object.defineProperty(d,u,h):d[u]=s[u]}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 u=a.urls||a.url;a.url&&!a.urls&&i.deprecated("RTCIceServer.url","RTCIceServer.urls");var h=typeof u=="string";return h&&(u=[u]),u=u.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=h?u[0]:u,!!u.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
3
  m=`).map(function(r,o){return(o>0?"m="+r:r).trim()+`\r
4
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,o={},s=n.substr(n.indexOf(" ")+1).split(";"),l=0;l<s.length;l++)o[(r=s[l].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(l){n.parameters[l]?s.push(l+"="+n.parameters[l]):s.push(l)}),r+="a=fmtp:"+o+" "+s.join(";")+`\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
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
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
9
  `;return n.fingerprints.forEach(function(s){o+="a=fingerprint:"+s.algorithm+" "+s.value+`\r
10
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
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:[]},o=i.splitLines(n)[0].split(" "),s=3;s<o.length;s++){var l=o[s],d=i.matchPrefix(n,"a=rtpmap:"+l+" ")[0];if(d){var a=i.parseRtpMap(d),u=i.matchPrefix(n,"a=fmtp:"+l+" ");switch(a.parameters=u.length?i.parseFmtp(u[0]):{},a.rtcpFeedback=i.matchPrefix(n,"a=rtcp-fb:"+l+" ").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(h){r.headerExtensions.push(i.parseExtmap(h))}),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(l){return l.preferredPayloadType!==void 0?l.preferredPayloadType:l.payloadType}).join(" ")+`\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),u=i.matchPrefix(n,"a=fmtp:"+c+" ");switch(a.parameters=u.length?i.parseFmtp(u[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(h){r.headerExtensions.push(i.parseExtmap(h))}),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
14
  `,o+=`c=IN IP4 0.0.0.0\r
15
15
  `,o+=`a=rtcp:9 IN IP4 0.0.0.0\r
16
- `,r.codecs.forEach(function(l){o+=i.writeRtpMap(l),o+=i.writeFmtp(l),o+=i.writeRtcpFb(l)});var s=0;return r.codecs.forEach(function(l){l.maxptime>s&&(s=l.maxptime)}),s>0&&(o+="a=maxptime:"+s+`\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
17
  `),o+=`a=rtcp-mux\r
18
- `,r.headerExtensions&&r.headerExtensions.forEach(function(l){o+=i.writeExtmap(l)}),o},i.parseRtpEncodingParameters=function(n){var r,o=[],s=i.parseRtpParameters(n),l=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"}),u=a.length>0&&a[0].ssrc,h=i.matchPrefix(n,"a=ssrc-group:FID").map(function(E){return E.substr(17).split(" ").map(function(b){return parseInt(b,10)})});h.length>0&&h[0].length>1&&h[0][0]===u&&(r=h[0][1]),s.codecs.forEach(function(E){if(E.name.toUpperCase()==="RTX"&&E.parameters.apt){var b={ssrc:u,codecPayloadType:parseInt(E.parameters.apt,10)};u&&r&&(b.rtx={ssrc:r}),o.push(b),l&&((b=JSON.parse(JSON.stringify(b))).fec={ssrc:u,mechanism:d?"red+ulpfec":"red"},o.push(b))}}),o.length===0&&u&&o.push({ssrc:u});var m=i.matchPrefix(n,"b=");return m.length&&(m=m[0].indexOf("b=TIAS:")===0?parseInt(m[0].substr(7),10):m[0].indexOf("b=AS:")===0?1e3*parseInt(m[0].substr(5),10)*.95-16e3:void 0,o.forEach(function(E){E.maxBitrate=m})),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 l=i.matchPrefix(n,"a=rtcp-mux");return r.mux=l.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(l){return i.parseSsrcMedia(l)}).filter(function(l){return l.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 l=i.matchPrefix(n,"a=sctp-port:");if(l.length>0)return{port:parseInt(l[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
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"}),u=a.length>0&&a[0].ssrc,h=i.matchPrefix(n,"a=ssrc-group:FID").map(function(E){return E.substr(17).split(" ").map(function(b){return parseInt(b,10)})});h.length>0&&h[0].length>1&&h[0][0]===u&&(r=h[0][1]),s.codecs.forEach(function(E){if(E.name.toUpperCase()==="RTX"&&E.parameters.apt){var b={ssrc:u,codecPayloadType:parseInt(E.parameters.apt,10)};u&&r&&(b.rtx={ssrc:r}),o.push(b),c&&((b=JSON.parse(JSON.stringify(b))).fec={ssrc:u,mechanism:d?"red+ulpfec":"red"},o.push(b))}}),o.length===0&&u&&o.push({ssrc:u});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
@@ -26,17 +26,17 @@ a=ice-pwd:`+n.password+`\r
26
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,o,s){var l=i.writeRtpDescription(n.kind,r);if(l+=i.writeIceParameters(n.iceGatherer.getLocalParameters()),l+=i.writeDtlsParameters(n.dtlsTransport.getLocalParameters(),o==="offer"?"actpass":"active"),l+="a=mid:"+n.mid+`\r
30
- `,n.direction?l+="a="+n.direction+`\r
31
- `:n.rtpSender&&n.rtpReceiver?l+=`a=sendrecv\r
32
- `:n.rtpSender?l+=`a=sendonly\r
33
- `:n.rtpReceiver?l+=`a=recvonly\r
34
- `:l+=`a=inactive\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
+ `,n.direction?c+="a="+n.direction+`\r
31
+ `:n.rtpSender&&n.rtpReceiver?c+=`a=sendrecv\r
32
+ `:n.rtpSender?c+=`a=sendonly\r
33
+ `:n.rtpReceiver?c+=`a=recvonly\r
34
+ `:c+=`a=inactive\r
35
35
  `,n.rtpSender){var d="msid:"+s.id+" "+n.rtpSender.track.id+`\r
36
- `;l+="a="+d,l+="a=ssrc:"+n.sendEncodingParameters[0].ssrc+" "+d,n.sendEncodingParameters[0].rtx&&(l+="a=ssrc:"+n.sendEncodingParameters[0].rtx.ssrc+" "+d,l+="a=ssrc-group:FID "+n.sendEncodingParameters[0].ssrc+" "+n.sendEncodingParameters[0].rtx.ssrc+`\r
37
- `)}return l+="a=ssrc:"+n.sendEncodingParameters[0].ssrc+" cname:"+i.localCName+`\r
38
- `,n.rtpSender&&n.sendEncodingParameters[0].rtx&&(l+="a=ssrc:"+n.sendEncodingParameters[0].rtx.ssrc+" cname:"+i.localCName+`\r
39
- `),l},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(c,e,t){"use strict";var i=c("sdp");function n(u){return{inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[u.type]||u.type}function r(u,h,m,E,b){var y=i.writeRtpDescription(u.kind,h);if(y+=i.writeIceParameters(u.iceGatherer.getLocalParameters()),y+=i.writeDtlsParameters(u.dtlsTransport.getLocalParameters(),m==="offer"?"actpass":b||"active"),y+="a=mid:"+u.mid+`\r
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
+ `)}return c+="a=ssrc:"+n.sendEncodingParameters[0].ssrc+" cname:"+i.localCName+`\r
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 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(u){return{inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[u.type]||u.type}function r(u,h,f,E,b){var y=i.writeRtpDescription(u.kind,h);if(y+=i.writeIceParameters(u.iceGatherer.getLocalParameters()),y+=i.writeDtlsParameters(u.dtlsTransport.getLocalParameters(),f==="offer"?"actpass":b||"active"),y+="a=mid:"+u.mid+`\r
40
40
  `,u.rtpSender&&u.rtpReceiver?y+=`a=sendrecv\r
41
41
  `:u.rtpSender?y+=`a=sendonly\r
42
42
  `:u.rtpReceiver?y+=`a=recvonly\r
@@ -45,16 +45,16 @@ t=0 0\r
45
45
  `;y+="a="+p,y+="a=ssrc:"+u.sendEncodingParameters[0].ssrc+" "+p,u.sendEncodingParameters[0].rtx&&(y+="a=ssrc:"+u.sendEncodingParameters[0].rtx.ssrc+" "+p,y+="a=ssrc-group:FID "+u.sendEncodingParameters[0].ssrc+" "+u.sendEncodingParameters[0].rtx.ssrc+`\r
46
46
  `)}return y+="a=ssrc:"+u.sendEncodingParameters[0].ssrc+" cname:"+i.localCName+`\r
47
47
  `,u.rtpSender&&u.sendEncodingParameters[0].rtx&&(y+="a=ssrc:"+u.sendEncodingParameters[0].rtx.ssrc+" cname:"+i.localCName+`\r
48
- `),y}function o(u,h){var m=!1;return(u=JSON.parse(JSON.stringify(u))).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&&!m?(m=!0,!0):g.indexOf("stun:")===0&&h>=14393&&g.indexOf("?transport=udp")===-1}),delete E.url,E.urls=y?b[0]:b,!!b.length}})}function s(u,h){var m={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,f){var v=E(y.parameters.apt,p),w=E(g.parameters.apt,f);return v&&w&&v.name.toLowerCase()===w.name.toLowerCase()};return u.codecs.forEach(function(y){for(var g=0;g<h.codecs.length;g++){var p=h.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,u.codecs,h.codecs))continue;(p=JSON.parse(JSON.stringify(p))).numChannels=Math.min(y.numChannels,p.numChannels),m.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}}}),u.headerExtensions.forEach(function(y){for(var g=0;g<h.headerExtensions.length;g++){var p=h.headerExtensions[g];if(y.uri===p.uri){m.headerExtensions.push(p);break}}}),m}function l(u,h,m){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"]}}[h][u].indexOf(m)!==-1}function d(u,h){var m=u.getRemoteCandidates().find(function(E){return h.foundation===E.foundation&&h.ip===E.ip&&h.port===E.port&&h.priority===E.priority&&h.protocol===E.protocol&&h.type===E.type});return m||u.addRemoteCandidate(h),!m}function a(u,h){var m=new Error(h);return m.name=u,m.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[u],m}e.exports=function(u,h){function m(g,p){p.addTrack(g),p.dispatchEvent(new u.MediaStreamTrackEvent("addtrack",{track:g}))}function E(g,p,f,v){var w=new Event("track");w.track=p,w.receiver=f,w.transceiver={receiver:f},w.streams=v,u.setTimeout(function(){g._dispatchEvent("track",w)})}var b=function(g){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",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||[],h),this._iceGatherers=[],g.iceCandidatePoolSize)for(var v=g.iceCandidatePoolSize;v>0;v--)this._iceGatherers.push(new u.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 f=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&&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(g,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===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||(f=this.transceivers[v]);return f||(f=this._createTransceiver(g.kind)),this._maybeFireNegotiationNeeded(),this.localStreams.indexOf(p)===-1&&this.localStreams.push(p),f.track=g,f.stream=p,f.rtpSender=new u.RTCRtpSender(g,f.dtlsTransport),f.rtpSender},b.prototype.addStream=function(g){var p=this;if(h>=15025)g.getTracks().forEach(function(v){p.addTrack(v,g)});else{var f=g.clone();g.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(g){if(this._isClosed)throw a("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(g instanceof u.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 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(g){var p=this;g.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(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 f=this;if(p&&g>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var v=new u.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",f.transceivers[g].bufferedCandidateEvents!==null&&f.transceivers[g].bufferedCandidateEvents.push(w)},v.addEventListener("localcandidate",this.transceivers[g].bufferCandidates),v},b.prototype._gather=function(g,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:g,sdpMLineIndex:p};var C=x.candidate,R=!C||Object.keys(C).length===0;if(R)v.state!=="new"&&v.state!=="gathering"||(v.state="completed");else{v.state==="new"&&(v.state="gathering"),C.component=1,C.ufrag=v.getLocalParameters().usernameFragment;var P=i.writeCandidate(C);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]+=R?`a=end-of-candidates\r
48
+ `),y}function o(u,h){var f=!1;return(u=JSON.parse(JSON.stringify(u))).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&&h>=14393&&g.indexOf("?transport=udp")===-1}),delete E.url,E.urls=y?b[0]:b,!!b.length}})}function s(u,h){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 u.codecs.forEach(function(y){for(var g=0;g<h.codecs.length;g++){var p=h.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,u.codecs,h.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}}}),u.headerExtensions.forEach(function(y){for(var g=0;g<h.headerExtensions.length;g++){var p=h.headerExtensions[g];if(y.uri===p.uri){f.headerExtensions.push(p);break}}}),f}function c(u,h,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"]}}[h][u].indexOf(f)!==-1}function d(u,h){var f=u.getRemoteCandidates().find(function(E){return h.foundation===E.foundation&&h.ip===E.ip&&h.port===E.port&&h.priority===E.priority&&h.protocol===E.protocol&&h.type===E.type});return f||u.addRemoteCandidate(h),!f}function a(u,h){var f=new Error(h);return f.name=u,f.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[u],f}e.exports=function(u,h){function f(g,p){p.addTrack(g),p.dispatchEvent(new u.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,u.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||[],h),this._iceGatherers=[],g.iceCandidatePoolSize)for(var v=g.iceCandidatePoolSize;v>0;v--)this._iceGatherers.push(new u.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 u.RTCRtpSender(g,m.dtlsTransport),m.rtpSender},b.prototype.addStream=function(g){var p=this;if(h>=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 u.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 u.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 C=x.candidate,R=!C||Object.keys(C).length===0;if(R)v.state!=="new"&&v.state!=="gathering"||(v.state="completed");else{v.state==="new"&&(v.state="gathering"),C.component=1,C.ufrag=v.getLocalParameters().usernameFragment;var P=i.writeCandidate(C);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]+=R?`a=end-of-candidates\r
49
49
  `:"a="+T.candidate.candidate+`\r
50
- `,f._localDescription.sdp=i.getDescription(f._localDescription.sdp)+S.join("");var M=f.transceivers.every(function(I){return I.iceGatherer&&I.iceGatherer.state==="completed"});f.iceGatheringState!=="gathering"&&(f.iceGatheringState="gathering",f._emitGatheringStateChange()),R||f._dispatchEvent("icecandidate",T),M&&(f._dispatchEvent("icecandidate",new Event("icecandidate")),f.iceGatheringState="complete",f._emitGatheringStateChange())}},u.setTimeout(function(){w.forEach(function(x){v.onlocalcandidate(x)})},0)}},b.prototype._createIceAndDtlsTransports=function(){var g=this,p=new u.RTCIceTransport(null);p.onicestatechange=function(){g._updateIceConnectionState(),g._updateConnectionState()};var f=new u.RTCDtlsTransport(p);return f.ondtlsstatechange=function(){g._updateConnectionState()},f.onerror=function(){Object.defineProperty(f,"state",{value:"failed",writable:!0}),g._updateConnectionState()},{iceTransport:p,dtlsTransport:f}},b.prototype._disposeIceAndDtlsTransports=function(g){var p=this.transceivers[g].iceGatherer;p&&(delete p.onlocalcandidate,delete this.transceivers[g].iceGatherer);var f=this.transceivers[g].iceTransport;f&&(delete f.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,f){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)),f&&g.rtpReceiver&&v.codecs.length>0&&(g.kind==="video"&&g.recvEncodingParameters&&h<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,f,v=this;if(["offer","answer"].indexOf(g.type)===-1)return Promise.reject(a("TypeError",'Unsupported type "'+g.type+'"'));if(!l("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),f=p.shift(),p.forEach(function(x,T){var C=i.parseRtpParameters(x);v.transceivers[T].localCapabilities=C}),v.transceivers.forEach(function(x,T){v._gather(x.mid,T)});else if(g.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 C=v.transceivers[T],R=C.iceGatherer,P=C.iceTransport,S=C.dtlsTransport,M=C.localCapabilities,I=C.remoteCapabilities;if(!(i.isRejected(x)&&i.matchPrefix(x,"a=bundle-only").length===0)&&!C.rejected){var j=i.getIceParameters(x,f),H=i.getDtlsParameters(x,f);w&&(H.role="server"),v.usingBundle&&T!==0||(v._gather(C.mid,T),P.state==="new"&&P.start(R,j,w?"controlling":"controlled"),S.state==="new"&&S.start(H));var N=s(M,I);v._transceive(C,N.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(!l("setRemoteDescription",g.type,p.signalingState)||p._isClosed)return Promise.reject(a("InvalidStateError","Can not set remote "+g.type+" in state "+p.signalingState));var f={};p.remoteStreams.forEach(function(P){f[P.id]=P});var v=[],w=i.splitSections(g.sdp),x=w.shift(),T=i.matchPrefix(x,"a=ice-lite").length>0,C=i.matchPrefix(x,"a=group:BUNDLE ").length>0;p.usingBundle=C;var R=i.matchPrefix(x,"a=ice-options:")[0];return p.canTrickleIceCandidates=!!R&&R.substr(14).split(" ").indexOf("trickle")>=0,w.forEach(function(P,S){var M=i.splitLines(P),I=i.getKind(P),j=i.isRejected(P)&&i.matchPrefix(P,"a=bundle-only").length===0,H=M[0].substr(2).split(" ")[2],N=i.getDirection(P,x),W=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 G,He,fe,X,ze,dn,Xn,Mi,Rt;!j&&p.transceivers[S]&&p.transceivers[S].rejected&&(p.transceivers[S]=p._createTransceiver(I,!0));var ih,nh,rh=i.parseRtpParameters(P);j||(ih=i.getIceParameters(P,x),(nh=i.getDtlsParameters(P,x)).role="client"),Xn=i.parseRtpEncodingParameters(P);var oh=i.parseRtcpParameters(P),sh=i.matchPrefix(P,"a=end-of-candidates",x).length>0,Lr=i.matchPrefix(P,"a=candidate:").map(function(et){return i.parseCandidate(et)}).filter(function(et){return et.component===1});if((g.type==="offer"||g.type==="answer")&&!j&&C&&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&&(He=(G=p.transceivers[S]).iceGatherer,fe=G.iceTransport,X=G.dtlsTransport,ze=G.rtpReceiver,dn=G.sendEncodingParameters,Mi=G.localCapabilities,p.transceivers[S].recvEncodingParameters=Xn,p.transceivers[S].remoteCapabilities=rh,p.transceivers[S].rtcpParameters=oh,Lr.length&&fe.state==="new"&&(!T&&!sh||C&&S!==0?Lr.forEach(function(et){d(G.iceTransport,et)}):fe.setRemoteCandidates(Lr)),C&&S!==0||(fe.state==="new"&&fe.start(He,ih,"controlling"),X.state==="new"&&X.start(nh)),!s(G.localCapabilities,G.remoteCapabilities).codecs.filter(function(et){return et.name.toLowerCase()==="rtx"}).length&&G.sendEncodingParameters[0].rtx&&delete G.sendEncodingParameters[0].rtx,p._transceive(G,N==="sendrecv"||N==="recvonly",N==="sendrecv"||N==="sendonly"),!ze||N!=="sendrecv"&&N!=="sendonly"?delete G.rtpReceiver:(Rt=ze.track,W?(f[W.stream]||(f[W.stream]=new u.MediaStream),m(Rt,f[W.stream]),v.push([Rt,ze,f[W.stream]])):(f.default||(f.default=new u.MediaStream),m(Rt,f.default),v.push([Rt,ze,f.default]))));else{(G=p.transceivers[S]||p._createTransceiver(I)).mid=J,G.iceGatherer||(G.iceGatherer=p._createIceGatherer(S,C)),Lr.length&&G.iceTransport.state==="new"&&(!sh||C&&S!==0?Lr.forEach(function(et){d(G.iceTransport,et)}):G.iceTransport.setRemoteCandidates(Lr)),Mi=u.RTCRtpReceiver.getCapabilities(I),h<15019&&(Mi.codecs=Mi.codecs.filter(function(et){return et.name!=="rtx"})),dn=G.sendEncodingParameters||[{ssrc:1001*(2*S+2)}];var Hr,xl=!1;N==="sendrecv"||N==="sendonly"?(xl=!G.rtpReceiver,ze=G.rtpReceiver||new u.RTCRtpReceiver(G.dtlsTransport,I),xl&&(Rt=ze.track,W&&W.stream==="-"||(W?(f[W.stream]||(f[W.stream]=new u.MediaStream,Object.defineProperty(f[W.stream],"id",{get:function(){return W.stream}})),Object.defineProperty(Rt,"id",{get:function(){return W.track}}),Hr=f[W.stream]):(f.default||(f.default=new u.MediaStream),Hr=f.default)),Hr&&(m(Rt,Hr),G.associatedRemoteMediaStreams.push(Hr)),v.push([Rt,ze,Hr]))):G.rtpReceiver&&G.rtpReceiver.track&&(G.associatedRemoteMediaStreams.forEach(function(et){var Tl,ah,lh=et.getTracks().find(function(Tf){return Tf.id===G.rtpReceiver.track.id});lh&&(Tl=lh,(ah=et).removeTrack(Tl),ah.dispatchEvent(new u.MediaStreamTrackEvent("removetrack",{track:Tl})))}),G.associatedRemoteMediaStreams=[]),G.localCapabilities=Mi,G.remoteCapabilities=rh,G.rtpReceiver=ze,G.rtcpParameters=oh,G.sendEncodingParameters=dn,G.recvEncodingParameters=Xn,p._transceive(p.transceivers[S],!1,xl)}}}),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(f).forEach(function(P){var S=f[P];if(S.getTracks().length){if(p.remoteStreams.indexOf(S)===-1){p.remoteStreams.push(S);var M=new Event("addstream");M.stream=S,u.setTimeout(function(){p._dispatchEvent("addstream",M)})}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],[])}),u.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,u.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 f=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",f)}},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 f=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",f)}},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,f=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&&(f=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"&&--f<0&&(T.wantReceive=!1)});p>0||f>0;)p>0&&(g._createTransceiver("audio"),p--),f>0&&(g._createTransceiver("video"),f--);var w=i.writeSessionBoilerplate(g._sdpSessionId,g._sdpSessionVersion++);g.transceivers.forEach(function(T,C){var R=T.track,P=T.kind,S=T.mid||i.generateIdentifier();T.mid=S,T.iceGatherer||(T.iceGatherer=g._createIceGatherer(C,g.usingBundle));var M=u.RTCRtpSender.getCapabilities(P);h<15019&&(M.codecs=M.codecs.filter(function(j){return j.name!=="rtx"})),M.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)})}),M.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*C+1)}];R&&h>=15019&&P==="video"&&!I[0].rtx&&(I[0].rtx={ssrc:I[0].ssrc+1}),T.wantReceive&&(T.rtpReceiver=new u.RTCRtpReceiver(T.dtlsTransport,P)),T.localCapabilities=M,T.sendEncodingParameters=I}),g._config.bundlePolicy!=="max-compat"&&(w+="a=group:BUNDLE "+g.transceivers.map(function(T){return T.mid}).join(" ")+`\r
50
+ `,m._localDescription.sdp=i.getDescription(m._localDescription.sdp)+S.join("");var M=m.transceivers.every(function(I){return I.iceGatherer&&I.iceGatherer.state==="completed"});m.iceGatheringState!=="gathering"&&(m.iceGatheringState="gathering",m._emitGatheringStateChange()),R||m._dispatchEvent("icecandidate",T),M&&(m._dispatchEvent("icecandidate",new Event("icecandidate")),m.iceGatheringState="complete",m._emitGatheringStateChange())}},u.setTimeout(function(){w.forEach(function(x){v.onlocalcandidate(x)})},0)}},b.prototype._createIceAndDtlsTransports=function(){var g=this,p=new u.RTCIceTransport(null);p.onicestatechange=function(){g._updateIceConnectionState(),g._updateConnectionState()};var m=new u.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&&h<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 C=i.parseRtpParameters(x);v.transceivers[T].localCapabilities=C}),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 C=v.transceivers[T],R=C.iceGatherer,P=C.iceTransport,S=C.dtlsTransport,M=C.localCapabilities,I=C.remoteCapabilities;if(!(i.isRejected(x)&&i.matchPrefix(x,"a=bundle-only").length===0)&&!C.rejected){var j=i.getIceParameters(x,m),L=i.getDtlsParameters(x,m);w&&(L.role="server"),v.usingBundle&&T!==0||(v._gather(C.mid,T),P.state==="new"&&P.start(R,j,w?"controlling":"controlled"),S.state==="new"&&S.start(L));var F=s(M,I);v._transceive(C,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,C=i.matchPrefix(x,"a=group:BUNDLE ").length>0;p.usingBundle=C;var R=i.matchPrefix(x,"a=ice-options:")[0];return p.canTrickleIceCandidates=!!R&&R.substr(14).split(" ").indexOf("trickle")>=0,w.forEach(function(P,S){var M=i.splitLines(P),I=i.getKind(P),j=i.isRejected(P)&&i.matchPrefix(P,"a=bundle-only").length===0,L=M[0].substr(2).split(" ")[2],F=i.getDirection(P,x),W=i.parseMsid(P),Q=i.getMid(P)||i.generateIdentifier();if(j||I==="application"&&(L==="DTLS/SCTP"||L==="UDP/DTLS/SCTP"))p.transceivers[S]={mid:Q,kind:I,protocol:L,rejected:!0};else{var V,De,ue,q,Be,Ai,an,ui,pt;!j&&p.transceivers[S]&&p.transceivers[S].rejected&&(p.transceivers[S]=p._createTransceiver(I,!0));var Gd,qd,Xd=i.parseRtpParameters(P);j||(Gd=i.getIceParameters(P,x),(qd=i.getDtlsParameters(P,x)).role="client"),an=i.parseRtpEncodingParameters(P);var Qd=i.parseRtcpParameters(P),Yd=i.matchPrefix(P,"a=end-of-candidates",x).length>0,Qn=i.matchPrefix(P,"a=candidate:").map(function(Ye){return i.parseCandidate(Ye)}).filter(function(Ye){return Ye.component===1});if((g.type==="offer"||g.type==="answer")&&!j&&C&&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&&(De=(V=p.transceivers[S]).iceGatherer,ue=V.iceTransport,q=V.dtlsTransport,Be=V.rtpReceiver,Ai=V.sendEncodingParameters,ui=V.localCapabilities,p.transceivers[S].recvEncodingParameters=an,p.transceivers[S].remoteCapabilities=Xd,p.transceivers[S].rtcpParameters=Qd,Qn.length&&ue.state==="new"&&(!T&&!Yd||C&&S!==0?Qn.forEach(function(Ye){d(V.iceTransport,Ye)}):ue.setRemoteCandidates(Qn)),C&&S!==0||(ue.state==="new"&&ue.start(De,Gd,"controlling"),q.state==="new"&&q.start(qd)),!s(V.localCapabilities,V.remoteCapabilities).codecs.filter(function(Ye){return Ye.name.toLowerCase()==="rtx"}).length&&V.sendEncodingParameters[0].rtx&&delete V.sendEncodingParameters[0].rtx,p._transceive(V,F==="sendrecv"||F==="recvonly",F==="sendrecv"||F==="sendonly"),!Be||F!=="sendrecv"&&F!=="sendonly"?delete V.rtpReceiver:(pt=Be.track,W?(m[W.stream]||(m[W.stream]=new u.MediaStream),f(pt,m[W.stream]),v.push([pt,Be,m[W.stream]])):(m.default||(m.default=new u.MediaStream),f(pt,m.default),v.push([pt,Be,m.default]))));else{(V=p.transceivers[S]||p._createTransceiver(I)).mid=Q,V.iceGatherer||(V.iceGatherer=p._createIceGatherer(S,C)),Qn.length&&V.iceTransport.state==="new"&&(!Yd||C&&S!==0?Qn.forEach(function(Ye){d(V.iceTransport,Ye)}):V.iceTransport.setRemoteCandidates(Qn)),ui=u.RTCRtpReceiver.getCapabilities(I),h<15019&&(ui.codecs=ui.codecs.filter(function(Ye){return Ye.name!=="rtx"})),Ai=V.sendEncodingParameters||[{ssrc:1001*(2*S+2)}];var Yn,hl=!1;F==="sendrecv"||F==="sendonly"?(hl=!V.rtpReceiver,Be=V.rtpReceiver||new u.RTCRtpReceiver(V.dtlsTransport,I),hl&&(pt=Be.track,W&&W.stream==="-"||(W?(m[W.stream]||(m[W.stream]=new u.MediaStream,Object.defineProperty(m[W.stream],"id",{get:function(){return W.stream}})),Object.defineProperty(pt,"id",{get:function(){return W.track}}),Yn=m[W.stream]):(m.default||(m.default=new u.MediaStream),Yn=m.default)),Yn&&(f(pt,Yn),V.associatedRemoteMediaStreams.push(Yn)),v.push([pt,Be,Yn]))):V.rtpReceiver&&V.rtpReceiver.track&&(V.associatedRemoteMediaStreams.forEach(function(Ye){var ul,Kd,Jd=Ye.getTracks().find(function(gf){return gf.id===V.rtpReceiver.track.id});Jd&&(ul=Jd,(Kd=Ye).removeTrack(ul),Kd.dispatchEvent(new u.MediaStreamTrackEvent("removetrack",{track:ul})))}),V.associatedRemoteMediaStreams=[]),V.localCapabilities=ui,V.remoteCapabilities=Xd,V.rtpReceiver=Be,V.rtcpParameters=Qd,V.sendEncodingParameters=Ai,V.recvEncodingParameters=an,p._transceive(p.transceivers[S],!1,hl)}}}),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 M=new Event("addstream");M.stream=S,u.setTimeout(function(){p._dispatchEvent("addstream",M)})}v.forEach(function(I){var j=I[0],L=I[1];S.id===I[2].id&&E(p,j,L,[S])})}}),v.forEach(function(P){P[2]||E(p,P[0],P[1],[])}),u.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,u.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,C){var R=T.track,P=T.kind,S=T.mid||i.generateIdentifier();T.mid=S,T.iceGatherer||(T.iceGatherer=g._createIceGatherer(C,g.usingBundle));var M=u.RTCRtpSender.getCapabilities(P);h<15019&&(M.codecs=M.codecs.filter(function(j){return j.name!=="rtx"})),M.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(L){j.name.toLowerCase()===L.name.toLowerCase()&&j.clockRate===L.clockRate&&(j.preferredPayloadType=L.payloadType)})}),M.headerExtensions.forEach(function(j){(T.remoteCapabilities&&T.remoteCapabilities.headerExtensions||[]).forEach(function(L){j.uri===L.uri&&(j.id=L.id)})});var I=T.sendEncodingParameters||[{ssrc:1001*(2*C+1)}];R&&h>=15019&&P==="video"&&!I[0].rtx&&(I[0].rtx={ssrc:I[0].ssrc+1}),T.wantReceive&&(T.rtpReceiver=new u.RTCRtpReceiver(T.dtlsTransport,P)),T.localCapabilities=M,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
52
  `,g.transceivers.forEach(function(T,C){w+=r(T,T.localCapabilities,"offer",T.stream,g._dtlsRole),w+=`a=rtcp-rsize\r
53
53
  `,!T.iceGatherer||g.iceGatheringState==="new"||C!==0&&g.usingBundle||(T.iceGatherer.getLocalCandidates().forEach(function(R){R.component=1,w+="a="+i.writeCandidate(R)+`\r
54
54
  `}),T.iceGatherer.state==="completed"&&(w+=`a=end-of-candidates\r
55
55
  `))});var x=new u.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(g._remoteDescription.sdp).length;g.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
@@ -64,20 +64,20 @@ a=rtpmap:120 VP8/90000\r
64
64
  a=inactive\r
65
65
  a=mid:`+w.mid+`\r
66
66
  `);var T;w.stream&&(w.kind==="audio"?T=w.stream.getAudioTracks()[0]:w.kind==="video"&&(T=w.stream.getVideoTracks()[0]),T&&h>=15019&&w.kind==="video"&&!w.sendEncodingParameters[0].rtx&&(w.sendEncodingParameters[0].rtx={ssrc:w.sendEncodingParameters[0].ssrc+1}));var C=s(w.localCapabilities,w.remoteCapabilities);!C.codecs.filter(function(R){return R.name.toLowerCase()==="rtx"}).length&&w.sendEncodingParameters[0].rtx&&delete w.sendEncodingParameters[0].rtx,p+=r(w,C,"answer",w.stream,g._dtlsRole),w.rtcpParameters&&w.rtcpParameters.reducedSize&&(p+=`a=rtcp-rsize\r
67
- `)}});var v=new u.RTCSessionDescription({type:"answer",sdp:p});return Promise.resolve(v)},b.prototype.addIceCandidate=function(g){var p,f=this;return g&&g.sdpMLineIndex===void 0&&!g.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(g&&g.candidate!==""){var x=g.sdpMLineIndex;if(g.sdpMid){for(var T=0;T<f.transceivers.length;T++)if(f.transceivers[T].mid===g.sdpMid){x=T;break}}var C=f.transceivers[x];if(!C)return w(a("OperationError","Can not add ICE candidate"));if(C.rejected)return v();var R=Object.keys(g.candidate).length>0?i.parseCandidate(g.candidate):{};if(R.protocol==="tcp"&&(R.port===0||R.port===9)||R.component&&R.component!==1)return v();if((x===0||x>0&&C.iceTransport!==f.transceivers[0].iceTransport)&&!d(C.iceTransport,R))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(f._remoteDescription.sdp))[x]+="a="+(R.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(g){if(g&&g instanceof u.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 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(g){var p=u[g];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(g){var p=b.prototype[g];b.prototype[g]=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(g){var p=b.prototype[g];b.prototype[g]=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(g){var p=b.prototype[g];b.prototype[g]=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(c,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(l){return Promise.reject(function(d){return{name:{PermissionDeniedError:"NotAllowedError"}[d.name]||d.name,message:d.message,constraint:d.constraint,toString:function(){return this.name}}}(l))})}}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetUserMedia=i},{}],P3bV:[function(c,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(c,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimPeerConnection=u,t.shimReplaceTrack=h,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(c("../utils")),n=c("./filtericeservers"),r=l(c("rtcpeerconnection-shim")),o=c("./getusermedia"),s=c("./getdisplaymedia");function l(m){return m&&m.__esModule?m:{default:m}}function d(){if(typeof WeakMap!="function")return null;var m=new WeakMap;return d=function(){return m},m}function a(m){if(m&&m.__esModule)return m;if(m===null||typeof m!="object"&&typeof m!="function")return{default:m};var E=d();if(E&&E.has(m))return E.get(m);var b={},y=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var g in m)if(Object.prototype.hasOwnProperty.call(m,g)){var p=y?Object.getOwnPropertyDescriptor(m,g):null;p&&(p.get||p.set)?Object.defineProperty(b,g,p):b[g]=m[g]}return b.default=m,E&&E.set(m,b),b}function u(m,E){if(m.RTCIceGatherer&&(m.RTCIceCandidate||(m.RTCIceCandidate=function(g){return g}),m.RTCSessionDescription||(m.RTCSessionDescription=function(g){return g}),E.version<15025)){var b=Object.getOwnPropertyDescriptor(m.MediaStreamTrack.prototype,"enabled");Object.defineProperty(m.MediaStreamTrack.prototype,"enabled",{set:function(g){b.set.call(this,g);var p=new Event("enabled");p.enabled=g,this.dispatchEvent(p)}})}!m.RTCRtpSender||"dtmf"in m.RTCRtpSender.prototype||Object.defineProperty(m.RTCRtpSender.prototype,"dtmf",{get:function(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=new m.RTCDtmfSender(this):this.track.kind==="video"&&(this._dtmf=null)),this._dtmf}}),m.RTCDtmfSender&&!m.RTCDTMFSender&&(m.RTCDTMFSender=m.RTCDtmfSender);var y=(0,r.default)(m,E.version);m.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)},m.RTCPeerConnection.prototype=y.prototype}function h(m){!m.RTCRtpSender||"replaceTrack"in m.RTCRtpSender.prototype||(m.RTCRtpSender.prototype.replaceTrack=m.RTCRtpSender.prototype.setTrack)}},{"../utils":"iSxC","./filtericeservers":"NZ1C","rtcpeerconnection-shim":"NJ2u","./getusermedia":"YdKx","./getdisplaymedia":"P3bV"}],GzSv:[function(c,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetUserMedia=s;var i=r(c("../utils"));function n(){if(typeof WeakMap!="function")return null;var l=new WeakMap;return n=function(){return l},l}function r(l){if(l&&l.__esModule)return l;if(l===null||typeof l!="object"&&typeof l!="function")return{default:l};var d=n();if(d&&d.has(l))return d.get(l);var a={},u=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var h in l)if(Object.prototype.hasOwnProperty.call(l,h)){var m=u?Object.getOwnPropertyDescriptor(l,h):null;m&&(m.get||m.set)?Object.defineProperty(a,h,m):a[h]=l[h]}return a.default=l,d&&d.set(l,a),a}function o(l){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})(l)}function s(l,d){var a=l&&l.navigator,u=l&&l.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 h=function(y,g,p){g in y&&!(p in y)&&(y[p]=y[g],delete y[g])},m=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)),h(y.audio,"autoGainControl","mozAutoGainControl"),h(y.audio,"noiseSuppression","mozNoiseSuppression")),m(y)},u&&u.prototype.getSettings){var E=u.prototype.getSettings;u.prototype.getSettings=function(){var y=E.apply(this,arguments);return h(y,"mozAutoGainControl","autoGainControl"),h(y,"mozNoiseSuppression","noiseSuppression"),y}}if(u&&u.prototype.applyConstraints){var b=u.prototype.applyConstraints;u.prototype.applyConstraints=function(y){return this.kind==="audio"&&o(y)==="object"&&(y=JSON.parse(JSON.stringify(y)),h(y,"autoGainControl","mozAutoGainControl"),h(y,"noiseSuppression","mozNoiseSuppression")),b.apply(this,[y])}}}}},{"../utils":"iSxC"}],UuGU:[function(c,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(c,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimOnTrack=a,t.shimPeerConnection=u,t.shimSenderGetStats=h,t.shimReceiverGetStats=m,t.shimRemoveStream=E,t.shimRTCDataChannel=b,t.shimAddTransceiver=y,t.shimGetParameters=g,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=s(c("../utils")),n=c("./getusermedia"),r=c("./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 C in v)if(Object.prototype.hasOwnProperty.call(v,C)){var R=T?Object.getOwnPropertyDescriptor(v,C):null;R&&(R.get||R.set)?Object.defineProperty(x,C,R):x[C]=v[C]}return x.default=v,w&&w.set(v,x),x}function l(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 u(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(C){var R=v.RTCPeerConnection.prototype[C],P=l({},C,function(){return arguments[0]=new(C==="addIceCandidate"?v.RTCIceCandidate:v.RTCSessionDescription)(arguments[0]),R.apply(this,arguments)});v.RTCPeerConnection.prototype[C]=P[C]});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[C,R,P]=arguments;return T.apply(this,[C||null]).then(function(S){if(w.version<53&&!R)try{S.forEach(function(M){M.type=x[M.type]||M.type})}catch(M){if(M.name!=="TypeError")throw M;S.forEach(function(I,j){S.set(j,Object.assign({},I,{type:x[I.type]||I.type}))})}return S}).then(R,P)}}}function h(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,C=w.apply(this,[]);return C.forEach(function(R){return R._pc=T}),C});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 m(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(C){return C._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 C=w.apply(this,arguments);if(T){var{sender:R}=C,P=R.getParameters();"encodings"in P&&(P.encodings.length!==1||Object.keys(P.encodings[0]).length!==0)||(P.encodings=x.sendEncodings,R.sendEncodings=x.sendEncodings,this.setParametersPromises.push(R.setParameters(P).then(function(){delete R.sendEncodings}).catch(function(){delete R.sendEncodings})))}return C})}}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 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(c,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimLocalStreamsAPI=s,t.shimRemoteStreamsAPI=l,t.shimCallbacksAPI=d,t.shimGetUserMedia=a,t.shimConstraints=u,t.shimRTCIceServerUrls=h,t.shimTrackEventTransceiver=m,t.shimCreateOfferLegacy=E,t.shimAudioContext=b;var i=r(c("../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={},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,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 f=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(p)||this._localStreams.push(p),p.getAudioTracks().forEach(function(v){return g.call(f,v,p)}),p.getVideoTracks().forEach(function(v){return g.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]}),g.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 l(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 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 g=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)}})}),g.apply(p,arguments)}}}function d(y){if(o(y)==="object"&&y.RTCPeerConnection){var g=y.RTCPeerConnection.prototype,p=g.createOffer,f=g.createAnswer,v=g.setLocalDescription,w=g.setRemoteDescription,x=g.addIceCandidate;g.createOffer=function(C,R){var P=arguments.length>=2?arguments[2]:arguments[0],S=p.apply(this,[P]);return R?(S.then(C,R),Promise.resolve()):S},g.createAnswer=function(C,R){var P=arguments.length>=2?arguments[2]:arguments[0],S=f.apply(this,[P]);return R?(S.then(C,R),Promise.resolve()):S};var T=function(C,R,P){var S=v.apply(this,[C]);return P?(S.then(R,P),Promise.resolve()):S};g.setLocalDescription=T,T=function(C,R,P){var S=w.apply(this,[C]);return P?(S.then(R,P),Promise.resolve()):S},g.setRemoteDescription=T,T=function(C,R,P){var S=x.apply(this,[C]);return P?(S.then(R,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,f=p.getUserMedia.bind(p);g.mediaDevices.getUserMedia=function(v){return f(u(v))}}!g.getUserMedia&&g.mediaDevices&&g.mediaDevices.getUserMedia&&(g.getUserMedia=function(v,w,x){g.mediaDevices.getUserMedia(v).then(w,x)}.bind(g))}function u(y){return y&&y.video!==void 0?Object.assign({},y,{video:i.compactObject(y.video)}):y}function h(y){if(y.RTCPeerConnection){var g=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 g(p,f)},y.RTCPeerConnection.prototype=g.prototype,"generateCertificate"in g&&Object.defineProperty(y.RTCPeerConnection,"generateCertificate",{get:function(){return g.generateCertificate}})}}function m(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 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 g.apply(this,arguments)}}function b(y){o(y)!=="object"||y.AudioContext||(y.AudioContext=y.webkitAudioContext)}},{"../utils":"iSxC"}],GOQK:[function(c,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimRTCIceCandidate=d,t.shimMaxMessageSize=a,t.shimSendThrowTypeError=u,t.shimConnectionState=h,t.removeExtmapAllowMixed=m,t.shimAddIceCandidateNullOrEmpty=E;var i=s(c("sdp")),n=o(c("./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 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(g,f,v):g[f]=b[f]}return g.default=b,y&&y.set(b,g),g}function s(b){return b&&b.__esModule?b:{default:b}}function l(b){return(l=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(l(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),f=i.default.parseCandidate(g.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(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(M){var I=i.default.parseMLine(M);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 M=parseInt(S[1],10);return M!=M?-1:M}(arguments[0]),w=(C=v,R=65536,y.browser==="firefox"&&(R=y.version<57?C===-1?16384:2147483637:y.version<60?y.version===57?65535:65536:2147483637),R),x=function(P,S){var M=65536;y.browser==="firefox"&&y.version===57&&(M=65535);var I=i.default.matchPrefix(P.sdp,"a=max-message-size:");return I.length>0?M=parseInt(I[0].substr(19),10):y.browser==="firefox"&&S!==-1&&(M=2147483637),M}(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 C,R;return g.apply(this,arguments)}}}function u(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,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 h(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(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 m(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 f=p.sdp.split(`
67
+ `)}});var v=new u.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 C=m.transceivers[x];if(!C)return w(a("OperationError","Can not add ICE candidate"));if(C.rejected)return v();var R=Object.keys(g.candidate).length>0?i.parseCandidate(g.candidate):{};if(R.protocol==="tcp"&&(R.port===0||R.port===9)||R.component&&R.component!==1)return v();if((x===0||x>0&&C.iceTransport!==m.transceivers[0].iceTransport)&&!d(C.iceTransport,R))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="+(R.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 u.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=u[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=u,t.shimReplaceTrack=h,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 u(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 h(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={},u=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var h in c)if(Object.prototype.hasOwnProperty.call(c,h)){var f=u?Object.getOwnPropertyDescriptor(c,h):null;f&&(f.get||f.set)?Object.defineProperty(a,h,f):a[h]=c[h]}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,u=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 h=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)),h(y.audio,"autoGainControl","mozAutoGainControl"),h(y.audio,"noiseSuppression","mozNoiseSuppression")),f(y)},u&&u.prototype.getSettings){var E=u.prototype.getSettings;u.prototype.getSettings=function(){var y=E.apply(this,arguments);return h(y,"mozAutoGainControl","autoGainControl"),h(y,"mozNoiseSuppression","noiseSuppression"),y}}if(u&&u.prototype.applyConstraints){var b=u.prototype.applyConstraints;u.prototype.applyConstraints=function(y){return this.kind==="audio"&&o(y)==="object"&&(y=JSON.parse(JSON.stringify(y)),h(y,"autoGainControl","mozAutoGainControl"),h(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=u,t.shimSenderGetStats=h,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 C in v)if(Object.prototype.hasOwnProperty.call(v,C)){var R=T?Object.getOwnPropertyDescriptor(v,C):null;R&&(R.get||R.set)?Object.defineProperty(x,C,R):x[C]=v[C]}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 u(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(C){var R=v.RTCPeerConnection.prototype[C],P=c({},C,function(){return arguments[0]=new(C==="addIceCandidate"?v.RTCIceCandidate:v.RTCSessionDescription)(arguments[0]),R.apply(this,arguments)});v.RTCPeerConnection.prototype[C]=P[C]});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[C,R,P]=arguments;return T.apply(this,[C||null]).then(function(S){if(w.version<53&&!R)try{S.forEach(function(M){M.type=x[M.type]||M.type})}catch(M){if(M.name!=="TypeError")throw M;S.forEach(function(I,j){S.set(j,Object.assign({},I,{type:x[I.type]||I.type}))})}return S}).then(R,P)}}}function h(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,C=w.apply(this,[]);return C.forEach(function(R){return R._pc=T}),C});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(C){return C._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 C=w.apply(this,arguments);if(T){var{sender:R}=C,P=R.getParameters();"encodings"in P&&(P.encodings.length!==1||Object.keys(P.encodings[0]).length!==0)||(P.encodings=x.sendEncodings,R.sendEncodings=x.sendEncodings,this.setParametersPromises.push(R.setParameters(P).then(function(){delete R.sendEncodings}).catch(function(){delete R.sendEncodings})))}return C})}}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=u,t.shimRTCIceServerUrls=h,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(C,R){var P=arguments.length>=2?arguments[2]:arguments[0],S=p.apply(this,[P]);return R?(S.then(C,R),Promise.resolve()):S},g.createAnswer=function(C,R){var P=arguments.length>=2?arguments[2]:arguments[0],S=m.apply(this,[P]);return R?(S.then(C,R),Promise.resolve()):S};var T=function(C,R,P){var S=v.apply(this,[C]);return P?(S.then(R,P),Promise.resolve()):S};g.setLocalDescription=T,T=function(C,R,P){var S=w.apply(this,[C]);return P?(S.then(R,P),Promise.resolve()):S},g.setRemoteDescription=T,T=function(C,R,P){var S=x.apply(this,[C]);return P?(S.then(R,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(u(v))}}!g.getUserMedia&&g.mediaDevices&&g.mediaDevices.getUserMedia&&(g.getUserMedia=function(v,w,x){g.mediaDevices.getUserMedia(v).then(w,x)}.bind(g))}function u(y){return y&&y.video!==void 0?Object.assign({},y,{video:i.compactObject(y.video)}):y}function h(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=u,t.shimConnectionState=h,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(M){var I=i.default.parseMLine(M);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 M=parseInt(S[1],10);return M!=M?-1:M}(arguments[0]),w=(C=v,R=65536,y.browser==="firefox"&&(R=y.version<57?C===-1?16384:2147483637:y.version<60?y.version===57?65535:65536:2147483637),R),x=function(P,S){var M=65536;y.browser==="firefox"&&y.version===57&&(M=65535);var I=i.default.matchPrefix(P.sdp,"a=max-message-size:");return I.length>0?M=parseInt(I[0].substr(19),10):y.browser==="firefox"&&S!==-1&&(M=2147483637),M}(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 C,R;return g.apply(this,arguments)}}}function u(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 h(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 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(c,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.adapterFactory=u;var i=a(c("./utils")),n=a(c("./chrome/chrome_shim")),r=a(c("./edge/edge_shim")),o=a(c("./firefox/firefox_shim")),s=a(c("./safari/safari_shim")),l=a(c("./common_shim"));function d(){if(typeof WeakMap!="function")return null;var h=new WeakMap;return d=function(){return h},h}function a(h){if(h&&h.__esModule)return h;if(h===null||typeof h!="object"&&typeof h!="function")return{default:h};var m=d();if(m&&m.has(h))return m.get(h);var E={},b=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var y in h)if(Object.prototype.hasOwnProperty.call(h,y)){var g=b?Object.getOwnPropertyDescriptor(h,y):null;g&&(g.get||g.set)?Object.defineProperty(E,y,g):E[y]=h[y]}return E.default=h,m&&m.set(h,E),E}function u(){var{window:h}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},m=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0},E=i.log,b=i.detectBrowser(h),y={browserDetails:b,commonShim:l,extractVersion:i.extractVersion,disableLog:i.disableLog,disableWarnings:i.disableWarnings};switch(b.browser){case"chrome":if(!n||!n.shimPeerConnection||!m.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,l.shimAddIceCandidateNullOrEmpty(h,b),n.shimGetUserMedia(h,b),n.shimMediaStream(h,b),n.shimPeerConnection(h,b),n.shimOnTrack(h,b),n.shimAddTrackRemoveTrack(h,b),n.shimGetSendersWithDtmf(h,b),n.shimGetStats(h,b),n.shimSenderReceiverGetStats(h,b),n.fixNegotiationNeeded(h,b),l.shimRTCIceCandidate(h,b),l.shimConnectionState(h,b),l.shimMaxMessageSize(h,b),l.shimSendThrowTypeError(h,b),l.removeExtmapAllowMixed(h,b);break;case"firefox":if(!o||!o.shimPeerConnection||!m.shimFirefox)return E("Firefox shim is not included in this adapter release."),y;E("adapter.js shimming firefox."),y.browserShim=o,l.shimAddIceCandidateNullOrEmpty(h,b),o.shimGetUserMedia(h,b),o.shimPeerConnection(h,b),o.shimOnTrack(h,b),o.shimRemoveStream(h,b),o.shimSenderGetStats(h,b),o.shimReceiverGetStats(h,b),o.shimRTCDataChannel(h,b),o.shimAddTransceiver(h,b),o.shimGetParameters(h,b),o.shimCreateOffer(h,b),o.shimCreateAnswer(h,b),l.shimRTCIceCandidate(h,b),l.shimConnectionState(h,b),l.shimMaxMessageSize(h,b),l.shimSendThrowTypeError(h,b);break;case"edge":if(!r||!r.shimPeerConnection||!m.shimEdge)return E("MS edge shim is not included in this adapter release."),y;E("adapter.js shimming edge."),y.browserShim=r,r.shimGetUserMedia(h,b),r.shimGetDisplayMedia(h,b),r.shimPeerConnection(h,b),r.shimReplaceTrack(h,b),l.shimMaxMessageSize(h,b),l.shimSendThrowTypeError(h,b);break;case"safari":if(!s||!m.shimSafari)return E("Safari shim is not included in this adapter release."),y;E("adapter.js shimming safari."),y.browserShim=s,l.shimAddIceCandidateNullOrEmpty(h,b),s.shimRTCIceServerUrls(h,b),s.shimCreateOfferLegacy(h,b),s.shimCallbacksAPI(h,b),s.shimLocalStreamsAPI(h,b),s.shimRemoteStreamsAPI(h,b),s.shimTrackEventTransceiver(h,b),s.shimGetUserMedia(h,b),s.shimAudioContext(h,b),l.shimRTCIceCandidate(h,b),l.shimMaxMessageSize(h,b),l.shimSendThrowTypeError(h,b),l.removeExtmapAllowMixed(h,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(c,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var i=c("./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(c,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(c("webrtc-adapter"));t.webRTCAdapter=n.default},{"webrtc-adapter":"tI1X"}],I31f:[function(c,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Supports=void 0;var i=c("./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 l=!1;try{(r=new RTCPeerConnection).addTransceiver("audio"),l=!0}catch{}finally{r&&r.close()}return l},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=u;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 h=new WeakMap;return d=function(){return h},h}function a(h){if(h&&h.__esModule)return h;if(h===null||typeof h!="object"&&typeof h!="function")return{default:h};var f=d();if(f&&f.has(h))return f.get(h);var E={},b=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var y in h)if(Object.prototype.hasOwnProperty.call(h,y)){var g=b?Object.getOwnPropertyDescriptor(h,y):null;g&&(g.get||g.set)?Object.defineProperty(E,y,g):E[y]=h[y]}return E.default=h,f&&f.set(h,E),E}function u(){var{window:h}=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(h),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(h,b),n.shimGetUserMedia(h,b),n.shimMediaStream(h,b),n.shimPeerConnection(h,b),n.shimOnTrack(h,b),n.shimAddTrackRemoveTrack(h,b),n.shimGetSendersWithDtmf(h,b),n.shimGetStats(h,b),n.shimSenderReceiverGetStats(h,b),n.fixNegotiationNeeded(h,b),c.shimRTCIceCandidate(h,b),c.shimConnectionState(h,b),c.shimMaxMessageSize(h,b),c.shimSendThrowTypeError(h,b),c.removeExtmapAllowMixed(h,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(h,b),o.shimGetUserMedia(h,b),o.shimPeerConnection(h,b),o.shimOnTrack(h,b),o.shimRemoveStream(h,b),o.shimSenderGetStats(h,b),o.shimReceiverGetStats(h,b),o.shimRTCDataChannel(h,b),o.shimAddTransceiver(h,b),o.shimGetParameters(h,b),o.shimCreateOffer(h,b),o.shimCreateAnswer(h,b),c.shimRTCIceCandidate(h,b),c.shimConnectionState(h,b),c.shimMaxMessageSize(h,b),c.shimSendThrowTypeError(h,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(h,b),r.shimGetDisplayMedia(h,b),r.shimPeerConnection(h,b),r.shimReplaceTrack(h,b),c.shimMaxMessageSize(h,b),c.shimSendThrowTypeError(h,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(h,b),s.shimRTCIceServerUrls(h,b),s.shimCreateOfferLegacy(h,b),s.shimCallbacksAPI(h,b),s.shimLocalStreamsAPI(h,b),s.shimRemoteStreamsAPI(h,b),s.shimTrackEventTransceiver(h,b),s.shimGetUserMedia(h,b),s.shimAudioContext(h,b),c.shimRTCIceCandidate(h,b),c.shimMaxMessageSize(h,b),c.shimSendThrowTypeError(h,b),c.removeExtmapAllowMixed(h,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(c,e,t){"use strict";var i=this&&this.__createBinding||(Object.create?function(d,a,u,h){h===void 0&&(h=u),Object.defineProperty(d,h,{enumerable:!0,get:function(){return a[u]}})}:function(d,a,u,h){h===void 0&&(h=u),d[h]=a[u]}),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 u in d)u!=="default"&&Object.prototype.hasOwnProperty.call(d,u)&&i(a,d,u);return n(a,d),a};Object.defineProperty(t,"__esModule",{value:!0}),t.util=void 0;var o=r(c("peerjs-js-binarypack")),s=c("./supports"),l={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=l,this.browser=s.Supports.getBrowser(),this.browserVersion=s.Supports.getVersion(),this.supports=function(){var a,u={browser:s.Supports.isBrowserSupported(),webRTC:s.Supports.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!u.webRTC)return u;try{a=new RTCPeerConnection(l),u.audioVideo=!0;var h=void 0;try{h=a.createDataChannel("_PEERJSTEST",{ordered:!0}),u.data=!0,u.reliable=!!h.ordered;try{h.binaryType="blob",u.binaryBlob=!s.Supports.isIOS}catch{}}catch{}finally{h&&h.close()}}catch{}finally{a&&a.close()}return u}(),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 u=[],h=a.size,m=Math.ceil(h/t.util.chunkedMTU),E=0,b=0;b<h;){var y=Math.min(h,b+t.util.chunkedMTU),g=a.slice(b,y),p={__peerData:this._dataCount,n:E,data:g,total:m};u.push(p),b=y,E++}return this._dataCount++,u},d.prototype.blobToArrayBuffer=function(a,u){var h=new FileReader;return h.onload=function(m){m.target&&u(m.target.result)},h.readAsArrayBuffer(a),h},d.prototype.binaryStringToArrayBuffer=function(a){for(var u=new Uint8Array(a.length),h=0;h<a.length;h++)u[h]=255&a.charCodeAt(h);return u.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(c,e,t){"use strict";var i=Object.prototype.hasOwnProperty,n="~";function r(){}function o(a,u,h){this.fn=a,this.context=u,this.once=h||!1}function s(a,u,h,m,E){if(typeof h!="function")throw new TypeError("The listener must be a function");var b=new o(h,m||a,E),y=n?n+u:u;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 l(a,u){--a._eventsCount==0?a._events=new r:delete a._events[u]}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,u,h=[];if(this._eventsCount===0)return h;for(u in a=this._events)i.call(a,u)&&h.push(n?u.slice(1):u);return Object.getOwnPropertySymbols?h.concat(Object.getOwnPropertySymbols(a)):h},d.prototype.listeners=function(a){var u=n?n+a:a,h=this._events[u];if(!h)return[];if(h.fn)return[h.fn];for(var m=0,E=h.length,b=new Array(E);m<E;m++)b[m]=h[m].fn;return b},d.prototype.listenerCount=function(a){var u=n?n+a:a,h=this._events[u];return h?h.fn?1:h.length:0},d.prototype.emit=function(a,u,h,m,E,b){var y=n?n+a:a;if(!this._events[y])return!1;var g,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,u),!0;case 3:return f.fn.call(f.context,u,h),!0;case 4:return f.fn.call(f.context,u,h,m),!0;case 5:return f.fn.call(f.context,u,h,m,E),!0;case 6:return f.fn.call(f.context,u,h,m,E,b),!0}for(p=1,g=new Array(v-1);p<v;p++)g[p-1]=arguments[p];f.fn.apply(f.context,g)}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,u);break;case 3:f[p].fn.call(f[p].context,u,h);break;case 4:f[p].fn.call(f[p].context,u,h,m);break;default:if(!g)for(w=1,g=new Array(v-1);w<v;w++)g[w-1]=arguments[w];f[p].fn.apply(f[p].context,g)}}return!0},d.prototype.on=function(a,u,h){return s(this,a,u,h,!1)},d.prototype.once=function(a,u,h){return s(this,a,u,h,!0)},d.prototype.removeListener=function(a,u,h,m){var E=n?n+a:a;if(!this._events[E])return this;if(!u)return l(this,E),this;var b=this._events[E];if(b.fn)b.fn!==u||m&&!b.once||h&&b.context!==h||l(this,E);else{for(var y=0,g=[],p=b.length;y<p;y++)(b[y].fn!==u||m&&!b[y].once||h&&b[y].context!==h)&&g.push(b[y]);g.length?this._events[E]=g.length===1?g[0]:g:l(this,E)}return this},d.prototype.removeAllListeners=function(a){var u;return a?(u=n?n+a:a,this._events[u]&&l(this,u)):(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(c,e,t){"use strict";var i=this&&this.__read||function(l,d){var a=typeof Symbol=="function"&&l[Symbol.iterator];if(!a)return l;var u,h,m=a.call(l),E=[];try{for(;(d===void 0||d-- >0)&&!(u=m.next()).done;)E.push(u.value)}catch(b){h={error:b}}finally{try{u&&!u.done&&(a=m.return)&&a.call(m)}finally{if(h)throw h.error}}return E},n=this&&this.__spreadArray||function(l,d){for(var a=0,u=d.length,h=l.length;a<u;a++,h++)l[h]=d[a];return l};Object.defineProperty(t,"__esModule",{value:!0}),t.LogLevel=void 0;var r,o="PeerJS: ";(function(l){l[l.Disabled=0]="Disabled",l[l.Errors=1]="Errors",l[l.Warnings=2]="Warnings",l[l.All=3]="All"})(r=t.LogLevel||(t.LogLevel={}));var s=function(){function l(){this._logLevel=r.Disabled}return Object.defineProperty(l.prototype,"logLevel",{get:function(){return this._logLevel},set:function(d){this._logLevel=d},enumerable:!1,configurable:!0}),l.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)))},l.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)))},l.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)))},l.prototype.setLogFunction=function(d){this._print=d},l.prototype._print=function(d){for(var a=[],u=1;u<arguments.length;u++)a[u-1]=arguments[u];var h=n([o],i(a));for(var m in h)h[m]instanceof Error&&(h[m]="("+h[m].name+") "+h[m].message);d>=r.All?console.log.apply(console,n([],i(h))):d>=r.Warnings?console.warn.apply(console,n(["WARNING"],i(h))):d>=r.Errors&&console.error.apply(console,n(["ERROR"],i(h)))},l}();t.default=new s},{}],ZRYf:[function(c,e,t){"use strict";var i,n,r,o,s,l,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"}(l=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(c,e,t){"use strict";var i=this&&this.__extends||function(){var h=function(m,E){return(h=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])})(m,E)};return function(m,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=m}h(m,E),m.prototype=E===null?Object.create(E):(b.prototype=E.prototype,new b)}}(),n=this&&this.__read||function(h,m){var E=typeof Symbol=="function"&&h[Symbol.iterator];if(!E)return h;var b,y,g=E.call(h),p=[];try{for(;(m===void 0||m-- >0)&&!(b=g.next()).done;)p.push(b.value)}catch(f){y={error:f}}finally{try{b&&!b.done&&(E=g.return)&&E.call(g)}finally{if(y)throw y.error}}return p},r=this&&this.__spreadArray||function(h,m){for(var E=0,b=m.length,y=h.length;E<b;E++,y++)h[y]=m[E];return h},o=this&&this.__values||function(h){var m=typeof Symbol=="function"&&Symbol.iterator,E=m&&h[m],b=0;if(E)return E.call(h);if(h&&typeof h.length=="number")return{next:function(){return h&&b>=h.length&&(h=void 0),{value:h&&h[b++],done:!h}}};throw new TypeError(m?"Object is not iterable.":"Symbol.iterator is not defined.")},s=this&&this.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(t,"__esModule",{value:!0}),t.Socket=void 0;var l=c("eventemitter3"),d=s(c("./logger")),a=c("./enums"),u=function(h){function m(E,b,y,g,p,f){f===void 0&&(f=5e3);var v=h.call(this)||this;v.pingInterval=f,v._disconnected=!0,v._messagesQueue=[];var w=E?"wss://":"ws://";return v._baseUrl=w+b+":"+y+g+"peerjs?key="+p,v}return i(m,h),m.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 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())})},m.prototype._scheduleHeartbeat=function(){var E=this;this._wsPingTimer=setTimeout(function(){E._sendHeartbeat()},this.pingInterval)},m.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")},m.prototype._wsOpen=function(){return!!this._socket&&this._socket.readyState===1},m.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 f=p.value;this.send(f)}}catch(v){E={error:v}}finally{try{p&&!p.done&&(b=g.return)&&b.call(g)}finally{if(E)throw E.error}}},m.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)},m.prototype.close=function(){this._disconnected||(this._cleanup(),this._disconnected=!0)},m.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)},m}(l.EventEmitter);t.Socket=u},{eventemitter3:"JJlS","./logger":"WOs9","./enums":"ZRYf"}],HCdX:[function(c,e,t){"use strict";var i=this&&this.__assign||function(){return(i=Object.assign||function(u){for(var h,m=1,E=arguments.length;m<E;m++)for(var b in h=arguments[m])Object.prototype.hasOwnProperty.call(h,b)&&(u[b]=h[b]);return u}).apply(this,arguments)},n=this&&this.__awaiter||function(u,h,m,E){return new(m||(m=Promise))(function(b,y){function g(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 m?w:new m(function(x){x(w)})).then(g,p)}f((E=E.apply(u,h||[])).next())})},r=this&&this.__generator||function(u,h){var m,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(f){return function(v){return function(w){if(m)throw new TypeError("Generator is already executing.");for(;g;)try{if(m=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=h.call(u,g)}catch(x){w=[6,x],E=0}finally{m=b=0}if(5&w[0])throw w[1];return{value:w[0]?w[1]:void 0,done:!0}}([f,v])}}},o=this&&this.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(t,"__esModule",{value:!0}),t.Negotiator=void 0;var s=c("./util"),l=o(c("./logger")),d=c("./enums"),a=function(){function u(h){this.connection=h}return u.prototype.startConnection=function(h){var m=this._startPeerConnection();if(this.connection.peerConnection=m,this.connection.type===d.ConnectionType.Media&&h._stream&&this._addTracksToConnection(h._stream,m),h.originator){if(this.connection.type===d.ConnectionType.Data){var E=this.connection,b={ordered:!!h.reliable},y=m.createDataChannel(E.label,b);E.initialize(y)}this._makeOffer()}else this.handleSDP("OFFER",h.sdp)},u.prototype._startPeerConnection=function(){l.default.log("Creating RTCPeerConnection.");var h=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(h),h},u.prototype._setupListeners=function(h){var m=this,E=this.connection.peer,b=this.connection.connectionId,y=this.connection.type,g=this.connection.provider;l.default.log("Listening for ICE candidates."),h.onicecandidate=function(p){p.candidate&&p.candidate.candidate&&(l.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}))},h.oniceconnectionstatechange=function(){switch(h.iceConnectionState){case"failed":l.default.log("iceConnectionState is failed, closing connections to "+E),m.connection.emit(d.ConnectionEventType.Error,new Error("Negotiation of connection to "+E+" failed.")),m.connection.close();break;case"closed":l.default.log("iceConnectionState is closed, closing connections to "+E),m.connection.emit(d.ConnectionEventType.Error,new Error("Connection to "+E+" closed.")),m.connection.close();break;case"disconnected":l.default.log("iceConnectionState changed to disconnected on the connection with "+E);break;case"completed":h.onicecandidate=s.util.noop}m.connection.emit(d.ConnectionEventType.IceStateChanged,h.iceConnectionState)},l.default.log("Listening for data channel"),h.ondatachannel=function(p){l.default.log("Received data channel");var f=p.channel;g.getConnection(E,b).initialize(f)},l.default.log("Listening for remote stream"),h.ontrack=function(p){l.default.log("Received remote stream");var f=p.streams[0],v=g.getConnection(E,b);if(v.type===d.ConnectionType.Media){var w=v;m._addStreamToMediaConnection(f,w)}}},u.prototype.cleanup=function(){l.default.log("Cleaning up PeerConnection to "+this.connection.peer);var h=this.connection.peerConnection;if(h){this.connection.peerConnection=null,h.onicecandidate=h.oniceconnectionstatechange=h.ondatachannel=h.ontrack=function(){};var m=h.signalingState!=="closed",E=!1;if(this.connection.type===d.ConnectionType.Data){var b=this.connection.dataChannel;b&&(E=!!b.readyState&&b.readyState!=="closed")}(m||E)&&h.close()}},u.prototype._makeOffer=function(){return n(this,void 0,Promise,function(){var h,m,E,b,y,g,p;return r(this,function(f){switch(f.label){case 0:h=this.connection.peerConnection,m=this.connection.provider,f.label=1;case 1:return f.trys.push([1,7,,8]),[4,h.createOffer(this.connection.options.constraints)];case 2:E=f.sent(),l.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,h.setLocalDescription(E)];case 4:return f.sent(),l.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})),m.socket.send({type:d.ServerMessageType.Offer,payload:b,dst:this.connection.peer}),[3,6];case 5:return(g=f.sent())!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(m.emitError(d.PeerErrorType.WebRTC,g),l.default.log("Failed to setLocalDescription, ",g)),[3,6];case 6:return[3,8];case 7:return p=f.sent(),m.emitError(d.PeerErrorType.WebRTC,p),l.default.log("Failed to createOffer, ",p),[3,8];case 8:return[2]}})})},u.prototype._makeAnswer=function(){return n(this,void 0,Promise,function(){var h,m,E,b,y;return r(this,function(g){switch(g.label){case 0:h=this.connection.peerConnection,m=this.connection.provider,g.label=1;case 1:return g.trys.push([1,7,,8]),[4,h.createAnswer()];case 2:E=g.sent(),l.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,h.setLocalDescription(E)];case 4:return g.sent(),l.default.log("Set localDescription:",E,"for:"+this.connection.peer),m.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(),m.emitError(d.PeerErrorType.WebRTC,b),l.default.log("Failed to setLocalDescription, ",b),[3,6];case 6:return[3,8];case 7:return y=g.sent(),m.emitError(d.PeerErrorType.WebRTC,y),l.default.log("Failed to create answer, ",y),[3,8];case 8:return[2]}})})},u.prototype.handleSDP=function(h,m){return n(this,void 0,Promise,function(){var E,b,y,g;return r(this,function(p){switch(p.label){case 0:m=new RTCSessionDescription(m),E=this.connection.peerConnection,b=this.connection.provider,l.default.log("Setting remote description",m),y=this,p.label=1;case 1:return p.trys.push([1,5,,6]),[4,E.setRemoteDescription(m)];case 2:return p.sent(),l.default.log("Set remoteDescription:"+h+" for:"+this.connection.peer),h!=="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),l.default.log("Failed to setRemoteDescription, ",g),[3,6];case 6:return[2]}})})},u.prototype.handleCandidate=function(h){return n(this,void 0,Promise,function(){var m,E,b,y,g,p;return r(this,function(f){switch(f.label){case 0:l.default.log("handleCandidate:",h),m=h.candidate,E=h.sdpMLineIndex,b=h.sdpMid,y=this.connection.peerConnection,g=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:m}))];case 2:return f.sent(),l.default.log("Added ICE candidate for:"+this.connection.peer),[3,4];case 3:return p=f.sent(),g.emitError(d.PeerErrorType.WebRTC,p),l.default.log("Failed to handleCandidate, ",p),[3,4];case 4:return[2]}})})},u.prototype._addTracksToConnection=function(h,m){if(l.default.log("add tracks from stream "+h.id+" to peer connection"),!m.addTrack)return l.default.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");h.getTracks().forEach(function(E){m.addTrack(E,h)})},u.prototype._addStreamToMediaConnection=function(h,m){l.default.log("add stream "+h.id+" to media connection "+m.connectionId),m.addStream(h)},u}();t.Negotiator=a},{"./util":"BHXf","./logger":"WOs9","./enums":"ZRYf"}],tQFK:[function(c,e,t){"use strict";var i=this&&this.__extends||function(){var o=function(s,l){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,a){d.__proto__=a}||function(d,a){for(var u in a)Object.prototype.hasOwnProperty.call(a,u)&&(d[u]=a[u])})(s,l)};return function(s,l){if(typeof l!="function"&&l!==null)throw new TypeError("Class extends value "+String(l)+" is not a constructor or null");function d(){this.constructor=s}o(s,l),s.prototype=l===null?Object.create(l):(d.prototype=l.prototype,new d)}}();Object.defineProperty(t,"__esModule",{value:!0}),t.BaseConnection=void 0;var n=c("eventemitter3"),r=function(o){function s(l,d,a){var u=o.call(this)||this;return u.peer=l,u.provider=d,u.options=a,u._open=!1,u.metadata=a.metadata,u}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(c,e,t){"use strict";var i=this&&this.__extends||function(){var m=function(E,b){return(m=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}m(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(m){for(var E,b=1,y=arguments.length;b<y;b++)for(var g in E=arguments[b])Object.prototype.hasOwnProperty.call(E,g)&&(m[g]=E[g]);return m}).apply(this,arguments)},r=this&&this.__values||function(m){var E=typeof Symbol=="function"&&Symbol.iterator,b=E&&m[E],y=0;if(b)return b.call(m);if(m&&typeof m.length=="number")return{next:function(){return m&&y>=m.length&&(m=void 0),{value:m&&m[y++],done:!m}}};throw new TypeError(E?"Object is not iterable.":"Symbol.iterator is not defined.")},o=this&&this.__importDefault||function(m){return m&&m.__esModule?m:{default:m}};Object.defineProperty(t,"__esModule",{value:!0}),t.MediaConnection=void 0;var s=c("./util"),l=o(c("./logger")),d=c("./negotiator"),a=c("./enums"),u=c("./baseconnection"),h=function(m){function E(b,y,g){var p=m.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,m),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){l.default.log("Receiving stream",b),this._remoteStream=b,m.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:l.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)l.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){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,m.prototype.emit.call(this,a.ConnectionEventType.Close))},E.ID_PREFIX="mc_",E}(u.BaseConnection);t.MediaConnection=h},{"./util":"BHXf","./logger":"WOs9","./negotiator":"HCdX","./enums":"ZRYf","./baseconnection":"tQFK"}],GGp6:[function(c,e,t){"use strict";var i=this&&this.__extends||function(){var l=function(d,a){return(l=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(u,h){u.__proto__=h}||function(u,h){for(var m in h)Object.prototype.hasOwnProperty.call(h,m)&&(u[m]=h[m])})(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 u(){this.constructor=d}l(d,a),d.prototype=a===null?Object.create(a):(u.prototype=a.prototype,new u)}}(),n=this&&this.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(t,"__esModule",{value:!0}),t.EncodingQueue=void 0;var r=c("eventemitter3"),o=n(c("./logger")),s=function(l){function d(){var a=l.call(this)||this;return a.fileReader=new FileReader,a._queue=[],a._processing=!1,a.fileReader.onload=function(u){a._processing=!1,u.target&&a.emit("done",u.target.result),a.doNextTask()},a.fileReader.onerror=function(u){o.default.error("EncodingQueue error:",u),a._processing=!1,a.destroy(),a.emit("error",u)},a}return i(d,l),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(c,e,t){"use strict";var i=this&&this.__extends||function(){var m=function(E,b){return(m=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}m(E,b),E.prototype=b===null?Object.create(b):(y.prototype=b.prototype,new y)}}(),n=this&&this.__values||function(m){var E=typeof Symbol=="function"&&Symbol.iterator,b=E&&m[E],y=0;if(b)return b.call(m);if(m&&typeof m.length=="number")return{next:function(){return m&&y>=m.length&&(m=void 0),{value:m&&m[y++],done:!m}}};throw new TypeError(E?"Object is not iterable.":"Symbol.iterator is not defined.")},r=this&&this.__importDefault||function(m){return m&&m.__esModule?m:{default:m}};Object.defineProperty(t,"__esModule",{value:!0}),t.DataConnection=void 0;var o=c("./util"),s=r(c("./logger")),l=c("./negotiator"),d=c("./enums"),a=c("./baseconnection"),u=c("./encodingQueue"),h=function(m){function E(b,y,g){var p=m.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 u.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(f){p._bufferedSend(f)}),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 l.Negotiator(p),p._negotiator.startConnection(p.options._payload||{originator:!0}),p}return i(E,m),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,f=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)f=o.util.unpack(g);else if(p===String){var v=o.util.binaryStringToArrayBuffer(g);f=o.util.unpack(v)}}else this.serialization===d.SerializationType.JSON&&(f=this.parse(g));f.__peerData?this._handleChunk(f):m.prototype.emit.call(this,d.ConnectionEventType.Data,f)},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,m.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 m.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 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&&(g=f.return)&&g.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: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=h},{"./util":"BHXf","./logger":"WOs9","./negotiator":"HCdX","./enums":"ZRYf","./baseconnection":"tQFK","./encodingQueue":"GGp6"}],in7L:[function(c,e,t){"use strict";var i=this&&this.__awaiter||function(d,a,u,h){return new(u||(u=Promise))(function(m,E){function b(p){try{g(h.next(p))}catch(f){E(f)}}function y(p){try{g(h.throw(p))}catch(f){E(f)}}function g(p){var f;p.done?m(p.value):(f=p.value,f instanceof u?f:new u(function(v){v(f)})).then(b,y)}g((h=h.apply(d,a||[])).next())})},n=this&&this.__generator||function(d,a){var u,h,m,E,b={label:0,sent:function(){if(1&m[0])throw m[1];return m[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(f){if(u)throw new TypeError("Generator is already executing.");for(;b;)try{if(u=1,h&&(m=2&f[0]?h.return:f[0]?h.throw||((m=h.return)&&m.call(h),0):h.next)&&!(m=m.call(h,f[1])).done)return m;switch(h=0,m&&(f=[2&f[0],m.value]),f[0]){case 0:case 1:m=f;break;case 4:return b.label++,{value:f[1],done:!1};case 5:b.label++,h=f[1],f=[0];continue;case 7:f=b.ops.pop(),b.trys.pop();continue;default:if(!(m=(m=b.trys).length>0&&m[m.length-1])&&(f[0]===6||f[0]===2)){b=0;continue}if(f[0]===3&&(!m||f[1]>m[0]&&f[1]<m[3])){b.label=f[1];break}if(f[0]===6&&b.label<m[1]){b.label=m[1],m=f;break}if(m&&b.label<m[2]){b.label=m[2],b.ops.push(f);break}m[2]&&b.ops.pop(),b.trys.pop();continue}f=a.call(d,b)}catch(v){f=[6,v],h=0}finally{u=m=0}if(5&f[0])throw f[1];return{value:f[0]?f[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=c("./util"),s=r(c("./logger")),l=function(){function d(a){this._options=a}return d.prototype._buildUrl=function(a){var u=(this._options.secure?"https://":"http://")+this._options.host+":"+this._options.port+this._options.path+this._options.key+"/"+a;return u+="?ts="+new Date().getTime()+Math.random()},d.prototype.retrieveId=function(){return i(this,void 0,Promise,function(){var a,u,h,m;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((u=E.sent()).status!==200)throw new Error("Error. Status:"+u.status);return[2,u.text()];case 3:throw h=E.sent(),s.default.error("Error retrieving ID",h),m="",this._options.path==="/"&&this._options.host!==o.util.CLOUD_HOST&&(m=" 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."+m);case 4:return[2]}})})},d.prototype.listAllPeers=function(){return i(this,void 0,Promise,function(){var a,u,h,m;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((u=E.sent()).status!==200)throw u.status===401?(h="",h=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. "+h)):new Error("Error. Status:"+u.status);return[2,u.json()];case 3:throw m=E.sent(),s.default.error("Error retrieving list peers",m),new Error("Could not get list peers from the server."+m);case 4:return[2]}})})},d}();t.API=l},{"./util":"BHXf","./logger":"WOs9"}],Hxpd:[function(c,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.")},o=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),C=[];try{for(;(f===void 0||f-- >0)&&!(w=T.next()).done;)C.push(w.value)}catch(R){x={error:R}}finally{try{w&&!w.done&&(v=T.return)&&v.call(T)}finally{if(x)throw x.error}}return C},s=this&&this.__importDefault||function(p){return p&&p.__esModule?p:{default:p}};Object.defineProperty(t,"__esModule",{value:!0}),t.Peer=void 0;var l=c("eventemitter3"),d=c("./util"),a=s(c("./logger")),u=c("./socket"),h=c("./mediaconnection"),m=c("./dataconnection"),E=c("./enums"),b=c("./api"),y=function(){return function(){}}(),g=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(C){return T._initialize(C)}).catch(function(C){return T._abort(E.PeerErrorType.ServerError,C)}),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),C=T.next();!C.done;C=T.next()){var R=o(C.value,2),P=R[0],S=R[1];x[P]=S}}catch(M){v={error:M}}finally{try{C&&!C.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 u.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,C=v.payload,R=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,C.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 "+R),this._cleanupPeer(R),this._connections.delete(R);break;case E.ServerMessageType.Expire:this.emitError(E.PeerErrorType.PeerUnavailable,"Could not connect to peer "+R);break;case E.ServerMessageType.Offer:var P=C.connectionId;if((H=this.getConnection(R,P))&&(H.close(),a.default.warn("Offer received for existing Connection ID:"+P)),C.type===E.ConnectionType.Media)H=new h.MediaConnection(R,this,{connectionId:P,_payload:C,metadata:C.metadata}),this._addConnection(R,H),this.emit(E.PeerEventType.Call,H);else{if(C.type!==E.ConnectionType.Data)return void a.default.warn("Received malformed connection type:"+C.type);H=new m.DataConnection(R,this,{connectionId:P,_payload:C,metadata:C.metadata,label:C.label,serialization:C.serialization,reliable:C.reliable}),this._addConnection(R,H),this.emit(E.PeerEventType.Connection,H)}var S=this._getMessages(P);try{for(var M=r(S),I=M.next();!I.done;I=M.next()){var j=I.value;H.handleMessage(j)}}catch(N){w={error:N}}finally{try{I&&!I.done&&(x=M.return)&&x.call(M)}finally{if(w)throw w.error}}break;default:if(!C)return void a.default.warn("You received a malformed message from "+R+" of type "+T);var H;P=C.connectionId,(H=this.getConnection(R,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 m.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 h.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,C=this._connections.get(v);if(!C)return null;try{for(var R=r(C),P=R.next();!P.done;P=R.next()){var S=P.value;if(S.connectionId===w)return S}}catch(M){x={error:M}}finally{try{P&&!P.done&&(T=R.return)&&T.call(R)}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 C=T.value;this._cleanupPeer(C),this._connections.delete(C)}}catch(R){v={error:R}}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 C=r(T),R=C.next();!R.done;R=C.next())R.value.close()}catch(P){w={error:P}}finally{try{R&&!R.done&&(x=C.return)&&x.call(C)}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}(l.EventEmitter);t.Peer=g},{eventemitter3:"JJlS","./util":"BHXf","./logger":"WOs9","./socket":"wJlv","./mediaconnection":"dbHP","./dataconnection":"GBTQ","./enums":"ZRYf","./api":"in7L"}],iTK6:[function(c,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.peerjs=void 0;var i=c("./util"),n=c("./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 ep=Jo((Nx,$u)=>{(function(){var c="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(c.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((c.indexOf(t.charAt(n-1))&Math.pow(2,-2*r+8)-1)<<r*2|c.indexOf(t.charAt(n))>>>6-r*2);return i}};$u.exports=e})()});var _c=Jo((zx,tp)=>{var wc={utf8:{stringToBytes:function(c){return wc.bin.stringToBytes(unescape(encodeURIComponent(c)))},bytesToString:function(c){return decodeURIComponent(escape(wc.bin.bytesToString(c)))}},bin:{stringToBytes:function(c){for(var e=[],t=0;t<c.length;t++)e.push(c.charCodeAt(t)&255);return e},bytesToString:function(c){for(var e=[],t=0;t<c.length;t++)e.push(String.fromCharCode(c[t]));return e.join("")}}};tp.exports=wc});var rp=Jo((Ux,np)=>{np.exports=function(c){return c!=null&&(ip(c)||zb(c)||!!c._isBuffer)};function ip(c){return!!c.constructor&&typeof c.constructor.isBuffer=="function"&&c.constructor.isBuffer(c)}function zb(c){return typeof c.readFloatLE=="function"&&typeof c.slice=="function"&&ip(c.slice(0,0))}});var sp=Jo((Vx,op)=>{(function(){var c=ep(),e=_c().utf8,t=rp(),i=_c().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=c.bytesToWords(r),l=r.length*8,d=1732584193,a=-271733879,u=-1732584194,h=271733878,m=0;m<s.length;m++)s[m]=(s[m]<<8|s[m]>>>24)&16711935|(s[m]<<24|s[m]>>>8)&4278255360;s[l>>>5]|=128<<l%32,s[(l+64>>>9<<4)+14]=l;for(var E=n._ff,b=n._gg,y=n._hh,g=n._ii,m=0;m<s.length;m+=16){var p=d,f=a,v=u,w=h;d=E(d,a,u,h,s[m+0],7,-680876936),h=E(h,d,a,u,s[m+1],12,-389564586),u=E(u,h,d,a,s[m+2],17,606105819),a=E(a,u,h,d,s[m+3],22,-1044525330),d=E(d,a,u,h,s[m+4],7,-176418897),h=E(h,d,a,u,s[m+5],12,1200080426),u=E(u,h,d,a,s[m+6],17,-1473231341),a=E(a,u,h,d,s[m+7],22,-45705983),d=E(d,a,u,h,s[m+8],7,1770035416),h=E(h,d,a,u,s[m+9],12,-1958414417),u=E(u,h,d,a,s[m+10],17,-42063),a=E(a,u,h,d,s[m+11],22,-1990404162),d=E(d,a,u,h,s[m+12],7,1804603682),h=E(h,d,a,u,s[m+13],12,-40341101),u=E(u,h,d,a,s[m+14],17,-1502002290),a=E(a,u,h,d,s[m+15],22,1236535329),d=b(d,a,u,h,s[m+1],5,-165796510),h=b(h,d,a,u,s[m+6],9,-1069501632),u=b(u,h,d,a,s[m+11],14,643717713),a=b(a,u,h,d,s[m+0],20,-373897302),d=b(d,a,u,h,s[m+5],5,-701558691),h=b(h,d,a,u,s[m+10],9,38016083),u=b(u,h,d,a,s[m+15],14,-660478335),a=b(a,u,h,d,s[m+4],20,-405537848),d=b(d,a,u,h,s[m+9],5,568446438),h=b(h,d,a,u,s[m+14],9,-1019803690),u=b(u,h,d,a,s[m+3],14,-187363961),a=b(a,u,h,d,s[m+8],20,1163531501),d=b(d,a,u,h,s[m+13],5,-1444681467),h=b(h,d,a,u,s[m+2],9,-51403784),u=b(u,h,d,a,s[m+7],14,1735328473),a=b(a,u,h,d,s[m+12],20,-1926607734),d=y(d,a,u,h,s[m+5],4,-378558),h=y(h,d,a,u,s[m+8],11,-2022574463),u=y(u,h,d,a,s[m+11],16,1839030562),a=y(a,u,h,d,s[m+14],23,-35309556),d=y(d,a,u,h,s[m+1],4,-1530992060),h=y(h,d,a,u,s[m+4],11,1272893353),u=y(u,h,d,a,s[m+7],16,-155497632),a=y(a,u,h,d,s[m+10],23,-1094730640),d=y(d,a,u,h,s[m+13],4,681279174),h=y(h,d,a,u,s[m+0],11,-358537222),u=y(u,h,d,a,s[m+3],16,-722521979),a=y(a,u,h,d,s[m+6],23,76029189),d=y(d,a,u,h,s[m+9],4,-640364487),h=y(h,d,a,u,s[m+12],11,-421815835),u=y(u,h,d,a,s[m+15],16,530742520),a=y(a,u,h,d,s[m+2],23,-995338651),d=g(d,a,u,h,s[m+0],6,-198630844),h=g(h,d,a,u,s[m+7],10,1126891415),u=g(u,h,d,a,s[m+14],15,-1416354905),a=g(a,u,h,d,s[m+5],21,-57434055),d=g(d,a,u,h,s[m+12],6,1700485571),h=g(h,d,a,u,s[m+3],10,-1894986606),u=g(u,h,d,a,s[m+10],15,-1051523),a=g(a,u,h,d,s[m+1],21,-2054922799),d=g(d,a,u,h,s[m+8],6,1873313359),h=g(h,d,a,u,s[m+15],10,-30611744),u=g(u,h,d,a,s[m+6],15,-1560198380),a=g(a,u,h,d,s[m+13],21,1309151649),d=g(d,a,u,h,s[m+4],6,-145523070),h=g(h,d,a,u,s[m+11],10,-1120210379),u=g(u,h,d,a,s[m+2],15,718787259),a=g(a,u,h,d,s[m+9],21,-343485551),d=d+p>>>0,a=a+f>>>0,u=u+v>>>0,h=h+w>>>0}return c.endian([d,a,u,h])};n._ff=function(r,o,s,l,d,a,u){var h=r+(o&s|~o&l)+(d>>>0)+u;return(h<<a|h>>>32-a)+o},n._gg=function(r,o,s,l,d,a,u){var h=r+(o&l|s&~l)+(d>>>0)+u;return(h<<a|h>>>32-a)+o},n._hh=function(r,o,s,l,d,a,u){var h=r+(o^s^l)+(d>>>0)+u;return(h<<a|h>>>32-a)+o},n._ii=function(r,o,s,l,d,a,u){var h=r+(s^(o|~l))+(d>>>0)+u;return(h<<a|h>>>32-a)+o},n._blocksize=16,n._digestsize=16,op.exports=function(r,o){if(r==null)throw new Error("Illegal argument "+r);var s=c.wordsToBytes(n(r,o));return o&&o.asBytes?s:o&&o.asString?i.bytesToString(s):c.bytesToHex(s)}})()});import{DepthTexture as rv,WebGLRenderer as ov}from"three";import*as Oe from"three";import*as Ut from"three";var Ol=()=>c=>c;var kl=!1,Sl=[];setTimeout(()=>{kl&&console.log(Sl)},100);function Al(){return new URLSearchParams(window.location.search)}function B(c){kl&&!Sl.includes(c)&&Sl.push(c);let e=Al();if(e.has(c)){let t=e.get(c);return t||!0}return!1}kl=B("help")===!0;function jr(c,e,t){c.has(e)?c.set(e,t.toString()):c.append(e,t.toString())}function ph(c,e){window.history.replaceState(null,c,"?"+e.toString())}function fh(c,e){return Math.floor(Math.random()*(e-c+1))+c}var hh=["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"],uh=["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 mh(){let c=hh[Math.floor(Math.random()*hh.length)],e=uh[Math.floor(Math.random()*uh.length)];return c+"_"+e}function gh(c){return c=c.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),c.trim()}function Qn(c,e,t=!0,i=!1){if(e==null)return null;if(e.userData&&e.userData.guid===c)return e;if(e.guid==c)return e;if(i&&e.userData?.components){for(let n of e.userData.components)if(n.guid===c)return n}if(t){if(e.scenes)for(let n in e.scenes){let r=e.scenes[n],o=Qn(c,r,t,i);if(o)return o}if(e.children)for(let n in e.children){let r=e.children[n],o=Qn(c,r,t,i);if(o)return o}}}function Zo(c,e){if(c!=null&&typeof c=="object"){let t;Array.isArray(c)?t=[]:(t=Object.create(c),Object.assign(t,c));for(let i of Object.keys(c)){let n=c[i];e&&!e(c,i,n)?t[i]=n:n?.clone!==void 0&&typeof n.clone=="function"?t[i]=n.clone():t[i]=Zo(n,e)}return t}return c}function bh(c){return new Promise((e,t)=>{setTimeout(e,c)})}var Rl=B("debugsourcepath");function un(c,e){if(c===void 0)return Rl&&console.warn("getPath: source is undefined, returning uri",e),e;if(e.startsWith("http"))return Rl&&console.warn("getPath: uri is absolute, returning uri",e),e;let t=c.lastIndexOf("/");if(t>=0){let i=c.substring(0,t+1),n=e.lastIndexOf("/");return n>=0?i+=e.substring(n+1):i+=e,Rl&&console.log("getPath:",c,` - changed uri from
78
+ isUnifiedPlanSupported:`+this.isUnifiedPlanSupported()},n}())},{"./adapter":"sXtV"}],BHXf:[function(l,e,t){"use strict";var i=this&&this.__createBinding||(Object.create?function(d,a,u,h){h===void 0&&(h=u),Object.defineProperty(d,h,{enumerable:!0,get:function(){return a[u]}})}:function(d,a,u,h){h===void 0&&(h=u),d[h]=a[u]}),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 u in d)u!=="default"&&Object.prototype.hasOwnProperty.call(d,u)&&i(a,d,u);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,u={browser:s.Supports.isBrowserSupported(),webRTC:s.Supports.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!u.webRTC)return u;try{a=new RTCPeerConnection(c),u.audioVideo=!0;var h=void 0;try{h=a.createDataChannel("_PEERJSTEST",{ordered:!0}),u.data=!0,u.reliable=!!h.ordered;try{h.binaryType="blob",u.binaryBlob=!s.Supports.isIOS}catch{}}catch{}finally{h&&h.close()}}catch{}finally{a&&a.close()}return u}(),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 u=[],h=a.size,f=Math.ceil(h/t.util.chunkedMTU),E=0,b=0;b<h;){var y=Math.min(h,b+t.util.chunkedMTU),g=a.slice(b,y),p={__peerData:this._dataCount,n:E,data:g,total:f};u.push(p),b=y,E++}return this._dataCount++,u},d.prototype.blobToArrayBuffer=function(a,u){var h=new FileReader;return h.onload=function(f){f.target&&u(f.target.result)},h.readAsArrayBuffer(a),h},d.prototype.binaryStringToArrayBuffer=function(a){for(var u=new Uint8Array(a.length),h=0;h<a.length;h++)u[h]=255&a.charCodeAt(h);return u.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,u,h){this.fn=a,this.context=u,this.once=h||!1}function s(a,u,h,f,E){if(typeof h!="function")throw new TypeError("The listener must be a function");var b=new o(h,f||a,E),y=n?n+u:u;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,u){--a._eventsCount==0?a._events=new r:delete a._events[u]}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,u,h=[];if(this._eventsCount===0)return h;for(u in a=this._events)i.call(a,u)&&h.push(n?u.slice(1):u);return Object.getOwnPropertySymbols?h.concat(Object.getOwnPropertySymbols(a)):h},d.prototype.listeners=function(a){var u=n?n+a:a,h=this._events[u];if(!h)return[];if(h.fn)return[h.fn];for(var f=0,E=h.length,b=new Array(E);f<E;f++)b[f]=h[f].fn;return b},d.prototype.listenerCount=function(a){var u=n?n+a:a,h=this._events[u];return h?h.fn?1:h.length:0},d.prototype.emit=function(a,u,h,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,u),!0;case 3:return m.fn.call(m.context,u,h),!0;case 4:return m.fn.call(m.context,u,h,f),!0;case 5:return m.fn.call(m.context,u,h,f,E),!0;case 6:return m.fn.call(m.context,u,h,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,u);break;case 3:m[p].fn.call(m[p].context,u,h);break;case 4:m[p].fn.call(m[p].context,u,h,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,u,h){return s(this,a,u,h,!1)},d.prototype.once=function(a,u,h){return s(this,a,u,h,!0)},d.prototype.removeListener=function(a,u,h,f){var E=n?n+a:a;if(!this._events[E])return this;if(!u)return c(this,E),this;var b=this._events[E];if(b.fn)b.fn!==u||f&&!b.once||h&&b.context!==h||c(this,E);else{for(var y=0,g=[],p=b.length;y<p;y++)(b[y].fn!==u||f&&!b[y].once||h&&b[y].context!==h)&&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 u;return a?(u=n?n+a:a,this._events[u]&&c(this,u)):(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 u,h,f=a.call(c),E=[];try{for(;(d===void 0||d-- >0)&&!(u=f.next()).done;)E.push(u.value)}catch(b){h={error:b}}finally{try{u&&!u.done&&(a=f.return)&&a.call(f)}finally{if(h)throw h.error}}return E},n=this&&this.__spreadArray||function(c,d){for(var a=0,u=d.length,h=c.length;a<u;a++,h++)c[h]=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=[],u=1;u<arguments.length;u++)a[u-1]=arguments[u];var h=n([o],i(a));for(var f in h)h[f]instanceof Error&&(h[f]="("+h[f].name+") "+h[f].message);d>=r.All?console.log.apply(console,n([],i(h))):d>=r.Warnings?console.warn.apply(console,n(["WARNING"],i(h))):d>=r.Errors&&console.error.apply(console,n(["ERROR"],i(h)))},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 h=function(f,E){return(h=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}h(f,E),f.prototype=E===null?Object.create(E):(b.prototype=E.prototype,new b)}}(),n=this&&this.__read||function(h,f){var E=typeof Symbol=="function"&&h[Symbol.iterator];if(!E)return h;var b,y,g=E.call(h),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(h,f){for(var E=0,b=f.length,y=h.length;E<b;E++,y++)h[y]=f[E];return h},o=this&&this.__values||function(h){var f=typeof Symbol=="function"&&Symbol.iterator,E=f&&h[f],b=0;if(E)return E.call(h);if(h&&typeof h.length=="number")return{next:function(){return h&&b>=h.length&&(h=void 0),{value:h&&h[b++],done:!h}}};throw new TypeError(f?"Object is not iterable.":"Symbol.iterator is not defined.")},s=this&&this.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(t,"__esModule",{value:!0}),t.Socket=void 0;var c=l("eventemitter3"),d=s(l("./logger")),a=l("./enums"),u=function(h){function f(E,b,y,g,p,m){m===void 0&&(m=5e3);var v=h.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,h),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=u},{eventemitter3:"JJlS","./logger":"WOs9","./enums":"ZRYf"}],HCdX:[function(l,e,t){"use strict";var i=this&&this.__assign||function(){return(i=Object.assign||function(u){for(var h,f=1,E=arguments.length;f<E;f++)for(var b in h=arguments[f])Object.prototype.hasOwnProperty.call(h,b)&&(u[b]=h[b]);return u}).apply(this,arguments)},n=this&&this.__awaiter||function(u,h,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(u,h||[])).next())})},r=this&&this.__generator||function(u,h){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=h.call(u,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(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(t,"__esModule",{value:!0}),t.Negotiator=void 0;var s=l("./util"),c=o(l("./logger")),d=l("./enums"),a=function(){function u(h){this.connection=h}return u.prototype.startConnection=function(h){var f=this._startPeerConnection();if(this.connection.peerConnection=f,this.connection.type===d.ConnectionType.Media&&h._stream&&this._addTracksToConnection(h._stream,f),h.originator){if(this.connection.type===d.ConnectionType.Data){var E=this.connection,b={ordered:!!h.reliable},y=f.createDataChannel(E.label,b);E.initialize(y)}this._makeOffer()}else this.handleSDP("OFFER",h.sdp)},u.prototype._startPeerConnection=function(){c.default.log("Creating RTCPeerConnection.");var h=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(h),h},u.prototype._setupListeners=function(h){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."),h.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}))},h.oniceconnectionstatechange=function(){switch(h.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":h.onicecandidate=s.util.noop}f.connection.emit(d.ConnectionEventType.IceStateChanged,h.iceConnectionState)},c.default.log("Listening for data channel"),h.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"),h.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)}}},u.prototype.cleanup=function(){c.default.log("Cleaning up PeerConnection to "+this.connection.peer);var h=this.connection.peerConnection;if(h){this.connection.peerConnection=null,h.onicecandidate=h.oniceconnectionstatechange=h.ondatachannel=h.ontrack=function(){};var f=h.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)&&h.close()}},u.prototype._makeOffer=function(){return n(this,void 0,Promise,function(){var h,f,E,b,y,g,p;return r(this,function(m){switch(m.label){case 0:h=this.connection.peerConnection,f=this.connection.provider,m.label=1;case 1:return m.trys.push([1,7,,8]),[4,h.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,h.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]}})})},u.prototype._makeAnswer=function(){return n(this,void 0,Promise,function(){var h,f,E,b,y;return r(this,function(g){switch(g.label){case 0:h=this.connection.peerConnection,f=this.connection.provider,g.label=1;case 1:return g.trys.push([1,7,,8]),[4,h.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,h.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]}})})},u.prototype.handleSDP=function(h,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:"+h+" for:"+this.connection.peer),h!=="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]}})})},u.prototype.handleCandidate=function(h){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:",h),f=h.candidate,E=h.sdpMLineIndex,b=h.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]}})})},u.prototype._addTracksToConnection=function(h,f){if(c.default.log("add tracks from stream "+h.id+" to peer connection"),!f.addTrack)return c.default.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");h.getTracks().forEach(function(E){f.addTrack(E,h)})},u.prototype._addStreamToMediaConnection=function(h,f){c.default.log("add stream "+h.id+" to media connection "+f.connectionId),f.addStream(h)},u}();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 u in a)Object.prototype.hasOwnProperty.call(a,u)&&(d[u]=a[u])})(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 u=o.call(this)||this;return u.peer=c,u.provider=d,u.options=a,u._open=!1,u.metadata=a.metadata,u}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"),u=l("./baseconnection"),h=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}(u.BaseConnection);t.MediaConnection=h},{"./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(u,h){u.__proto__=h}||function(u,h){for(var f in h)Object.prototype.hasOwnProperty.call(h,f)&&(u[f]=h[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 u(){this.constructor=d}c(d,a),d.prototype=a===null?Object.create(a):(u.prototype=a.prototype,new u)}}(),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(u){a._processing=!1,u.target&&a.emit("done",u.target.result),a.doNextTask()},a.fileReader.onerror=function(u){o.default.error("EncodingQueue error:",u),a._processing=!1,a.destroy(),a.emit("error",u)},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"),u=l("./encodingQueue"),h=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 u.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=h},{"./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,u,h){return new(u||(u=Promise))(function(f,E){function b(p){try{g(h.next(p))}catch(m){E(m)}}function y(p){try{g(h.throw(p))}catch(m){E(m)}}function g(p){var m;p.done?f(p.value):(m=p.value,m instanceof u?m:new u(function(v){v(m)})).then(b,y)}g((h=h.apply(d,a||[])).next())})},n=this&&this.__generator||function(d,a){var u,h,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(u)throw new TypeError("Generator is already executing.");for(;b;)try{if(u=1,h&&(f=2&m[0]?h.return:m[0]?h.throw||((f=h.return)&&f.call(h),0):h.next)&&!(f=f.call(h,m[1])).done)return f;switch(h=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++,h=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],h=0}finally{u=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 u=(this._options.secure?"https://":"http://")+this._options.host+":"+this._options.port+this._options.path+this._options.key+"/"+a;return u+="?ts="+new Date().getTime()+Math.random()},d.prototype.retrieveId=function(){return i(this,void 0,Promise,function(){var a,u,h,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((u=E.sent()).status!==200)throw new Error("Error. Status:"+u.status);return[2,u.text()];case 3:throw h=E.sent(),s.default.error("Error retrieving ID",h),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,u,h,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((u=E.sent()).status!==200)throw u.status===401?(h="",h=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. "+h)):new Error("Error. Status:"+u.status);return[2,u.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),C=[];try{for(;(m===void 0||m-- >0)&&!(w=T.next()).done;)C.push(w.value)}catch(R){x={error:R}}finally{try{w&&!w.done&&(v=T.return)&&v.call(T)}finally{if(x)throw x.error}}return C},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")),u=l("./socket"),h=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(C){return T._initialize(C)}).catch(function(C){return T._abort(E.PeerErrorType.ServerError,C)}),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),C=T.next();!C.done;C=T.next()){var R=o(C.value,2),P=R[0],S=R[1];x[P]=S}}catch(M){v={error:M}}finally{try{C&&!C.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 u.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,C=v.payload,R=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,C.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 "+R),this._cleanupPeer(R),this._connections.delete(R);break;case E.ServerMessageType.Expire:this.emitError(E.PeerErrorType.PeerUnavailable,"Could not connect to peer "+R);break;case E.ServerMessageType.Offer:var P=C.connectionId;if((L=this.getConnection(R,P))&&(L.close(),a.default.warn("Offer received for existing Connection ID:"+P)),C.type===E.ConnectionType.Media)L=new h.MediaConnection(R,this,{connectionId:P,_payload:C,metadata:C.metadata}),this._addConnection(R,L),this.emit(E.PeerEventType.Call,L);else{if(C.type!==E.ConnectionType.Data)return void a.default.warn("Received malformed connection type:"+C.type);L=new f.DataConnection(R,this,{connectionId:P,_payload:C,metadata:C.metadata,label:C.label,serialization:C.serialization,reliable:C.reliable}),this._addConnection(R,L),this.emit(E.PeerEventType.Connection,L)}var S=this._getMessages(P);try{for(var M=r(S),I=M.next();!I.done;I=M.next()){var j=I.value;L.handleMessage(j)}}catch(F){w={error:F}}finally{try{I&&!I.done&&(x=M.return)&&x.call(M)}finally{if(w)throw w.error}}break;default:if(!C)return void a.default.warn("You received a malformed message from "+R+" of type "+T);var L;P=C.connectionId,(L=this.getConnection(R,P))&&L.peerConnection?L.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 h.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,C=this._connections.get(v);if(!C)return null;try{for(var R=r(C),P=R.next();!P.done;P=R.next()){var S=P.value;if(S.connectionId===w)return S}}catch(M){x={error:M}}finally{try{P&&!P.done&&(T=R.return)&&T.call(R)}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 C=T.value;this._cleanupPeer(C),this._connections.delete(C)}}catch(R){v={error:R}}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 C=r(T),R=C.next();!R.done;R=C.next())R.value.close()}catch(P){w={error:P}}finally{try{R&&!R.done&&(x=C.return)&&x.call(C)}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 Gu=Kr((ux,Wu)=>{(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}};Wu.exports=e})()});var dc=Kr((px,qu)=>{var cc={utf8:{stringToBytes:function(l){return cc.bin.stringToBytes(unescape(encodeURIComponent(l)))},bytesToString:function(l){return decodeURIComponent(escape(cc.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("")}}};qu.exports=cc});var Yu=Kr((fx,Qu)=>{Qu.exports=function(l){return l!=null&&(Xu(l)||Mb(l)||!!l._isBuffer)};function Xu(l){return!!l.constructor&&typeof l.constructor.isBuffer=="function"&&l.constructor.isBuffer(l)}function Mb(l){return typeof l.readFloatLE=="function"&&typeof l.slice=="function"&&Xu(l.slice(0,0))}});var Ju=Kr((mx,Ku)=>{(function(){var l=Gu(),e=dc().utf8,t=Yu(),i=dc().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,u=-1732584194,h=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=u,w=h;d=E(d,a,u,h,s[f+0],7,-680876936),h=E(h,d,a,u,s[f+1],12,-389564586),u=E(u,h,d,a,s[f+2],17,606105819),a=E(a,u,h,d,s[f+3],22,-1044525330),d=E(d,a,u,h,s[f+4],7,-176418897),h=E(h,d,a,u,s[f+5],12,1200080426),u=E(u,h,d,a,s[f+6],17,-1473231341),a=E(a,u,h,d,s[f+7],22,-45705983),d=E(d,a,u,h,s[f+8],7,1770035416),h=E(h,d,a,u,s[f+9],12,-1958414417),u=E(u,h,d,a,s[f+10],17,-42063),a=E(a,u,h,d,s[f+11],22,-1990404162),d=E(d,a,u,h,s[f+12],7,1804603682),h=E(h,d,a,u,s[f+13],12,-40341101),u=E(u,h,d,a,s[f+14],17,-1502002290),a=E(a,u,h,d,s[f+15],22,1236535329),d=b(d,a,u,h,s[f+1],5,-165796510),h=b(h,d,a,u,s[f+6],9,-1069501632),u=b(u,h,d,a,s[f+11],14,643717713),a=b(a,u,h,d,s[f+0],20,-373897302),d=b(d,a,u,h,s[f+5],5,-701558691),h=b(h,d,a,u,s[f+10],9,38016083),u=b(u,h,d,a,s[f+15],14,-660478335),a=b(a,u,h,d,s[f+4],20,-405537848),d=b(d,a,u,h,s[f+9],5,568446438),h=b(h,d,a,u,s[f+14],9,-1019803690),u=b(u,h,d,a,s[f+3],14,-187363961),a=b(a,u,h,d,s[f+8],20,1163531501),d=b(d,a,u,h,s[f+13],5,-1444681467),h=b(h,d,a,u,s[f+2],9,-51403784),u=b(u,h,d,a,s[f+7],14,1735328473),a=b(a,u,h,d,s[f+12],20,-1926607734),d=y(d,a,u,h,s[f+5],4,-378558),h=y(h,d,a,u,s[f+8],11,-2022574463),u=y(u,h,d,a,s[f+11],16,1839030562),a=y(a,u,h,d,s[f+14],23,-35309556),d=y(d,a,u,h,s[f+1],4,-1530992060),h=y(h,d,a,u,s[f+4],11,1272893353),u=y(u,h,d,a,s[f+7],16,-155497632),a=y(a,u,h,d,s[f+10],23,-1094730640),d=y(d,a,u,h,s[f+13],4,681279174),h=y(h,d,a,u,s[f+0],11,-358537222),u=y(u,h,d,a,s[f+3],16,-722521979),a=y(a,u,h,d,s[f+6],23,76029189),d=y(d,a,u,h,s[f+9],4,-640364487),h=y(h,d,a,u,s[f+12],11,-421815835),u=y(u,h,d,a,s[f+15],16,530742520),a=y(a,u,h,d,s[f+2],23,-995338651),d=g(d,a,u,h,s[f+0],6,-198630844),h=g(h,d,a,u,s[f+7],10,1126891415),u=g(u,h,d,a,s[f+14],15,-1416354905),a=g(a,u,h,d,s[f+5],21,-57434055),d=g(d,a,u,h,s[f+12],6,1700485571),h=g(h,d,a,u,s[f+3],10,-1894986606),u=g(u,h,d,a,s[f+10],15,-1051523),a=g(a,u,h,d,s[f+1],21,-2054922799),d=g(d,a,u,h,s[f+8],6,1873313359),h=g(h,d,a,u,s[f+15],10,-30611744),u=g(u,h,d,a,s[f+6],15,-1560198380),a=g(a,u,h,d,s[f+13],21,1309151649),d=g(d,a,u,h,s[f+4],6,-145523070),h=g(h,d,a,u,s[f+11],10,-1120210379),u=g(u,h,d,a,s[f+2],15,718787259),a=g(a,u,h,d,s[f+9],21,-343485551),d=d+p>>>0,a=a+m>>>0,u=u+v>>>0,h=h+w>>>0}return l.endian([d,a,u,h])};n._ff=function(r,o,s,c,d,a,u){var h=r+(o&s|~o&c)+(d>>>0)+u;return(h<<a|h>>>32-a)+o},n._gg=function(r,o,s,c,d,a,u){var h=r+(o&c|s&~c)+(d>>>0)+u;return(h<<a|h>>>32-a)+o},n._hh=function(r,o,s,c,d,a,u){var h=r+(o^s^c)+(d>>>0)+u;return(h<<a|h>>>32-a)+o},n._ii=function(r,o,s,c,d,a,u){var h=r+(s^(o|~c))+(d>>>0)+u;return(h<<a|h>>>32-a)+o},n._blocksize=16,n._digestsize=16,Ku.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 Kb,WebGLRenderer as Jb}from"three";import*as _e from"three";import*as Tt from"three";var bl=()=>l=>l;var vl=!1,ml=[];setTimeout(()=>{vl&&console.log(ml)},100);function yl(){return new URLSearchParams(window.location.search)}function H(l){vl&&!ml.includes(l)&&ml.push(l);let e=yl();if(e.has(l)){let t=e.get(l);return t||!0}return!1}vl=H("help")===!0;function Kn(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 oh(l){return l=l.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),l.trim()}function ln(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=ln(l,r,t,i);if(o)return o}if(e.children)for(let n in e.children){let r=e.children[n],o=ln(l,r,t,i);if(o)return o}}}function Jr(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]=Jr(n,e)}return t}return l}function sh(l){return new Promise((e,t)=>{setTimeout(e,l)})}var fl=H("debugsourcepath");function Di(l,e){if(l===void 0)return fl&&console.warn("getPath: source is undefined, returning uri",e),e;if(e.startsWith("http"))return fl&&console.warn("getPath: uri is absolute, returning uri",e),e;let t=l.lastIndexOf("/");if(t>=0){let i=l.substring(0,t+1),n=e.lastIndexOf("/");return n>=0?i+=e.substring(n+1):i+=e,fl&&console.log("getPath:",l,` - changed uri from
79
79
  `,e,`
80
- \u2192 `,i),i}return e}var Pl=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}},hn=class{_watches=[];constructor(e,t){if(Array.isArray(t))for(let i of t)this._watches.push(new hn(e,i));else this._watches.push(new Pl(e,t))}subscribeWrite(e){for(let t of this._watches)t.subscribeWrite(e)}apply(){for(let e of this._watches)e.apply()}revoke(){for(let e of this._watches)e.revoke()}dispose(){for(let e of this._watches)e.dispose();this._watches.length=0}};var si=B("gizmos"),tt=B("debugextension");var js=B("debugresolvedependencies"),Af=["/extensions/","extensions/"],If=[{prefix:"/nodes/",dependencyName:"node"},{prefix:"/meshes/",dependencyName:"mesh"},{prefix:"/materials/",dependencyName:"material"},{prefix:"/textures/",dependencyName:"texture"},{prefix:"/animations/",dependencyName:"animation"},{prefix:"nodes/",dependencyName:"node"},{prefix:"meshes/",dependencyName:"mesh"},{prefix:"materials/",dependencyName:"material"},{prefix:"textures/",dependencyName:"texture"},{prefix:"animations/",dependencyName:"animation"}];async function Bs(c,e){js&&console.log(c,e);let t=[];Il(If,c,e,t);let i=await Promise.all(t);return typeof e=="string"&&i.length===1?i[0]:i}function Il(c,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=vh(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 c){let l=Ml(s.prefix,r);if(l>=0){js&&console.log(s,l,s.dependencyName),i.push(e?.getDependency(s.dependencyName,l).then(d=>(t[n]=d,d)));break}}}else if(Array.isArray(r))for(let o=0;o<r.length;o++){let s=r[o],l=vh(e,s);if(l!==null){typeof l.then=="function"?i.push(l.then(d=>r[o]=d)):r[o]=l;continue}for(let d of c){let a=Ml(d.prefix,s);if(a>=0){js&&console.log(d,a,d.dependencyName),i.push(e?.getDependency(d.dependencyName,a).then(u=>r[o]=u));break}}typeof s=="object"&&Il(c,e,s,i)}else typeof r=="object"&&Il(c,e,r,i)}else typeof t=="string"&&Mf(c,e,t,i)}function vh(c,e){if(c&&c.plugins&&typeof e=="string"){for(let t of Af)if(e.startsWith(t)){let i=e.substring(t.length),n=i.indexOf("/");n>=0&&(i=i.substring(0,n));let r=c.plugins[i];if(tt&&console.log(i,r),typeof r?.resolve=="function"){let o=e.substring(t.length+i.length+1);return r.resolve(c,o)}break}}return null}function Mf(c,e,t,i){for(let n of c){let r=Ml(n.prefix,t);if(r>=0)return js&&console.log(n,r,n.dependencyName),i.push(e?.getDependency(n.dependencyName,r).then(o=>o)),!0}return!1}function Ml(c,e){if(typeof e=="string"&&e.startsWith(c)){let t=e.substring(c.length),i=Number.parseInt(t);if(i>=0)return i}return-1}var Dl=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]}},L=new Dl;var Br=B("debugserializer"),Ll=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])}Br&&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){Br&&console.log("invalid type");return}let i=e.name??e.constructor?.name;if(!i){Br&&console.log("invalid name",i);return}let n=this.getSerializer(i);if(n!==void 0)return Br&&console.log("FOUND "+i,e.name,e.constructor.name,n,this.typeMap),n;let r=Object.getPrototypeOf(e);if(!(r.prototype||r.constructor)){Br&&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 l=this.getSerializerForConstructor(s,++t);if(l){Br&&console.log("FOUND "+s.constructor.name,s.name,s,l);let d=s.name??s.constructor.name;d==="Function"?console.error("Registering Function is not allowed, something went wrong",e,s,l):this.register(d,l)}return l}}},yh=new Ll,Di=class{constructor(e){if(Array.isArray(e))for(let t of e)yh.register(t.name,this);else yh.register(e.name,this)}},Fs=class{root;gltf;gltfId;object;target;nodeId;nodeToObject;objectToNode;context;path;constructor(e){this.root=e}};function Ns(c,e){if(e==null||c==null)return;let t=!1;for(let i of Object.keys(e)){let n=Df(c,i);t&&n===void 0||(!n||n.writable===!0||n?.set!==void 0)&&(c[i]=e[i])}}function Df(c,e){let t;do t=Object.getOwnPropertyDescriptor(c,e);while(!t&&(c=Object.getPrototypeOf(c)));return t}var $o=class{key;keyType;source;constructor(e){this.key=e.key,this.keyType=e.type,this.source=e}};var zs=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 Ut.Vector2];_pointerPositionsLastFrame=[new Ut.Vector2];_pointerPositionsDelta=[new Ut.Vector2];_pointerPositionsRC=[new Ut.Vector2];_pointerPositionDown=[new Ut.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 typeof e=="number"&&(console.warn("Use of keycode as number is not recommended, please use KeyCode or string instead"),e=String.fromCharCode(e)),this.context.application.isVisible&&this.context.application.hasFocus&&this.keysPressed[e]?.startFrame===this.context.time.frameCount&&this.keysPressed[e].pressed}isKeyUp(e){return typeof e=="number"&&(console.warn("Use of keycode as number is not recommended, please use KeyCode or string instead"),e=String.fromCharCode(e)),this.context.application.isVisible&&this.context.application.hasFocus&&this.keysPressed[e]?.frame===this.context.time.frameCount&&!this.keysPressed[e].pressed}isKeyPressed(e){return typeof e=="number"&&(e=String.fromCharCode(e)),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.key];t&&t.pressed||(this.keysPressed[e.key]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:e.key},this.onDispatchEvent("keydown",new $o(e)))}onKeyPressed(e){if(!this.context.application.hasFocus)return;let t=this.keysPressed[e.key];!t||(t.pressed=!0,t.frame=this.context.time.frameCount+1,this.onDispatchEvent("keypress",new $o(e)))}onKeyUp(e){if(!this.context.application.hasFocus)return;let t=this.keysPressed[e.key];!t||(t.pressed=!1,t.frame=this.context.time.frameCount+1,this.onDispatchEvent("keyup",new $o(e)))}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;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){if(e.defaultPrevented||e.pointerType===void 0&&e.pointerId===void 0)return;let t=e.pointerType==="mouse"?e.button:this.getPointerIndex(e.pointerId);e.pointerId===void 0&&e.button!==void 0&&(t=e.button),t<0&&(t=0);let i={button:t,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,source:e};this.onMove(i),this.onDispatchEvent("pointermove",e)}onPointerUp(e){if(e.defaultPrevented||e.pointerType===void 0&&e.pointerId===void 0)return;let t=e.pointerType==="mouse"?e.button:this.getPointerIndex(e.pointerId);e.pointerId===void 0&&e.button!==void 0&&(t=e.button),this._pointerIds[t]=-1,this.onUp({button:t,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,source:e}),this.onDispatchEvent("pointerup",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 Ut.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),this.onDispatchEvent("pointerdown",e)}}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 Ut.Vector2);for(;e.button>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new Ut.Vector2);for(;e.button>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new Ut.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 Ut.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}onDispatchEvent(e,t){let i=Z.Current;try{Z.Current=this.context;let n=new Event(e);Ns(n,t),this.dispatchEvent(n)}finally{Z.Current=i}}};var St=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 St){let i=this.elements,n=e.elements,r=t.elements,o=i[0],s=i[1],l=i[2],d=i[3],a=i[4],u=i[5],h=i[6],m=i[7],E=i[8],b=n[0],y=n[1],g=n[2],p=n[3],f=n[4],v=n[5],w=n[6],x=n[7],T=n[8];return r[0]=o*b+s*p+l*w,r[1]=o*y+s*f+l*x,r[2]=o*g+s*v+l*T,r[3]=d*b+a*p+u*w,r[4]=d*y+a*f+u*x,r[5]=d*g+a*v+u*T,r[6]=h*b+m*p+E*w,r[7]=h*y+m*f+E*x,r[8]=h*g+m*v+E*T,t}scale(e,t=new St){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 l=3,d=l,a,u=4,h;do{if(o=d-l,r[o+4*o]===0){for(s=o+1;s<d;s++)if(r[o+4*s]!==0){a=u;do h=u-a,r[h+4*o]+=r[h+4*s];while(--a);break}}if(r[o+4*o]!==0)for(s=o+1;s<d;s++){let m=r[o+4*s]/r[o+4*o];a=u;do h=u-a,r[h+4*s]=h<=o?0:r[h+4*s]-r[h+4*o]*m;while(--a)}}while(--l);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 St){let n=Lf,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,l=s,d,a=6,u;do{if(r=l-s,n[r+6*r]===0){for(o=r+1;o<l;o++)if(n[r+6*o]!==0){d=a;do u=a-d,n[u+6*r]+=n[u+6*o];while(--d);break}}if(n[r+6*r]!==0)for(o=r+1;o<l;o++){let h=n[r+6*o]/n[r+6*r];d=a;do u=a-d,n[u+6*o]=u<=r?0:n[u+6*o]-n[u+6*r]*h;while(--d)}}while(--s);r=2;do{o=r-1;do{let h=n[r+6*o]/n[r+6*r];d=6;do u=6-d,n[u+6*o]=n[u+6*o]-n[u+6*r]*h;while(--d)}while(o--)}while(--r);r=2;do{let h=1/n[r+6*r];d=6;do u=6-d,n[u+6*r]=n[u+6*r]*h;while(--d)}while(r--);r=2;do{o=2;do{if(u=n[3+o+6*r],isNaN(u)||u===1/0)throw"Could not reverse! A=["+this.toString()+"]";e.e(r,o,u)}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,l=n+n,d=t*o,a=t*s,u=t*l,h=i*s,m=i*l,E=n*l,b=r*o,y=r*s,g=r*l,p=this.elements;return p[3*0+0]=1-(h+E),p[3*0+1]=a-g,p[3*0+2]=u+y,p[3*1+0]=a+g,p[3*1+1]=1-(d+E),p[3*1+2]=m-b,p[3*2+0]=u-y,p[3*2+1]=m+b,p[3*2+2]=1-(d+h),this}transpose(e=new St){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}},Lf=[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,l=this.z;return t.x=s*r-l*n,t.y=l*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 St([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=Hf,r=1/i;n.set(this.x*r,this.y*r,this.z*r);let o=jf;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(Eh),Eh.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 Hf=new _,jf=new _,Eh=new _,qe=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 l=1;l<e.length;l++){let d=e[l];s&&(s.vmult(d,wh),d=wh),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 qe().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,l=n.z<=i.z&&i.z<=r.z||t.z<=r.z&&r.z<=i.z;return o&&s&&l}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,l){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),l.copy(a)}toLocalFrame(e,t){let i=_h,n=i[0],r=i[1],o=i[2],s=i[3],l=i[4],d=i[5],a=i[6],u=i[7];this.getCorners(n,r,o,s,l,d,a,u);for(let h=0;h!==8;h++){let m=i[h];e.pointToLocal(m,m)}return t.setFromPoints(i)}toWorldFrame(e,t){let i=_h,n=i[0],r=i[1],o=i[2],s=i[3],l=i[4],d=i[5],a=i[6],u=i[7];this.getCorners(n,r,o,s,l,d,a,u);for(let h=0;h!==8;h++){let m=i[h];e.pointToWorld(m,m)}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,l=(this.upperBound.x-i.x)*n,d=(this.lowerBound.y-i.y)*r,a=(this.upperBound.y-i.y)*r,u=(this.lowerBound.z-i.z)*o,h=(this.upperBound.z-i.z)*o,m=Math.max(Math.max(Math.min(s,l),Math.min(d,a)),Math.min(u,h)),E=Math.min(Math.min(Math.max(s,l),Math.max(d,a)),Math.max(u,h));return!(E<0||m>E)}},wh=new _,_h=[new _,new _,new _,new _,new _,new _,new _,new _],Xs=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}},Qs=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}},ae=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=Bf,n=Ff;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 ae){let i=this.x,n=this.y,r=this.z,o=this.w,s=e.x,l=e.y,d=e.z,a=e.w;return t.x=i*a+o*s+n*d-r*l,t.y=n*a+o*l+r*s-i*d,t.z=r*a+o*d+i*l-n*s,t.w=o*a-i*s-n*l-r*d,t}inverse(e=new ae){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 ae){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,l=this.z,d=this.w,a=d*i+s*r-l*n,u=d*n+l*i-o*r,h=d*r+o*n-s*i,m=-o*i-s*n-l*r;return t.x=a*d+m*-o+u*-l-h*-s,t.y=u*d+m*-s+h*-o-a*-l,t.z=h*d+m*-l+a*-s-u*-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,l=this.z,d=this.w;switch(t){case"YZX":let a=o*s+l*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 u=o*o,h=s*s,m=l*l;i=Math.atan2(2*s*d-2*o*l,1-2*h-2*m),n=Math.asin(2*a),r=Math.atan2(2*o*d-2*s*l,1-2*u-2*m)}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),l=Math.sin(e/2),d=Math.sin(t/2),a=Math.sin(i/2);return n==="XYZ"?(this.x=l*o*s+r*d*a,this.y=r*d*s-l*o*a,this.z=r*o*a+l*d*s,this.w=r*o*s-l*d*a):n==="YXZ"?(this.x=l*o*s+r*d*a,this.y=r*d*s-l*o*a,this.z=r*o*a-l*d*s,this.w=r*o*s+l*d*a):n==="ZXY"?(this.x=l*o*s-r*d*a,this.y=r*d*s+l*o*a,this.z=r*o*a+l*d*s,this.w=r*o*s-l*d*a):n==="ZYX"?(this.x=l*o*s-r*d*a,this.y=r*d*s+l*o*a,this.z=r*o*a-l*d*s,this.w=r*o*s+l*d*a):n==="YZX"?(this.x=l*o*s+r*d*a,this.y=r*d*s+l*o*a,this.z=r*o*a-l*d*s,this.w=r*o*s-l*d*a):n==="XZY"&&(this.x=l*o*s-r*d*a,this.y=r*d*s-l*o*a,this.z=r*o*a+l*d*s,this.w=r*o*s+l*d*a),this}clone(){return new ae(this.x,this.y,this.z,this.w)}slerp(e,t,i=new ae){let n=this.x,r=this.y,o=this.z,s=this.w,l=e.x,d=e.y,a=e.z,u=e.w,h,m,E,b,y;return m=n*l+r*d+o*a+s*u,m<0&&(m=-m,l=-l,d=-d,a=-a,u=-u),1-m>1e-6?(h=Math.acos(m),E=Math.sin(h),b=Math.sin((1-t)*h)/E,y=Math.sin(t*h)/E):(b=1-t,y=t),i.x=b*n+y*l,i.y=b*r+y*d,i.z=b*o+y*a,i.w=b*s+y*u,i}integrate(e,t,i,n=new ae){let r=e.x*i.x,o=e.y*i.y,s=e.z*i.z,l=this.x,d=this.y,a=this.z,u=this.w,h=t*.5;return n.x+=h*(r*u+o*a-s*d),n.y+=h*(o*u+s*l-r*a),n.z+=h*(s*u+r*d-o*l),n.w+=h*(-r*l-o*d-s*a),n}},Bf=new _,Ff=new _,Nf={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=Nf;var te=class{constructor(e={}){this.position=void 0,this.quaternion=void 0,this.position=new _,this.quaternion=new ae,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(xh),xh.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}},xh=new ae,Jn=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 l=0;l!==s;l++){let d=(l+1)%s;t[o[l]].vsub(t[o[d]],n),n.normalize();let a=!1;for(let u=0;u!==i.length;u++)if(i[u].almostEquals(n)||i[u].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]];Jn.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,l,d){let a=new _,u=-1,h=-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>h&&(h=b,u=E)}let m=[];for(let E=0;E<i.faces[u].length;E++){let b=i.vertices[i.faces[u][E]],y=new _;y.copy(b),r.vmult(y,y),n.vadd(y,y),m.push(y)}u>=0&&this.clipFaceAgainstHull(o,e,t,m,s,l,d)}findSeparatingAxis(e,t,i,n,r,o,s,l){let d=new _,a=new _,u=new _,h=new _,m=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 f=s?s[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,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=l?l.length:e.faces.length;for(let p=0;p<g;p++){let f=l?l[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,o.copy(a))}}for(let g=0;g!==y.uniqueEdges.length;g++){i.vmult(y.uniqueEdges[g],h);for(let p=0;p!==e.uniqueEdges.length;p++)if(r.vmult(e.uniqueEdges[p],m),h.cross(m,E),!E.almostZero()){E.normalize();let f=y.testSepAxis(E,e,t,i,n,r);if(f===!1)return!1;f<b&&(b=f,o.copy(E))}}return n.vsub(t,u),u.dot(o)>0&&o.negate(o),!0}testSepAxis(e,t,i,n,r,o){let s=this;Jn.project(s,e,i,n,Hl),Jn.project(t,e,r,o,jl);let l=Hl[0],d=Hl[1],a=jl[0],u=jl[1];if(l<u||a<d)return!1;let h=l-u,m=a-d;return h<m?h:m}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 l=new _,d=new _,a=new _,u=new _,h=new _,m=new _,E=new _,b=new _,y=this,g=[],p=n,f=g,v=-1,w=Number.MAX_VALUE;for(let P=0;P<y.faces.length;P++){l.copy(y.faceNormals[P]),i.vmult(l,l);let S=l.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]],M=y.vertices[x[(P+1)%T]];S.vsub(M,d),a.copy(d),i.vmult(a,a),t.vadd(a,a),u.copy(this.faceNormals[v]),i.vmult(u,u),t.vadd(u,u),a.cross(u,h),h.negate(h),m.copy(S),i.vmult(m,m),t.vadd(m,m);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 C=this.getPlaneConstantOfFace(v);b.copy(E),i.vmult(b,b);let R=C-b.dot(t);for(let P=0;P<p.length;P++){let S=b.dot(p[P])+R;if(S<=r&&(console.log("clamped: depth="+S+" to minDist="+r),S=r),S<=o){let M=p[P];if(S<=1e-6){let I={point:M,normal:b,depth:S};s.push(I)}}}}clipFaceAgainstPlane(e,t,i,n){let r,o,s=e.length;if(s<2)return t;let l=e[e.length-1],d=e[0];r=i.dot(l)+n;for(let a=0;a<s;a++){if(d=e[a],o=i.dot(d)+n,r<0)if(o<0){let u=new _;u.copy(d),t.push(u)}else{let u=new _;l.lerp(d,r/(r-o),u),t.push(u)}else if(o<0){let u=new _;l.lerp(d,r/(r-o),u),t.push(u),t.push(d)}l=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,l,d,a,u,h=new _;for(let m=0;m<r.length;m++){h.copy(r[m]),t.vmult(h,h),e.vadd(h,h);let E=h;(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),(l===void 0||E.z<l)&&(l=E.z),(u===void 0||E.z>u)&&(u=E.z)}i.set(o,s,l),n.set(d,a,u)}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],l=t[i[o][0]],d=new _;e.vsub(l,d);let a=s.dot(d),u=new _;r.vsub(l,u);let h=s.dot(u);if(a<0&&h>0||a>0&&h<0)return!1}return-1}static project(e,t,i,n,r){let o=e.vertices.length,s=zf,l=0,d=0,a=Uf,u=e.vertices;a.setZero(),te.vectorToLocalFrame(i,n,t,s),te.pointToLocalFrame(i,n,a,a);let h=a.dot(s);d=l=u[0].dot(s);for(let m=1;m<o;m++){let E=u[m].dot(s);E>l&&(l=E),E<d&&(d=E)}if(d-=h,l-=h,d>l){let m=d;d=l,l=m}r[0]=l,r[1]=d}},Hl=[],jl=[],zf=new _,Uf=new _,Zn=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)],l=new Jn({vertices:r,faces:o,axes:s});this.convexPolyhedronRepresentation=l,l.material=this.material}calculateLocalInertia(e,t=new _){return Zn.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++)pn.set(r[o][0],r[o][1],r[o][2]),t.vmult(pn,pn),e.vadd(pn,pn),i(pn.x,pn.y,pn.z)}calculateWorldAABB(e,t,i,n){let r=this.halfExtents;ai[0].set(r.x,r.y,r.z),ai[1].set(-r.x,r.y,r.z),ai[2].set(-r.x,-r.y,r.z),ai[3].set(-r.x,-r.y,-r.z),ai[4].set(r.x,-r.y,-r.z),ai[5].set(r.x,r.y,-r.z),ai[6].set(-r.x,r.y,-r.z),ai[7].set(r.x,-r.y,r.z);let o=ai[0];t.vmult(o,o),e.vadd(o,o),n.copy(o),i.copy(o);for(let s=1;s<8;s++){let l=ai[s];t.vmult(l,l),e.vadd(l,l);let d=l.x,a=l.y,u=l.z;d>n.x&&(n.x=d),a>n.y&&(n.y=a),u>n.z&&(n.z=u),d<i.x&&(i.x=d),a<i.y&&(i.y=a),u<i.z&&(i.z=u)}}},pn=new _,ai=[new _,new _,new _,new _,new _,new _,new _,new _],Kl={DYNAMIC:1,STATIC:2,KINEMATIC:4},Jl={AWAKE:0,SLEEPY:1,SLEEPING:2},U=class extends Qs{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=U.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?U.STATIC:U.DYNAMIC,typeof e.type==typeof U.STATIC&&(this.type=e.type),this.allowSleep=typeof e.allowSleep<"u"?e.allowSleep:!0,this.sleepState=U.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 ae,this.initQuaternion=new ae,this.previousQuaternion=new ae,this.interpolatedQuaternion=new ae,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 St,this.invMassSolve=0,this.invInertiaSolve=new _,this.invInertiaWorldSolve=new St,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 qe,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=U.AWAKE,this.wakeUpAfterNarrowphase=!1,e===U.SLEEPING&&this.dispatchEvent(U.wakeupEvent)}sleep(){this.sleepState=U.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===U.AWAKE&&i<n?(this.sleepState=U.SLEEPY,this.timeLastSleepy=e,this.dispatchEvent(U.sleepyEvent)):t===U.SLEEPY&&i>n?this.wakeUp():t===U.SLEEPY&&e-this.timeLastSleepy>this.sleepTimeLimit&&(this.sleep(),this.dispatchEvent(U.sleepEvent))}}updateSolveMassProperties(){this.sleepState===U.SLEEPING||this.type===U.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 ae;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(),l=o.boundingSphereRadius;s+l>n&&(n=s+l)}this.boundingRadius=n}updateAABB(){let e=this.shapes,t=this.shapeOffsets,i=this.shapeOrientations,n=e.length,r=Vf,o=Gf,s=this.quaternion,l=this.aabb,d=Wf;for(let a=0;a!==n;a++){let u=e[a];s.vmult(t[a],r),r.vadd(this.position,r),s.mult(i[a],o),u.calculateWorldAABB(r,o,d.lowerBound,d.upperBound),a===0?l.copy(d):l.extend(d)}this.aabbNeedsUpdate=!1}updateInertiaWorld(e){let t=this.invInertia;if(!(t.x===t.y&&t.y===t.z&&!e)){let i=qf,n=Xf;i.setRotationFromQuaternion(this.quaternion),i.transpose(n),i.scale(t,i),i.mmult(n,this.invInertiaWorld)}}applyForce(e,t=new _){if(this.type!==U.DYNAMIC)return;this.sleepState===U.SLEEPING&&this.wakeUp();let i=Qf;t.cross(e,i),this.force.vadd(e,this.force),this.torque.vadd(i,this.torque)}applyLocalForce(e,t=new _){if(this.type!==U.DYNAMIC)return;let i=Yf,n=Kf;this.vectorToWorldFrame(e,i),this.vectorToWorldFrame(t,n),this.applyForce(i,n)}applyTorque(e){this.type===U.DYNAMIC&&(this.sleepState===U.SLEEPING&&this.wakeUp(),this.torque.vadd(e,this.torque))}applyImpulse(e,t=new _){if(this.type!==U.DYNAMIC)return;this.sleepState===U.SLEEPING&&this.wakeUp();let i=t,n=Jf;n.copy(e),n.scale(this.invMass,n),this.velocity.vadd(n,this.velocity);let r=Zf;i.cross(e,r),this.invInertiaWorld.vmult(r,r),this.angularVelocity.vadd(r,this.angularVelocity)}applyLocalImpulse(e,t=new _){if(this.type!==U.DYNAMIC)return;let i=$f,n=em;this.vectorToWorldFrame(e,i),this.vectorToWorldFrame(t,n),this.applyImpulse(i,n)}updateMassProperties(){let e=tm;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),Zn.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===U.DYNAMIC||this.type===U.KINEMATIC)||this.sleepState===U.SLEEPING)return;let n=this.velocity,r=this.angularVelocity,o=this.position,s=this.force,l=this.torque,d=this.quaternion,a=this.invMass,u=this.invInertiaWorld,h=this.linearFactor,m=a*e;n.x+=s.x*m*h.x,n.y+=s.y*m*h.y,n.z+=s.z*m*h.z;let E=u.elements,b=this.angularFactor,y=l.x*b.x,g=l.y*b.y,p=l.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()}};U.idCounter=0;U.COLLIDE_EVENT_NAME="collide";U.DYNAMIC=Kl.DYNAMIC;U.STATIC=Kl.STATIC;U.KINEMATIC=Kl.KINEMATIC;U.AWAKE=Jl.AWAKE;U.SLEEPY=Jl.SLEEPY;U.SLEEPING=Jl.SLEEPING;U.wakeupEvent={type:"wakeup"};U.sleepyEvent={type:"sleepy"};U.sleepEvent={type:"sleep"};var Vf=new _,Gf=new ae,Wf=new qe,qf=new St,Xf=new St,Qf=new _,Yf=new _,Kf=new _,Jf=new _,Zf=new _,$f=new _,em=new _,tm=new _,zl=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&U.STATIC)!==0||e.sleepState===U.SLEEPING)&&((t.type&U.STATIC)!==0||t.sleepState===U.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=im;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=nm,n=rm,r=om,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 l=n[s].id,d=r[s].id,a=l<d?l+","+d:d+","+l;i[a]=s,i.keys.push(a)}for(let s=0;s!==i.keys.length;s++){let l=i.keys.pop(),d=i[l];e.push(n[d]),t.push(r[d]),delete i[l]}}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."),[]}},im=new _,nm={keys:[]},rm=[],om=[];var dw=new _,Ul=class extends zl{constructor(){super()}collisionPairs(e,t,i){let n=e.bodies,r=n.length,o,s;for(let l=0;l!==r;l++)for(let d=0;d!==l;d++)o=n[l],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}},rs=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}},Lh,Hh,jh,Bh,Fh,Nh,zh,Zl={CLOSEST:1,ANY:2,ALL:4};Lh=V.types.SPHERE;Hh=V.types.PLANE;jh=V.types.BOX;Bh=V.types.CYLINDER;Fh=V.types.CONVEXPOLYHEDRON;Nh=V.types.HEIGHTFIELD;zh=V.types.TRIMESH;var me=class{get[Lh](){return this._intersectSphere}get[Hh](){return this._intersectPlane}get[jh](){return this._intersectBox}get[Bh](){return this._intersectConvex}get[Fh](){return this._intersectConvex}get[Nh](){return this._intersectHeightfield}get[zh](){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=me.ANY,this.result=new rs,this.hasHit=!1,this.callback=i=>{}}intersectWorld(e,t){return this.mode=t.mode||me.ANY,this.result=t.result||new rs,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(Th),Bl.length=0,e.broadphase.aabbQuery(e,Th,Bl),this.intersectBodies(Bl),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=sm,r=am;for(let o=0,s=e.shapes.length;o<s;o++){let l=e.shapes[o];if(!(i&&!l.collisionResponse)&&(e.quaternion.mult(e.shapeOrientations[o],r),e.quaternion.vmult(e.shapeOffsets[o],n),n.vadd(e.position,n),this.intersectShape(l,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(wm(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,l=this.direction,d=new _(0,0,1);t.vmult(d,d);let a=new _;o.vsub(i,a);let u=a.dot(d);s.vsub(i,a);let h=a.dot(d);if(u*h>0||o.distanceTo(s)<u)return;let m=d.dot(l);if(Math.abs(m)<this.precision)return;let E=new _,b=new _,y=new _;o.vsub(i,E);let g=-d.dot(E)/m;l.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=lm;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=cm,l,d,a,u;l=d=0,a=u=e.data.length-1;let h=new qe;o.getAABB(h),e.getIndexOfPosition(h.lowerBound.x,h.lowerBound.y,s,!0),l=Math.max(l,s[0]),d=Math.max(d,s[1]),e.getIndexOfPosition(h.upperBound.x,h.upperBound.y,s,!0),a=Math.min(a,s[0]+1),u=Math.min(u,s[1]+1);for(let m=l;m<a;m++)for(let E=d;E<u;E++){if(this.result.shouldStop)return;if(e.getAabbAtIndex(m,E,h),!!h.overlapsRay(o)){if(e.getConvexTrianglePillar(m,E,!1),te.pointToWorldFrame(i,t,e.pillarOffset,Us),this._intersectConvex(e.pillarConvex,t,Us,n,r,Ch),this.result.shouldStop)return;e.getConvexTrianglePillar(m,E,!0),te.pointToWorldFrame(i,t,e.pillarOffset,Us),this._intersectConvex(e.pillarConvex,t,Us,n,r,Ch)}}}_intersectSphere(e,t,i,n,r){let o=this.from,s=this.to,l=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)),u=(o.x-i.x)**2+(o.y-i.y)**2+(o.z-i.z)**2-l**2,h=a**2-4*d*u,m=dm,E=hm;if(!(h<0))if(h===0)o.lerp(s,h,m),m.vsub(i,E),E.normalize(),this.reportIntersection(E,m,r,n,-1);else{let b=(-a-Math.sqrt(h))/(2*d),y=(-a+Math.sqrt(h))/(2*d);if(b>=0&&b<=1&&(o.lerp(s,b,m),m.vsub(i,E),E.normalize(),this.reportIntersection(E,m,r,n,-1)),this.result.shouldStop)return;y>=0&&y<=1&&(o.lerp(s,y,m),m.vsub(i,E),E.normalize(),this.reportIntersection(E,m,r,n,-1))}}_intersectConvex(e,t,i,n,r,o){let s=um,l=Rh,d=o&&o.faceList||null,a=e.faces,u=e.vertices,h=e.faceNormals,m=this.direction,E=this.from,b=this.to,y=E.distanceTo(b),g=d?d.length:a.length,p=this.result;for(let f=0;!p.shouldStop&&f<g;f++){let v=d?d[f]:f,w=a[v],x=h[v],T=t,C=i;l.copy(u[w[0]]),T.vmult(l,l),l.vadd(C,l),l.vsub(E,l),T.vmult(x,s);let R=m.dot(s);if(Math.abs(R)<this.precision)continue;let P=s.dot(l)/R;if(!(P<0)){m.scale(P,it),it.vadd(E,it),Vt.copy(u[w[0]]),T.vmult(Vt,Vt),C.vadd(Vt,Vt);for(let S=1;!p.shouldStop&&S<w.length-1;S++){li.copy(u[w[S]]),ci.copy(u[w[S+1]]),T.vmult(li,li),T.vmult(ci,ci),C.vadd(li,li),C.vadd(ci,ci);let M=it.distanceTo(E);!(me.pointInTriangle(it,Vt,li,ci)||me.pointInTriangle(it,li,Vt,ci))||M>y||this.reportIntersection(s,it,r,n,v)}}}}_intersectTrimesh(e,t,i,n,r,o){let s=pm,l=ym,d=Em,a=Rh,u=fm,h=mm,m=gm,E=vm,b=bm,y=e.indices;e.vertices;let g=this.from,p=this.to,f=this.direction;d.position.copy(i),d.quaternion.copy(t),te.vectorToLocalFrame(i,t,f,u),te.pointToLocalFrame(i,t,g,h),te.pointToLocalFrame(i,t,p,m),m.x*=e.scale.x,m.y*=e.scale.y,m.z*=e.scale.z,h.x*=e.scale.x,h.y*=e.scale.y,h.z*=e.scale.z,m.vsub(h,u),u.normalize();let v=h.distanceSquared(m);e.tree.rayQuery(this,d,l);for(let w=0,x=l.length;!this.result.shouldStop&&w!==x;w++){let T=l[w];e.getNormal(T,s),e.getVertex(y[T*3],Vt),Vt.vsub(h,a);let C=u.dot(s),R=s.dot(a)/C;if(R<0)continue;u.scale(R,it),it.vadd(h,it),e.getVertex(y[T*3+1],li),e.getVertex(y[T*3+2],ci);let P=it.distanceSquared(h);!(me.pointInTriangle(it,li,Vt,ci)||me.pointInTriangle(it,Vt,li,ci))||P>v||(te.vectorToWorldFrame(t,s,b),te.pointToWorldFrame(i,t,it,E),this.reportIntersection(b,E,r,n,T))}l.length=0}reportIntersection(e,t,i,n,r){let o=this.from,s=this.to,l=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 me.ALL:this.hasHit=!0,d.set(o,s,e,t,i,n,l),d.hasHit=!0,this.callback(d);break;case me.CLOSEST:(l<d.distance||!d.hasHit)&&(this.hasHit=!0,d.hasHit=!0,d.set(o,s,e,t,i,n,l));break;case me.ANY:this.hasHit=!0,d.hasHit=!0,d.set(o,s,e,t,i,n,l),d.shouldStop=!0;break}}static pointInTriangle(e,t,i,n){n.vsub(t,Kn),i.vsub(t,es),e.vsub(t,Fl);let r=Kn.dot(Kn),o=Kn.dot(es),s=Kn.dot(Fl),l=es.dot(es),d=es.dot(Fl),a,u;return(a=l*s-o*d)>=0&&(u=r*d-o*s)>=0&&a+u<r*l-o*o}};me.CLOSEST=Zl.CLOSEST;me.ANY=Zl.ANY;me.ALL=Zl.ALL;var Th=new qe,Bl=[],es=new _,Fl=new _,sm=new _,am=new ae,it=new _,Vt=new _,li=new _,ci=new _,Ch={faceList:[0]},Us=new _,lm=new me,cm=[],dm=new _,hm=new _,um=new _,Rh=new _,pm=new _,fm=new _,mm=new _,gm=new _,bm=new _,vm=new _;new qe;var ym=[],Em=new te,Kn=new _,Vs=new _;function wm(c,e,t){t.vsub(c,Kn);let i=Kn.dot(e);return e.scale(i,Vs),Vs.vadd(c,Vs),t.distanceTo(Vs)}var Ys=class{static defaults(e={},t){for(let i in t)i in e||(e[i]=t[i]);return e}},os=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=Ys.defaults(i,{collideConnected:!0,wakeUpBodies:!0}),this.equations=[],this.bodyA=e,this.bodyB=t,this.id=os.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}};os.idCounter=0;var Ks=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 Ks,this.jacobianElementB=new Ks,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,l=n.angularVelocity;return e.multiplyVectors(r,s)+t.multiplyVectors(o,l)}computeGWlambda(){let e=this.jacobianElementA,t=this.jacobianElementB,i=this.bi,n=this.bj,r=i.vlambda,o=n.vlambda,s=i.wlambda,l=n.wlambda;return e.multiplyVectors(r,s)+t.multiplyVectors(o,l)}computeGiMf(){let e=this.jacobianElementA,t=this.jacobianElementB,i=this.bi,n=this.bj,r=i.force,o=i.torque,s=n.force,l=n.torque,d=i.invMassSolve,a=n.invMassSolve;return r.scale(d,Sh),s.scale(a,Ph),i.invInertiaWorldSolve.vmult(o,Oh),n.invInertiaWorldSolve.vmult(l,kh),e.multiplyVectors(Sh,Oh)+t.multiplyVectors(Ph,kh)}computeGiMGt(){let e=this.jacobianElementA,t=this.jacobianElementB,i=this.bi,n=this.bj,r=i.invMassSolve,o=n.invMassSolve,s=i.invInertiaWorldSolve,l=n.invInertiaWorldSolve,d=r+o;return s.vmult(e.rotational,Gs),d+=Gs.dot(e.rotational),l.vmult(t.rotational,Gs),d+=Gs.dot(t.rotational),d}addToWlambda(e){let t=this.jacobianElementA,i=this.jacobianElementB,n=this.bi,r=this.bj,o=_m;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 Sh=new _,Ph=new _,Oh=new _,kh=new _,Gs=new _,_m=new _,Vl=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,l=xm,d=Tm,a=n.velocity,u=n.angularVelocity;n.force,n.torque;let h=r.velocity,m=r.angularVelocity;r.force,r.torque;let E=Cm,b=this.jacobianElementA,y=this.jacobianElementB,g=this.ni;o.cross(g,l),s.cross(g,d),g.negate(b.spatial),l.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),f=this.restitution+1,v=f*h.dot(g)-f*a.dot(g)+m.dot(d)-u.dot(l),w=this.computeGiMf();return-p*t-v*i-e*w}getImpactVelocityAlongNormal(){let e=Rm,t=Sm,i=Pm,n=Om,r=km;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)}},xm=new _,Tm=new _,Cm=new _,Rm=new _,Sm=new _,Pm=new _,Om=new _,km=new _;var hw=new _,uw=new _;var pw=new _,fw=new _;var mw=new _,gw=new _,Js=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=Am,o=Im,s=this.t;i.cross(s,r),n.cross(s,o);let l=this.jacobianElementA,d=this.jacobianElementB;s.negate(l.spatial),r.negate(l.rotational),d.spatial.copy(s),d.rotational.copy(o);let a=this.computeGW(),u=this.computeGiMf();return-a*t-e*u}},Am=new _,Im=new _,zr=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=Ys.defaults(i,{friction:.3,restitution:.3,contactEquationStiffness:1e7,contactEquationRelaxation:3,frictionEquationStiffness:1e7,frictionEquationRelaxation:3}),this.id=zr.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}};zr.idCounter=0;var Ur=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=Ur.idCounter++,this.friction=typeof e.friction<"u"?e.friction:-1,this.restitution=typeof e.restitution<"u"?e.restitution:-1}};Ur.idCounter=0;var Zs=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=Mm,s=Dm,l=Lm,d=Hm,a=Vm,u=jm,h=Bm,m=Fm,E=Nm,b=zm,y=Um;this.getWorldAnchorA(u),this.getWorldAnchorB(h),u.vsub(n.position,m),h.vsub(r.position,E),h.vsub(u,o);let g=o.length();s.copy(o),s.normalize(),r.velocity.vsub(n.velocity,l),r.angularVelocity.cross(E,a),l.vadd(a,l),n.angularVelocity.cross(m,a),l.vsub(a,l),s.scale(-e*(g-i)-t*l.dot(s),d),n.force.vsub(d,n.force),r.force.vadd(d,r.force),m.cross(d,b),E.cross(d,y),n.torque.vsub(b,n.torque),r.torque.vadd(y,r.torque)}},Mm=new _,Dm=new _,Lm=new _,Hm=new _,jm=new _,Bm=new _,Fm=new _,Nm=new _,zm=new _,Um=new _,Vm=new _;var bw=new _,vw=new _;var yw=new _,Ew=new _,ww=new _;new me;var _w=new _,xw=new _,Tw=[new _(1,0,0),new _(0,1,0),new _(0,0,1)],Cw=new _;var Rw=new _,Sw=new _,Pw=new _;var Ow=new _,kw=new _,Aw=new _,Iw=new _;var Mw=new _,Dw=new _,Lw=new _;var $s=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 l=o[s];i[l]=e[l]-r,n[l]=e[l]+r}}};var Hw=new _,jw=new _;var Bw=new _,Fw=new _,Nw=new _,zw=new _,Uw=new _,Vw=new _,Gw=new _;var Ww=new _;var qw=new _,Xw=new _,Qw=new _,Yw=new _,Kw=new _,Jw=new _,Zw=new _,$w=new _,e_=new _;var t_=new _,i_=new qe;var n_=new _,r_=new qe,o_=new _,s_=new _,a_=new _,l_=new _,c_=new _,d_=new _,h_=new _,u_=new qe,p_=new _,f_=new te,m_=new qe,Gl=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}},Wl=class extends Gl{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,l=t.bodies,d=l.length,a=e,u,h,m,E,b,y;if(s!==0)for(let v=0;v!==d;v++)l[v].updateSolveMassProperties();let g=Wm,p=qm,f=Gm;g.length=s,p.length=s,f.length=s;for(let v=0;v!==s;v++){let w=o[v];f[v]=0,p[v]=w.computeB(a),g[v]=1/w.computeC()}if(s!==0){for(let x=0;x!==d;x++){let T=l[x],C=T.vlambda,R=T.wlambda;C.set(0,0,0),R.set(0,0,0)}for(i=0;i!==n;i++){E=0;for(let x=0;x!==s;x++){let T=o[x];u=p[x],h=g[x],y=f[x],b=T.computeGWlambda(),m=h*(u-b-T.eps*y),y+m<T.minForce?m=T.minForce-y:y+m>T.maxForce&&(m=T.maxForce-y),f[x]+=m,E+=m>0?m:-m,T.addToWlambda(m)}if(E*E<r)break}for(let x=0;x!==d;x++){let T=l[x],C=T.velocity,R=T.angularVelocity;T.vlambda.vmul(T.linearFactor,T.vlambda),C.vadd(T.vlambda,C),T.wlambda.vmul(T.angularFactor,T.wlambda),R.vadd(T.wlambda,R)}let v=o.length,w=1/a;for(;v--;)o[v].multiplier=f[v]*w}return i}},Gm=[],Wm=[],qm=[];var g_=U.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}},Xl=class extends ql{constructor(...e){super(...e),this.type=_}constructObject(){return new _}},Uh,Vh,Gh,Wh,qh,Xh,Qh,Yh,Kh,Jh,Zh,$h,eu,tu,iu,nu,ru,ou,su,au,lu,cu,du,hu,uu,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};Uh=de.sphereSphere;Vh=de.spherePlane;Gh=de.boxBox;Wh=de.sphereBox;qh=de.planeBox;Xh=de.convexConvex;Qh=de.sphereConvex;Yh=de.planeConvex;Kh=de.boxConvex;Jh=de.sphereHeightfield;Zh=de.boxHeightfield;$h=de.convexHeightfield;eu=de.sphereParticle;tu=de.planeParticle;iu=de.boxParticle;nu=de.convexParticle;ru=de.cylinderCylinder;ou=de.sphereCylinder;su=de.planeCylinder;au=de.boxCylinder;lu=de.convexCylinder;cu=de.heightfieldCylinder;du=de.particleCylinder;hu=de.sphereTrimesh;uu=de.planeTrimesh;var Ql=class{get[Uh](){return this.sphereSphere}get[Vh](){return this.spherePlane}get[Gh](){return this.boxBox}get[Wh](){return this.sphereBox}get[qh](){return this.planeBox}get[Xh](){return this.convexConvex}get[Qh](){return this.sphereConvex}get[Yh](){return this.planeConvex}get[Kh](){return this.boxConvex}get[Jh](){return this.sphereHeightfield}get[Zh](){return this.boxHeightfield}get[$h](){return this.convexHeightfield}get[eu](){return this.sphereParticle}get[tu](){return this.planeParticle}get[iu](){return this.boxParticle}get[nu](){return this.convexParticle}get[ru](){return this.convexConvex}get[ou](){return this.sphereConvex}get[su](){return this.planeConvex}get[au](){return this.boxConvex}get[lu](){return this.convexConvex}get[cu](){return this.heightfieldCylinder}get[du](){return this.particleCylinder}get[hu](){return this.sphereTrimesh}get[uu](){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 Xl,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 Vl(e,t),s.enabled=e.collisionResponse&&t.collisionResponse&&i.collisionResponse&&n.collisionResponse;let l=this.currentContactMaterial;s.restitution=l.restitution,s.setSpookParams(l.contactEquationStiffness,l.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,l=this.currentContactMaterial,d=l.friction,a=r.material||i.material,u=o.material||n.material;if(a&&u&&a.friction>=0&&u.friction>=0&&(d=a.friction*u.friction),d>0){let h=d*s.gravity.length(),m=i.invMass+n.invMass;m>0&&(m=1/m);let E=this.frictionEquationPool,b=E.length?E.pop():new Js(i,n,h*m),y=E.length?E.pop():new Js(i,n,h*m);return b.bi=y.bi=i,b.bj=y.bj=n,b.minForce=y.minForce=-h*m,b.maxForce=y.maxForce=h*m,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(l.frictionEquationStiffness,l.frictionEquationRelaxation,s.dt),y.setSpookParams(l.frictionEquationStiffness,l.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];Yn.setZero(),Fr.setZero(),Nr.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?(Yn.vadd(t.ni,Yn),Fr.vadd(t.ri,Fr),Nr.vadd(t.rj,Nr)):(Yn.vsub(t.ni,Yn),Fr.vadd(t.rj,Fr),Nr.vadd(t.ri,Nr));let o=1/e;Fr.scale(o,i.ri),Nr.scale(o,i.rj),n.ri.copy(i.ri),n.rj.copy(i.rj),Yn.normalize(),Yn.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 l=Ym,d=Km,a=Xm,u=Qm;for(let h=0,m=e.length;h!==m;h++){let E=e[h],b=t[h],y=null;E.material&&b.material&&(y=i.getContactMaterial(E.material,b.material)||null);let g=E.type&U.KINEMATIC&&b.type&U.STATIC||E.type&U.STATIC&&b.type&U.KINEMATIC||E.type&U.KINEMATIC&&b.type&U.KINEMATIC;for(let p=0;p<E.shapes.length;p++){E.quaternion.mult(E.shapeOrientations[p],l),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],u),u.vadd(b.position,u);let w=b.shapes[v];if(!(f.collisionFilterMask&w.collisionFilterGroup&&w.collisionFilterMask&f.collisionFilterGroup)||a.distanceTo(u)>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,C=this[T];if(C){let R=!1;f.type<w.type?R=C.call(this,f,w,a,u,l,d,E,b,f,w,g):R=C.call(this,w,f,u,a,d,l,b,E,f,w,g),R&&g&&(i.shapeOverlapKeeper.set(f.id,w.id),i.bodyOverlapKeeper.set(E.id,b.id))}}}}}sphereSphere(e,t,i,n,r,o,s,l,d,a,u){if(u)return i.distanceSquared(n)<(e.radius+t.radius)**2;let h=this.createContactEquation(s,l,e,t,d,a);n.vsub(i,h.ni),h.ni.normalize(),h.ri.copy(h.ni),h.rj.copy(h.ni),h.ri.scale(e.radius,h.ri),h.rj.scale(-t.radius,h.rj),h.ri.vadd(i,h.ri),h.ri.vsub(s.position,h.ri),h.rj.vadd(n,h.rj),h.rj.vsub(l.position,h.rj),this.result.push(h),this.createFrictionEquationsFromContact(h,this.frictionResult)}spherePlane(e,t,i,n,r,o,s,l,d,a,u){let h=this.createContactEquation(s,l,e,t,d,a);if(h.ni.set(0,0,1),o.vmult(h.ni,h.ni),h.ni.negate(h.ni),h.ni.normalize(),h.ni.scale(e.radius,h.ri),i.vsub(n,Ws),h.ni.scale(h.ni.dot(Ws),Ah),Ws.vsub(Ah,h.rj),-Ws.dot(h.ni)<=e.radius){if(u)return!0;let m=h.ri,E=h.rj;m.vadd(i,m),m.vsub(s.position,m),E.vadd(n,E),E.vsub(l.position,E),this.result.push(h),this.createFrictionEquationsFromContact(h,this.frictionResult)}}boxBox(e,t,i,n,r,o,s,l,d,a,u){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,l,e,t,u)}sphereBox(e,t,i,n,r,o,s,l,d,a,u){let h=this.v3pool,m=_g;i.vsub(n,qs),t.getSideNormals(m,o);let E=e.radius,b=!1,y=Tg,g=Cg,p=Rg,f=null,v=0,w=0,x=0,T=null;for(let N=0,W=m.length;N!==W&&b===!1;N++){let J=yg;J.copy(m[N]);let G=J.length();J.normalize();let He=qs.dot(J);if(He<G+E&&He>0){let fe=Eg,X=wg;fe.copy(m[(N+1)%3]),X.copy(m[(N+2)%3]);let ze=fe.length(),dn=X.length();fe.normalize(),X.normalize();let Xn=qs.dot(fe),Mi=qs.dot(X);if(Xn<ze&&Xn>-ze&&Mi<dn&&Mi>-dn){let Rt=Math.abs(He-G-E);if((T===null||Rt<T)&&(T=Rt,w=Xn,x=Mi,f=G,y.copy(J),g.copy(fe),p.copy(X),v++,u))return!0}}}if(v){b=!0;let N=this.createContactEquation(s,l,e,t,d,a);y.scale(-E,N.ri),N.ni.copy(y),N.ni.negate(N.ni),y.scale(f,y),g.scale(w,g),y.vadd(g,y),p.scale(x,p),y.vadd(p,N.rj),N.ri.vadd(i,N.ri),N.ri.vsub(s.position,N.ri),N.rj.vadd(n,N.rj),N.rj.vsub(l.position,N.rj),this.result.push(N),this.createFrictionEquationsFromContact(N,this.frictionResult)}let C=h.get(),R=xg;for(let N=0;N!==2&&!b;N++)for(let W=0;W!==2&&!b;W++)for(let J=0;J!==2&&!b;J++)if(C.set(0,0,0),N?C.vadd(m[0],C):C.vsub(m[0],C),W?C.vadd(m[1],C):C.vsub(m[1],C),J?C.vadd(m[2],C):C.vsub(m[2],C),n.vadd(C,R),R.vsub(i,R),R.lengthSquared()<E*E){if(u)return!0;b=!0;let G=this.createContactEquation(s,l,e,t,d,a);G.ri.copy(R),G.ri.normalize(),G.ni.copy(G.ri),G.ri.scale(E,G.ri),G.rj.copy(C),G.ri.vadd(i,G.ri),G.ri.vsub(s.position,G.ri),G.rj.vadd(n,G.rj),G.rj.vsub(l.position,G.rj),this.result.push(G),this.createFrictionEquationsFromContact(G,this.frictionResult)}h.release(C),C=null;let P=h.get(),S=h.get(),M=h.get(),I=h.get(),j=h.get(),H=m.length;for(let N=0;N!==H&&!b;N++)for(let W=0;W!==H&&!b;W++)if(N%3!==W%3){m[W].cross(m[N],P),P.normalize(),m[N].vadd(m[W],S),M.copy(i),M.vsub(S,M),M.vsub(n,M);let J=M.dot(P);P.scale(J,I);let G=0;for(;G===N%3||G===W%3;)G++;j.copy(i),j.vsub(I,j),j.vsub(S,j),j.vsub(n,j);let He=Math.abs(J),fe=j.length();if(He<m[G].length()&&fe<E){if(u)return!0;b=!0;let X=this.createContactEquation(s,l,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(l.position,X.rj),this.result.push(X),this.createFrictionEquationsFromContact(X,this.frictionResult)}}h.release(P,S,M,I,j)}planeBox(e,t,i,n,r,o,s,l,d,a,u){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,l,e,t,u)}convexConvex(e,t,i,n,r,o,s,l,d,a,u,h,m){let E=zg;if(!(i.distanceTo(n)>e.boundingSphereRadius+t.boundingSphereRadius)&&e.findSeparatingAxis(t,i,r,n,o,E,h,m)){let b=[],y=Ug;e.clipAgainstHull(i,r,t,n,o,E,-100,100,b);let g=0;for(let p=0;p!==b.length;p++){if(u)return!0;let f=this.createContactEquation(s,l,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(s.position,v),w.vadd(n,w),w.vsub(l.position,w),this.result.push(f),g++,this.enableFrictionReduction||this.createFrictionEquationsFromContact(f,this.frictionResult)}this.enableFrictionReduction&&g&&this.createFrictionFromAverage(g)}}sphereConvex(e,t,i,n,r,o,s,l,d,a,u){let h=this.v3pool;i.vsub(n,Sg);let m=t.faceNormals,E=t.faces,b=t.vertices,y=e.radius,g=!1;for(let p=0;p!==b.length;p++){let f=b[p],v=Ag;o.vmult(f,v),n.vadd(v,v);let w=kg;if(v.vsub(i,w),w.lengthSquared()<y*y){if(u)return!0;g=!0;let x=this.createContactEquation(s,l,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(l.position,x.rj),this.result.push(x),this.createFrictionEquationsFromContact(x,this.frictionResult);return}}for(let p=0,f=E.length;p!==f&&g===!1;p++){let v=m[p],w=E[p],x=Ig;o.vmult(v,x);let T=Mg;o.vmult(b[w[0]],T),T.vadd(n,T);let C=Dg;x.scale(-y,C),i.vadd(C,C);let R=Lg;C.vsub(T,R);let P=R.dot(x),S=Hg;if(i.vsub(T,S),P<0&&S.dot(x)>0){let M=[];for(let I=0,j=w.length;I!==j;I++){let H=h.get();o.vmult(b[w[I]],H),n.vadd(H,H),M.push(H)}if(vg(M,x,i)){if(u)return!0;g=!0;let I=this.createContactEquation(s,l,e,t,d,a);x.scale(-y,I.ri),x.negate(I.ni);let j=h.get();x.scale(-P,j);let H=h.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(l.position,I.rj),I.ri.vadd(i,I.ri),I.ri.vsub(s.position,I.ri),h.release(j),h.release(H),this.result.push(I),this.createFrictionEquationsFromContact(I,this.frictionResult);for(let N=0,W=M.length;N!==W;N++)h.release(M[N]);return}else for(let I=0;I!==w.length;I++){let j=h.get(),H=h.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 N=Pg;H.vsub(j,N);let W=Og;N.unit(W);let J=h.get(),G=h.get();i.vsub(j,G);let He=G.dot(W);W.scale(He,J),J.vadd(j,J);let fe=h.get();if(J.vsub(i,fe),He>0&&He*He<N.lengthSquared()&&fe.lengthSquared()<y*y){if(u)return!0;let X=this.createContactEquation(s,l,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(l.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 ze=0,dn=M.length;ze!==dn;ze++)h.release(M[ze]);h.release(j),h.release(H),h.release(J),h.release(fe),h.release(G);return}h.release(j),h.release(H),h.release(J),h.release(fe),h.release(G)}for(let I=0,j=M.length;I!==j;I++)h.release(M[I])}}}planeConvex(e,t,i,n,r,o,s,l,d,a,u){let h=jg,m=Bg;m.set(0,0,1),r.vmult(m,m);let E=0,b=Fg;for(let y=0;y!==t.vertices.length;y++)if(h.copy(t.vertices[y]),o.vmult(h,h),n.vadd(h,h),h.vsub(i,b),m.dot(b)<=0){if(u)return!0;let p=this.createContactEquation(s,l,e,t,d,a),f=Ng;m.scale(m.dot(b),f),h.vsub(f,f),f.vsub(i,p.ri),p.ni.copy(m),h.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(l.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,l,d,a,u){return e.convexPolyhedronRepresentation.material=e.material,e.convexPolyhedronRepresentation.collisionResponse=e.collisionResponse,this.convexConvex(e.convexPolyhedronRepresentation,t,i,n,r,o,s,l,e,t,u)}sphereHeightfield(e,t,i,n,r,o,s,l,d,a,u){let h=t.data,m=e.radius,E=t.elementSize,b=eb,y=$g;te.pointToLocalFrame(n,o,i,y);let g=Math.floor((y.x-m)/E)-1,p=Math.ceil((y.x+m)/E)+1,f=Math.floor((y.y-m)/E)-1,v=Math.ceil((y.y+m)/E)+1;if(p<0||v<0||g>h.length||f>h[0].length)return;g<0&&(g=0),p<0&&(p=0),f<0&&(f=0),v<0&&(v=0),g>=h.length&&(g=h.length-1),p>=h.length&&(p=h.length-1),v>=h[0].length&&(v=h[0].length-1),f>=h[0].length&&(f=h[0].length-1);let w=[];t.getRectMinMax(g,f,p,v,w);let x=w[0],T=w[1];if(y.z-m>T||y.z+m<x)return;let C=this.result;for(let R=g;R<p;R++)for(let P=f;P<v;P++){let S=C.length,M=!1;if(t.getConvexTrianglePillar(R,P,!1),te.pointToWorldFrame(n,o,t.pillarOffset,b),i.distanceTo(b)<t.pillarConvex.boundingSphereRadius+e.boundingSphereRadius&&(M=this.sphereConvex(e,t.pillarConvex,i,b,r,o,s,l,e,t,u)),u&&M||(t.getConvexTrianglePillar(R,P,!0),te.pointToWorldFrame(n,o,t.pillarOffset,b),i.distanceTo(b)<t.pillarConvex.boundingSphereRadius+e.boundingSphereRadius&&(M=this.sphereConvex(e,t.pillarConvex,i,b,r,o,s,l,e,t,u)),u&&M))return!0;if(C.length-S>2)return}}boxHeightfield(e,t,i,n,r,o,s,l,d,a,u){return e.convexPolyhedronRepresentation.material=e.material,e.convexPolyhedronRepresentation.collisionResponse=e.collisionResponse,this.convexHeightfield(e.convexPolyhedronRepresentation,t,i,n,r,o,s,l,e,t,u)}convexHeightfield(e,t,i,n,r,o,s,l,d,a,u){let h=t.data,m=t.elementSize,E=e.boundingSphereRadius,b=Jg,y=Zg,g=Kg;te.pointToLocalFrame(n,o,i,g);let p=Math.floor((g.x-E)/m)-1,f=Math.ceil((g.x+E)/m)+1,v=Math.floor((g.y-E)/m)-1,w=Math.ceil((g.y+E)/m)+1;if(f<0||w<0||p>h.length||v>h[0].length)return;p<0&&(p=0),f<0&&(f=0),v<0&&(v=0),w<0&&(w=0),p>=h.length&&(p=h.length-1),f>=h.length&&(f=h.length-1),w>=h[0].length&&(w=h[0].length-1),v>=h[0].length&&(v=h[0].length-1);let x=[];t.getRectMinMax(p,v,f,w,x);let T=x[0],C=x[1];if(!(g.z-E>C||g.z+E<T))for(let R=p;R<f;R++)for(let P=v;P<w;P++){let S=!1;if(t.getConvexTrianglePillar(R,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,l,null,null,u,y,null)),u&&S||(t.getConvexTrianglePillar(R,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,l,null,null,u,y,null)),u&&S))return!0}}sphereParticle(e,t,i,n,r,o,s,l,d,a,u){let h=qg;if(h.set(0,0,1),n.vsub(i,h),h.lengthSquared()<=e.radius*e.radius){if(u)return!0;let E=this.createContactEquation(l,s,t,e,d,a);h.normalize(),E.rj.copy(h),E.rj.scale(e.radius,E.rj),E.ni.copy(h),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,l,d,a,u){let h=Vg;h.set(0,0,1),s.quaternion.vmult(h,h);let m=Gg;if(n.vsub(s.position,m),h.dot(m)<=0){if(u)return!0;let b=this.createContactEquation(l,s,t,e,d,a);b.ni.copy(h),b.ni.negate(b.ni),b.ri.set(0,0,0);let y=Wg;h.scale(h.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,l,d,a,u){return e.convexPolyhedronRepresentation.material=e.material,e.convexPolyhedronRepresentation.collisionResponse=e.collisionResponse,this.convexParticle(e.convexPolyhedronRepresentation,t,i,n,r,o,s,l,e,t,u)}convexParticle(e,t,i,n,r,o,s,l,d,a,u){let h=-1,m=Qg,E=Yg,b=null,y=Xg;if(y.copy(n),y.vsub(i,y),r.conjugate(Ih),Ih.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 f=[e.worldVertices[e.faces[g][0]]],v=e.worldFaceNormals[g];n.vsub(f[0],Mh);let w=-v.dot(Mh);if(b===null||Math.abs(w)<Math.abs(b)){if(u)return!0;b=w,h=g,m.copy(v)}}if(h!==-1){let g=this.createContactEquation(l,s,t,e,d,a);m.scale(b,E),E.vadd(n,E),E.vsub(i,E),g.rj.copy(E),m.negate(g.ni),g.ri.set(0,0,0);let p=g.ri,f=g.rj;p.vadd(n,p),p.vsub(l.position,p),f.vadd(i,f),f.vsub(s.position,f),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,l,d,a,u){return this.convexHeightfield(t,e,n,i,o,r,l,s,d,a,u)}particleCylinder(e,t,i,n,r,o,s,l,d,a,u){return this.convexParticle(t,e,n,i,o,r,l,s,d,a,u)}sphereTrimesh(e,t,i,n,r,o,s,l,d,a,u){let h=rg,m=og,E=sg,b=ag,y=lg,g=cg,p=pg,f=ng,v=tg,w=fg;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=ig,C=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()<=C){if(f.copy(T),te.pointToWorldFrame(n,o,f,T),T.vsub(i,v),u)return!0;let H=this.createContactEquation(s,l,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(l.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],h),t.getVertex(t.indices[w[I]*3+(j+1)%3],m),m.vsub(h,E),y.vsub(m,g);let H=g.dot(E);y.vsub(h,g);let N=g.dot(E);if(N>0&&H<0&&(y.vsub(h,g),b.copy(E),b.normalize(),N=g.dot(b),b.scale(N,g),g.vadd(h,g),g.distanceTo(y)<e.radius)){if(u)return!0;let J=this.createContactEquation(s,l,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(l.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 R=dg,P=hg,S=ug,M=eg;for(let I=0,j=w.length;I!==j;I++){t.getTriangleVertices(w[I],R,P,S),t.getNormal(w[I],M),y.vsub(R,g);let H=g.dot(M);if(M.scale(H,g),y.vsub(g,g),H=g.distanceTo(y),me.pointInTriangle(g,R,P,S)&&H<e.radius){if(u)return!0;let N=this.createContactEquation(s,l,e,t,d,a);g.vsub(y,N.ni),N.ni.normalize(),N.ni.scale(e.radius,N.ri),N.ri.vadd(i,N.ri),N.ri.vsub(s.position,N.ri),te.pointToWorldFrame(n,o,g,g),g.vsub(l.position,N.rj),te.vectorToWorldFrame(o,N.ni,N.ni),te.vectorToWorldFrame(o,N.ri,N.ri),this.result.push(N),this.createFrictionEquationsFromContact(N,this.frictionResult)}}w.length=0}planeTrimesh(e,t,i,n,r,o,s,l,d,a,u){let h=new _,m=Jm;m.set(0,0,1),r.vmult(m,m);for(let E=0;E<t.vertices.length/3;E++){t.getVertex(E,h);let b=new _;b.copy(h),te.pointToWorldFrame(n,o,b,h);let y=Zm;if(h.vsub(i,y),m.dot(y)<=0){if(u)return!0;let p=this.createContactEquation(s,l,e,t,d,a);p.ni.copy(m);let f=$m;m.scale(y.dot(m),f),h.vsub(f,f),p.ri.copy(f),p.ri.vsub(s.position,p.ri),p.rj.copy(h),p.rj.vsub(l.position,p.rj),this.result.push(p),this.createFrictionEquationsFromContact(p,this.frictionResult)}}}},Yn=new _,Fr=new _,Nr=new _,Xm=new _,Qm=new _,Ym=new ae,Km=new ae,Jm=new _,Zm=new _,$m=new _,eg=new _,tg=new _,ig=new _,ng=new _,rg=new _,og=new _,sg=new _,ag=new _,lg=new _,cg=new _,dg=new _,hg=new _,ug=new _,pg=new qe,fg=[],Ws=new _,Ah=new _,mg=new _,gg=new _,bg=new _;function vg(c,e,t){let i=null,n=c.length;for(let r=0;r!==n;r++){let o=c[r],s=mg;c[(r+1)%n].vsub(o,s);let l=gg;s.cross(e,l);let d=bg;t.vsub(o,d);let a=l.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 qs=new _,yg=new _,Eg=new _,wg=new _,_g=[new _,new _,new _,new _,new _,new _],xg=new _,Tg=new _,Cg=new _,Rg=new _,Sg=new _,Pg=new _,Og=new _,kg=new _,Ag=new _,Ig=new _,Mg=new _,Dg=new _,Lg=new _,Hg=new _,jg=new _,Bg=new _,Fg=new _,Ng=new _,zg=new _,Ug=new _,Vg=new _,Gg=new _,Wg=new _,qg=new _,Ih=new ae,Xg=new _,Qg=new _,Mh=new _,Yg=new _,Kg=new _,Jg=new _,Zg=[0],$g=new _,eb=new _,ea=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 l=0;l<r;l++){let d=!1,a=i[l];for(;a>n[s];)s++;d=a===n[s],d||Dh(e,a)}s=0;for(let l=0;l<o;l++){let d=!1,a=n[l];for(;a>i[s];)s++;d=i[s]===a,d||Dh(t,a)}}};function Dh(c,e){c.push((e&4294901760)>>16,e&65535)}var Yl=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]}}},ta=class extends Qs{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 Ul,this.bodies=[],this.hasActiveBodies=!1,this.solver=e.solver!==void 0?e.solver:new Wl,this.constraints=[],this.narrowphase=new Ql(this),this.collisionMatrix=new Xs,this.collisionMatrixPrevious=new Xs,this.bodyOverlapKeeper=new ea,this.shapeOverlapKeeper=new ea,this.materials=[],this.contactmaterials=[],this.contactMaterialTable=new Yl,this.defaultMaterial=new Ur("default"),this.defaultContactMaterial=new zr(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 rs?this.raycastClosest(e,t,{skipBackfaces:!0},i):this.raycastAll(e,t,{skipBackfaces:!0},i)}raycastAll(e,t,i={},n){return i.mode=me.ALL,i.from=e,i.to=t,i.callback=n,Nl.intersectWorld(this,i)}raycastAny(e,t,i={},n){return i.mode=me.ANY,i.from=e,i.to=t,i.result=n,Nl.intersectWorld(this,i)}raycastClosest(e,t,i={},n){return i.mode=me.CLOSEST,i.from=e,i.to=t,i.result=n,Nl.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 U&&(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=Ie.now(),r=0;for(;this.accumulator>=e&&r<i&&(this.internalStep(e),this.accumulator-=e,r++,!(Ie.now()-n>e*1e3)););this.accumulator=this.accumulator%e;let o=this.accumulator/e;for(let s=0;s!==this.bodies.length;s++){let l=this.bodies[s];l.previousPosition.lerp(l.position,o,l.interpolatedPosition),l.previousQuaternion.slerp(l.quaternion,o,l.interpolatedQuaternion),l.previousQuaternion.normalize()}this.time+=t}}internalStep(e){this.dt=e;let t=this.contacts,i=ob,n=sb,r=this.numObjects(),o=this.bodies,s=this.solver,l=this.gravity,d=this.doProfiling,a=this.profile,u=U.DYNAMIC,h=-1/0,m=this.constraints,E=rb;l.length();let b=l.x,y=l.y,g=l.z,p=0;for(d&&(h=Ie.now()),p=0;p!==r;p++){let I=o[p];if(I.type===u){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&&(h=Ie.now()),i.length=0,n.length=0,this.broadphase.collisionPairs(this,i,n),d&&(a.broadphase=Ie.now()-h);let f=m.length;for(p=0;p!==f;p++){let I=m[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&&(h=Ie.now());let v=nb,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=Ie.now()-h),d&&(h=Ie.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,N=j.bj,W=j.si,J=j.sj,G;if(H.material&&N.material?G=this.getContactMaterial(H.material,N.material)||this.defaultContactMaterial:G=this.defaultContactMaterial,G.friction,H.material&&N.material&&(H.material.friction>=0&&N.material.friction>=0&&H.material.friction*N.material.friction,H.material.restitution>=0&&N.material.restitution>=0&&(j.restitution=H.material.restitution*N.material.restitution)),s.addEquation(j),H.allowSleep&&H.type===U.DYNAMIC&&H.sleepState===U.SLEEPING&&N.sleepState===U.AWAKE&&N.type!==U.STATIC){let He=N.velocity.lengthSquared()+N.angularVelocity.lengthSquared(),fe=N.sleepSpeedLimit**2;He>=fe*2&&(H.wakeUpAfterNarrowphase=!0)}if(N.allowSleep&&N.type===U.DYNAMIC&&N.sleepState===U.SLEEPING&&H.sleepState===U.AWAKE&&H.type!==U.STATIC){let He=H.velocity.lengthSquared()+H.angularVelocity.lengthSquared(),fe=H.sleepSpeedLimit**2;He>=fe*2&&(N.wakeUpAfterNarrowphase=!0)}this.collisionMatrix.set(H,N,!0),this.collisionMatrixPrevious.get(H,N)||(ts.body=N,ts.contact=j,H.dispatchEvent(ts),ts.body=H,N.dispatchEvent(ts)),this.bodyOverlapKeeper.set(H.id,N.id),this.shapeOverlapKeeper.set(W.id,J.id)}for(this.emitContactEvents(),d&&(a.makeContactConstraints=Ie.now()-h,h=Ie.now()),p=0;p!==r;p++){let I=o[p];I.wakeUpAfterNarrowphase&&(I.wakeUp(),I.wakeUpAfterNarrowphase=!1)}for(f=m.length,p=0;p!==f;p++){let I=m[p];I.update();for(let j=0,H=I.equations.length;j!==H;j++){let N=I.equations[j];s.addEquation(N)}}s.solve(e,this),d&&(a.solve=Ie.now()-h),s.removeAllEquations();let C=Math.pow;for(p=0;p!==r;p++){let I=o[p];if(I.type&u){let j=C(1-I.linearDamping,e),H=I.velocity;H.scale(j,H);let N=I.angularVelocity;if(N){let W=C(1-I.angularDamping,e);N.scale(W,N)}}}for(this.dispatchEvent(ib),p=0;p!==r;p++){let I=o[p];I.preStep&&I.preStep.call(I)}d&&(h=Ie.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=Ie.now()-h),this.stepnumber+=1,this.dispatchEvent(tb),p=0;p!==r;p++){let I=o[p],j=I.postStep;j&&j.call(I)}let M=!0;if(this.allowSleep)for(M=!1,p=0;p!==r;p++){let I=o[p];I.sleepTick(this.time),I.sleepState!==U.SLEEPING&&(M=!0)}this.hasActiveBodies=M}emitContactEvents(){let e=this.hasAnyEventListener("beginContact"),t=this.hasAnyEventListener("endContact");if((e||t)&&this.bodyOverlapKeeper.getDiff(Li,Hi),e){for(let r=0,o=Li.length;r<o;r+=2)is.bodyA=this.getBodyById(Li[r]),is.bodyB=this.getBodyById(Li[r+1]),this.dispatchEvent(is);is.bodyA=is.bodyB=null}if(t){for(let r=0,o=Hi.length;r<o;r+=2)ns.bodyA=this.getBodyById(Hi[r]),ns.bodyB=this.getBodyById(Hi[r+1]),this.dispatchEvent(ns);ns.bodyA=ns.bodyB=null}Li.length=Hi.length=0;let i=this.hasAnyEventListener("beginShapeContact"),n=this.hasAnyEventListener("endShapeContact");if((i||n)&&this.shapeOverlapKeeper.getDiff(Li,Hi),i){for(let r=0,o=Li.length;r<o;r+=2){let s=this.getShapeById(Li[r]),l=this.getShapeById(Li[r+1]);ji.shapeA=s,ji.shapeB=l,s&&(ji.bodyA=s.body),l&&(ji.bodyB=l.body),this.dispatchEvent(ji)}ji.bodyA=ji.bodyB=ji.shapeA=ji.shapeB=null}if(n){for(let r=0,o=Hi.length;r<o;r+=2){let s=this.getShapeById(Hi[r]),l=this.getShapeById(Hi[r+1]);Bi.shapeA=s,Bi.shapeB=l,s&&(Bi.bodyA=s.body),l&&(Bi.bodyB=l.body),this.dispatchEvent(Bi)}Bi.bodyA=Bi.bodyB=Bi.shapeA=Bi.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 qe;var Nl=new me,Ie=globalThis.performance||{};if(!Ie.now){let c=Date.now();Ie.timing&&Ie.timing.navigationStart&&(c=Ie.timing.navigationStart),Ie.now=()=>Date.now()-c}var tb={type:"postStep"},ib={type:"preStep"},ts={type:U.COLLIDE_EVENT_NAME,body:null,contact:null},nb=[],rb=[],ob=[],sb=[],Li=[],Hi=[],is={type:"beginContact",bodyA:null,bodyB:null},ns={type:"endContact",bodyA:null,bodyB:null},ji={type:"beginShapeContact",bodyA:null,bodyB:null,shapeA:null,shapeB:null},Bi={type:"endShapeContact",bodyA:null,bodyB:null,shapeA:null,shapeB:null};import*as be from"three";import{MeshBasicMaterial as ab,SphereGeometry as pu,BoxGeometry as fu,PlaneGeometry as mu,Mesh as fn,CylinderGeometry as lb,BufferGeometry as ec,Float32BufferAttribute as tc}from"three";function cb(c,e,{color:t=65280,scale:i=1,onInit:n,onUpdate:r,autoUpdate:o}={}){let s=[],l=new ab({color:t??65280,wireframe:!0}),d=new _,a=new _,u=new _,h=new ae,m=new pu(1),E=new fu(1,1,1),b=new mu(10,10,10,10);function y(C){let R=new ec,P=[];for(let M=0;M<C.vertices.length;M++){let I=C.vertices[M];P.push(I.x,I.y,I.z)}R.setAttribute("position",new tc(P,3));let S=[];for(let M=0;M<C.faces.length;M++){let I=C.faces[M],j=I[0];for(let H=1;H<I.length-1;H++){let N=I[H],W=I[H+1];S.push(j,N,W)}}return R.setIndex(S),R.computeBoundingSphere(),R.computeVertexNormals(),R}function g(C){let R=new ec,P=[],S=d,M=a,I=u;for(let j=0;j<C.indices.length/3;j++)C.getTriangleVertices(j,S,M,I),P.push(S.x,S.y,S.z),P.push(M.x,M.y,M.z),P.push(I.x,I.y,I.z);return R.setAttribute("position",new tc(P,3)),R.computeBoundingSphere(),R.computeVertexNormals(),R}function p(C){let R=new ec,P=C.elementSize||1,S=C.data.flatMap((I,j)=>I.flatMap((H,N)=>[j*P,N*P,H])),M=[];for(let I=0;I<C.data.length-1;I++)for(let j=0;j<C.data[I].length-1;j++){let H=C.data[I].length,N=I*H+j;M.push(N+1,N+H,N+H+1),M.push(N+H,N+1,N)}return R.setIndex(M),R.setAttribute("position",new tc(S,3)),R.computeBoundingSphere(),R.computeVertexNormals(),R}function f(C){let R=new fn,{SPHERE:P,BOX:S,PLANE:M,CYLINDER:I,CONVEXPOLYHEDRON:j,TRIMESH:H,HEIGHTFIELD:N}=V.types;switch(C.type){case P:{R=new fn(m,l);break}case S:{R=new fn(E,l);break}case M:{R=new fn(b,l);break}case I:{let W=new lb(C.radiusTop,C.radiusBottom,C.height,C.numSegments);R=new fn(W,l),C.geometryId=W.id;break}case j:{let W=y(C);R=new fn(W,l),C.geometryId=W.id;break}case H:{let W=g(C);R=new fn(W,l),C.geometryId=W.id;break}case N:{let W=p(C);R=new fn(W,l),C.geometryId=W.id;break}}return c.add(R),R}function v(C,R){let{SPHERE:P,BOX:S,PLANE:M,CYLINDER:I,CONVEXPOLYHEDRON:j,TRIMESH:H,HEIGHTFIELD:N}=V.types;switch(R.type){case P:{let{radius:W}=R;C.scale.set(W*i,W*i,W*i);break}case S:{C.scale.copy(R.halfExtents),C.scale.multiplyScalar(2*i);break}case M:break;case I:{C.scale.set(1*i,1*i,1*i);break}case j:{C.scale.set(1*i,1*i,1*i);break}case H:{C.scale.copy(R.scale).multiplyScalar(i);break}case N:{C.scale.set(1*i,1*i,1*i);break}}}function w(C,R){if(!C)return!1;let{geometry:P}=C;return P instanceof pu&&R.type===V.types.SPHERE||P instanceof fu&&R.type===V.types.BOX||P instanceof mu&&R.type===V.types.PLANE||P.id===R.geometryId&&R.type===V.types.CYLINDER||P.id===R.geometryId&&R.type===V.types.CONVEXPOLYHEDRON||P.id===R.geometryId&&R.type===V.types.TRIMESH||P.id===R.geometryId&&R.type===V.types.HEIGHTFIELD}function x(C,R){let P=s[C],S=!1;return w(P,R)||(P&&c.remove(P),s[C]=P=f(R),S=!0),v(P,R),S}function T(){let C=s,R=d,P=h,S=0;for(let M of e)for(let I=0;I!==M.shapes.length;I++){let j=M.shapes[I],H=x(S,j),N=C[S];N&&(M.quaternion.vmult(M.shapeOffsets[I],R),M.position.vadd(R,R),M.quaternion.mult(M.shapeOrientations[I],P),N.position.copy(R),N.quaternion.copy(P),H&&n instanceof Function&&n(M,N,j),!H&&r instanceof Function&&r(M,N,j)),S++}for(let M=S;M<C.length;M++){let I=C[M];I&&c.remove(I)}C.length=S,o!==!1&&requestAnimationFrame(T)}return o!==!1&&requestAnimationFrame(T),{update:T}}var gu=cb;import*as le from"three";var ic=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}},K=new ic;import{Vector3 as db,Quaternion as hb,Uniform as ub}from"three";var rc=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]}},x_=new hb().setFromAxisAngle(new db(0,1,0),Math.PI);var oc=new rc(()=>new le.Vector3,100);function q(c,e=null,t=!0){let i=e??oc.get();return c?c.parent?(t&&c.updateWorldMatrix(!0,!1),c.matrixWorldNeedsUpdate&&c.updateMatrixWorld(),i.setFromMatrixPosition(c.matrixWorld),i):i.copy(c.position):i.set(0,0,0)}function oe(c,e){if(!c)return;let t=oc.get();e!==t&&t.copy(e),(c?.parent??c).worldToLocal(t),c.position.set(t.x,t.y,t.z)}function Vr(c,e,t,i){let n=oc.get();n.set(e,t,i),oe(c,n)}var er=new le.Quaternion,ss=new le.Quaternion,nc=new le.Quaternion;function Pe(c,e=null){if(!c)return ss.set(0,0,0,1);let t=e??ss;return c.parent?(c.getWorldQuaternion(t),t):t.copy(c.quaternion)}function Xe(c,e){if(!c)return;e!==er&&er.copy(e);let t=er;c?.parent?.getWorldQuaternion(nc),nc.invert();let n=nc.multiply(t);c.quaternion.set(n.x,n.y,n.z,n.w)}function yu(c,e,t,i,n){er.set(e,t,i,n),Xe(c,er)}var ia=new le.Vector3,T_=new le.Vector3;function na(c,e=null){return c?c.parent?(c.getWorldScale(e??ia),e??ia):ia.copy(c.position):ia.set(0,0,0)}var C_=new le.Vector3,R_=new le.Quaternion;var bu=new le.Euler,vu=new le.Euler,pb=new le.Vector3;function fb(c){return c.getWorldQuaternion(ss),vu.setFromQuaternion(ss),vu}function Eu(c,e){Xe(c,ss.setFromEuler(e))}function ra(c){let e=fb(c),t=pb;return t.set(e.x,e.y,e.z),t.x=K.toDegrees(t.x),t.y=K.toDegrees(t.y),t.z=K.toDegrees(t.z),t}function oa(c,e,t,i,n=!0){n&&(e=K.toRadians(e),t=K.toRadians(t),i=K.toRadians(i)),bu.set(e,t,i),er.setFromEuler(bu),Xe(c,er)}function as(c,e=!0){!c||(e?function t(i){console.groupCollapsed((i.name?i.name:"(no name : "+i.type+")")+" %o",i),i.children.forEach(t),console.groupEnd()}(c):c.traverse(function(t){for(var i="|___",n=t;n.parent!==null;)i=" "+i,n=n.parent;console.log(i+t.name+" <"+t.type+">")}))}var S_=new le.PlaneGeometry(2,2,1,1),P_=new le.WebGLRenderer({antialias:!1}),O_=new le.PerspectiveCamera,k_=new le.Scene,A_=new le.ShaderMaterial({uniforms:{blitTexture:new ub(null)},vertexShader:`
80
+ \u2192 `,i),i}return e}var gl=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}},Mi=class{_watches=[];constructor(e,t){if(Array.isArray(t))for(let i of t)this._watches.push(new Mi(e,i));else this._watches.push(new gl(e,t))}subscribeWrite(e){for(let t of this._watches)t.subscribeWrite(e)}apply(){for(let e of this._watches)e.apply()}revoke(){for(let e of this._watches)e.revoke()}dispose(){for(let e of this._watches)e.dispose();this._watches.length=0}};var Ut=H("gizmos"),Ke=H("debugextension");var ts=H("debugresolvedependencies"),xf=["/extensions/","extensions/"],Tf=[{prefix:"/nodes/",dependencyName:"node"},{prefix:"/meshes/",dependencyName:"mesh"},{prefix:"/materials/",dependencyName:"material"},{prefix:"/textures/",dependencyName:"texture"},{prefix:"/animations/",dependencyName:"animation"},{prefix:"nodes/",dependencyName:"node"},{prefix:"meshes/",dependencyName:"mesh"},{prefix:"materials/",dependencyName:"material"},{prefix:"textures/",dependencyName:"texture"},{prefix:"animations/",dependencyName:"animation"}];async function is(l,e){ts&&console.log(l,e);let t=[];El(Tf,l,e,t);let i=await Promise.all(t);return typeof e=="string"&&i.length===1?i[0]:i}function El(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=ah(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=wl(s.prefix,r);if(c>=0){ts&&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=ah(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=wl(d.prefix,s);if(a>=0){ts&&console.log(d,a,d.dependencyName),i.push(e?.getDependency(d.dependencyName,a).then(u=>r[o]=u));break}}typeof s=="object"&&El(l,e,s,i)}else typeof r=="object"&&El(l,e,r,i)}else typeof t=="string"&&Cf(l,e,t,i)}function ah(l,e){if(l&&l.plugins&&typeof e=="string"){for(let t of xf)if(e.startsWith(t)){let i=e.substring(t.length),n=i.indexOf("/");n>=0&&(i=i.substring(0,n));let r=l.plugins[i];if(Ke&&console.log(i,r),typeof r?.resolve=="function"){let o=e.substring(t.length+i.length+1);return r.resolve(l,o)}break}}return null}function Cf(l,e,t,i){for(let n of l){let r=wl(n.prefix,t);if(r>=0)return ts&&console.log(n,r,n.dependencyName),i.push(e?.getDependency(n.dependencyName,r).then(o=>o)),!0}return!1}function wl(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 _l=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]}},Zr=new _l;var Jn=H("debugserializer"),xl=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])}Jn&&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){Jn&&console.log("invalid type");return}let i=e.name??e.constructor?.name;if(!i){Jn&&console.log("invalid name",i);return}let n=this.getSerializer(i);if(n!==void 0)return Jn&&console.log("FOUND "+i,e.name,e.constructor.name,n,this.typeMap),n;let r=Object.getPrototypeOf(e);if(!(r.prototype||r.constructor)){Jn&&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){Jn&&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}}},lh=new xl,pi=class{constructor(e){if(Array.isArray(e))for(let t of e)lh.register(t.name,this);else lh.register(e.name,this)}},ns=class{root;gltf;gltfId;object;target;nodeId;nodeToObject;objectToNode;context;path;constructor(e){this.root=e}};function rs(l,e){if(e==null||l==null)return;let t=!1;for(let i of Object.keys(e)){let n=Rf(l,i);t&&n===void 0||(!n||n.writable===!0||n?.set!==void 0)&&(l[i]=e[i])}}function Rf(l,e){let t;do t=Object.getOwnPropertyDescriptor(l,e);while(!t&&(l=Object.getPrototypeOf(l)));return t}var $r=class{key;keyType;source;constructor(e){this.key=e.key,this.keyType=e.type,this.source=e}};var os=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 Tt.Vector2];_pointerPositionsLastFrame=[new Tt.Vector2];_pointerPositionsDelta=[new Tt.Vector2];_pointerPositionsRC=[new Tt.Vector2];_pointerPositionDown=[new Tt.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 typeof e=="number"&&(console.warn("Use of keycode as number is not recommended, please use KeyCode or string instead"),e=String.fromCharCode(e)),this.context.application.isVisible&&this.context.application.hasFocus&&this.keysPressed[e]?.startFrame===this.context.time.frameCount&&this.keysPressed[e].pressed}isKeyUp(e){return typeof e=="number"&&(console.warn("Use of keycode as number is not recommended, please use KeyCode or string instead"),e=String.fromCharCode(e)),this.context.application.isVisible&&this.context.application.hasFocus&&this.keysPressed[e]?.frame===this.context.time.frameCount&&!this.keysPressed[e].pressed}isKeyPressed(e){return typeof e=="number"&&(e=String.fromCharCode(e)),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.key];t&&t.pressed||(this.keysPressed[e.key]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:e.key},this.onDispatchEvent("keydown",new $r(e)))}onKeyPressed(e){if(!this.context.application.hasFocus)return;let t=this.keysPressed[e.key];!t||(t.pressed=!0,t.frame=this.context.time.frameCount+1,this.onDispatchEvent("keypress",new $r(e)))}onKeyUp(e){if(!this.context.application.hasFocus)return;let t=this.keysPressed[e.key];!t||(t.pressed=!1,t.frame=this.context.time.frameCount+1,this.onDispatchEvent("keyup",new $r(e)))}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;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){if(e.defaultPrevented||e.pointerType===void 0&&e.pointerId===void 0)return;let t=e.pointerType==="mouse"?e.button:this.getPointerIndex(e.pointerId);e.pointerId===void 0&&e.button!==void 0&&(t=e.button),t<0&&(t=0);let i={button:t,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,source:e};this.onMove(i),this.onDispatchEvent("pointermove",e)}onPointerUp(e){if(e.defaultPrevented||e.pointerType===void 0&&e.pointerId===void 0)return;let t=e.pointerType==="mouse"?e.button:this.getPointerIndex(e.pointerId);e.pointerId===void 0&&e.button!==void 0&&(t=e.button),this._pointerIds[t]=-1,this.onUp({button:t,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,source:e}),this.onDispatchEvent("pointerup",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 Tt.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),this.onDispatchEvent("pointerdown",e)}}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 Tt.Vector2);for(;e.button>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new Tt.Vector2);for(;e.button>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new Tt.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 Tt.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}onDispatchEvent(e,t){let i=J.Current;try{J.Current=this.context;let n=new Event(e);rs(n,t),this.dispatchEvent(n)}finally{J.Current=i}}};var ft=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 ft){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],u=i[5],h=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+u*w,r[4]=d*y+a*m+u*x,r[5]=d*g+a*v+u*T,r[6]=h*b+f*p+E*w,r[7]=h*y+f*m+E*x,r[8]=h*g+f*v+E*T,t}scale(e,t=new ft){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,u=4,h;do{if(o=d-c,r[o+4*o]===0){for(s=o+1;s<d;s++)if(r[o+4*s]!==0){a=u;do h=u-a,r[h+4*o]+=r[h+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=u;do h=u-a,r[h+4*s]=h<=o?0:r[h+4*s]-r[h+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 ft){let n=Sf,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,u;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 u=a-d,n[u+6*r]+=n[u+6*o];while(--d);break}}if(n[r+6*r]!==0)for(o=r+1;o<c;o++){let h=n[r+6*o]/n[r+6*r];d=a;do u=a-d,n[u+6*o]=u<=r?0:n[u+6*o]-n[u+6*r]*h;while(--d)}}while(--s);r=2;do{o=r-1;do{let h=n[r+6*o]/n[r+6*r];d=6;do u=6-d,n[u+6*o]=n[u+6*o]-n[u+6*r]*h;while(--d)}while(o--)}while(--r);r=2;do{let h=1/n[r+6*r];d=6;do u=6-d,n[u+6*r]=n[u+6*r]*h;while(--d)}while(r--);r=2;do{o=2;do{if(u=n[3+o+6*r],isNaN(u)||u===1/0)throw"Could not reverse! A=["+this.toString()+"]";e.e(r,o,u)}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,u=t*c,h=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-(h+E),p[3*0+1]=a-g,p[3*0+2]=u+y,p[3*1+0]=a+g,p[3*1+1]=1-(d+E),p[3*1+2]=f-b,p[3*2+0]=u-y,p[3*2+1]=f+b,p[3*2+2]=1-(d+h),this}transpose(e=new ft){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}},Sf=[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 ft([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=Pf,r=1/i;n.set(this.x*r,this.y*r,this.z*r);let o=Of;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(ch),ch.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 Pf=new _,Of=new _,ch=new _,ze=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,dh),d=dh),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 ze().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=hh,n=i[0],r=i[1],o=i[2],s=i[3],c=i[4],d=i[5],a=i[6],u=i[7];this.getCorners(n,r,o,s,c,d,a,u);for(let h=0;h!==8;h++){let f=i[h];e.pointToLocal(f,f)}return t.setFromPoints(i)}toWorldFrame(e,t){let i=hh,n=i[0],r=i[1],o=i[2],s=i[3],c=i[4],d=i[5],a=i[6],u=i[7];this.getCorners(n,r,o,s,c,d,a,u);for(let h=0;h!==8;h++){let f=i[h];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,u=(this.lowerBound.z-i.z)*o,h=(this.upperBound.z-i.z)*o,f=Math.max(Math.max(Math.min(s,c),Math.min(d,a)),Math.min(u,h)),E=Math.min(Math.min(Math.max(s,c),Math.max(d,a)),Math.max(u,h));return!(E<0||f>E)}},dh=new _,hh=[new _,new _,new _,new _,new _,new _,new _,new _],hs=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}},us=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}},re=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=kf,n=If;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 re){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 re){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 re){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,u=d*n+c*i-o*r,h=d*r+o*n-s*i,f=-o*i-s*n-c*r;return t.x=a*d+f*-o+u*-c-h*-s,t.y=u*d+f*-s+h*-o-a*-c,t.z=h*d+f*-c+a*-s-u*-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 u=o*o,h=s*s,f=c*c;i=Math.atan2(2*s*d-2*o*c,1-2*h-2*f),n=Math.asin(2*a),r=Math.atan2(2*o*d-2*s*c,1-2*u-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 re(this.x,this.y,this.z,this.w)}slerp(e,t,i=new re){let n=this.x,r=this.y,o=this.z,s=this.w,c=e.x,d=e.y,a=e.z,u=e.w,h,f,E,b,y;return f=n*c+r*d+o*a+s*u,f<0&&(f=-f,c=-c,d=-d,a=-a,u=-u),1-f>1e-6?(h=Math.acos(f),E=Math.sin(h),b=Math.sin((1-t)*h)/E,y=Math.sin(t*h)/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*u,i}integrate(e,t,i,n=new re){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,u=this.w,h=t*.5;return n.x+=h*(r*u+o*a-s*d),n.y+=h*(o*u+s*c-r*a),n.z+=h*(s*u+r*d-o*c),n.w+=h*(-r*c-o*d-s*a),n}},kf=new _,If=new _,Af={SPHERE:1,PLANE:2,BOX:4,COMPOUND:8,CONVEXPOLYHEDRON:16,HEIGHTFIELD:32,PARTICLE:64,CYLINDER:128,TRIMESH:256},U=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=U.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}};U.idCounter=0;U.types=Af;var ee=class{constructor(e={}){this.position=void 0,this.quaternion=void 0,this.position=new _,this.quaternion=new re,e.position&&this.position.copy(e.position),e.quaternion&&this.quaternion.copy(e.quaternion)}pointToLocal(e,t){return ee.pointToLocalFrame(this.position,this.quaternion,e,t)}pointToWorld(e,t){return ee.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(uh),uh.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}},uh=new re,hn=class extends U{constructor(e={}){let{vertices:t=[],faces:i=[],normals:n=[],axes:r,boundingSphereRadius:o}=e;super({type:U.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 u=0;u!==i.length;u++)if(i[u].almostEquals(n)||i[u].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]];hn.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 _,u=-1,h=-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>h&&(h=b,u=E)}let f=[];for(let E=0;E<i.faces[u].length;E++){let b=i.vertices[i.faces[u][E]],y=new _;y.copy(b),r.vmult(y,y),n.vadd(y,y),f.push(y)}u>=0&&this.clipFaceAgainstHull(o,e,t,f,s,c,d)}findSeparatingAxis(e,t,i,n,r,o,s,c){let d=new _,a=new _,u=new _,h=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],h);for(let p=0;p!==e.uniqueEdges.length;p++)if(r.vmult(e.uniqueEdges[p],f),h.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,u),u.dot(o)>0&&o.negate(o),!0}testSepAxis(e,t,i,n,r,o){let s=this;hn.project(s,e,i,n,Tl),hn.project(t,e,r,o,Cl);let c=Tl[0],d=Tl[1],a=Cl[0],u=Cl[1];if(c<u||a<d)return!1;let h=c-u,f=a-d;return h<f?h: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 _,u=new _,h=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]],M=y.vertices[x[(P+1)%T]];S.vsub(M,d),a.copy(d),i.vmult(a,a),t.vadd(a,a),u.copy(this.faceNormals[v]),i.vmult(u,u),t.vadd(u,u),a.cross(u,h),h.negate(h),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 L=j-b.dot(t);for(this.clipFaceAgainstPlane(p,m,b,L);p.length;)p.shift();for(;m.length;)p.push(m.shift())}E.copy(this.faceNormals[v]);let C=this.getPlaneConstantOfFace(v);b.copy(E),i.vmult(b,b);let R=C-b.dot(t);for(let P=0;P<p.length;P++){let S=b.dot(p[P])+R;if(S<=r&&(console.log("clamped: depth="+S+" to minDist="+r),S=r),S<=o){let M=p[P];if(S<=1e-6){let I={point:M,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 u=new _;u.copy(d),t.push(u)}else{let u=new _;c.lerp(d,r/(r-o),u),t.push(u)}else if(o<0){let u=new _;c.lerp(d,r/(r-o),u),t.push(u),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,u,h=new _;for(let f=0;f<r.length;f++){h.copy(r[f]),t.vmult(h,h),e.vadd(h,h);let E=h;(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),(u===void 0||E.z>u)&&(u=E.z)}i.set(o,s,c),n.set(d,a,u)}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),u=new _;r.vsub(c,u);let h=s.dot(u);if(a<0&&h>0||a>0&&h<0)return!1}return-1}static project(e,t,i,n,r){let o=e.vertices.length,s=Mf,c=0,d=0,a=Df,u=e.vertices;a.setZero(),ee.vectorToLocalFrame(i,n,t,s),ee.pointToLocalFrame(i,n,a,a);let h=a.dot(s);d=c=u[0].dot(s);for(let f=1;f<o;f++){let E=u[f].dot(s);E>c&&(c=E),E<d&&(d=E)}if(d-=h,c-=h,d>c){let f=d;d=c,c=f}r[0]=c,r[1]=d}},Tl=[],Cl=[],Mf=new _,Df=new _,un=class extends U{constructor(e){super({type:U.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 hn({vertices:r,faces:o,axes:s});this.convexPolyhedronRepresentation=c,c.material=this.material}calculateLocalInertia(e,t=new _){return un.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++)Li.set(r[o][0],r[o][1],r[o][2]),t.vmult(Li,Li),e.vadd(Li,Li),i(Li.x,Li.y,Li.z)}calculateWorldAABB(e,t,i,n){let r=this.halfExtents;Vt[0].set(r.x,r.y,r.z),Vt[1].set(-r.x,r.y,r.z),Vt[2].set(-r.x,-r.y,r.z),Vt[3].set(-r.x,-r.y,-r.z),Vt[4].set(r.x,-r.y,-r.z),Vt[5].set(r.x,r.y,-r.z),Vt[6].set(-r.x,r.y,-r.z),Vt[7].set(r.x,-r.y,r.z);let o=Vt[0];t.vmult(o,o),e.vadd(o,o),n.copy(o),i.copy(o);for(let s=1;s<8;s++){let c=Vt[s];t.vmult(c,c),e.vadd(c,c);let d=c.x,a=c.y,u=c.z;d>n.x&&(n.x=d),a>n.y&&(n.y=a),u>n.z&&(n.z=u),d<i.x&&(i.x=d),a<i.y&&(i.y=a),u<i.z&&(i.z=u)}}},Li=new _,Vt=[new _,new _,new _,new _,new _,new _,new _,new _],Bl={DYNAMIC:1,STATIC:2,KINEMATIC:4},Fl={AWAKE:0,SLEEPY:1,SLEEPING:2},z=class extends us{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=z.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?z.STATIC:z.DYNAMIC,typeof e.type==typeof z.STATIC&&(this.type=e.type),this.allowSleep=typeof e.allowSleep<"u"?e.allowSleep:!0,this.sleepState=z.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 re,this.initQuaternion=new re,this.previousQuaternion=new re,this.interpolatedQuaternion=new re,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 ft,this.invMassSolve=0,this.invInertiaSolve=new _,this.invInertiaWorldSolve=new ft,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 ze,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=z.AWAKE,this.wakeUpAfterNarrowphase=!1,e===z.SLEEPING&&this.dispatchEvent(z.wakeupEvent)}sleep(){this.sleepState=z.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===z.AWAKE&&i<n?(this.sleepState=z.SLEEPY,this.timeLastSleepy=e,this.dispatchEvent(z.sleepyEvent)):t===z.SLEEPY&&i>n?this.wakeUp():t===z.SLEEPY&&e-this.timeLastSleepy>this.sleepTimeLimit&&(this.sleep(),this.dispatchEvent(z.sleepEvent))}}updateSolveMassProperties(){this.sleepState===z.SLEEPING||this.type===z.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 re;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=Lf,o=Hf,s=this.quaternion,c=this.aabb,d=jf;for(let a=0;a!==n;a++){let u=e[a];s.vmult(t[a],r),r.vadd(this.position,r),s.mult(i[a],o),u.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=Bf,n=Ff;i.setRotationFromQuaternion(this.quaternion),i.transpose(n),i.scale(t,i),i.mmult(n,this.invInertiaWorld)}}applyForce(e,t=new _){if(this.type!==z.DYNAMIC)return;this.sleepState===z.SLEEPING&&this.wakeUp();let i=Nf;t.cross(e,i),this.force.vadd(e,this.force),this.torque.vadd(i,this.torque)}applyLocalForce(e,t=new _){if(this.type!==z.DYNAMIC)return;let i=zf,n=Uf;this.vectorToWorldFrame(e,i),this.vectorToWorldFrame(t,n),this.applyForce(i,n)}applyTorque(e){this.type===z.DYNAMIC&&(this.sleepState===z.SLEEPING&&this.wakeUp(),this.torque.vadd(e,this.torque))}applyImpulse(e,t=new _){if(this.type!==z.DYNAMIC)return;this.sleepState===z.SLEEPING&&this.wakeUp();let i=t,n=Vf;n.copy(e),n.scale(this.invMass,n),this.velocity.vadd(n,this.velocity);let r=Wf;i.cross(e,r),this.invInertiaWorld.vmult(r,r),this.angularVelocity.vadd(r,this.angularVelocity)}applyLocalImpulse(e,t=new _){if(this.type!==z.DYNAMIC)return;let i=Gf,n=qf;this.vectorToWorldFrame(e,i),this.vectorToWorldFrame(t,n),this.applyImpulse(i,n)}updateMassProperties(){let e=Xf;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),un.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===z.DYNAMIC||this.type===z.KINEMATIC)||this.sleepState===z.SLEEPING)return;let n=this.velocity,r=this.angularVelocity,o=this.position,s=this.force,c=this.torque,d=this.quaternion,a=this.invMass,u=this.invInertiaWorld,h=this.linearFactor,f=a*e;n.x+=s.x*f*h.x,n.y+=s.y*f*h.y,n.z+=s.z*f*h.z;let E=u.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()}};z.idCounter=0;z.COLLIDE_EVENT_NAME="collide";z.DYNAMIC=Bl.DYNAMIC;z.STATIC=Bl.STATIC;z.KINEMATIC=Bl.KINEMATIC;z.AWAKE=Fl.AWAKE;z.SLEEPY=Fl.SLEEPY;z.SLEEPING=Fl.SLEEPING;z.wakeupEvent={type:"wakeup"};z.sleepyEvent={type:"sleepy"};z.sleepEvent={type:"sleep"};var Lf=new _,Hf=new re,jf=new ze,Bf=new ft,Ff=new ft,Nf=new _,zf=new _,Uf=new _,Vf=new _,Wf=new _,Gf=new _,qf=new _,Xf=new _,Ol=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&z.STATIC)!==0||e.sleepState===z.SLEEPING)&&((t.type&z.STATIC)!==0||t.sleepState===z.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=Qf;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=Yf,n=Kf,r=Jf,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."),[]}},Qf=new _,Yf={keys:[]},Kf=[],Jf=[];var ZE=new _,kl=class extends Ol{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}},ro=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}},Th,Ch,Rh,Sh,Ph,Oh,kh,Nl={CLOSEST:1,ANY:2,ALL:4};Th=U.types.SPHERE;Ch=U.types.PLANE;Rh=U.types.BOX;Sh=U.types.CYLINDER;Ph=U.types.CONVEXPOLYHEDRON;Oh=U.types.HEIGHTFIELD;kh=U.types.TRIMESH;var pe=class{get[Th](){return this._intersectSphere}get[Ch](){return this._intersectPlane}get[Rh](){return this._intersectBox}get[Sh](){return this._intersectConvex}get[Ph](){return this._intersectConvex}get[Oh](){return this._intersectHeightfield}get[kh](){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=pe.ANY,this.result=new ro,this.hasHit=!1,this.callback=i=>{}}intersectWorld(e,t){return this.mode=t.mode||pe.ANY,this.result=t.result||new ro,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(ph),Rl.length=0,e.broadphase.aabbQuery(e,ph,Rl),this.intersectBodies(Rl),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=Zf,r=$f;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(pm(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 u=a.dot(d);s.vsub(i,a);let h=a.dot(d);if(u*h>0||o.distanceTo(s)<u)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=em;o.from.copy(this.from),o.to.copy(this.to),ee.pointToLocalFrame(i,t,o.from,o.from),ee.pointToLocalFrame(i,t,o.to,o.to),o.updateDirection();let s=tm,c,d,a,u;c=d=0,a=u=e.data.length-1;let h=new ze;o.getAABB(h),e.getIndexOfPosition(h.lowerBound.x,h.lowerBound.y,s,!0),c=Math.max(c,s[0]),d=Math.max(d,s[1]),e.getIndexOfPosition(h.upperBound.x,h.upperBound.y,s,!0),a=Math.min(a,s[0]+1),u=Math.min(u,s[1]+1);for(let f=c;f<a;f++)for(let E=d;E<u;E++){if(this.result.shouldStop)return;if(e.getAabbAtIndex(f,E,h),!!h.overlapsRay(o)){if(e.getConvexTrianglePillar(f,E,!1),ee.pointToWorldFrame(i,t,e.pillarOffset,ss),this._intersectConvex(e.pillarConvex,t,ss,n,r,fh),this.result.shouldStop)return;e.getConvexTrianglePillar(f,E,!0),ee.pointToWorldFrame(i,t,e.pillarOffset,ss),this._intersectConvex(e.pillarConvex,t,ss,n,r,fh)}}}_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)),u=(o.x-i.x)**2+(o.y-i.y)**2+(o.z-i.z)**2-c**2,h=a**2-4*d*u,f=im,E=nm;if(!(h<0))if(h===0)o.lerp(s,h,f),f.vsub(i,E),E.normalize(),this.reportIntersection(E,f,r,n,-1);else{let b=(-a-Math.sqrt(h))/(2*d),y=(-a+Math.sqrt(h))/(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=rm,c=mh,d=o&&o.faceList||null,a=e.faces,u=e.vertices,h=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=h[v],T=t,C=i;c.copy(u[w[0]]),T.vmult(c,c),c.vadd(C,c),c.vsub(E,c),T.vmult(x,s);let R=f.dot(s);if(Math.abs(R)<this.precision)continue;let P=s.dot(c)/R;if(!(P<0)){f.scale(P,Je),Je.vadd(E,Je),Ct.copy(u[w[0]]),T.vmult(Ct,Ct),C.vadd(Ct,Ct);for(let S=1;!p.shouldStop&&S<w.length-1;S++){Wt.copy(u[w[S]]),Gt.copy(u[w[S+1]]),T.vmult(Wt,Wt),T.vmult(Gt,Gt),C.vadd(Wt,Wt),C.vadd(Gt,Gt);let M=Je.distanceTo(E);!(pe.pointInTriangle(Je,Ct,Wt,Gt)||pe.pointInTriangle(Je,Wt,Ct,Gt))||M>y||this.reportIntersection(s,Je,r,n,v)}}}}_intersectTrimesh(e,t,i,n,r,o){let s=om,c=hm,d=um,a=mh,u=sm,h=am,f=lm,E=dm,b=cm,y=e.indices;e.vertices;let g=this.from,p=this.to,m=this.direction;d.position.copy(i),d.quaternion.copy(t),ee.vectorToLocalFrame(i,t,m,u),ee.pointToLocalFrame(i,t,g,h),ee.pointToLocalFrame(i,t,p,f),f.x*=e.scale.x,f.y*=e.scale.y,f.z*=e.scale.z,h.x*=e.scale.x,h.y*=e.scale.y,h.z*=e.scale.z,f.vsub(h,u),u.normalize();let v=h.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],Ct),Ct.vsub(h,a);let C=u.dot(s),R=s.dot(a)/C;if(R<0)continue;u.scale(R,Je),Je.vadd(h,Je),e.getVertex(y[T*3+1],Wt),e.getVertex(y[T*3+2],Gt);let P=Je.distanceSquared(h);!(pe.pointInTriangle(Je,Wt,Ct,Gt)||pe.pointInTriangle(Je,Ct,Wt,Gt))||P>v||(ee.vectorToWorldFrame(t,s,b),ee.pointToWorldFrame(i,t,Je,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 pe.ALL:this.hasHit=!0,d.set(o,s,e,t,i,n,c),d.hasHit=!0,this.callback(d);break;case pe.CLOSEST:(c<d.distance||!d.hasHit)&&(this.hasHit=!0,d.hasHit=!0,d.set(o,s,e,t,i,n,c));break;case pe.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,dn),i.vsub(t,eo),e.vsub(t,Sl);let r=dn.dot(dn),o=dn.dot(eo),s=dn.dot(Sl),c=eo.dot(eo),d=eo.dot(Sl),a,u;return(a=c*s-o*d)>=0&&(u=r*d-o*s)>=0&&a+u<r*c-o*o}};pe.CLOSEST=Nl.CLOSEST;pe.ANY=Nl.ANY;pe.ALL=Nl.ALL;var ph=new ze,Rl=[],eo=new _,Sl=new _,Zf=new _,$f=new re,Je=new _,Ct=new _,Wt=new _,Gt=new _,fh={faceList:[0]},ss=new _,em=new pe,tm=[],im=new _,nm=new _,rm=new _,mh=new _,om=new _,sm=new _,am=new _,lm=new _,cm=new _,dm=new _;new ze;var hm=[],um=new ee,dn=new _,as=new _;function pm(l,e,t){t.vsub(l,dn);let i=dn.dot(e);return e.scale(i,as),as.vadd(l,as),t.distanceTo(as)}var ps=class{static defaults(e={},t){for(let i in t)i in e||(e[i]=t[i]);return e}},oo=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=ps.defaults(i,{collideConnected:!0,wakeUpBodies:!0}),this.equations=[],this.bodyA=e,this.bodyB=t,this.id=oo.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}};oo.idCounter=0;var fs=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)}},pn=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=pn.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 fs,this.jacobianElementB=new fs,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,gh),s.scale(a,bh),i.invInertiaWorldSolve.vmult(o,vh),n.invInertiaWorldSolve.vmult(c,yh),e.multiplyVectors(gh,vh)+t.multiplyVectors(bh,yh)}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,ls),d+=ls.dot(e.rotational),c.vmult(t.rotational,ls),d+=ls.dot(t.rotational),d}addToWlambda(e){let t=this.jacobianElementA,i=this.jacobianElementB,n=this.bi,r=this.bj,o=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,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}};pn.idCounter=0;var gh=new _,bh=new _,vh=new _,yh=new _,ls=new _,fm=new _,Il=class extends pn{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=mm,d=gm,a=n.velocity,u=n.angularVelocity;n.force,n.torque;let h=r.velocity,f=r.angularVelocity;r.force,r.torque;let E=bm,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*h.dot(g)-m*a.dot(g)+f.dot(d)-u.dot(c),w=this.computeGiMf();return-p*t-v*i-e*w}getImpactVelocityAlongNormal(){let e=vm,t=ym,i=Em,n=wm,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)}},mm=new _,gm=new _,bm=new _,vm=new _,ym=new _,Em=new _,wm=new _,_m=new _;var $E=new _,ew=new _;var tw=new _,iw=new _;var nw=new _,rw=new _,ms=class extends pn{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=xm,o=Tm,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(),u=this.computeGiMf();return-a*t-e*u}},xm=new _,Tm=new _,er=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=ps.defaults(i,{friction:.3,restitution:.3,contactEquationStiffness:1e7,contactEquationRelaxation:3,frictionEquationStiffness:1e7,frictionEquationRelaxation:3}),this.id=er.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}};er.idCounter=0;var tr=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=tr.idCounter++,this.friction=typeof e.friction<"u"?e.friction:-1,this.restitution=typeof e.restitution<"u"?e.restitution:-1}};tr.idCounter=0;var gs=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=Cm,s=Rm,c=Sm,d=Pm,a=Lm,u=Om,h=km,f=Im,E=Am,b=Mm,y=Dm;this.getWorldAnchorA(u),this.getWorldAnchorB(h),u.vsub(n.position,f),h.vsub(r.position,E),h.vsub(u,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)}},Cm=new _,Rm=new _,Sm=new _,Pm=new _,Om=new _,km=new _,Im=new _,Am=new _,Mm=new _,Dm=new _,Lm=new _;var ow=new _,sw=new _;var aw=new _,lw=new _,cw=new _;new pe;var dw=new _,hw=new _,uw=[new _(1,0,0),new _(0,1,0),new _(0,0,1)],pw=new _;var fw=new _,mw=new _,gw=new _;var bw=new _,vw=new _,yw=new _,Ew=new _;var ww=new _,_w=new _,xw=new _;var bs=class extends U{constructor(e){if(super({type:U.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 Tw=new _,Cw=new _;var Rw=new _,Sw=new _,Pw=new _,Ow=new _,kw=new _,Iw=new _,Aw=new _;var Mw=new _;var Dw=new _,Lw=new _,Hw=new _,jw=new _,Bw=new _,Fw=new _,Nw=new _,zw=new _,Uw=new _;var Vw=new _,Ww=new ze;var Gw=new _,qw=new ze,Xw=new _,Qw=new _,Yw=new _,Kw=new _,Jw=new _,Zw=new _,$w=new _,e_=new ze,t_=new _,i_=new ee,n_=new ze,Al=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}},Ml=class extends Al{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,u,h,f,E,b,y;if(s!==0)for(let v=0;v!==d;v++)c[v].updateSolveMassProperties();let g=jm,p=Bm,m=Hm;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],C=T.vlambda,R=T.wlambda;C.set(0,0,0),R.set(0,0,0)}for(i=0;i!==n;i++){E=0;for(let x=0;x!==s;x++){let T=o[x];u=p[x],h=g[x],y=m[x],b=T.computeGWlambda(),f=h*(u-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],C=T.velocity,R=T.angularVelocity;T.vlambda.vmul(T.linearFactor,T.vlambda),C.vadd(T.vlambda,C),T.wlambda.vmul(T.angularFactor,T.wlambda),R.vadd(T.wlambda,R)}let v=o.length,w=1/a;for(;v--;)o[v].multiplier=m[v]*w}return i}},Hm=[],jm=[],Bm=[];var r_=z.STATIC;var Dl=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}},Ll=class extends Dl{constructor(...e){super(...e),this.type=_}constructObject(){return new _}},Ih,Ah,Mh,Dh,Lh,Hh,jh,Bh,Fh,Nh,zh,Uh,Vh,Wh,Gh,qh,Xh,Qh,Yh,Kh,Jh,Zh,$h,eu,tu,se={sphereSphere:U.types.SPHERE,spherePlane:U.types.SPHERE|U.types.PLANE,boxBox:U.types.BOX|U.types.BOX,sphereBox:U.types.SPHERE|U.types.BOX,planeBox:U.types.PLANE|U.types.BOX,convexConvex:U.types.CONVEXPOLYHEDRON,sphereConvex:U.types.SPHERE|U.types.CONVEXPOLYHEDRON,planeConvex:U.types.PLANE|U.types.CONVEXPOLYHEDRON,boxConvex:U.types.BOX|U.types.CONVEXPOLYHEDRON,sphereHeightfield:U.types.SPHERE|U.types.HEIGHTFIELD,boxHeightfield:U.types.BOX|U.types.HEIGHTFIELD,convexHeightfield:U.types.CONVEXPOLYHEDRON|U.types.HEIGHTFIELD,sphereParticle:U.types.PARTICLE|U.types.SPHERE,planeParticle:U.types.PLANE|U.types.PARTICLE,boxParticle:U.types.BOX|U.types.PARTICLE,convexParticle:U.types.PARTICLE|U.types.CONVEXPOLYHEDRON,cylinderCylinder:U.types.CYLINDER,sphereCylinder:U.types.SPHERE|U.types.CYLINDER,planeCylinder:U.types.PLANE|U.types.CYLINDER,boxCylinder:U.types.BOX|U.types.CYLINDER,convexCylinder:U.types.CONVEXPOLYHEDRON|U.types.CYLINDER,heightfieldCylinder:U.types.HEIGHTFIELD|U.types.CYLINDER,particleCylinder:U.types.PARTICLE|U.types.CYLINDER,sphereTrimesh:U.types.SPHERE|U.types.TRIMESH,planeTrimesh:U.types.PLANE|U.types.TRIMESH};Ih=se.sphereSphere;Ah=se.spherePlane;Mh=se.boxBox;Dh=se.sphereBox;Lh=se.planeBox;Hh=se.convexConvex;jh=se.sphereConvex;Bh=se.planeConvex;Fh=se.boxConvex;Nh=se.sphereHeightfield;zh=se.boxHeightfield;Uh=se.convexHeightfield;Vh=se.sphereParticle;Wh=se.planeParticle;Gh=se.boxParticle;qh=se.convexParticle;Xh=se.cylinderCylinder;Qh=se.sphereCylinder;Yh=se.planeCylinder;Kh=se.boxCylinder;Jh=se.convexCylinder;Zh=se.heightfieldCylinder;$h=se.particleCylinder;eu=se.sphereTrimesh;tu=se.planeTrimesh;var Hl=class{get[Ih](){return this.sphereSphere}get[Ah](){return this.spherePlane}get[Mh](){return this.boxBox}get[Dh](){return this.sphereBox}get[Lh](){return this.planeBox}get[Hh](){return this.convexConvex}get[jh](){return this.sphereConvex}get[Bh](){return this.planeConvex}get[Fh](){return this.boxConvex}get[Nh](){return this.sphereHeightfield}get[zh](){return this.boxHeightfield}get[Uh](){return this.convexHeightfield}get[Vh](){return this.sphereParticle}get[Wh](){return this.planeParticle}get[Gh](){return this.boxParticle}get[qh](){return this.convexParticle}get[Xh](){return this.convexConvex}get[Qh](){return this.sphereConvex}get[Yh](){return this.planeConvex}get[Kh](){return this.boxConvex}get[Jh](){return this.convexConvex}get[Zh](){return this.heightfieldCylinder}get[$h](){return this.particleCylinder}get[eu](){return this.sphereTrimesh}get[tu](){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 Ll,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 Il(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,u=o.material||n.material;if(a&&u&&a.friction>=0&&u.friction>=0&&(d=a.friction*u.friction),d>0){let h=d*s.gravity.length(),f=i.invMass+n.invMass;f>0&&(f=1/f);let E=this.frictionEquationPool,b=E.length?E.pop():new ms(i,n,h*f),y=E.length?E.pop():new ms(i,n,h*f);return b.bi=y.bi=i,b.bj=y.bj=n,b.minForce=y.minForce=-h*f,b.maxForce=y.maxForce=h*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];cn.setZero(),Zn.setZero(),$n.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?(cn.vadd(t.ni,cn),Zn.vadd(t.ri,Zn),$n.vadd(t.rj,$n)):(cn.vsub(t.ni,cn),Zn.vadd(t.rj,Zn),$n.vadd(t.ri,$n));let o=1/e;Zn.scale(o,i.ri),$n.scale(o,i.rj),n.ri.copy(i.ri),n.rj.copy(i.rj),cn.normalize(),cn.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=zm,d=Um,a=Fm,u=Nm;for(let h=0,f=e.length;h!==f;h++){let E=e[h],b=t[h],y=null;E.material&&b.material&&(y=i.getContactMaterial(E.material,b.material)||null);let g=E.type&z.KINEMATIC&&b.type&z.STATIC||E.type&z.STATIC&&b.type&z.KINEMATIC||E.type&z.KINEMATIC&&b.type&z.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],u),u.vadd(b.position,u);let w=b.shapes[v];if(!(m.collisionFilterMask&w.collisionFilterGroup&&w.collisionFilterMask&m.collisionFilterGroup)||a.distanceTo(u)>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,C=this[T];if(C){let R=!1;m.type<w.type?R=C.call(this,m,w,a,u,c,d,E,b,m,w,g):R=C.call(this,w,m,u,a,d,c,b,E,m,w,g),R&&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,u){if(u)return i.distanceSquared(n)<(e.radius+t.radius)**2;let h=this.createContactEquation(s,c,e,t,d,a);n.vsub(i,h.ni),h.ni.normalize(),h.ri.copy(h.ni),h.rj.copy(h.ni),h.ri.scale(e.radius,h.ri),h.rj.scale(-t.radius,h.rj),h.ri.vadd(i,h.ri),h.ri.vsub(s.position,h.ri),h.rj.vadd(n,h.rj),h.rj.vsub(c.position,h.rj),this.result.push(h),this.createFrictionEquationsFromContact(h,this.frictionResult)}spherePlane(e,t,i,n,r,o,s,c,d,a,u){let h=this.createContactEquation(s,c,e,t,d,a);if(h.ni.set(0,0,1),o.vmult(h.ni,h.ni),h.ni.negate(h.ni),h.ni.normalize(),h.ni.scale(e.radius,h.ri),i.vsub(n,cs),h.ni.scale(h.ni.dot(cs),Eh),cs.vsub(Eh,h.rj),-cs.dot(h.ni)<=e.radius){if(u)return!0;let f=h.ri,E=h.rj;f.vadd(i,f),f.vsub(s.position,f),E.vadd(n,E),E.vsub(c.position,E),this.result.push(h),this.createFrictionEquationsFromContact(h,this.frictionResult)}}boxBox(e,t,i,n,r,o,s,c,d,a,u){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,u)}sphereBox(e,t,i,n,r,o,s,c,d,a,u){let h=this.v3pool,f=fg;i.vsub(n,ds),t.getSideNormals(f,o);let E=e.radius,b=!1,y=gg,g=bg,p=vg,m=null,v=0,w=0,x=0,T=null;for(let F=0,W=f.length;F!==W&&b===!1;F++){let Q=hg;Q.copy(f[F]);let V=Q.length();Q.normalize();let De=ds.dot(Q);if(De<V+E&&De>0){let ue=ug,q=pg;ue.copy(f[(F+1)%3]),q.copy(f[(F+2)%3]);let Be=ue.length(),Ai=q.length();ue.normalize(),q.normalize();let an=ds.dot(ue),ui=ds.dot(q);if(an<Be&&an>-Be&&ui<Ai&&ui>-Ai){let pt=Math.abs(De-V-E);if((T===null||pt<T)&&(T=pt,w=an,x=ui,m=V,y.copy(Q),g.copy(ue),p.copy(q),v++,u))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 C=h.get(),R=mg;for(let F=0;F!==2&&!b;F++)for(let W=0;W!==2&&!b;W++)for(let Q=0;Q!==2&&!b;Q++)if(C.set(0,0,0),F?C.vadd(f[0],C):C.vsub(f[0],C),W?C.vadd(f[1],C):C.vsub(f[1],C),Q?C.vadd(f[2],C):C.vsub(f[2],C),n.vadd(C,R),R.vsub(i,R),R.lengthSquared()<E*E){if(u)return!0;b=!0;let V=this.createContactEquation(s,c,e,t,d,a);V.ri.copy(R),V.ri.normalize(),V.ni.copy(V.ri),V.ri.scale(E,V.ri),V.rj.copy(C),V.ri.vadd(i,V.ri),V.ri.vsub(s.position,V.ri),V.rj.vadd(n,V.rj),V.rj.vsub(c.position,V.rj),this.result.push(V),this.createFrictionEquationsFromContact(V,this.frictionResult)}h.release(C),C=null;let P=h.get(),S=h.get(),M=h.get(),I=h.get(),j=h.get(),L=f.length;for(let F=0;F!==L&&!b;F++)for(let W=0;W!==L&&!b;W++)if(F%3!==W%3){f[W].cross(f[F],P),P.normalize(),f[F].vadd(f[W],S),M.copy(i),M.vsub(S,M),M.vsub(n,M);let Q=M.dot(P);P.scale(Q,I);let V=0;for(;V===F%3||V===W%3;)V++;j.copy(i),j.vsub(I,j),j.vsub(S,j),j.vsub(n,j);let De=Math.abs(Q),ue=j.length();if(De<f[V].length()&&ue<E){if(u)return!0;b=!0;let q=this.createContactEquation(s,c,e,t,d,a);S.vadd(I,q.rj),q.rj.copy(q.rj),j.negate(q.ni),q.ni.normalize(),q.ri.copy(q.rj),q.ri.vadd(n,q.ri),q.ri.vsub(i,q.ri),q.ri.normalize(),q.ri.scale(E,q.ri),q.ri.vadd(i,q.ri),q.ri.vsub(s.position,q.ri),q.rj.vadd(n,q.rj),q.rj.vsub(c.position,q.rj),this.result.push(q),this.createFrictionEquationsFromContact(q,this.frictionResult)}}h.release(P,S,M,I,j)}planeBox(e,t,i,n,r,o,s,c,d,a,u){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,u)}convexConvex(e,t,i,n,r,o,s,c,d,a,u,h,f){let E=Mg;if(!(i.distanceTo(n)>e.boundingSphereRadius+t.boundingSphereRadius)&&e.findSeparatingAxis(t,i,r,n,o,E,h,f)){let b=[],y=Dg;e.clipAgainstHull(i,r,t,n,o,E,-100,100,b);let g=0;for(let p=0;p!==b.length;p++){if(u)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,u){let h=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=xg;o.vmult(m,v),n.vadd(v,v);let w=_g;if(v.vsub(i,w),w.lengthSquared()<y*y){if(u)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=Tg;o.vmult(v,x);let T=Cg;o.vmult(b[w[0]],T),T.vadd(n,T);let C=Rg;x.scale(-y,C),i.vadd(C,C);let R=Sg;C.vsub(T,R);let P=R.dot(x),S=Pg;if(i.vsub(T,S),P<0&&S.dot(x)>0){let M=[];for(let I=0,j=w.length;I!==j;I++){let L=h.get();o.vmult(b[w[I]],L),n.vadd(L,L),M.push(L)}if(dg(M,x,i)){if(u)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=h.get();x.scale(-P,j);let L=h.get();x.scale(-y,L),i.vsub(n,I.rj),I.rj.vadd(L,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),h.release(j),h.release(L),this.result.push(I),this.createFrictionEquationsFromContact(I,this.frictionResult);for(let F=0,W=M.length;F!==W;F++)h.release(M[F]);return}else for(let I=0;I!==w.length;I++){let j=h.get(),L=h.get();o.vmult(b[w[(I+1)%w.length]],j),o.vmult(b[w[(I+2)%w.length]],L),n.vadd(j,j),n.vadd(L,L);let F=Eg;L.vsub(j,F);let W=wg;F.unit(W);let Q=h.get(),V=h.get();i.vsub(j,V);let De=V.dot(W);W.scale(De,Q),Q.vadd(j,Q);let ue=h.get();if(Q.vsub(i,ue),De>0&&De*De<F.lengthSquared()&&ue.lengthSquared()<y*y){if(u)return!0;let q=this.createContactEquation(s,c,e,t,d,a);Q.vsub(n,q.rj),Q.vsub(i,q.ni),q.ni.normalize(),q.ni.scale(y,q.ri),q.rj.vadd(n,q.rj),q.rj.vsub(c.position,q.rj),q.ri.vadd(i,q.ri),q.ri.vsub(s.position,q.ri),this.result.push(q),this.createFrictionEquationsFromContact(q,this.frictionResult);for(let Be=0,Ai=M.length;Be!==Ai;Be++)h.release(M[Be]);h.release(j),h.release(L),h.release(Q),h.release(ue),h.release(V);return}h.release(j),h.release(L),h.release(Q),h.release(ue),h.release(V)}for(let I=0,j=M.length;I!==j;I++)h.release(M[I])}}}planeConvex(e,t,i,n,r,o,s,c,d,a,u){let h=Og,f=kg;f.set(0,0,1),r.vmult(f,f);let E=0,b=Ig;for(let y=0;y!==t.vertices.length;y++)if(h.copy(t.vertices[y]),o.vmult(h,h),n.vadd(h,h),h.vsub(i,b),f.dot(b)<=0){if(u)return!0;let p=this.createContactEquation(s,c,e,t,d,a),m=Ag;f.scale(f.dot(b),m),h.vsub(m,m),m.vsub(i,p.ri),p.ni.copy(f),h.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,u){return e.convexPolyhedronRepresentation.material=e.material,e.convexPolyhedronRepresentation.collisionResponse=e.collisionResponse,this.convexConvex(e.convexPolyhedronRepresentation,t,i,n,r,o,s,c,e,t,u)}sphereHeightfield(e,t,i,n,r,o,s,c,d,a,u){let h=t.data,f=e.radius,E=t.elementSize,b=qg,y=Gg;ee.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>h.length||m>h[0].length)return;g<0&&(g=0),p<0&&(p=0),m<0&&(m=0),v<0&&(v=0),g>=h.length&&(g=h.length-1),p>=h.length&&(p=h.length-1),v>=h[0].length&&(v=h[0].length-1),m>=h[0].length&&(m=h[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 C=this.result;for(let R=g;R<p;R++)for(let P=m;P<v;P++){let S=C.length,M=!1;if(t.getConvexTrianglePillar(R,P,!1),ee.pointToWorldFrame(n,o,t.pillarOffset,b),i.distanceTo(b)<t.pillarConvex.boundingSphereRadius+e.boundingSphereRadius&&(M=this.sphereConvex(e,t.pillarConvex,i,b,r,o,s,c,e,t,u)),u&&M||(t.getConvexTrianglePillar(R,P,!0),ee.pointToWorldFrame(n,o,t.pillarOffset,b),i.distanceTo(b)<t.pillarConvex.boundingSphereRadius+e.boundingSphereRadius&&(M=this.sphereConvex(e,t.pillarConvex,i,b,r,o,s,c,e,t,u)),u&&M))return!0;if(C.length-S>2)return}}boxHeightfield(e,t,i,n,r,o,s,c,d,a,u){return e.convexPolyhedronRepresentation.material=e.material,e.convexPolyhedronRepresentation.collisionResponse=e.collisionResponse,this.convexHeightfield(e.convexPolyhedronRepresentation,t,i,n,r,o,s,c,e,t,u)}convexHeightfield(e,t,i,n,r,o,s,c,d,a,u){let h=t.data,f=t.elementSize,E=e.boundingSphereRadius,b=Vg,y=Wg,g=Ug;ee.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>h.length||v>h[0].length)return;p<0&&(p=0),m<0&&(m=0),v<0&&(v=0),w<0&&(w=0),p>=h.length&&(p=h.length-1),m>=h.length&&(m=h.length-1),w>=h[0].length&&(w=h[0].length-1),v>=h[0].length&&(v=h[0].length-1);let x=[];t.getRectMinMax(p,v,m,w,x);let T=x[0],C=x[1];if(!(g.z-E>C||g.z+E<T))for(let R=p;R<m;R++)for(let P=v;P<w;P++){let S=!1;if(t.getConvexTrianglePillar(R,P,!1),ee.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,u,y,null)),u&&S||(t.getConvexTrianglePillar(R,P,!0),ee.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,u,y,null)),u&&S))return!0}}sphereParticle(e,t,i,n,r,o,s,c,d,a,u){let h=Bg;if(h.set(0,0,1),n.vsub(i,h),h.lengthSquared()<=e.radius*e.radius){if(u)return!0;let E=this.createContactEquation(c,s,t,e,d,a);h.normalize(),E.rj.copy(h),E.rj.scale(e.radius,E.rj),E.ni.copy(h),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,u){let h=Lg;h.set(0,0,1),s.quaternion.vmult(h,h);let f=Hg;if(n.vsub(s.position,f),h.dot(f)<=0){if(u)return!0;let b=this.createContactEquation(c,s,t,e,d,a);b.ni.copy(h),b.ni.negate(b.ni),b.ri.set(0,0,0);let y=jg;h.scale(h.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,u){return e.convexPolyhedronRepresentation.material=e.material,e.convexPolyhedronRepresentation.collisionResponse=e.collisionResponse,this.convexParticle(e.convexPolyhedronRepresentation,t,i,n,r,o,s,c,e,t,u)}convexParticle(e,t,i,n,r,o,s,c,d,a,u){let h=-1,f=Ng,E=zg,b=null,y=Fg;if(y.copy(n),y.vsub(i,y),r.conjugate(wh),wh.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],_h);let w=-v.dot(_h);if(b===null||Math.abs(w)<Math.abs(b)){if(u)return!0;b=w,h=g,f.copy(v)}}if(h!==-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,u){return this.convexHeightfield(t,e,n,i,o,r,c,s,d,a,u)}particleCylinder(e,t,i,n,r,o,s,c,d,a,u){return this.convexParticle(t,e,n,i,o,r,c,s,d,a,u)}sphereTrimesh(e,t,i,n,r,o,s,c,d,a,u){let h=Km,f=Jm,E=Zm,b=$m,y=eg,g=tg,p=og,m=Ym,v=Xm,w=sg;ee.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=Qm,C=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()<=C){if(m.copy(T),ee.pointToWorldFrame(n,o,m,T),T.vsub(i,v),u)return!0;let L=this.createContactEquation(s,c,e,t,d,a);L.ni.copy(v),L.ni.normalize(),L.ri.copy(L.ni),L.ri.scale(e.radius,L.ri),L.ri.vadd(i,L.ri),L.ri.vsub(s.position,L.ri),L.rj.copy(T),L.rj.vsub(c.position,L.rj),this.result.push(L),this.createFrictionEquationsFromContact(L,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],h),t.getVertex(t.indices[w[I]*3+(j+1)%3],f),f.vsub(h,E),y.vsub(f,g);let L=g.dot(E);y.vsub(h,g);let F=g.dot(E);if(F>0&&L<0&&(y.vsub(h,g),b.copy(E),b.normalize(),F=g.dot(b),b.scale(F,g),g.vadd(h,g),g.distanceTo(y)<e.radius)){if(u)return!0;let Q=this.createContactEquation(s,c,e,t,d,a);g.vsub(y,Q.ni),Q.ni.normalize(),Q.ni.scale(e.radius,Q.ri),Q.ri.vadd(i,Q.ri),Q.ri.vsub(s.position,Q.ri),ee.pointToWorldFrame(n,o,g,g),g.vsub(c.position,Q.rj),ee.vectorToWorldFrame(o,Q.ni,Q.ni),ee.vectorToWorldFrame(o,Q.ri,Q.ri),this.result.push(Q),this.createFrictionEquationsFromContact(Q,this.frictionResult)}}let R=ig,P=ng,S=rg,M=qm;for(let I=0,j=w.length;I!==j;I++){t.getTriangleVertices(w[I],R,P,S),t.getNormal(w[I],M),y.vsub(R,g);let L=g.dot(M);if(M.scale(L,g),y.vsub(g,g),L=g.distanceTo(y),pe.pointInTriangle(g,R,P,S)&&L<e.radius){if(u)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),ee.pointToWorldFrame(n,o,g,g),g.vsub(c.position,F.rj),ee.vectorToWorldFrame(o,F.ni,F.ni),ee.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,u){let h=new _,f=Vm;f.set(0,0,1),r.vmult(f,f);for(let E=0;E<t.vertices.length/3;E++){t.getVertex(E,h);let b=new _;b.copy(h),ee.pointToWorldFrame(n,o,b,h);let y=Wm;if(h.vsub(i,y),f.dot(y)<=0){if(u)return!0;let p=this.createContactEquation(s,c,e,t,d,a);p.ni.copy(f);let m=Gm;f.scale(y.dot(f),m),h.vsub(m,m),p.ri.copy(m),p.ri.vsub(s.position,p.ri),p.rj.copy(h),p.rj.vsub(c.position,p.rj),this.result.push(p),this.createFrictionEquationsFromContact(p,this.frictionResult)}}}},cn=new _,Zn=new _,$n=new _,Fm=new _,Nm=new _,zm=new re,Um=new re,Vm=new _,Wm=new _,Gm=new _,qm=new _,Xm=new _,Qm=new _,Ym=new _,Km=new _,Jm=new _,Zm=new _,$m=new _,eg=new _,tg=new _,ig=new _,ng=new _,rg=new _,og=new ze,sg=[],cs=new _,Eh=new _,ag=new _,lg=new _,cg=new _;function dg(l,e,t){let i=null,n=l.length;for(let r=0;r!==n;r++){let o=l[r],s=ag;l[(r+1)%n].vsub(o,s);let c=lg;s.cross(e,c);let d=cg;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 ds=new _,hg=new _,ug=new _,pg=new _,fg=[new _,new _,new _,new _,new _,new _],mg=new _,gg=new _,bg=new _,vg=new _,yg=new _,Eg=new _,wg=new _,_g=new _,xg=new _,Tg=new _,Cg=new _,Rg=new _,Sg=new _,Pg=new _,Og=new _,kg=new _,Ig=new _,Ag=new _,Mg=new _,Dg=new _,Lg=new _,Hg=new _,jg=new _,Bg=new _,wh=new re,Fg=new _,Ng=new _,_h=new _,zg=new _,Ug=new _,Vg=new _,Wg=[0],Gg=new _,qg=new _,vs=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||xh(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||xh(t,a)}}};function xh(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]}}},ys=class extends us{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 kl,this.bodies=[],this.hasActiveBodies=!1,this.solver=e.solver!==void 0?e.solver:new Ml,this.constraints=[],this.narrowphase=new Hl(this),this.collisionMatrix=new hs,this.collisionMatrixPrevious=new hs,this.bodyOverlapKeeper=new vs,this.shapeOverlapKeeper=new vs,this.materials=[],this.contactmaterials=[],this.contactMaterialTable=new jl,this.defaultMaterial=new tr("default"),this.defaultContactMaterial=new er(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 ro?this.raycastClosest(e,t,{skipBackfaces:!0},i):this.raycastAll(e,t,{skipBackfaces:!0},i)}raycastAll(e,t,i={},n){return i.mode=pe.ALL,i.from=e,i.to=t,i.callback=n,Pl.intersectWorld(this,i)}raycastAny(e,t,i={},n){return i.mode=pe.ANY,i.from=e,i.to=t,i.result=n,Pl.intersectWorld(this,i)}raycastClosest(e,t,i={},n){return i.mode=pe.CLOSEST,i.from=e,i.to=t,i.result=n,Pl.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 z&&(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=Re.now(),r=0;for(;this.accumulator>=e&&r<i&&(this.internalStep(e),this.accumulator-=e,r++,!(Re.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=Jg,n=Zg,r=this.numObjects(),o=this.bodies,s=this.solver,c=this.gravity,d=this.doProfiling,a=this.profile,u=z.DYNAMIC,h=-1/0,f=this.constraints,E=Kg;c.length();let b=c.x,y=c.y,g=c.z,p=0;for(d&&(h=Re.now()),p=0;p!==r;p++){let I=o[p];if(I.type===u){let j=I.force,L=I.mass;j.x+=L*b,j.y+=L*y,j.z+=L*g}}for(let I=0,j=this.subsystems.length;I!==j;I++)this.subsystems[I].update();d&&(h=Re.now()),i.length=0,n.length=0,this.broadphase.collisionPairs(this,i,n),d&&(a.broadphase=Re.now()-h);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&&(h=Re.now());let v=Yg,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=Re.now()-h),d&&(h=Re.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],L=j.bi,F=j.bj,W=j.si,Q=j.sj,V;if(L.material&&F.material?V=this.getContactMaterial(L.material,F.material)||this.defaultContactMaterial:V=this.defaultContactMaterial,V.friction,L.material&&F.material&&(L.material.friction>=0&&F.material.friction>=0&&L.material.friction*F.material.friction,L.material.restitution>=0&&F.material.restitution>=0&&(j.restitution=L.material.restitution*F.material.restitution)),s.addEquation(j),L.allowSleep&&L.type===z.DYNAMIC&&L.sleepState===z.SLEEPING&&F.sleepState===z.AWAKE&&F.type!==z.STATIC){let De=F.velocity.lengthSquared()+F.angularVelocity.lengthSquared(),ue=F.sleepSpeedLimit**2;De>=ue*2&&(L.wakeUpAfterNarrowphase=!0)}if(F.allowSleep&&F.type===z.DYNAMIC&&F.sleepState===z.SLEEPING&&L.sleepState===z.AWAKE&&L.type!==z.STATIC){let De=L.velocity.lengthSquared()+L.angularVelocity.lengthSquared(),ue=L.sleepSpeedLimit**2;De>=ue*2&&(F.wakeUpAfterNarrowphase=!0)}this.collisionMatrix.set(L,F,!0),this.collisionMatrixPrevious.get(L,F)||(to.body=F,to.contact=j,L.dispatchEvent(to),to.body=L,F.dispatchEvent(to)),this.bodyOverlapKeeper.set(L.id,F.id),this.shapeOverlapKeeper.set(W.id,Q.id)}for(this.emitContactEvents(),d&&(a.makeContactConstraints=Re.now()-h,h=Re.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,L=I.equations.length;j!==L;j++){let F=I.equations[j];s.addEquation(F)}}s.solve(e,this),d&&(a.solve=Re.now()-h),s.removeAllEquations();let C=Math.pow;for(p=0;p!==r;p++){let I=o[p];if(I.type&u){let j=C(1-I.linearDamping,e),L=I.velocity;L.scale(j,L);let F=I.angularVelocity;if(F){let W=C(1-I.angularDamping,e);F.scale(W,F)}}}for(this.dispatchEvent(Qg),p=0;p!==r;p++){let I=o[p];I.preStep&&I.preStep.call(I)}d&&(h=Re.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=Re.now()-h),this.stepnumber+=1,this.dispatchEvent(Xg),p=0;p!==r;p++){let I=o[p],j=I.postStep;j&&j.call(I)}let M=!0;if(this.allowSleep)for(M=!1,p=0;p!==r;p++){let I=o[p];I.sleepTick(this.time),I.sleepState!==z.SLEEPING&&(M=!0)}this.hasActiveBodies=M}emitContactEvents(){let e=this.hasAnyEventListener("beginContact"),t=this.hasAnyEventListener("endContact");if((e||t)&&this.bodyOverlapKeeper.getDiff(fi,mi),e){for(let r=0,o=fi.length;r<o;r+=2)io.bodyA=this.getBodyById(fi[r]),io.bodyB=this.getBodyById(fi[r+1]),this.dispatchEvent(io);io.bodyA=io.bodyB=null}if(t){for(let r=0,o=mi.length;r<o;r+=2)no.bodyA=this.getBodyById(mi[r]),no.bodyB=this.getBodyById(mi[r+1]),this.dispatchEvent(no);no.bodyA=no.bodyB=null}fi.length=mi.length=0;let i=this.hasAnyEventListener("beginShapeContact"),n=this.hasAnyEventListener("endShapeContact");if((i||n)&&this.shapeOverlapKeeper.getDiff(fi,mi),i){for(let r=0,o=fi.length;r<o;r+=2){let s=this.getShapeById(fi[r]),c=this.getShapeById(fi[r+1]);gi.shapeA=s,gi.shapeB=c,s&&(gi.bodyA=s.body),c&&(gi.bodyB=c.body),this.dispatchEvent(gi)}gi.bodyA=gi.bodyB=gi.shapeA=gi.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]);bi.shapeA=s,bi.shapeB=c,s&&(bi.bodyA=s.body),c&&(bi.bodyB=c.body),this.dispatchEvent(bi)}bi.bodyA=bi.bodyB=bi.shapeA=bi.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 ze;var Pl=new pe,Re=globalThis.performance||{};if(!Re.now){let l=Date.now();Re.timing&&Re.timing.navigationStart&&(l=Re.timing.navigationStart),Re.now=()=>Date.now()-l}var Xg={type:"postStep"},Qg={type:"preStep"},to={type:z.COLLIDE_EVENT_NAME,body:null,contact:null},Yg=[],Kg=[],Jg=[],Zg=[],fi=[],mi=[],io={type:"beginContact",bodyA:null,bodyB:null},no={type:"endContact",bodyA:null,bodyB:null},gi={type:"beginShapeContact",bodyA:null,bodyB:null,shapeA:null,shapeB:null},bi={type:"endShapeContact",bodyA:null,bodyB:null,shapeA:null,shapeB:null};import*as me from"three";import{MeshBasicMaterial as $g,SphereGeometry as iu,BoxGeometry as nu,PlaneGeometry as ru,Mesh as Hi,CylinderGeometry as eb,BufferGeometry as Ul,Float32BufferAttribute as Vl}from"three";function tb(l,e,{color:t=65280,scale:i=1,onInit:n,onUpdate:r,autoUpdate:o}={}){let s=[],c=new $g({color:t??65280,wireframe:!0}),d=new _,a=new _,u=new _,h=new re,f=new iu(1),E=new nu(1,1,1),b=new ru(10,10,10,10);function y(C){let R=new Ul,P=[];for(let M=0;M<C.vertices.length;M++){let I=C.vertices[M];P.push(I.x,I.y,I.z)}R.setAttribute("position",new Vl(P,3));let S=[];for(let M=0;M<C.faces.length;M++){let I=C.faces[M],j=I[0];for(let L=1;L<I.length-1;L++){let F=I[L],W=I[L+1];S.push(j,F,W)}}return R.setIndex(S),R.computeBoundingSphere(),R.computeVertexNormals(),R}function g(C){let R=new Ul,P=[],S=d,M=a,I=u;for(let j=0;j<C.indices.length/3;j++)C.getTriangleVertices(j,S,M,I),P.push(S.x,S.y,S.z),P.push(M.x,M.y,M.z),P.push(I.x,I.y,I.z);return R.setAttribute("position",new Vl(P,3)),R.computeBoundingSphere(),R.computeVertexNormals(),R}function p(C){let R=new Ul,P=C.elementSize||1,S=C.data.flatMap((I,j)=>I.flatMap((L,F)=>[j*P,F*P,L])),M=[];for(let I=0;I<C.data.length-1;I++)for(let j=0;j<C.data[I].length-1;j++){let L=C.data[I].length,F=I*L+j;M.push(F+1,F+L,F+L+1),M.push(F+L,F+1,F)}return R.setIndex(M),R.setAttribute("position",new Vl(S,3)),R.computeBoundingSphere(),R.computeVertexNormals(),R}function m(C){let R=new Hi,{SPHERE:P,BOX:S,PLANE:M,CYLINDER:I,CONVEXPOLYHEDRON:j,TRIMESH:L,HEIGHTFIELD:F}=U.types;switch(C.type){case P:{R=new Hi(f,c);break}case S:{R=new Hi(E,c);break}case M:{R=new Hi(b,c);break}case I:{let W=new eb(C.radiusTop,C.radiusBottom,C.height,C.numSegments);R=new Hi(W,c),C.geometryId=W.id;break}case j:{let W=y(C);R=new Hi(W,c),C.geometryId=W.id;break}case L:{let W=g(C);R=new Hi(W,c),C.geometryId=W.id;break}case F:{let W=p(C);R=new Hi(W,c),C.geometryId=W.id;break}}return l.add(R),R}function v(C,R){let{SPHERE:P,BOX:S,PLANE:M,CYLINDER:I,CONVEXPOLYHEDRON:j,TRIMESH:L,HEIGHTFIELD:F}=U.types;switch(R.type){case P:{let{radius:W}=R;C.scale.set(W*i,W*i,W*i);break}case S:{C.scale.copy(R.halfExtents),C.scale.multiplyScalar(2*i);break}case M:break;case I:{C.scale.set(1*i,1*i,1*i);break}case j:{C.scale.set(1*i,1*i,1*i);break}case L:{C.scale.copy(R.scale).multiplyScalar(i);break}case F:{C.scale.set(1*i,1*i,1*i);break}}}function w(C,R){if(!C)return!1;let{geometry:P}=C;return P instanceof iu&&R.type===U.types.SPHERE||P instanceof nu&&R.type===U.types.BOX||P instanceof ru&&R.type===U.types.PLANE||P.id===R.geometryId&&R.type===U.types.CYLINDER||P.id===R.geometryId&&R.type===U.types.CONVEXPOLYHEDRON||P.id===R.geometryId&&R.type===U.types.TRIMESH||P.id===R.geometryId&&R.type===U.types.HEIGHTFIELD}function x(C,R){let P=s[C],S=!1;return w(P,R)||(P&&l.remove(P),s[C]=P=m(R),S=!0),v(P,R),S}function T(){let C=s,R=d,P=h,S=0;for(let M of e)for(let I=0;I!==M.shapes.length;I++){let j=M.shapes[I],L=x(S,j),F=C[S];F&&(M.quaternion.vmult(M.shapeOffsets[I],R),M.position.vadd(R,R),M.quaternion.mult(M.shapeOrientations[I],P),F.position.copy(R),F.quaternion.copy(P),L&&n instanceof Function&&n(M,F,j),!L&&r instanceof Function&&r(M,F,j)),S++}for(let M=S;M<C.length;M++){let I=C[M];I&&l.remove(I)}C.length=S,o!==!1&&requestAnimationFrame(T)}return o!==!1&&requestAnimationFrame(T),{update:T}}var ou=tb;import*as oe from"three";var Wl=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}},K=new Wl;import{Vector3 as ib,Quaternion as nb,Uniform as rb}from"three";var ql=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]}},h_=new nb().setFromAxisAngle(new ib(0,1,0),Math.PI);var Xl=new ql(()=>new oe.Vector3,100);function G(l,e=null,t=!0){let i=e??Xl.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 ne(l,e){if(!l)return;let t=Xl.get();e!==t&&t.copy(e),(l?.parent??l).worldToLocal(t),l.position.set(t.x,t.y,t.z)}function ir(l,e,t,i){let n=Xl.get();n.set(e,t,i),ne(l,n)}var fn=new oe.Quaternion,so=new oe.Quaternion,Gl=new oe.Quaternion;function we(l,e=null){if(!l)return so.set(0,0,0,1);let t=e??so;return l.parent?(l.getWorldQuaternion(t),t):t.copy(l.quaternion)}function Ue(l,e){if(!l)return;e!==fn&&fn.copy(e);let t=fn;l?.parent?.getWorldQuaternion(Gl),Gl.invert();let n=Gl.multiply(t);l.quaternion.set(n.x,n.y,n.z,n.w)}function lu(l,e,t,i,n){fn.set(e,t,i,n),Ue(l,fn)}var Es=new oe.Vector3,u_=new oe.Vector3;function ws(l,e=null){return l?l.parent?(l.getWorldScale(e??Es),e??Es):Es.copy(l.position):Es.set(0,0,0)}var p_=new oe.Vector3,f_=new oe.Quaternion;var su=new oe.Euler,au=new oe.Euler,ob=new oe.Vector3;function sb(l){return l.getWorldQuaternion(so),au.setFromQuaternion(so),au}function cu(l,e){Ue(l,so.setFromEuler(e))}function _s(l){let e=sb(l),t=ob;return t.set(e.x,e.y,e.z),t.x=K.toDegrees(t.x),t.y=K.toDegrees(t.y),t.z=K.toDegrees(t.z),t}function xs(l,e,t,i,n=!0){n&&(e=K.toRadians(e),t=K.toRadians(t),i=K.toRadians(i)),su.set(e,t,i),fn.setFromEuler(su),Ue(l,fn)}function ao(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 m_=new oe.PlaneGeometry(2,2,1,1),g_=new oe.WebGLRenderer({antialias:!1}),b_=new oe.PerspectiveCamera,v_=new oe.Scene,y_=new oe.ShaderMaterial({uniforms:{blitTexture:new rb(null)},vertexShader:`
81
81
  varying vec2 vUv;
82
82
  void main(){
83
83
  vUv = uv;
@@ -90,8 +90,13 @@ a=extmap-allow-mixed`)!==-1){var f=p.sdp.split(`
90
90
  uv.y = 1.0 - uv.y;
91
91
  gl_FragColor = vec4(uv.xy, 0, 1);
92
92
  gl_FragColor = texture2D( blitTexture, uv);
93
- }`});import{Vector3 as mb}from"three";var ls=Symbol("object"),Gr=class{get __internalCollision(){return this.collision}get __internalInvertedSourceReceiver(){return this.invert}invert;collision;targetBody;me;_normal;get normal(){if(!this._normal){let e=this.collision.contact.ni;this._normal=new mb(e.x,e.y,e.z)}return this._normal}_collider;get collider(){return this._collider||(this._collider=getComponentInChildren(this.gameObject,Collider)),this._collider}get gameObject(){return this.targetBody[ls]}constructor(e,t,i=!1){this.invert=i,this.me=e,this.collision=t,this.targetBody=this.invert?t.target:t.body}};var sa=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),re=class{static isUsingInstancing(e){return e.__isUsingInstancing===!0}static markDirty(e,t=!0){if(!!e&&(this.isUsingInstancing(e)&&(e[sa]=!0,e.matrixWorldNeedsUpdate=!0),t))for(let i of e.children)re.markDirty(i,!0)}};function tr(c,e){try{e?c(e):c()}catch(t){return console.error(t),!1}return!0}var hi="__isActiveInHierarchy",ir="builtin_components";var vb=B("debugnewscripts"),ge=[];function Ni(c){if(!(c.new_scripts.length<=0)){if(vb&&console.log("Register new components",c.new_scripts.length,c.alias?"element: "+c.alias:""),c.new_scripts_pre_setup_callbacks.length>0){for(let e of c.new_scripts_pre_setup_callbacks)!e||e();c.new_scripts_pre_setup_callbacks.length=0}ge.length=0,c.new_scripts.length>0&&ge.push(...c.new_scripts),c.new_scripts.length=0;for(let e=0;e<ge.length;e++)try{let t=ge[e];if(t.destroyed)continue;if(!t.gameObject){console.error("MISSING GAMEOBJECT - will ignore",t),ge.splice(e,1),e--;continue}t.context=c,gn(t.gameObject),sc(t,c)}catch(t){console.error(t),Fi(ge[e],c),ge.splice(e,1),e--}for(let e=0;e<ge.length;e++)try{let t=ge[e];if(t.destroyed){Fi(ge[e],c),ge.splice(e,1),e--;continue}t.__internalAwake!==void 0&&(t.gameObject||console.error("MISSING GAMEOBJECT",t,t.gameObject),gn(t.gameObject),t.activeAndEnabled&&tr(t.__internalAwake.bind(t)))}catch(t){console.error(t),Fi(ge[e],c),ge.splice(e,1),e--}for(let e=0;e<ge.length;e++)try{let t=ge[e];if(t.destroyed||t.enabled===!1||(gn(t.gameObject),t.activeAndEnabled===!1))continue;t.__internalEnable!==void 0&&(t.enabled=!0,tr(t.__internalEnable.bind(t)))}catch(t){console.error(t),Fi(ge[e],c),ge.splice(e,1),e--}for(let e=0;e<ge.length;e++)try{let t=ge[e];if(t.destroyed||!t.gameObject)continue;c.new_script_start.push(t)}catch(t){console.error(t),Fi(ge[e],c),ge.splice(e,1),e--}ge.length=0;for(let e of c.new_scripts_post_setup_callbacks)e&&e();c.new_scripts_post_setup_callbacks.length=0}}function _u(c){!c||(c.__internalDisable(),Fi(c,c.context))}function aa(c,e){for(let t=0;t<c.new_script_start.length;t++)try{let i=c.new_script_start[t];if(e!==void 0&&i.gameObject!==e||i.destroyed||i.activeAndEnabled===!1)continue;tr(i.__internalAwake.bind(i)),tr(i.__internalEnable.bind(i)),tr(i.__internalStart.bind(i)),c.new_script_start.splice(t,1),t--}catch(i){console.error(i),Fi(c.new_script_start[t],c),c.new_script_start.splice(t,1),t--}}function sc(c,e){e.scripts.indexOf(c)===-1&&(e.scripts.push(c),c.earlyUpdate&&e.scripts_earlyUpdate.push(c),c.update&&e.scripts_update.push(c),c.lateUpdate&&e.scripts_lateUpdate.push(c),c.onBeforeRender&&e.scripts_onBeforeRender.push(c),c.onAfterRender&&e.scripts_onAfterRender.push(c))}function Fi(c,e){mn(c,e.new_scripts),mn(c,e.new_script_start),mn(c,e.scripts),mn(c,e.scripts_earlyUpdate),mn(c,e.scripts_update),mn(c,e.scripts_lateUpdate),mn(c,e.scripts_onBeforeRender),mn(c,e.scripts_onAfterRender),e.stopAllCoroutinesFrom(c)}function mn(c,e){let t=e.indexOf(c);t>=0&&e.splice(t,1)}var yb={},wu={};function xu(){if(!Z.Current){console.trace("Invalid call - no current context.");return}Tu(Z.Current.scene,Z.Current.scene.visible,!0)}function Tu(c,e,t){let i=!1,n=Wr(c);if(yb[c.uuid]=n,e&&(e=Wr(c)),c[hi]=e,!i){let r=wu[c.uuid];r!==void 0&&r!==e&&t&&Eb(c,o=>{e?(tr(o.__internalAwake.bind(o)),o.enabled=!0):o.enabled=!1})}if(wu[c.uuid]=e,c.children)for(let r of c.children)Tu(r,e,t)}function gn(c){let e=!0,t=c,i=!1;for(;t&&t;){if(t.type==="Scene"&&(i=!0),!Wr(t)){e=!1;break}t=t.parent}if(!c){console.error("GO is null");return}c[hi]=e&&i}function Eb(c,e){if(c.userData?.components)for(let t of c.userData.components)e(t)}import*as cs from"three";var Ru=/^(?:[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 wb(c){return typeof c=="string"&&Ru.test(c)}var Su=wb;var je=[];for(let c=0;c<256;++c)je.push((c+256).toString(16).slice(1));function Pu(c,e=0){return(je[c[e+0]]+je[c[e+1]]+je[c[e+2]]+je[c[e+3]]+"-"+je[c[e+4]]+je[c[e+5]]+"-"+je[c[e+6]]+je[c[e+7]]+"-"+je[c[e+8]]+je[c[e+9]]+"-"+je[c[e+10]]+je[c[e+11]]+je[c[e+12]]+je[c[e+13]]+je[c[e+14]]+je[c[e+15]]).toLowerCase()}function _b(c){if(!Su(c))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(c.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(c.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(c.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(c.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(c.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 Ou=_b;function xb(c){c=unescape(encodeURIComponent(c));let e=[];for(let t=0;t<c.length;++t)e.push(c.charCodeAt(t));return e}var Tb="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Cb="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function ac(c,e,t){function i(n,r,o,s){var l;if(typeof n=="string"&&(n=xb(n)),typeof r=="string"&&(r=Ou(r)),((l=r)===null||l===void 0?void 0:l.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 Pu(d)}try{i.name=c}catch{}return i.DNS=Tb,i.URL=Cb,i}function Rb(c,e,t,i){switch(c){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 lc(c,e){return c<<e|c>>>32-e}function Sb(c){let e=[1518500249,1859775393,2400959708,3395469782],t=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof c=="string"){let o=unescape(encodeURIComponent(c));c=[];for(let s=0;s<o.length;++s)c.push(o.charCodeAt(s))}else Array.isArray(c)||(c=Array.prototype.slice.call(c));c.push(128);let i=c.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 l=0;l<16;++l)s[l]=c[o*64+l*4]<<24|c[o*64+l*4+1]<<16|c[o*64+l*4+2]<<8|c[o*64+l*4+3];r[o]=s}r[n-1][14]=(c.length-1)*8/Math.pow(2,32),r[n-1][14]=Math.floor(r[n-1][14]),r[n-1][15]=(c.length-1)*8&4294967295;for(let o=0;o<n;++o){let s=new Uint32Array(80);for(let m=0;m<16;++m)s[m]=r[o][m];for(let m=16;m<80;++m)s[m]=lc(s[m-3]^s[m-8]^s[m-14]^s[m-16],1);let l=t[0],d=t[1],a=t[2],u=t[3],h=t[4];for(let m=0;m<80;++m){let E=Math.floor(m/20),b=lc(l,5)+Rb(E,d,a,u)+h+e[E]+s[m]>>>0;h=u,u=a,a=lc(d,30)>>>0,d=l,l=b}t[0]=t[0]+l>>>0,t[1]=t[1]+d>>>0,t[2]=t[2]+a>>>0,t[3]=t[3]+u>>>0,t[4]=t[4]+h>>>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 ku=Sb;var Pb=ac("v5",80,ku),cc=Pb;var la=B("debugcomponents"),Ob="eff8ba80-635d-11ec-90d6-0242ac120003",Qe=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,cc(e.toString(),Ob)}static createFromString(e){return new Qe(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 ca=class{guid;constructor(e){this.guid=e}};function qr(c,e,t=!0){if(!c)return;let i=c;if(Gt(c,t),!e){console.warn("Can not send destroy: No networking connection provided",c.guid);return}if(!e.isConnected){console.warn("Can not send destroy: not connected",c.guid);return}let n=c.guid;if(!n&&i.uuid&&(n=i.uuid),!n){console.warn("Can not send destroy: failed to find guid",c);return}let r=new ca(n);e.send("instance-destroyed",r,2)}function Au(c,e){let t=new ca(c);e.send("instance-destroyed",t,2)}function Iu(c){c.connection.beginListen("instance-destroyed",e=>{la&&console.log("[Remote] Destroyed",c.scene,e);let t=nr(e.guid,c.scene);t&&Gt(t)})}var dc=class{guid;originalGuid;seed;visible;hostData;dontSave;parent;position;rotation;scale;constructor(e,t){this.originalGuid=e,this.guid=t}};function da(c,e,t,i){let n=c;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}=kb(n,e);if(o){let l=o;if(l.guid){la&&console.log("[Local] new instance","gameobject:",o?.guid);let d=new dc(n.guid,l.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:l.position.x,y:l.position.y,z:l.position.z}),d.rotation||(d.rotation={x:l.quaternion.x,y:l.quaternion.y,z:l.quaternion.z,w:l.quaternion.w}),d.scale||(d.scale={x:l.scale.x,y:l.scale.y,z:l.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",l)}return o}function ha(){return Math.random()*9999999}function Mu(c){c.connection.beginListen("new-instance-created",async e=>{let t=await Ab(e.originalGuid,c.scene);if(!t){console.warn("could not find object that was instantiated: "+e.guid);return}let i=new Be;e.position&&(i.position=new cs.Vector3(e.position.x,e.position.y,e.position.z)),e.rotation&&(i.rotation=new cs.Quaternion(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w)),e.scale&&(i.scale=new cs.Vector3(e.scale.x,e.scale.y,e.scale.z)),i.parent=e.parent,e.seed&&(i.idProvider=new Qe(e.seed)),i.visible=e.visible,i.context=c,la&&c.alias&&console.log("[Remote] instantiate in: "+c.alias);let n=rr(t,i);n&&(e.parent==="scene"&&c.scene.add(n),la&&console.log("[Remote] new instance","gameobject:",n?.guid,t))})}function kb(c,e){let t=ha(),i=e??new Be;i.idProvider=new Qe(t);let n=rr(c,i);return{seed:t,instance:n}}var Du={};function Lu(c,e){Du[c]=e}async function Ab(c,e){let t=Du[c];if(t!=null){let i=await t(c);if(i)return i}return Hu(c,e)}function Hu(c,e){if(e===null||!c)return null;if(e.guid===c)return e;if(e.children)for(let t of e.children){let i=Hu(c,t);if(i)return i}return null}var ju=new Map;function Bu(c){if(!c)return;let e=c.prototype;if(!e)return;let t=ju.get(e);t||(t=Ib(e),ju.set(e,t)),t.apply(c)}function Ib(c){return new uc(c)}var uc=class{$symbol;extensions;descriptors;constructor(e){this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(e),this.descriptors=new Array;for(let t=0;t<this.extensions.length;t++){let i=this.extensions[t],n=Object.getOwnPropertyDescriptor(e,i);n&&this.descriptors.push(n)}}apply(e){if(!e[this.$symbol]){e[this.$symbol]=!0;for(let t=0;t<this.extensions.length;t++){let i=this.extensions[t],n=this.descriptors[t];n&&Object.defineProperty(e,i,n)}}}};import{Object3D as Wt}from"three";var pc=B("debuggetcomponent");function Mb(c){return c==null||c.isObject3D?c:c.object&&c.object.isObject3D?c.object:c}function ua(c,e){if(!c||!c.userData.components)return;let t=c.userData.components.indexOf(e);t<0||(e.gameObject=null,c.userData.components.splice(t,1))}function pa(c,e){let t=or(e,c);if(t)return t;let i=new e;return ds(c,i)}function ds(c,e,t=!0){c.userData||(c.userData={}),c.userData.components||(c.userData.components=[]),c.userData.components.push(e),e.gameObject=c,fa(e);try{e.__internalAwake&&t&&(gn(c),e.__internalAwake())}catch(i){console.error(i)}return e}function Fu(c,e){if(c.gameObject!==e){if(c.gameObject&&c.gameObject.userData.components){let t=c.gameObject.userData.components.indexOf(c);c.gameObject.userData.components.splice(t,1)}if(!e.userData.components)e.userData.components=[];else if(e.userData.components.includes(c))return;e.userData.components.push(c),c.gameObject=e}}function Nu(c){if(c.gameObject&&c.gameObject.userData.components){let e=c.gameObject.userData.components.indexOf(c);c.gameObject.userData.components.splice(e,1)}c.__internalDisable&&c.__internalDisable(),c.onDestroy&&c.onDestroy(),Fi(c,c.context??Z.Current),c.__internalDestroy(),c.gameObject=null}function zu(c,e,t){if(!e?.userData?.components)return null;pc&&console.log("FIND",c);for(let i=0;i<e.userData.components.length;i++){let n=e.userData.components[i];if(c===null||n.constructor.name===c.name||n.constructor.name===c)if(pc&&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===c)if(pc&&console.log("MATCH BY PROTOYPE",r),t)t.push(n);else return n;r=Object.getPrototypeOf(r)}while(r)}return t}function or(c,e){return zu(c,e)}function Qr(c,e,t){return t||(t=[]),zu(c,e,t)}function Yr(c,e,t){let i=or(c,e);if(t===!1&&i.enabled===!1)return null;if(i)return i;for(let n=0;n<e?.children?.length;n++){let r=Yr(c,e.children[n]);if(r)return r}return null}function Kr(c,e,t){t||(t=[]),Qr(c,e,t);for(let i=0;i<e?.children?.length;i++)Kr(c,e.children[i],t);return t}function Xr(c,e){if(!e)return null;if(Array.isArray(e)){for(let i=0;i<e.length;i++){let n=Mb(e[i]),r=Xr(c,n);if(r)return r}return null}let t=or(c,e);return t||Xr(c,e.parent)}function hs(c,e,t){return t||(t=[]),e?(Qr(c,e,t),hs(c,e.parent,t)):t}function Uu(c,e,t){if(!c)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[hi]===!1)continue;if(r.constructor==c)return r;let o=Yr(c,r);if(o)return o}return null}function Vu(c,e,t){if(!c)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==c)return r;Kr(c,r,e)}return e}function ma(c){c&&c.isObject3D===!0&&Bu(c)}Object.defineProperty(Wt.prototype,"activeSelf",{get:function(){return this.visible},set:function(c){let e=typeof c=="number"?c>.5:c;this.visible=e}});Wt.prototype.SetActive=function(c){this.visible=c};Wt.prototype.addNewComponent=function(c){return ds(this,new c)};Wt.prototype.removeComponent=function(c){return ua(this,c)};Wt.prototype.getOrAddComponent=function(c){return pa(this,c)};Wt.prototype.getComponent=function(c){return or(c,this)};Wt.prototype.getComponents=function(c,e){return Qr(this,c,e)};Wt.prototype.getComponentInChildren=function(c){return Yr(this,c)};Wt.prototype.getComponentsInChildren=function(c,e){return Kr(c,this,e)};Wt.prototype.getComponentInParent=function(c){return Xr(this,c)};Wt.prototype.getComponentsInParent=function(c,e){return hs(this,c,e)};var sr=B("debuggetcomponent"),Db=(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))(Db||{}),Be=class{idProvider;parent;keepWorldPosition;position;rotation;scale;visible;context};function Wr(c){return c.visible||ga(c)}function Wu(c){return c[hi]||ga(c)}function qu(c,e){c.__isUsingInstancing=e}function ga(c){return re.isUsingInstancing(c)}function nr(c,e){return Qn(c,e,!0,!0)}function Gt(c,e=!0,t=!0){let i=c;if(i.isComponent){i.__internalDestroy();return}let n=c;if(sr&&console.log(n),e&&n.children)for(let o of n.children)Gt(o,e,!1);let r=n.userData.components;if(r){let o=r.length;for(let s=0;s<r.length;s++)r[s].__internalDestroy(),r.length<o&&(o=r.length,s--)}t&&n.removeFromParent()}function Pt(c,e,t=!0){if(!!c){if(c.isObject3D||new Error("Expected Object3D but got "+c),c.userData?.components)for(let i=0;i<c.userData.components.length;i++){let n=c.userData.components[i];if(n?.isComponent===!0){let r=e(n);if(r!==void 0)return r}}if(t&&c.children)for(let i=0;i<c.children.length;i++){let n=c.children[i];if(!n)continue;let r=Pt(n,e,t);if(r!==void 0)return r}}}function rr(c,e=null){if(c===null)return null;let t=null;e!==null&&(e.x!==void 0?(t=new Be,t.position=e):t=e);let i=Z.Current;t?.context&&(i=t.context),sr&&i.alias&&console.log("context",i.alias),t&&!t.idProvider&&(t.idProvider=new Qe(Date.now()));let n=[],r={},o={},s=Xu(i,c,t,n,r,o);s&&(Hb(r),Lb(o,r)),sr&&(as(c,!0),as(s,!0));let l={};for(let d in n){let a=n[d],u=a.guid;t&&t.idProvider&&(a.guid=t.idProvider.generateUUID(),l[u]=a.guid,sr&&console.log(a.name,a.guid)),fa(a,i),a.__internalNewInstanceCreated&&a.__internalNewInstanceCreated()}for(let d in n){let a=n[d];a.resolveGuids&&a.resolveGuids(l),a.enabled!==!1&&(a.enabled=!0)}return Ni(i),s}function Xu(c,e,t,i,n,r){if(!e)return null;let o=e.userData;e.userData={};let s=e.children;e.children=[];let l;if(l=e.clone(!1),ma(l),e.userData=o,e.children=s,n[e.uuid]={original:e,clone:l},e.type==="SkinnedMesh"&&(r[e.uuid]={original:e,clone:l}),t?.visible!==void 0&&(l.visible=t.visible),t?.idProvider){l.uuid=t.idProvider.generateUUID();let a=l;a&&(a.guid=l.uuid)}e.animations&&e.animations.length>0&&(l.animations=[...e.animations]);let d=e.parent;if(d&&d.add(l),t?.position?oe(l,t.position):l.position.copy(e.position),t?.rotation?Xe(l,t.rotation):l.quaternion.copy(e.quaternion),t?.scale?l.scale.copy(t.scale):l.scale.copy(e.scale),t?.parent&&t.parent!=="scene"){let a=null;if(typeof t.parent=="string"?a=Qn(t.parent,c.scene,!0):a=t.parent,a){let u=t.keepWorldPosition===!0?a.attach:a.add;u?u.call(a,l):console.error("Invalid parent object",a,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(let[a,u]of Object.entries(e.userData))a!=="components"&&(l.userData[a]=u);if(e.userData?.components){let a=e.userData.components,u=[];l.userData.components=u;for(let h=0;h<a.length;h++){let m=a[h],E=Object.create(m);Object.assign(E,m),u.push(E),E.gameObject=l,i.push(E)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0);for(let a in e.children){let u=e.children[a],h=Xu(c,u,t,i,n,r);h&&l.add(h)}return l}function Lb(c,e){for(let t in c){let i=c[t],n=i.original,r=n.skeleton,o=i.clone;if(!r){console.warn("Skinned mesh has no skeleton?",i);continue}let s=r.bones,l=o.skeleton.clone();o.skeleton=l,o.bindMatrix.clone().copy(n.bindMatrix),o.bindMatrixInverse.copy(n.bindMatrixInverse);let d=[];l.bones=d;for(let a=0;a<s.length;a++){let u=s[a],m=e[u.uuid].clone;d.push(m)}}for(let t in c){let i=c[t].clone;i.skeleton.update(),i.bind(i.skeleton,i.bindMatrix),i.updateMatrixWorld(!0)}}function Hb(c){for(let e in c){let i=c[e].clone;if(i.userData?.components)for(let n=0;n<i.userData.components.length;n++){let r=i.userData.components[n],o=Object.entries(r);for(let[s,l]of o)if(Array.isArray(l)){let d=[];r[s]=d;for(let a=0;a<l.length;a++){let u=l[a];if(typeof u!="object"){d.push(u);continue}let h=Gu(r,s,u,c);h!==void 0?d.push(h):d.push(u)}}else if(typeof l=="object"){let d=Gu(r,s,l,c);d!==void 0&&(r[s]=d)}}}}function Gu(c,e,t,i){if(t!=null){if(t.isComponent===!0){let n=t.gameObject;if(n){let r=n.uuid,o=i[r]?.clone;if(!o){sr&&console.log("reference did not change",e,c,t);return}let s=n.userData.components.indexOf(t);if(s>=0)return sr&&console.log(e,r),o.userData.components[s];console.warn("could not find component",e,t)}}else if(t.isObject3D===!0){if(e==="gameObject")return;let n=t;if(n){let r=n.uuid,o=i[r]?.clone;if(o)return sr&&console.log(e,"old",t,"new",o),o}}}}var us=B("debugphysics"),jb=B("debugcollisions"),ba=class{mass=1;kinematic=!1;physicsEvents=!1;drag=0;angularDrag=.05;sleepThreshold=.01},ps=class{obj;parent;body;shapes=[];collisonCallback=null;_hasRigidbody=!1;_didSleepLastStep=!1;constructor(e,t){this.obj=e,this.parent=e.parent,this.body=t,this.body&&(this.body[ls]=e)}},_e=class{ray=void 0;cam=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 be.Vector2),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setMask(e){this.layerMask||(this.layerMask=new be.Layers);let t=this.layerMask;t?t.mask=e:this.layerMask=e}};z(_e,"AllLayers",4294967295);var fc=class{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}},va=class{raycaster=new be.Raycaster;defaultRaycastOptions=new _e;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:0},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new be.Layers;sphereOverlap(e,t){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;let i=new be.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 be.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 l=q(e).distanceTo(t.center);return new fc(e,l,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=e.cam??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 be.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 ta;objects=[];tempPosition=new be.Vector3;tempQuaternion=new be.Quaternion;constructor(e){if(this.context=e,this.world.gravity.set(0,-9.82,0),us){let t={};t.onInit=(i,n,r)=>{n.layers.set(-1)},gu(e.scene,this.world.bodies,t)}this.world.addEventListener("beginContact",this.onBeginContact.bind(this)),this.world.addEventListener("endContact",this.onEndContact.bind(this))}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}}t.shapes.length>0&&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=U.KINEMATIC:i.type=U.DYNAMIC,t.drag&&(i.linearDamping=t.drag),t.angularDrag&&(i.angularDamping=t.angularDrag),t.sleepThreshold&&(i.sleepSpeedLimit=t.sleepThreshold),i.shapes.length>0&&this.world.addBody(i);let n=new ps(e,i);return n._hasRigidbody=!0,this.objects.push(n),us&&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),l=new Zn(s);l.collisionResponse=!t,i=i.clone(),i.multiply(o);let d=this.addShape(e,l,i,r);if(d!==null){if(this.world.addBody(d),this.isAlreadyRegistered(d))return l;let a=new ps(e,d);this.objects.push(a)}return l}addSphereCollider(e,t,i,n){let r=this.tempPosition;e.getWorldScale(r);let o=Math.max(r.x,r.y,r.z),s=new $s(i*o);t=t.clone(),t.multiply(r);let l=this.addShape(e,s,t,n);if(l!==null){if(this.world.addBody(l),this.isAlreadyRegistered(l))return s;let d=new ps(e,l);this.objects.push(d)}return s}addMeshCollider(e){us&&console.warn("TODO mesh collider not yet supported")}isAlreadyRegistered(e){for(let t of this.objects)if(t.body===e)return!0;return!1}tempMat1=new be.Matrix4;tempMat2=new be.Matrix4;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=U.KINEMATIC),r){i.x*=-1;let o=e.position,s=e.quaternion;if(n&&n.gameObject!==e)this.tempMat1.copy(e.matrixWorld),this.tempMat2.copy(n.gameObject.matrixWorld).invert(),this.tempMat1.premultiply(this.tempMat2),this.tempMat1.decompose(o,s,this.tempPosition);else{o=q(e);let a=r.position;o.x-=a.x,o.y-=a.y,o.z-=a.z,s=Pe(e);let u=new be.Quaternion(r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w);s.multiply(u.invert())}o.add(i);let l=new _(o.x,o.y,o.z),d=new ae(s.x,s.y,s.z,s.w);r.addShape(t,l,d),r.updateMassProperties(),this.world.addBody(r)}return r}step(e){this._isUpdatingPhysicsWorld=!0,e=Math.min(e,1/30),this.world.step(e),this._isUpdatingPhysicsWorld=!1,us&&this.context.time.frameCount%60}temp=new be.Vector3;tempQuat=new be.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),us&&(!t._didSleepLastStep&&i.sleepState===U.SLEEPING?console.log("BODY SLEEPING",i):t._didSleepLastStep&&i.sleepState!==U.SLEEPING&&console.log("BODY WOKE UP",i)),t._didSleepLastStep=i.sleepState===U.SLEEPING;let n=t.obj;if(i.type===U.KINEMATIC){let r=q(n,this.temp);i.position.set(r.x,r.y,r.z);let o=Pe(n,this.tempQuat);i.quaternion.set(o.x,o.y,o.z,o.w);continue}if(t.parent&&n.parent===t.parent){yu(n,i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w);let r=i.position;Vr(n,r.x,r.y,r.z),i.velocity.length()>i.sleepSpeedLimit&&re.markDirty(n)}}this._isUpdatingPhysicsWorld=!1}internalCreateBody(e,t){let i=new U;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 ae(r.x,r.y,r.z,r.w),i.type=U.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)}onBeginContact(e){}raiseCollisionEvents(e,t){let i=new Gr(e,t);if(jb&&console.log("collision between",t.contact.bi,t.contact.bj,e,t),Pt(e,n=>{n.__internalHandleCollision(i,!1)}),i.collider&&!i.collider.attachedRigidbody&&i.collider.isTrigger){let n=new Gr(i.gameObject,t,!0);Pt(i.gameObject,r=>{r.__internalHandleCollision(n,!0)})}}onEndContact(e){let t=e.bodyA[ls],i=e.bodyB[ls];Pt(i,n=>{n.__internalHandleExitCollisionEvent(t,!1)}),Pt(t,n=>{let r=n;r.isCollider&&!r.attachedRigidbody&&r.isTrigger&&Pt(r.gameObject,o=>{o.__internalHandleExitCollisionEvent(i,!0)})})}};import{Clock as Bb}from"three";var ya=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 Bb;_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 Nb}from"websocket-ts";var mc={};dh(mc,{Behaviour:()=>D,Component:()=>dt,GameObject:()=>A});import*as Ye from"three";var A=class extends Ye.Object3D{guid;static setActive(e,t,i=!0){!e||(e.visible=t,gn(e),t&&i&&aa(Z.Current,e))}static isActiveSelf(e){return Wr(e)}static isActiveInHierarchy(e){return Wu(e)}static markAsInstancedRendered(e,t){qu(e,t)}static isUsingInstancing(e){return ga(e)}static foreachComponent(e,t,i=!0){return Pt(e,t,i)}static instantiateSynced(e,t){return e?da(e,t):null}static instantiate(e,t=null){return rr(e,t)}static destroySynced(e,t,i=!0){if(!e)return;let n=e;t=t??Z.Current,qr(n,t.connection,i)}static destroy(e,t=!0,i=!0){return Gt(e,t,i)}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),gn(e),i?A.foreachComponent(e,n=>{sc(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),A.foreachComponent(e,t=>{_u(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 ds(e,n,i),n}static addComponent(e,t){if(t.gameObject==null)throw new Error("Did you mean to create a new component? Use addNewComponent");Fu(t,e)}static removeComponent(e){return ua(e.gameObject,e),e}static getOrAddComponent(e,t){return pa(e,t)}static getComponent(e,t){return e===null?null:or(t,e)}static getComponents(e,t,i=null){return e===null?i??[]:Qr(t,e,i)}static findByGuid(e,t){return nr(e,t)}static findObjectOfType(e,t,i=!0){return Uu(e,t,i)}static findObjectsOfType(e,t){let i=[];return Vu(e,i,t),i}static getComponentInChildren(e,t){return Yr(t,e)}static getComponentsInChildren(e,t,i=null){return Kr(t,e,i??void 0)}static getComponentInParent(e,t){return Xr(t,e)}static getComponentsInParent(e,t,i=null){return hs(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]}},qt=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[hi];return e===void 0?!0:e}set __isActiveInHierarchy(e){!this.gameObject||(this.gameObject[hi]=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||this.__internalDestroy()}__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,this.__internalResetsCachedPhysicsData()}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(){return this.__didEnable?!1:(this.__didEnable=!0,this.onEnable(),!0)}__internalDisable(){!this.__didEnable||(this.__didEnable=!1,this._collisionExitRoutine=void 0,this.onDisable(),this._collisions?.clear())}__internalDestroy(){this.__destroyed||(this.__destroyed=!0,this.destroy?.call(this),Nu(this))}get enabled(){return this.__isEnabled??!0}set enabled(e){typeof e=="number"&&(e>=.5?e=!0:e=!1),this.__didAwake&&(e?this.__internalEnable():this.__internalDisable())}constructor(){this.__internalNewInstanceCreated()}_collisionExitRoutine;_collisions=null;_triggerExitRoutine;_triggerCollisions=null;get collisionsCount(){return this._collisions?.size??0}__internalResetsCachedPhysicsData(){this._collisionExitRoutine=null,this._collisions=null,this._triggerExitRoutine=null,this._triggerCollisions=null}__internalHandleCollision(e,t){if(t){if(!this.onTriggerEnter&&!this.onTriggerStay&&!this.onTriggerExit)return}else if(!this.onCollisionEnter&&!this.onCollisionStay&&!this.onCollisionExit)return;let i=e.gameObject;t&&!this._triggerCollisions?this._triggerCollisions=new Map:this._collisions||(this._collisions=new Map);let n=t?this._triggerCollisions:this._collisions;if(n.has(i)){let r=n.get(i);r.frame=this.context.time.frameCount,r.col=e,t?this.onTriggerStay?.(e):this.onCollisionStay?.call(this,e)}else{let r={col:e,frame:this.context.time.frameCount};n.set(i,r),t?this.onTriggerEnter?.(e):this.onCollisionEnter?.call(this,e)}}__internalHandleExitCollisionEvent(e,t){if(t){if(!this._triggerCollisions)return}else if(!this._collisions)return;let n=(t?this._triggerCollisions:this._collisions).get(e);!n||(n.exitFrame=this.context.time.frameCount,this.__waitForCollisionExit(t),t||this.onCollisionExitRaw?.call(this,n.col))}__waitForCollisionExit(e){if(e?this._triggerExitRoutine:this._collisionExitRoutine)return;let i=e?this._triggerCollisions:this._collisions,n=this,r=10;function*o(){for(;i&&i.size>0;){for(let l of i.keys()){let d=i.get(l);d.frame!==void 0&&n.context.time.frameCount-d.frame>=r&&(i.delete(l),e?n.onTriggerExit?.(d.col):n.onCollisionExit?.call(n,d.col))}for(let l=0;l<r;l++)yield}e?n._triggerExitRoutine=void 0:n._collisionExitRoutine=null}let s=this.startCoroutine(o(),4);e?this._triggerExitRoutine=s:this._collisionExitRoutine=s}_worldPosition=void 0;_worldQuaternion=void 0;_worldEuler=void 0;_worldRotation=void 0;get worldPosition(){return this._worldPosition||(this._worldPosition=new Ye.Vector3),q(this.gameObject,this._worldPosition),this._worldPosition}set worldPosition(e){oe(this.gameObject,e)}setWorldPosition(e,t,i){qt._worldPositionBuffer.set(e,t,i),this.worldPosition=qt._worldPositionBuffer}get worldQuaternion(){return this._worldQuaternion||(this._worldQuaternion=new Ye.Quaternion),Pe(this.gameObject,this._worldQuaternion)}set worldQuaternion(e){Xe(this.gameObject,e)}setWorldQuaternion(e,t,i,n){qt._worldQuaternionBuffer.set(e,t,i,n),this.worldQuaternion=qt._worldQuaternionBuffer}get worldEuler(){return this._worldEuler||(this._worldEuler=new Ye.Euler),this._worldEuler.setFromQuaternion(this.worldQuaternion),this._worldEuler}set worldEuler(e){this._worldQuaternion||(this._worldQuaternion=new Ye.Quaternion),this._worldQuaternion?.setFromEuler(e),this.worldQuaternion=this._worldQuaternion}get worldRotation(){let e=this.worldEuler;this._worldRotation||(this._worldRotation=new Ye.Vector3);let t=this._worldRotation;return t.set(e.x,e.y,e.z),t.x=K.toDegrees(t.x),t.y=K.toDegrees(t.y),t.z=K.toDegrees(t.z),t}set worldRotation(e){this.setWorldRotation(e.x,e.y,e.z,!0)}setWorldRotation(e,t,i,n=!0){n&&(e=K.toRadians(e),t=K.toRadians(t),i=K.toRadians(i)),qt._worldEulerBuffer.set(e,t,i),qt._worldQuaternionBuffer.setFromEuler(qt._worldEulerBuffer),this.worldQuaternion=qt._worldQuaternionBuffer}get forward(){return qt._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}},dt=qt;z(dt,"_worldPositionBuffer",new Ye.Vector3),z(dt,"_worldQuaternionBuffer",new Ye.Quaternion),z(dt,"_worldEulerBuffer",new Ye.Euler),z(dt,"_tempQuaternionBuffer2",new Ye.Quaternion),z(dt,"_forward",new Ye.Vector3);var D=class extends dt{};function Qu(c=window.location.hostname){return new RegExp("[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}|localhost","gm").test(c)===!0}var ht=class extends D{url=null;urlParameterName=null;localhost=null;getWebsocketUrl(){let e=this.url?ht.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){let r=B(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=ht.IsLocalNetwork()&&t;return n&&(i=t),e?.startsWith("/")&&(i=(n?i:window.location.origin)+e),i}static IsLocalNetwork(e=window.location.hostname){return Qu(e)}};var ui=new Int32Array(2),Ea=new Float32Array(ui.buffer),wa=new Float64Array(ui.buffer),Jr=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;var Ue=class{constructor(e,t){this.low=e|0,this.high=t|0}static create(e,t){return e==0&&t==0?Ue.ZERO:new Ue(e,t)}toFloat64(){return(this.low>>>0)+this.high*4294967296}equals(e){return this.low==e.low&&this.high==e.high}};Ue.ZERO=new Ue(0,0);var fs;(function(c){c[c.UTF8_BYTES=1]="UTF8_BYTES",c[c.UTF16_STRING=2]="UTF16_STRING"})(fs||(fs={}));var pi=class{constructor(e){this.bytes_=e,this.position_=0}static allocate(e){return new pi(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 Ue(this.readInt32(e),this.readInt32(e+4))}readUint64(e){return new Ue(this.readUint32(e),this.readUint32(e+4))}readFloat32(e){return ui[0]=this.readInt32(e),Ea[0]}readFloat64(e){return ui[Jr?0:1]=this.readInt32(e),ui[Jr?1:0]=this.readInt32(e+4),wa[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){Ea[0]=t,this.writeInt32(e,ui[0])}writeFloat64(e,t){wa[0]=t,this.writeInt32(e,ui[Jr?0:1]),this.writeInt32(e+4,ui[Jr?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===fs.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 l=this.readUint8(e+r++);if(s<224)o=(s&31)<<6|l&63;else{let d=this.readUint8(e+r++);if(s<240)o=(s&15)<<12|(l&63)<<6|d&63;else{let a=this.readUint8(e+r++);o=(s&7)<<18|(l&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 Ue.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 ut=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=pi.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=ut.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=pi.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 l=this.bb.capacity()-this.vtables[t];if(r==this.bb.readInt16(l)){for(let d=2;d<r;d+=2)if(this.bb.readInt16(s+d)!=this.bb.readInt16(l+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 Ue.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 Yu={};function $r(c,e){Yu[c]=e}function Ku(c){let e=c.getBufferIdentifier(),t=Yu[e];return t(c)}function Ju(c){return typeof c.guid=="function"?c.guid():null}var bc=Ls(xa(),1);var Ta=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",pt=!!B("debugnet"),Ca=!!(pt||B("debugowner"));var yn=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||(Ca&&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 Ca&&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?(Ca&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(Ca&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}},Ra=class{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new Ta),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return pt}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(),pt&&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){pt&&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&&pt&&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;pt&&console.log("connecting");let t=A.findObjectOfType(ht,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 Nb(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{pt&&i==="pong"&&console.log("<<",i)}}async handleIncomingBinaryMessage(e){let t=await e.arrayBuffer();var i=new Uint8Array(t);let n=new pi(i),r=n.getBufferIdentifier(),o=this._listenersBinary[r],s=Ku(n),l=Ju(s);if(l&&typeof l=="string"&&(this._state[l]=s),!o)return;let d=s??n;for(let a of o)a(d)}handleIncomingStringMessage(e){if(pt&&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(pt&&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),pt&&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),pt&&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),pt&&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));pt&&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{EffectComposer as sv}from"three/examples/jsm/postprocessing/EffectComposer.js";import{RenderPass as av}from"three/examples/jsm/postprocessing/RenderPass";import*as En from"three";var ap=Ls(sp(),1),Sa=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 lp(c,e){let t=await c.arrayBuffer(),i=cp(t),n=c.name.split(".").pop(),r=i+"."+n,o=c.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 Sa(!0,r,i,c.size);console.log("begin uploading file",o,c.size);let a=new FormData;a.append("file",c);let u={};u.filesize=c.size,o&&(u.alias=o);let m=await(await fetch(e+"/upload/file",{method:"POST",body:a,headers:u})).json();if(m?.success===!1)return m.message!==void 0?console.error("Upload failed:",m.message):console.error("Upload failed"),null;console.assert(m.hash_sum===i,"hash sum did not match","received:",m.hash_sum,"expected:",i),m.success&&console.log("successfully uploaded",i,m.id);let E=new Sa(m.success,r,i,c.size);return E.url=e,E}function cp(c){return(0,ap.default)(new Uint8Array(c))}async function Pa(c,e,t,i,n=!1){try{let r=await fetch(i+"/download/file",{method:"POST",body:c});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 l=cp(s);return n||console.assert(l===e,"hash mismatch, downloaded file is invalid"),o.arrayBuffer()}catch(r){console.error(r)}return null}async function dp(c,e){let t=await fetch(c),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:u}=await i.read();if(u&&(s.push(u),o+=u.length,e.call(null,new ProgressEvent("progress",{loaded:o,total:r}))),a)break}let l=new Uint8Array(o),d=0;for(let a of s)l.set(a,d),d+=a.length;return l}function Oa(c,e,t){console.warn("Adding components on object has been temporarily disabled")}var Gb;function nt(){return Gb}var xc=class{guid;file_name;file_hash;file_size;position;seed;sender;serverUrl;parentGuid;boundsSize;constructor(e,t,i,n,r,o,s,l){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=l}};async function hp(c,e,t){let i=c.name;return i.endsWith(".gltf")||i.endsWith(".glb")?new Promise((n,r)=>{let o=new FileReader;o.readAsDataURL(c),o.onloadend=async s=>{let l=o.result,d=ha(),a=new Qe(d),u=await nt().loadSync(e,l,a,!0);if(u&&u.scene){let h=u.scene;if(!h.guid){let m=new Qe(d);h.guid=m.generateUUID()}t&&Wb(e.connection,c,d,h,t),Oa(h,a,u),n(u)}}}):(console.warn("Unsupported file type: "+i),console.log(c),null)}async function up(c,e){return new Promise(async(t,i)=>{let n=ha(),r=new Qe(n),o=await nt().loadSync(e,c.toString(),r,!0);if(o&&o.scene){let s=o.scene;Oa(s,r,o),t(o)}else console.warn("Unsupported file type: "+c.toString())})}function pp(c){c.connection.beginListen("file-spawned",async e=>{if(e.sender!==c.connection.connectionId){console.log("received file event",e),qb(e,c);let t=null;try{t=await Pa(e.file_name,e.file_hash,e.file_size,e.serverUrl)}finally{Xb(e,c)}if(t){let i=new Qe(e.seed),n=await nt().parseSync(c,t,null,i);if(n&&n.scene){let r=n.scene;if(Oa(r,i,n),e.parentGuid){let o=nr(e.parentGuid,c.scene);"add"in o&&o.add(r)}r.parent||c.scene.add(r),e.position!==null&&r.position.copy(e.position)}}else console.error("download didnt return file")}})}async function Wb(c,e,t,i,n){if(!c.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 lp(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 xc(c.connectionId,t,i.guid,r.filename,r.hash,e.size,i.position,r.url??n);i.parent&&(o.parentGuid=i.parent.guid),c.send("file-spawned",o)}var Tc={};function qb(c,e){let t=new En.BoxGeometry,i=new En.Mesh(t,new En.MeshBasicMaterial({color:65280})),n=new En.BoxHelper(i,5592405);if(Tc[c.guid]=n,e.scene.add(n),c.parentGuid){let r=nr(c.parentGuid,e.scene);r&&r.add(n)}c.position&&n.position.copy(c.position)}function Xb(c,e){let t=c.guid,i=Tc[t];i&&(delete Tc[t],i.removeFromParent())}import*as fp from"three";var Qx=B("debugassets");var ka=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:
94
- `+i.src),e.preventDefault())}})}texturesLoader=new fp.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 Ep from"three/examples/jsm/libs/stats.module";import{Vector4 as $b,EquirectangularReflectionMapping as Aa,sRGBEncoding as Ia,WebGLCubeRenderTarget as ev}from"three";import{LightProbeGenerator as tv}from"three/examples/jsm/lights/LightProbeGenerator.js";import*as mp from"three";var Yb=new mp.FileLoader;async function Cc(c){return new Promise((e,t)=>{Yb.load(c,e,void 0,t)})}import{Vector4 as Jx,FileLoader as Zx,DataTexture as Pc,RGBAFormat as Jb,Color as Zb}from"three";var ms=new Uint8Array(4);ms[0]=255;ms[1]=255;ms[2]=255;ms[3]=255;var tT=new Pc(ms,1,1,Jb);function gp(c,e=1){let t="alpha"in c,i=e*e,n=new Uint8Array(4*i),r=Math.floor(c.r*255),o=Math.floor(c.g*255),s=Math.floor(c.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(c.alpha*255):n[a+3]=255}let l=new Pc(n,e,e);return l.needsUpdate=!0,l}function bp(c,e,t,i=1,n=3){let s=i*n,l=[c,e,t],d=l.length,a=new Uint8Array(4*d*s),u=new Zb;for(let m=0;m<n;m++){let E=Math.floor(m/n*d),b=K.clamp(E+1,0,d-1),y=l[E],g=l[b],p=m/n*d%1;u.lerpColors(y,g,p);let f=Math.floor(u.r*255),v=Math.floor(u.g*255),w=Math.floor(u.b*255);for(let x=0;x<i;x++){let T=(m*i+x)*4;a[T+0]=f,a[T+1]=v,a[T+2]=w,a[T+3]=255}}let h=new Pc(a,i,n);return h.needsUpdate=!0,h}var Rc=class{stage;code;constructor(e,t){this.stage=e,this.code=t}},Sc=class{loaded=new Map;async loadShader(e){let t=await Cc(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 Cc(t),n=new Rc(e,i);return this.loaded.set(t,n),n}},iT=new Sc;var Oc=B("debugenvlight"),vp=(n=>(n[n.Skybox=0]="Skybox",n[n.Trilight=1]="Trilight",n[n.Flat=3]="Flat",n[n.Custom=4]="Custom",n))(vp||{});var Ma=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 $b;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 kc(this.context,t,1);this._lighting[e]=i}getReflection(e){return this._lighting[e]}enableReflection(e){switch(Oc&&console.log(this.sceneLightSettings?vp[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=Ia,n.mapping=Aa,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=bp(t[0],t[1],t[2],64,64);i.encoding=Ia,i.mapping=Aa,this.context.scene.environment=i}else console.error("Missing ambient trilight",this.sceneLightSettings.sourceId);return;case 3:if(this.sceneLightSettings.ambientLight){let t=gp(this.sceneLightSettings.ambientLight,64);t.encoding=Ia,t.mapping=Aa,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 Oc&&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={}},kc=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=Aa,t.encoding=Ia}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){Oc&&console.log("GENERATING LIGHT PROBE",t);let n=Math.min(t.image.width,512);i=new ev(n).fromEquirectangularTexture(this._context.renderer,t),this._source=i.texture}if(this._sphericalHarmonicsArray=[],i){let n=tv.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}};import{Object3D as iv}from"three";var ar=B("debugaddressables"),Da=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}},Ke=class{static getOrCreate(e,t,i){let n=un(e,t);ar&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",n);let r=i.addressables,o=r.findAssetReference(n);if(o)return o;let s=new Ke(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,Lu(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?Gt(this.asset.scene):Gt(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 dp(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=nt().parseSync(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=nt().loadSync(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 Ni(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 Be?e:null;if(r||(r=new Be),typeof e=="object"&&(e instanceof iv?r.parent=e:Object.assign(r,e)),t){r.context=n;let o=this.asset;o.guid=this.uri;let s=da(o,r,void 0,i);if(s)return s}else{let o=rr(this.asset,r);if(o)return o}}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}},Ac=class extends Di{constructor(){super([Ke])}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?Ke.getOrCreate(t.gltfId,e,t.context):(console.error("Missing spurce id"),null):(console.error("Missing context"),null):null}};new Ac;var La=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}}};import{FloatType as PT,HalfFloatType as OT,sRGBEncoding as kT}from"three";var DT=B("debuglightmapsextension"),Ic=(i=>(i[i.Lightmap=0]="Lightmap",i[i.Skybox=1]="Skybox",i[i.Reflection=2]="Reflection",i))(Ic||{});import*as fi from"three";var yp=!!B("debuglightmaps"),Ha=class{_context;_lightmaps=new Map;constructor(e){this._context=e}registerTexture(e,t,i,n){yp&&console.log("Registering lightmap",e,Ic[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 yp&&console.warn("Missing source id"),null;let n=this._lightmaps.get(e)?.get(t)??null;return!n?.length||n.length<=i?null:n[i]}};fi.ShaderChunk.lights_fragment_maps=fi.ShaderChunk.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vUv2 );",`
93
+ }`});import{Vector3 as ab}from"three";var lo=Symbol("object"),nr=class{get __internalCollision(){return this.collision}get __internalInvertedSourceReceiver(){return this.invert}invert;collision;targetBody;context;me;_normal;get normal(){if(!this._normal){let e=this.collision.contact.ni;this._normal=new ab(e.x,e.y,e.z)}return this._normal}_collider;get collider(){return this._collider||(this._collider=this.context.getCollider(this.gameObject)),this._collider}get gameObject(){return this.targetBody[lo]}constructor(e,t,i,n=!1){this.me=e,this.collision=t,this.context=i,this.targetBody=n?t.target:t.body,this.invert=n}};var Ts=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),ie=class{static isUsingInstancing(e){return e.__isUsingInstancing===!0}static markDirty(e,t=!0){if(!!e&&(this.isUsingInstancing(e)&&(e[Ts]=!0,e.matrixWorldNeedsUpdate=!0),t))for(let i of e.children)ie.markDirty(i,!0)}};function mn(l,e){try{e?l(e):l()}catch(t){return console.error(t),!1}return!0}var Xt="__isActiveInHierarchy",gn="builtin_components";var db=H("debugnewscripts"),fe=[];function yi(l){if(!(l.new_scripts.length<=0)){if(db&&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}fe.length=0,l.new_scripts.length>0&&fe.push(...l.new_scripts),l.new_scripts.length=0;for(let e=0;e<fe.length;e++)try{let t=fe[e];if(t.destroyed)continue;if(!t.gameObject){console.error("MISSING GAMEOBJECT - will ignore",t),fe.splice(e,1),e--;continue}t.context=l,Bi(t.gameObject),Ql(t,l)}catch(t){console.error(t),vi(fe[e],l),fe.splice(e,1),e--}for(let e=0;e<fe.length;e++)try{let t=fe[e];if(t.destroyed){vi(fe[e],l),fe.splice(e,1),e--;continue}t.__internalAwake!==void 0&&(t.gameObject||console.error("MISSING GAMEOBJECT",t,t.gameObject),Bi(t.gameObject),t.activeAndEnabled&&mn(t.__internalAwake.bind(t)))}catch(t){console.error(t),vi(fe[e],l),fe.splice(e,1),e--}for(let e=0;e<fe.length;e++)try{let t=fe[e];if(t.destroyed||t.enabled===!1||(Bi(t.gameObject),t.activeAndEnabled===!1))continue;t.__internalEnable!==void 0&&(t.enabled=!0,mn(t.__internalEnable.bind(t)))}catch(t){console.error(t),vi(fe[e],l),fe.splice(e,1),e--}for(let e=0;e<fe.length;e++)try{let t=fe[e];if(t.destroyed||!t.gameObject)continue;l.new_script_start.push(t)}catch(t){console.error(t),vi(fe[e],l),fe.splice(e,1),e--}fe.length=0;for(let e of l.new_scripts_post_setup_callbacks)e&&e();l.new_scripts_post_setup_callbacks.length=0}}function hu(l){!l||(l.__internalDisable(),vi(l,l.context))}function Cs(l,e){for(let t=0;t<l.new_script_start.length;t++)try{let i=l.new_script_start[t];if(e!==void 0&&i.gameObject!==e||i.destroyed||i.activeAndEnabled===!1)continue;mn(i.__internalAwake.bind(i)),mn(i.__internalEnable.bind(i)),mn(i.__internalStart.bind(i)),l.new_script_start.splice(t,1),t--}catch(i){console.error(i),vi(l.new_script_start[t],l),l.new_script_start.splice(t,1),t--}}function Ql(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 vi(l,e){ji(l,e.new_scripts),ji(l,e.new_script_start),ji(l,e.scripts),ji(l,e.scripts_earlyUpdate),ji(l,e.scripts_update),ji(l,e.scripts_lateUpdate),ji(l,e.scripts_onBeforeRender),ji(l,e.scripts_onAfterRender),e.stopAllCoroutinesFrom(l)}function ji(l,e){let t=e.indexOf(l);t>=0&&e.splice(t,1)}var hb={},du={};function uu(){if(!J.Current){console.trace("Invalid call - no current context.");return}pu(J.Current.scene,J.Current.scene.visible,!0)}function pu(l,e,t){let i=!1,n=rr(l);if(hb[l.uuid]=n,e&&(e=rr(l)),l[Xt]=e,!i){let r=du[l.uuid];r!==void 0&&r!==e&&t&&ub(l,o=>{e?(mn(o.__internalAwake.bind(o)),o.enabled=!0):o.enabled=!1})}if(du[l.uuid]=e,l.children)for(let r of l.children)pu(r,e,t)}function Bi(l){let e=!0,t=l,i=!1;for(;t&&t;){if(t.type==="Scene"&&(i=!0),!rr(t)){e=!1;break}t=t.parent}if(!l){console.error("GO is null");return}l[Xt]=e&&i}function ub(l,e){if(l.userData?.components)for(let t of l.userData.components)e(t)}import*as co from"three";var mu=/^(?:[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 pb(l){return typeof l=="string"&&mu.test(l)}var gu=pb;var Le=[];for(let l=0;l<256;++l)Le.push((l+256).toString(16).slice(1));function bu(l,e=0){return(Le[l[e+0]]+Le[l[e+1]]+Le[l[e+2]]+Le[l[e+3]]+"-"+Le[l[e+4]]+Le[l[e+5]]+"-"+Le[l[e+6]]+Le[l[e+7]]+"-"+Le[l[e+8]]+Le[l[e+9]]+"-"+Le[l[e+10]]+Le[l[e+11]]+Le[l[e+12]]+Le[l[e+13]]+Le[l[e+14]]+Le[l[e+15]]).toLowerCase()}function fb(l){if(!gu(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 vu=fb;function mb(l){l=unescape(encodeURIComponent(l));let e=[];for(let t=0;t<l.length;++t)e.push(l.charCodeAt(t));return e}var gb="6ba7b810-9dad-11d1-80b4-00c04fd430c8",bb="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Yl(l,e,t){function i(n,r,o,s){var c;if(typeof n=="string"&&(n=mb(n)),typeof r=="string"&&(r=vu(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 bu(d)}try{i.name=l}catch{}return i.DNS=gb,i.URL=bb,i}function vb(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 Kl(l,e){return l<<e|l>>>32-e}function yb(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]=Kl(s[f-3]^s[f-8]^s[f-14]^s[f-16],1);let c=t[0],d=t[1],a=t[2],u=t[3],h=t[4];for(let f=0;f<80;++f){let E=Math.floor(f/20),b=Kl(c,5)+vb(E,d,a,u)+h+e[E]+s[f]>>>0;h=u,u=a,a=Kl(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]+u>>>0,t[4]=t[4]+h>>>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 yu=yb;var Eb=Yl("v5",80,yu),Jl=Eb;var Rs=H("debugcomponents"),wb="eff8ba80-635d-11ec-90d6-0242ac120003",Ve=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,Jl(e.toString(),wb)}static createFromString(e){return new Ve(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 Ss=class{guid;constructor(e){this.guid=e}};function Ps(l,e,t=!0){if(!l)return;let i=l;if(Rt(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 Ss(n);e.send("instance-destroyed",r,2)}function Eu(l,e){let t=new Ss(l);e.send("instance-destroyed",t,2)}function wu(l){l.connection.beginListen("instance-destroyed",e=>{Rs&&console.log("[Remote] Destroyed",l.scene,e);let t=bn(e.guid,l.scene);t&&Rt(t)})}var Zl=class{guid;originalGuid;seed;visible;hostData;dontSave;parent;position;rotation;scale;constructor(e,t){this.originalGuid=e,this.guid=t}};function Os(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=J.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}=_b(n,e);if(o){let c=o;if(c.guid){Rs&&console.log("[Local] new instance","gameobject:",o?.guid);let d=new Zl(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 ks(){return Math.random()*9999999}function _u(l){l.connection.beginListen("new-instance-created",async e=>{let t=await xb(e.originalGuid,l.scene);if(!t){console.warn("could not find object that was instantiated: "+e.guid);return}let i=new He;e.position&&(i.position=new co.Vector3(e.position.x,e.position.y,e.position.z)),e.rotation&&(i.rotation=new co.Quaternion(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w)),e.scale&&(i.scale=new co.Vector3(e.scale.x,e.scale.y,e.scale.z)),i.parent=e.parent,e.seed&&(i.idProvider=new Ve(e.seed)),i.visible=e.visible,i.context=l,Rs&&l.alias&&console.log("[Remote] instantiate in: "+l.alias);let n=vn(t,i);n&&(e.parent==="scene"&&l.scene.add(n),Rs&&console.log("[Remote] new instance","gameobject:",n?.guid,t))})}function _b(l,e){let t=ks(),i=e??new He;i.idProvider=new Ve(t);let n=vn(l,i);return{seed:t,instance:n}}var xu={};function Tu(l,e){xu[l]=e}async function xb(l,e){let t=xu[l];if(t!=null){let i=await t(l);if(i)return i}return Cu(l,e)}function Cu(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=Cu(l,t);if(i)return i}return null}var Ru=new Map;function Su(l){if(!l)return;let e=l.prototype;if(!e)return;let t=Ru.get(e);t||(t=Tb(e),Ru.set(e,t)),t.apply(l)}function Tb(l){return new ec(l)}var ec=class{$symbol;extensions;descriptors;constructor(e){this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(e),this.descriptors=new Array;for(let t=0;t<this.extensions.length;t++){let i=this.extensions[t],n=Object.getOwnPropertyDescriptor(e,i);n&&this.descriptors.push(n)}}apply(e){if(!e[this.$symbol]){e[this.$symbol]=!0;for(let t=0;t<this.extensions.length;t++){let i=this.extensions[t],n=this.descriptors[t];n&&Object.defineProperty(e,i,n)}}}};import{Object3D as mt}from"three";var tc=H("debuggetcomponent");function Cb(l){return l==null||l.isObject3D?l:l.object&&l.object.isObject3D?l.object:l}function Is(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))}function As(l,e){let t=yn(l,e);if(t)return t;let i=new e;return ho(l,i)}function ho(l,e,t=!0){l.userData||(l.userData={}),l.userData.components||(l.userData.components=[]),l.userData.components.push(e),e.gameObject=l,Ms(e);try{e.__internalAwake&&t&&(Bi(l),e.__internalAwake())}catch(i){console.error(i)}return e}function Ou(l,e){if(e.gameObject!==l){if(e.gameObject&&e.gameObject.userData.components){let t=e.gameObject.userData.components.indexOf(e);e.gameObject.userData.components.splice(t,1)}if(!l.userData.components)l.userData.components=[];else if(l.userData.components.includes(e))return;l.userData.components.push(e),e.gameObject=l}}function ku(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(),vi(l,l.context??J.Current),l.__internalDestroy(),l.gameObject=null}var Pu=!1;function Iu(l,e,t){if(l!=null){if(!l.isObject3D){console.error("Object is not object3D");return}if(!l?.userData?.components)return null;if(typeof e=="string"&&(Pu||(Pu=!0,console.warn(`Accessing components by name is not supported.
94
+ Please use the component type instead. This may keep working in local development but it will fail when bundling your application.
95
+
96
+ You can import other modules your main module to get access to types
97
+ or if you use npmdefs you can make types available globally using globalThis:
98
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis`))),tc&&console.log("FIND",e),e!=null){for(let i=0;i<l.userData.components.length;i++){let n=l.userData.components[i];if(e===null||n.constructor.name===e.name||n.constructor.name===e)if(tc&&console.log("MATCH BY NAME",n),t)t.push(n);else return n}for(let i=0;i<l.userData.components.length;i++){let n=l.userData.components[i],r=Object.getPrototypeOf(n.constructor);do{if(r===e)if(tc&&console.log("MATCH BY PROTOYPE",r),t)t.push(n);else return n;r=Object.getPrototypeOf(r)}while(r)}return t}}}function yn(l,e){return Iu(l,e)}function sr(l,e,t){return t||(t=[]),Iu(l,e,t)}function Fi(l,e,t){let i=yn(l,e);if(t===!1&&i.enabled===!1)return null;if(i)return i;for(let n=0;n<l?.children?.length;n++){let r=Fi(l.children[n],e);if(r)return r}return null}function ar(l,e,t){t||(t=[]),sr(l,e,t);for(let i=0;i<l?.children?.length;i++)ar(l.children[i],e,t);return t}function or(l,e){if(!l)return null;if(Array.isArray(l)){for(let i=0;i<l.length;i++){let n=Cb(l[i]),r=or(n,e);if(r)return r}return null}let t=yn(l,e);return t||(l.parent?or(l.parent,e):null)}function uo(l,e,t){return t||(t=[]),l?(sr(l,e,t),l.parent?uo(l.parent,e,t):t):t}function Au(l,e,t){if(!l)return null;if(!e&&(e=J.Current,!e))return console.error("Can not search object without any needle context or scene!!!"),null;let i=e;if(i.isScene||(i=e?.scene),!i)return null;for(let n in i.children){let r=i.children[n];if(t===!1&&r[Xt]===!1)continue;if(r.constructor==l)return r;let o=Fi(r,l);if(o)return o}return null}function Mu(l,e,t){if(!l)return e;if(!t&&(t=J.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;ar(r,l,e)}return e}function Ds(l){l&&l.isObject3D===!0&&Su(l)}Object.getOwnPropertyDescriptor(mt.prototype,"activeSelf")||Object.defineProperty(mt.prototype,"activeSelf",{get:function(){return this.visible},set:function(l){let e=typeof l=="number"?l>.5:l;this.visible=e}});mt.prototype.SetActive=function(l){this.visible=l};mt.prototype.addNewComponent=function(l){return ho(this,new l)};mt.prototype.removeComponent=function(l){return Is(this,l)};mt.prototype.getOrAddComponent=function(l){return As(this,l)};mt.prototype.getComponent=function(l){return yn(this,l)};mt.prototype.getComponents=function(l,e){return sr(this,l,e)};mt.prototype.getComponentInChildren=function(l){return Fi(this,l)};mt.prototype.getComponentsInChildren=function(l,e){return ar(this,l,e)};mt.prototype.getComponentInParent=function(l){return or(this,l)};mt.prototype.getComponentsInParent=function(l,e){return uo(this,l,e)};var En=H("debuggetcomponent"),Rb=(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))(Rb||{}),He=class{idProvider;parent;keepWorldPosition;position;rotation;scale;visible;context};function rr(l){return l.visible||Ls(l)}function Lu(l){return l[Xt]||Ls(l)}function Hu(l,e){l.__isUsingInstancing=e}function Ls(l){return ie.isUsingInstancing(l)}function bn(l,e){return ln(l,e,!0,!0)}function Rt(l,e=!0,t=!0){let i=l;if(i.isComponent){i.__internalDestroy();return}let n=l;if(En&&console.log(n),e&&n.children)for(let o of n.children)Rt(o,e,!1);let r=n.userData.components;if(r){let o=r.length;for(let s=0;s<r.length;s++)r[s].__internalDestroy(),r.length<o&&(o=r.length,s--)}t&&n.removeFromParent()}function gt(l,e,t=!0){if(!!l){if(l.isObject3D||new Error("Expected Object3D but got "+l),l.userData?.components)for(let i=0;i<l.userData.components.length;i++){let n=l.userData.components[i];if(n?.isComponent===!0){let r=e(n);if(r!==void 0)return r}}if(t&&l.children)for(let i=0;i<l.children.length;i++){let n=l.children[i];if(!n)continue;let r=gt(n,e,t);if(r!==void 0)return r}}}function vn(l,e=null){if(l===null)return null;let t=null;e!==null&&(e.x!==void 0?(t=new He,t.position=e):t=e);let i=J.Current;t?.context&&(i=t.context),En&&i.alias&&console.log("context",i.alias),t&&!t.idProvider&&(t.idProvider=new Ve(Date.now()));let n=[],r={},o={},s=ju(i,l,t,n,r,o);s&&(Pb(r),Sb(o,r)),En&&(ao(l,!0),ao(s,!0));let c={};for(let d in n){let a=n[d],u=a.guid;t&&t.idProvider&&(a.guid=t.idProvider.generateUUID(),c[u]=a.guid,En&&console.log(a.name,a.guid)),Ms(a,i),a.__internalNewInstanceCreated&&a.__internalNewInstanceCreated()}for(let d in n){let a=n[d];a.resolveGuids&&a.resolveGuids(c),a.enabled!==!1&&(a.enabled=!0)}return yi(i),s}function ju(l,e,t,i,n,r){if(!e)return null;let o=e.userData;e.userData={};let s=e.children;e.children=[];let c;if(c=e.clone(!1),Ds(c),e.userData=o,e.children=s,n[e.uuid]={original:e,clone:c},e.type==="SkinnedMesh"&&(r[e.uuid]={original:e,clone:c}),t?.visible!==void 0&&(c.visible=t.visible),t?.idProvider){c.uuid=t.idProvider.generateUUID();let a=c;a&&(a.guid=c.uuid)}e.animations&&e.animations.length>0&&(c.animations=[...e.animations]);let d=e.parent;if(d&&d.add(c),t?.position?ne(c,t.position):c.position.copy(e.position),t?.rotation?Ue(c,t.rotation):c.quaternion.copy(e.quaternion),t?.scale?c.scale.copy(t.scale):c.scale.copy(e.scale),t?.parent&&t.parent!=="scene"){let a=null;if(typeof t.parent=="string"?a=ln(t.parent,l.scene,!0):a=t.parent,a){let u=t.keepWorldPosition===!0?a.attach:a.add;u?u.call(a,c):console.error("Invalid parent object",a,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(let[a,u]of Object.entries(e.userData))a!=="components"&&(c.userData[a]=u);if(e.userData?.components){let a=e.userData.components,u=[];c.userData.components=u;for(let h=0;h<a.length;h++){let f=a[h],E=Object.create(f);Object.assign(E,f),u.push(E),E.gameObject=c,i.push(E)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0);for(let a in e.children){let u=e.children[a],h=ju(l,u,t,i,n,r);h&&c.add(h)}return c}function Sb(l,e){for(let t in l){let i=l[t],n=i.original,r=n.skeleton,o=i.clone;if(!r){console.warn("Skinned mesh has no skeleton?",i);continue}let s=r.bones,c=o.skeleton.clone();o.skeleton=c,o.bindMatrix.clone().copy(n.bindMatrix),o.bindMatrixInverse.copy(n.bindMatrixInverse);let d=[];c.bones=d;for(let a=0;a<s.length;a++){let u=s[a],f=e[u.uuid].clone;d.push(f)}}for(let t in l){let i=l[t].clone;i.skeleton.update(),i.bind(i.skeleton,i.bindMatrix),i.updateMatrixWorld(!0)}}function Pb(l){for(let e in l){let i=l[e].clone;if(i.userData?.components)for(let n=0;n<i.userData.components.length;n++){let r=i.userData.components[n],o=Object.entries(r);for(let[s,c]of o)if(Array.isArray(c)){let d=[];r[s]=d;for(let a=0;a<c.length;a++){let u=c[a];if(typeof u!="object"){d.push(u);continue}let h=Du(r,s,u,l);h!==void 0?d.push(h):d.push(u)}}else if(typeof c=="object"){let d=Du(r,s,c,l);d!==void 0&&(r[s]=d)}}}}function Du(l,e,t,i){if(t!=null){if(t.isComponent===!0){let n=t.gameObject;if(n){let r=n.uuid,o=i[r]?.clone;if(!o){En&&console.log("reference did not change",e,l,t);return}let s=n.userData.components.indexOf(t);if(s>=0)return En&&console.log(e,r),o.userData.components[s];console.warn("could not find component",e,t)}}else if(t.isObject3D===!0){if(e==="gameObject")return;let n=t;if(n){let r=n.uuid,o=i[r]?.clone;if(o)return En&&console.log(e,"old",t,"new",o),o}}}}var po=H("debugphysics"),Ob=H("debugcollisions"),Hs=class{mass=1;kinematic=!1;physicsEvents=!1;drag=0;angularDrag=.05;sleepThreshold=.01},fo=class{obj;parent;body;shapes=[];collisonCallback=null;_hasRigidbody=!1;_didSleepLastStep=!1;constructor(e,t){this.obj=e,this.parent=e.parent,this.body=t,this.body&&(this.body[lo]=e)}},Se=class{ray=void 0;cam=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 me.Vector2),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setMask(e){this.layerMask||(this.layerMask=new me.Layers);let t=this.layerMask;t?t.mask=e:this.layerMask=e}};N(Se,"AllLayers",4294967295);var ic=class{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}},js=class{raycaster=new me.Raycaster;defaultRaycastOptions=new Se;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:0},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new me.Layers;sphereOverlap(e,t){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;let i=new me.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 me.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=G(e).distanceTo(t.center);return new ic(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=e.cam??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 me.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 ys;objects=[];tempPosition=new me.Vector3;tempQuaternion=new me.Quaternion;constructor(e){if(this.context=e,this.world.gravity.set(0,-9.82,0),po){let t={};t.onInit=(i,n,r)=>{n.layers.set(-1)},ou(e.scene,this.world.bodies,t)}this.world.addEventListener("beginContact",this.onBeginContact.bind(this)),this.world.addEventListener("endContact",this.onEndContact.bind(this))}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}}t.shapes.length>0&&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=z.KINEMATIC:i.type=z.DYNAMIC,t.drag&&(i.linearDamping=t.drag),t.angularDrag&&(i.angularDamping=t.angularDrag),t.sleepThreshold&&(i.sleepSpeedLimit=t.sleepThreshold),i.shapes.length>0&&this.world.addBody(i);let n=new fo(e,i);return n._hasRigidbody=!0,this.objects.push(n),po&&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 un(s);c.collisionResponse=!t,i=i.clone(),i.multiply(o);let d=this.addShape(e,c,i,r);if(d!==null){if(this.world.addBody(d),this.isAlreadyRegistered(d))return c;let a=new fo(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 bs(i*o);t=t.clone(),t.multiply(r);let c=this.addShape(e,s,t,n);if(c!==null){if(this.world.addBody(c),this.isAlreadyRegistered(c))return s;let d=new fo(e,c);this.objects.push(d)}return s}addMeshCollider(e){po&&console.warn("TODO mesh collider not yet supported")}isAlreadyRegistered(e){for(let t of this.objects)if(t.body===e)return!0;return!1}tempMat1=new me.Matrix4;tempMat2=new me.Matrix4;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=z.KINEMATIC),r){i.x*=-1;let o=e.position,s=e.quaternion;if(n&&n.gameObject!==e)this.tempMat1.copy(e.matrixWorld),this.tempMat2.copy(n.gameObject.matrixWorld).invert(),this.tempMat1.premultiply(this.tempMat2),this.tempMat1.decompose(o,s,this.tempPosition);else{o=G(e);let a=r.position;o.x-=a.x,o.y-=a.y,o.z-=a.z,s=we(e);let u=new me.Quaternion(r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w);s.multiply(u.invert())}o.add(i);let c=new _(o.x,o.y,o.z),d=new re(s.x,s.y,s.z,s.w);r.addShape(t,c,d),r.updateMassProperties(),this.world.addBody(r)}return r}step(e){this._isUpdatingPhysicsWorld=!0,e=Math.min(e,1/30),this.world.step(e),this._isUpdatingPhysicsWorld=!1,po&&this.context.time.frameCount%60}temp=new me.Vector3;tempQuat=new me.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),po&&(!t._didSleepLastStep&&i.sleepState===z.SLEEPING?console.log("BODY SLEEPING",i):t._didSleepLastStep&&i.sleepState!==z.SLEEPING&&console.log("BODY WOKE UP",i)),t._didSleepLastStep=i.sleepState===z.SLEEPING;let n=t.obj;if(i.type===z.KINEMATIC){let r=G(n,this.temp);i.position.set(r.x,r.y,r.z);let o=we(n,this.tempQuat);i.quaternion.set(o.x,o.y,o.z,o.w);continue}if(t.parent&&n.parent===t.parent){lu(n,i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w);let r=i.position;ir(n,r.x,r.y,r.z),i.velocity.length()>i.sleepSpeedLimit&&ie.markDirty(n)}}this._isUpdatingPhysicsWorld=!1}internalCreateBody(e,t){let i=new z;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 re(r.x,r.y,r.z,r.w),i.type=z.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)}onBeginContact(e){}collisionContext=new nc;raiseCollisionEvents(e,t){let i=new nr(e,t,this.collisionContext);if(Ob&&console.log("collision between",t.contact.bi,t.contact.bj,e,t),gt(e,n=>{n.__internalHandleCollision(i,!1)}),i.collider&&!i.collider.attachedRigidbody&&i.collider.isTrigger){let n=new nr(i.gameObject,t,this.collisionContext,!0);gt(i.gameObject,r=>{r.__internalHandleCollision(n,!0)})}}onEndContact(e){let t=e.bodyA[lo],i=e.bodyB[lo];gt(i,n=>{n.__internalHandleExitCollisionEvent(t,!1)}),gt(t,n=>{let r=n;r.isCollider&&!r.attachedRigidbody&&r.isTrigger&&gt(r.gameObject,o=>{o.__internalHandleExitCollisionEvent(i,!0)})})}},Bu=null;function Fu(l){Bu=l}var nc=class{getCollider(e){return Bu.getCollider(e)}};import{Clock as kb}from"three";var Bs=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 kb;_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 Ab}from"websocket-ts";var Qt=new Int32Array(2),Fs=new Float32Array(Qt.buffer),Ns=new Float64Array(Qt.buffer),lr=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;var Fe=class{constructor(e,t){this.low=e|0,this.high=t|0}static create(e,t){return e==0&&t==0?Fe.ZERO:new Fe(e,t)}toFloat64(){return(this.low>>>0)+this.high*4294967296}equals(e){return this.low==e.low&&this.high==e.high}};Fe.ZERO=new Fe(0,0);var mo;(function(l){l[l.UTF8_BYTES=1]="UTF8_BYTES",l[l.UTF16_STRING=2]="UTF16_STRING"})(mo||(mo={}));var Yt=class{constructor(e){this.bytes_=e,this.position_=0}static allocate(e){return new Yt(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 Fe(this.readInt32(e),this.readInt32(e+4))}readUint64(e){return new Fe(this.readUint32(e),this.readUint32(e+4))}readFloat32(e){return Qt[0]=this.readInt32(e),Fs[0]}readFloat64(e){return Qt[lr?0:1]=this.readInt32(e),Qt[lr?1:0]=this.readInt32(e+4),Ns[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){Fs[0]=t,this.writeInt32(e,Qt[0])}writeFloat64(e,t){Ns[0]=t,this.writeInt32(e,Qt[lr?0:1]),this.writeInt32(e+4,Qt[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===mo.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 Fe.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 nt=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=Yt.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=nt.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=Yt.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 Fe.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 Nu={};function dr(l,e){Nu[l]=e}function zu(l){let e=l.getBufferIdentifier(),t=Nu[e];return t(l)}function Uu(l){return typeof l.guid=="function"?l.guid():null}var oc=$o(Us(),1);var Vs=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 oc.default(e);t.on("error",i=>{console.error(i),this._host=void 0,this.trySetupClient(e)}),t.on("open",i=>{this._host=new ac(t)})}trySetupClient(e){this._client=new oc.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)})})}},sc=class{_peer;constructor(e){this._peer=e}};var ac=class extends sc{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 lc="wss://needle-tiny-starter.glitch.me/socket",rt=!!H("debugnet"),Ws=!!(rt||H("debugowner"));var zi=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||(Ws&&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 Ws&&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?(Ws&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(Ws&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}},Gs=class{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new Vs),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return rt}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(),rt&&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){rt&&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&&rt&&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)}netWebSocketUrlProvider;registerProvider(e){this.netWebSocketUrlProvider=e}connect(){if(this.connected)return;rt&&console.log("connecting");let e=this.netWebSocketUrlProvider?.getWebsocketUrl();e&&(lc=e),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 "+lc);let e=new Ab(lc).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{rt&&i==="pong"&&console.log("<<",i)}}async handleIncomingBinaryMessage(e){let t=await e.arrayBuffer();var i=new Uint8Array(t);let n=new Yt(i),r=n.getBufferIdentifier(),o=this._listenersBinary[r],s=zu(n),c=Uu(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(rt&&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(rt&&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),rt&&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),rt&&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),rt&&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));rt&&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{EffectComposer as Zb}from"three/examples/jsm/postprocessing/EffectComposer.js";import{RenderPass as $b}from"three/examples/jsm/postprocessing/RenderPass";import*as Ui from"three";var Zu=$o(Ju(),1),qs=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 $u(l,e){let t=await l.arrayBuffer(),i=ep(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 qs(!0,r,i,l.size);console.log("begin uploading file",o,l.size);let a=new FormData;a.append("file",l);let u={};u.filesize=l.size,o&&(u.alias=o);let f=await(await fetch(e+"/upload/file",{method:"POST",body:a,headers:u})).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 qs(f.success,r,i,l.size);return E.url=e,E}function ep(l){return(0,Zu.default)(new Uint8Array(l))}async function Xs(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=ep(s);return n||console.assert(c===e,"hash mismatch, downloaded file is invalid"),o.arrayBuffer()}catch(r){console.error(r)}return null}async function tp(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:u}=await i.read();if(u&&(s.push(u),o+=u.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}function Qs(l,e,t){console.warn("Adding components on object has been temporarily disabled")}var Hb;function Ze(){return Hb}var hc=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 ip(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=ks(),a=new Ve(d),u=await Ze().loadSync(e,c,a,!0);if(u&&u.scene){let h=u.scene;if(!h.guid){let f=new Ve(d);h.guid=f.generateUUID()}t&&jb(e.connection,l,d,h,t),Qs(h,a,u),n(u)}}}):(console.warn("Unsupported file type: "+i),console.log(l),null)}async function np(l,e){return new Promise(async(t,i)=>{let n=ks(),r=new Ve(n),o=await Ze().loadSync(e,l.toString(),r,!0);if(o&&o.scene){let s=o.scene;Qs(s,r,o),t(o)}else console.warn("Unsupported file type: "+l.toString())})}function rp(l){l.connection.beginListen("file-spawned",async e=>{if(e.sender!==l.connection.connectionId){console.log("received file event",e),Bb(e,l);let t=null;try{t=await Xs(e.file_name,e.file_hash,e.file_size,e.serverUrl)}finally{Fb(e,l)}if(t){let i=new Ve(e.seed),n=await Ze().parseSync(l,t,null,i);if(n&&n.scene){let r=n.scene;if(Qs(r,i,n),e.parentGuid){let o=bn(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 jb(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 $u(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 hc(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 uc={};function Bb(l,e){let t=new Ui.BoxGeometry,i=new Ui.Mesh(t,new Ui.MeshBasicMaterial({color:65280})),n=new Ui.BoxHelper(i,5592405);if(uc[l.guid]=n,e.scene.add(n),l.parentGuid){let r=bn(l.parentGuid,e.scene);r&&r.add(n)}l.position&&n.position.copy(l.position)}function Fb(l,e){let t=l.guid,i=uc[t];i&&(delete uc[t],i.removeFromParent())}import*as op from"three";var Ex=H("debugassets");var Ys=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:
99
+ `+i.src),e.preventDefault())}})}texturesLoader=new op.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 hp from"three/examples/jsm/libs/stats.module";import{Vector4 as Gb,EquirectangularReflectionMapping as Ks,sRGBEncoding as Js,WebGLCubeRenderTarget as qb}from"three";import{LightProbeGenerator as Xb}from"three/examples/jsm/lights/LightProbeGenerator.js";import*as sp from"three";var zb=new sp.FileLoader;async function pc(l){return new Promise((e,t)=>{zb.load(l,e,void 0,t)})}import{Vector4 as xx,FileLoader as Tx,DataTexture as gc,RGBAFormat as Vb,Color as Wb}from"three";var go=new Uint8Array(4);go[0]=255;go[1]=255;go[2]=255;go[3]=255;var Sx=new gc(go,1,1,Vb);function ap(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 gc(n,e,e);return c.needsUpdate=!0,c}function lp(l,e,t,i=1,n=3){let s=i*n,c=[l,e,t],d=c.length,a=new Uint8Array(4*d*s),u=new Wb;for(let f=0;f<n;f++){let E=Math.floor(f/n*d),b=K.clamp(E+1,0,d-1),y=c[E],g=c[b],p=f/n*d%1;u.lerpColors(y,g,p);let m=Math.floor(u.r*255),v=Math.floor(u.g*255),w=Math.floor(u.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 h=new gc(a,i,n);return h.needsUpdate=!0,h}var fc=class{stage;code;constructor(e,t){this.stage=e,this.code=t}},mc=class{loaded=new Map;async loadShader(e){let t=await pc(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 pc(t),n=new fc(e,i);return this.loaded.set(t,n),n}},Px=new mc;var bc=H("debugenvlight"),cp=(n=>(n[n.Skybox=0]="Skybox",n[n.Trilight=1]="Trilight",n[n.Flat=3]="Flat",n[n.Custom=4]="Custom",n))(cp||{});var Zs=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 Gb;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 vc(this.context,t,1);this._lighting[e]=i}getReflection(e){return this._lighting[e]}enableReflection(e){switch(bc&&console.log(this.sceneLightSettings?cp[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=Js,n.mapping=Ks,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=lp(t[0],t[1],t[2],64,64);i.encoding=Js,i.mapping=Ks,this.context.scene.environment=i}else console.error("Missing ambient trilight",this.sceneLightSettings.sourceId);return;case 3:if(this.sceneLightSettings.ambientLight){let t=ap(this.sceneLightSettings.ambientLight,64);t.encoding=Js,t.mapping=Ks,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 bc&&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={}},vc=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=Ks,t.encoding=Js}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){bc&&console.log("GENERATING LIGHT PROBE",t);let n=Math.min(t.image.width,512);i=new qb(n).fromEquirectangularTexture(this._context.renderer,t),this._source=i.texture}if(this._sphericalHarmonicsArray=[],i){let n=Xb.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}};import{Object3D as Qb}from"three";var wn=H("debugaddressables"),$s=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}},ot=class{static getOrCreate(e,t,i){let n=Di(e,t);wn&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",n);let r=i.addressables,o=r.findAssetReference(n);if(o)return o;let s=new ot(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,Tu(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&&(wn&&console.log("Unload",this.asset),this.asset.scene?Rt(this.asset.scene):Rt(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,wn&&console.log("Preload",this.uri);let e=await tp(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=J.Current;this._rawBinary?(this._loading=Ze().parseSync(t,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(wn&&console.log("Load async",this.uri),this._loading=Ze().loadSync(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 yi(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=J.Current;if(e||(e=n.scene),this.mustLoad&&await this.loadAssetAsync(),wn&&console.log("Instantiate",this.uri,"parent:",e),this.asset){wn&&console.log("Add to scene",this.asset);let r=e instanceof He?e:null;if(r||(r=new He),typeof e=="object"&&(e instanceof Qb?r.parent=e:Object.assign(r,e)),t){r.context=n;let o=this.asset;o.guid=this.uri;let s=Os(o,r,void 0,i);if(s)return s}else{let o=vn(this.asset,r);if(o)return o}}else wn&&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}},yc=class extends pi{constructor(){super([ot])}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?ot.getOrCreate(t.gltfId,e,t.context):(console.error("Missing spurce id"),null):(console.error("Missing context"),null):null}};new yc;var ea=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}}};import{FloatType as eT,HalfFloatType as tT,sRGBEncoding as iT}from"three";var sT=H("debuglightmapsextension"),Ec=(i=>(i[i.Lightmap=0]="Lightmap",i[i.Skybox=1]="Skybox",i[i.Reflection=2]="Reflection",i))(Ec||{});import*as Kt from"three";var dp=!!H("debuglightmaps"),ta=class{_context;_lightmaps=new Map;constructor(e){this._context=e}registerTexture(e,t,i,n){dp&&console.log("Registering lightmap",e,Ec[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 dp&&console.warn("Missing source id"),null;let n=this._lightmaps.get(e)?.get(t)??null;return!n?.length||n.length<=i?null:n[i]}};Kt.ShaderChunk.lights_fragment_maps=Kt.ShaderChunk.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vUv2 );",`
95
100
 
96
101
  vec2 lUv = vUv2.xy * lightmapScaleOffset.xy + vec2(lightmapScaleOffset.z, (1. - (lightmapScaleOffset.y + lightmapScaleOffset.w)));
97
102
  vec4 lightMapTexel = texture2D( lightMap, lUv);
@@ -99,7 +104,7 @@ a=extmap-allow-mixed`)!==-1){var f=p.sdp.split(`
99
104
  lightMapTexel.rgb *= lightMapTexel.a * 8.; // no idea where that "8" comes from... heuristically derived
100
105
  lightMapTexel.a = 1.;
101
106
  lightMapTexel = conv_sRGBToLinear(lightMapTexel);
102
- `);fi.ShaderChunk.lightmap_pars_fragment=`
107
+ `);Kt.ShaderChunk.lightmap_pars_fragment=`
103
108
  #ifdef USE_LIGHTMAP
104
109
  uniform sampler2D lightMap;
105
110
  uniform float lightMapIntensity;
@@ -110,12 +115,12 @@ a=extmap-allow-mixed`)!==-1){var f=p.sdp.split(`
110
115
  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 );
111
116
  }
112
117
  #endif
113
- `;fi.ShaderChunk.lights_fragment_begin=fi.ShaderChunk.lights_fragment_begin.replace("irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );",`
118
+ `;Kt.ShaderChunk.lights_fragment_begin=Kt.ShaderChunk.lights_fragment_begin.replace("irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );",`
114
119
  #if defined(USE_LIGHTMAP)
115
120
  irradiance += 0.;
116
121
  #else
117
122
  irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
118
- #endif`);fi.UniformsLib.lightmap.lightmapScaleOffset={value:new fi.Vector4(1,1,0,0)};var nv=B("debugplayerview");var Mc=class{userId;context;viewDevice="browser";get currentObject(){return this._object}set currentObject(e){this._object=e}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}removed=!1;_object;constructor(e,t){this.userId=e,this.context=t}},ja=class{context;playerViews=new Map;constructor(e){this.context=e}setPlayerView(e,t,i){let n=this.playerViews.get(e);n||(n=new Mc(e,this.context),this.playerViews.set(e,n)),n.viewDevice=i,n.currentObject=t,n.removed=!1}getPlayerView(e){if(!e)return;if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}removePlayerView(e,t){let i=this.playerViews.get(e);i?.viewDevice===t&&(nv&&console.log("REMOVE",e),i.removed=!0,this.playerViews.delete(e))}};var lv=B("debugSetup"),cv=B("stats"),Ba={};function fa(c,e){if(!c)return;let t=e?.new_scripts??Z.Current.new_scripts;t.includes(c)||t.push(c)}var kt=class{static get Current(){return this._current}static set Current(e){this._current=e}name;alias;isManagedExternally=!1;domElement;get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(e){if(e!==this._resolutionScaleFactor&&typeof e=="number"){if(e<=0){console.error("Invalid resolution scale factor",e);return}this._resolutionScaleFactor=e,this.updateSize()}}_resolutionScaleFactor=1;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||!1}xrSessionMode=void 0;get xrSession(){return this.renderer.xr?.getSession()}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;players;_sizeChanged=!1;_isCreated=!1;_stats=cv?Ep.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=B("postfx");this.renderer=new ov({antialias:!0}),this.renderer.toneMappingExposure=1,this.renderer.toneMapping=Oe.NoToneMapping,this.renderer.setClearColor(new Oe.Color("lightgrey"),0),this.renderer.antialias=!0,this.renderer.alpha=!1,this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=Oe.PCFSoftShadowMap,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputEncoding=Oe.sRGBEncoding,this.renderer.physicallyCorrectLights=!0,this.composer=i?new sv(this.renderer):null}this.scene=new Oe.Scene,this.application=new La(this),this.time=new ya,this.input=new zs(this),this.physics=new va(this),this.connection=new Ra(this),this.assets=new ka,this.rendererData=new Ma(this),this.addressables=new Da(this),this.lightmaps=new Ha(this),this.players=new ja(this),window.addEventListener("resize",()=>this._sizeChanged=!0),new ResizeObserver(i=>this._sizeChanged=!0).observe(this.domElement)}updateSize(){if(!this.isManagedExternally&&!this.renderer.xr.isPresenting){this._sizeChanged=!1;let e=this.resolutionScaleFactor,t=this.domWidth*e,i=this.domHeight*e,n=this.mainCamera;this.updateAspect(n),this.renderer.setSize(t,i),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.composer&&(this.composer.setSize(t,i),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,Gt(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()}removeCamera(e){if(!e)return;let t=this._cameraStack.indexOf(e);if(t>=0&&this._cameraStack.splice(t,1),this.mainCameraComponent===e&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){let i=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(i)}}_onBeforeRenderListeners={};addBeforeRenderListener(e,t){if(!this._onBeforeRenderListeners[e.uuid]){this._onBeforeRenderListeners[e.uuid]=[];let i=(n,r,o,s,l,d)=>{let a=this._onBeforeRenderListeners[e.uuid];if(!!a)for(let u=0;u<a.length;u++){let h=a[u];h(n,r,o,s,l,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{kt.Current=this,e&&await e(this,t)}catch(n){console.error(n),i=!1}if(!!i){this.isManagedExternally||this.domElement.prepend(this.renderer.domElement),Mu(this),Iu(this),pp(this),kt._current=this;for(let n=0;n<this.new_scripts.length;n++){let r=this.new_scripts[n];if(r.gameObject!==void 0&&r.gameObject!==null){r.gameObject.userData===void 0&&(r.gameObject.userData={}),r.gameObject.userData.components===void 0&&(r.gameObject.userData.components=[]);let o=r.gameObject.userData.components;o.includes(r)||o.push(r)}}if(this.post_setup_callbacks)for(let n=0;n<this.post_setup_callbacks.length;n++)kt._current=this,await this.post_setup_callbacks[n](this);if(this.mainCamera,kt._current=this,Ni(this),!this.isManagedExternally&&this.composer&&this.mainCamera){let n=new av(this.scene,this.mainCamera);this.renderer.setSize(this.domWidth,this.domHeight),this.composer.addPass(n),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)),lv&&as(this.scene,!0)}}render(e,t){for(this._stats?.begin(),kt._current=this,this.time.update(),Ni(this),xu(),aa(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&&(kt._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&&(kt._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&&(kt._current=this,n.lateUpdate())}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&&(kt._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&&(kt._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 Oe.WebGLRenderTarget(this.domWidth,this.domHeight),this._requireDepthTexture){let i=new rv(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new Oe.Texture,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=Oe.NearestFilter,this._renderTarget.texture.magFilter=Oe.NearestFilter,this._renderTarget.texture.format=Oe.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 u=s[s.length-1].next();if(u.done&&s.pop(),t(u)&&(r.chained||(r.chained=[]),r.chained.push(u.value)),!u.done)continue}let l=r.main.next();if(l.done===!0){i.splice(n,1),--n;continue}let d=l.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=kt;z(Z,"_current");var lr="ar",dv="quit-ar",Fa=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(`.${lr}`).forEach(o=>{!o||o!==this.arContainer&&(this._reparentedObjects.push({el:o,previousParent:o.parentElement}),this.arContainer?.appendChild(o))});let r=t.getElementsByClassName(dv);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(lr))return e;if(e.children){for(let i of e.children)if(!(!i||!i.classList)&&i.classList.contains(lr))return i}let t=document.createElement("div");return t.classList.add(lr),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 hv=B("debugloadingbar");function Dc(c){return c.index/c.count+c.progress.loaded/c.progress.total/c.count}var Na=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=Dc(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;hv&&(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=K.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 K.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}};import{DRACOLoader as Lc}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as wp}from"three/examples/jsm/loaders/KTX2Loader.js";var gs=B("debugdecoders"),Qt,wn;function Hc(c){c!==void 0&&typeof c=="string"&&(Qt||(Qt=new Lc),gs&&console.log("Setting draco decoder path to",c),Qt.setDecoderPath(c))}function jc(c){c!==void 0&&typeof c=="string"&&(Qt||(Qt=new Lc),gs&&console.log("Setting draco decoder type to",c),Qt.setDecoderConfig({type:c}))}function Bc(c){c!==void 0&&typeof c=="string"&&(wn||(wn=new wp),gs&&console.log("Setting ktx2 transcoder path to",c),wn.setTranscoderPath(c))}function za(c,e){Qt||(Qt=new Lc,Qt.setDecoderPath("./include/draco/"),Qt.setDecoderConfig({type:"js"}),gs&&console.log("Setting draco decoder path to","./include/draco/")),wn||(wn=new wp,wn.setTranscoderPath("./include/ktx2/"),gs&&console.log("Setting ktx2 transcoder path to","./include/ktx2/"),e.renderer&&wn.detectSupport(e.renderer)),c.setDRACOLoader(Qt),c.setKTX2Loader(wn)}var cr=B("debugwebcomponent"),Fc=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||A.destroySynced(this.previouslyAdded)),this.previouslyAdded=null,t||this.context.connection.send(this.networkEvent,e),this.previousSource=e,Z.Current=this.context;let n=await nt().loadSync(this.context,e,this.getHashFromString(e),!1);i||Ni(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}},pv="needle-engine",fv="vr",mv="desktop",gv=[lr,fv,mv],Nc=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=A;GameObject=A;_context=null;_overlay_ar;_loadingProgress01=0;_watcher;_loadingView;constructor(){super(),this._overlay_ar=new Fa}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 Fc(this.getAttribute("id")??r??"",this._context),i&&i.length>0){if(!n)for(;Object.keys(Ba).length<=0;){if(!this.isConnected)return;await bh(10)}let o=Ba[i]??window[i],s=null;if((!o||n)&&(n&&(i=n),o=async l=>{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 l=this.dispatchEvent(new CustomEvent("loadstart",{detail:{context:this._context,alias:r},cancelable:!0}));!this._loadingView&&l&&(this._loadingView=new Na(this)),l&&this._loadingView?.onLoadingBegin("begin load");let d=(u,h)=>{this._loadingProgress01=Dc(u),l&&this._loadingView?.onLoadingUpdate(u,h),this.dispatchEvent(new CustomEvent("progress",{detail:{context:this._context,name:u.name,progress:u.progress,index:u.index,count:u.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,l&&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',Ba)}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),Hc(i);break;case"dracoDecoderType":i==="wasm"||i==="js"?(cr&&console.log("dracoDecoderType",i),jc(i)):console.error("Invalid dracoDecoderType",i,"expected js or wasm");break;case"ktx2DecoderPath":cr&&console.log("ktx2DecoderPath",i),Bc(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,lr))}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 gv)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),Hc(e));let t=this.getAttribute("dracoDecoderType");t&&(cr&&console.log("using custom draco decoder type",t),jc(t));let i=this.getAttribute("ktx2DecoderPath");i&&(cr&&console.log("using custom ktx2 decoder path",i),Bc(i))}};window.customElements.define(pv,Nc);import{Vector3 as bv}from"three";var O=function(c){if(c===void 0&&(c=null),!Array.isArray(c))c=_p(c);else for(let e=0;e<c.length;e++){let t=c[e];c[e]=_p(t)}return function(e,t){Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});let i=e.$serializedTypes=e.$serializedTypes||{};i[t]=c}};function _p(c){switch(c?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return c}var _n=class extends D{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new bv}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),oe(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(q(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}};k([O(A)],_n.prototype,"from",2),k([O(A)],_n.prototype,"to",2);import*as eo from"three";var xn=class extends D{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&&re.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?eo.LoopRepeat:eo.LoopOnce),e.play();let r=new zc(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 eo.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([O()],xn.prototype,"playAutomatically",2),k([O()],xn.prototype,"randomStartTime",2);var zc=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}};var mi=class{time;value;inTangent;inWeight;outTangent;outWeight;weightedMode};k([O()],mi.prototype,"time",2),k([O()],mi.prototype,"value",2),k([O()],mi.prototype,"inTangent",2),k([O()],mi.prototype,"inWeight",2),k([O()],mi.prototype,"outTangent",2),k([O()],mi.prototype,"outWeight",2),k([O()],mi.prototype,"weightedMode",2);var dr=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 K.lerp(t.value,i.value,(e-t.time)/(i.time-t.time));t=i}return this.keys[this.keys.length-1].value}};k([O(mi)],dr.prototype,"keys",2);import{AnimationClip as vv,MathUtils as yv}from"three";var to=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 xp(c,e){return{name:"",isLooping:!1,guid:e?.generateUUID()??yv.generateUUID(),index:-1,clip:new vv(c,1,[])}}import{AnimationClip as Ev,AnimationMixer as wv,AxesHelper as _v,Euler as Tp,LoopOnce as xv,Quaternion as Yt,Vector3 as bs}from"three";import*as Va from"three";var Tn=B("debuganimatorcontroller"),Uc=B("debugrootmotion"),Jt=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){Tn&&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){Tn&&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 wv(this.animator.gameObject),this.createActions(this.animator)}clone(){let e=Zo(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 Jt(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,Tn&&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()&&(Tn&&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 l of o.conditions)if(!this.evaluateCondition(l)){s=!1;break}if(!!s){Tn&&s&&console.log("All conditions are met",o.conditions,i);for(let l of o.conditions){let d=this.model.parameters.find(a=>a.name===l.parameter);d?.type===9&&(d.value=!1)}if(i){let l=t.motion.clip.duration,d=l<=0?1:i.time/l;if(!o.hasExitTime||d>=o.exitTime&&i.time>=i.getClip().duration){i.clampWhenFinished=!0,Tn&&(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,l=new to(this._activeState,s,o,this._speed);for(let d of t.behaviours)d.instance&&d.instance.onStateUpdate?.call(d.instance,this.animator,l,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,u=new to(this._activeState,a,d,this._speed);for(let h of this._activeState.behaviours)h.instance?.onStateExit?.call(h.instance,this.animator,u,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 l=e.motion?.action;if(l){i=Math.max(0,Math.min(1,i)),l.isRunning()&&l.stop(),l.reset(),l.timeScale=this._speed,l.enabled=!0;let d=e.motion.clip.duration;if(l.time=i*d,l.clampWhenFinished=!0,l.setLoop(xv,0),t>0?l.fadeIn(t):l.setEffectiveWeight(1),l.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(l),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){let a=new to(e,i,d,this._speed);for(let u of this._activeState.behaviours)u.instance?.onStateEnter?.call(u.instance,this.animator,a,n)}}else console.warn("No action",e.motion,this);Tn&&console.log("TRANSITION FROM "+s?.name+" TO "+e.name,t,o,l,l?.getEffectiveTimeScale(),l?.getEffectiveWeight(),l?.isRunning(),l?.isScheduled(),l?.paused)}createAction(e){if(this._mixer.uncacheClip(e),this.animator?.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new Vc(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=xp(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 Ev;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=L.get(o.typeName),l=new s;l.isStateMachineBehaviour&&(l._context=this.context??void 0,Ns(l,o.properties),o.instance=l),Tn&&console.log("Created animator controller behaviour",r.name,o.typeName,o.properties,l)}}}}*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},Ua=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}},xe=class{set action(e){this._action=e}get action(){return this._action}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new bs;rotationChange=new Yt;constructor(e,t,i,n,r){if(this.context=e,this.root=t,this.clip=i,xe.firstKeyframeRotation[i.uuid]||(xe.firstKeyframeRotation[i.uuid]=new Va.Quaternion),r){let o=r.values;xe.firstKeyframeRotation[i.uuid].set(o[0],o[1],o[2],o[3])}xe.spaceRotation[i.uuid]||(xe.spaceRotation[i.uuid]=new Yt),xe.effectiveSpaceRotation[i.uuid]||(xe.effectiveSpaceRotation[i.uuid]=new Yt),xe.clipOffsetRotation[i.uuid]=new Yt,r&&xe.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=xe.lastObjRotation[this.root.uuid];xe.spaceRotation[this.clip.uuid].copy(t);{let i=new Va.Euler().setFromQuaternion(t);console.log("START",this.clip.name,K.toDegrees(i.y))}}getClipRotationOffset(){return xe.clipOffsetRotation[this.clip.uuid]}handlePosition(e,t){if(t){let i=this.root;Uc&&i.add(new _v),xe.lastObjPosition[i.uuid]||(xe.lastObjPosition[i.uuid]=new bs);let n=new bs,r=new bs,o=0;this.positionWrapper=new Ua(t,(s,l)=>{let d=this.action.getEffectiveWeight();if(Uc&&i.position.length()>8&&i.position.set(0,i.position.y,0),s>o){n.set(l[0],l[1],l[2]),n.sub(r),n.multiplyScalar(d),n.applyQuaternion(this.getClipRotationOffset());let a=this.clip.uuid;n.applyQuaternion(xe.spaceRotation[a]),this.positionChange.copy(n)}return r.fromArray(l),o=s,l[0]=0,l[1]=0,l[2]=0,l})}}handleRotation(e,t){if(t){if(Uc){let s=t.values,l=new Tp().setFromQuaternion(new Yt(s[0],s[1],s[2],s[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",K.toDegrees(l.y));let d=t.values.length-4,a=new Yt().set(s[d],s[d+1],s[d+2],s[d+3]),u=new Tp().setFromQuaternion(a);console.log(e.name,t.name,"LAST ROTATION IN TRACK",K.toDegrees(u.y))}let i=this.root;xe.lastObjRotation[i.uuid]||(xe.lastObjRotation[i.uuid]=new Yt);let n=0,r=new Yt,o=new Yt;this.rotationWrapper=new Ua(t,(s,l)=>(s>n&&(o.set(l[0],l[1],l[2],l[3]),r.invert(),o.multiply(r),this.rotationChange.copy(o)),r.fromArray(l),n=s,l[0]=0,l[1]=0,l[2]=0,l[3]=1,l))}}onBeforeUpdate(){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(){let e=this.action.getEffectiveWeight();this.positionChange.multiplyScalar(e),this.rotationChange.slerp(xe.identityQuaternion,1-e)}},Kt=xe;z(Kt,"lastObjPosition",{}),z(Kt,"lastObjRotation",{}),z(Kt,"firstKeyframeRotation",{}),z(Kt,"spaceRotation",{}),z(Kt,"effectiveSpaceRotation",{}),z(Kt,"clipOffsetRotation",{}),z(Kt,"identityQuaternion",new Yt);var Vc=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 Kt(this.controller.context,t,i,r,o);this.handler.push(s);let l=e.clipAction(i);return s.action=l,l}onStart(e){for(let t of this.handler)t.onStart(e)}onBeforeUpdate(){for(let e of this.handler)e.onBeforeUpdate()}summedPosition=new bs;summedRotation=new Yt;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),Kt.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 Tv=B("debuganimator"),At=class extends D{applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof Jt?this._animatorController=e:this._animatorController=new Jt(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=K.lerp(e.x,e.y,Math.random())}set minMaxOffsetNormalized(e){this.normalizedStartOffset=K.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}Tv&&console.log("ANIMATOR",this.name,this)}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.Reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}};k([O()],At.prototype,"applyRootMotion",2),k([O()],At.prototype,"hasRootMotion",2),k([O()],At.prototype,"keepAnimatorControllerStateOnDisable",2),k([O()],At.prototype,"runtimeAnimatorController",1);import*as Rp from"three";import*as vs from"three";import{PositionalAudioHelper as Cv}from"three/examples/jsm/helpers/PositionalAudioHelper.js";var rt=B("debugaudio");var Me=class extends D{static get userInteractionRegistered(){return Me._didCallBeginWaitForUserInteraction||(Me._didCallBeginWaitForUserInteraction=!0,Me._beginWaitForUserInteraction()),Me._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),Me._didCallBeginWaitForUserInteraction||(Me._didCallBeginWaitForUserInteraction=!0,Me._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);let i=(()=>{if(i!=null&&!Me._userInteractionRegistered){Me._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&&(rt&&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&&Me._userInteractionRegistered){let e=A.getComponent(this.context.mainCamera,Zt)??A.findObjectOfType(Zt,this.context);e?.listener&&(this.sound=new vs.PositionalAudio(e.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}_focusCallback;awake(){this.audioLoader=new vs.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&&Me._userInteractionRegistered&&this.play()},this.context.application.addEventListener("application-visible",this._focusCallback)}onDestroy(){this.context.application.removeEventListener("application-visible",this._focusCallback)}onEnable(){Me._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Me._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){rt&&console.log("audio buffer loaded"),Me.registerWaitForAllowAudio(()=>{rt&&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(),rt&&console.log(this.name,this.shouldPlay,Me.userInteractionRegistered,this),this.shouldPlay&&Me._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(rt&&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?rt&&!this.helper&&(this.helper=new Cv(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&(rt&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new vs.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){rt&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,rt&&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,rt&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying&&this.sound.play()}pause(){rt&&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(){rt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&(this._lastContextTime=this.sound?.context.currentTime,rt&&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,rt&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},ce=Me;z(ce,"_didCallBeginWaitForUserInteraction",!1),z(ce,"callbacks",[]),z(ce,"_userInteractionRegistered",!1),k([O()],ce.prototype,"clip",2),k([O()],ce.prototype,"playOnAwake",2),k([O()],ce.prototype,"loop",1),k([O()],ce.prototype,"spatialBlend",1),k([O()],ce.prototype,"minDistance",1),k([O()],ce.prototype,"maxDistance",1),k([O()],ce.prototype,"volume",1),k([O()],ce.prototype,"rollOffMode",2);import*as zi from"three";import{Color as Rv}from"three";var ye=class extends Rv{alpha=1;get isRGBAColor(){return!0}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=K.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 Pv}from"three";var Cp=B("debugcam"),he=class extends D{get aspect(){return this._cam instanceof Pv?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 zi.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){e!==this._clearFlags&&(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(){Cp&&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 zi.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),t.fov=this.fieldOfView;else{let i=this.orthographicSize*100;t=new zi.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.environmentIsTransparent()&&(!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.environmentIsTransparent()&&(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}}environmentIsTransparent(){let e=this.context.renderer.xr?.getSession();if(!e)return!1;let t=e.environmentBlendMode,i=t==="additive"||t==="alpha-blend";return t==="opaque"&&navigator.userAgent?.includes("OculusBrowser")&&this.context.xrSessionMode==="immersive-ar"?!0:i}enableSkybox(){this._skybox||(this._skybox=new Gc(this)),this._skybox.enable()}};k([O()],he.prototype,"fieldOfView",1),k([O()],he.prototype,"nearClipPlane",1),k([O()],he.prototype,"farClipPlane",1),k([O()],he.prototype,"clearFlags",1),k([O()],he.prototype,"orthographic",2),k([O()],he.prototype,"orthographicSize",2),k([O()],he.prototype,"ARBackgroundAlpha",2),k([O(ye)],he.prototype,"backgroundColor",1);var Gc=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?(Cp&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=zi.sRGBEncoding,this._skybox.mapping=zi.EquirectangularReflectionMapping,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this)}};var Zt=class extends D{get listener(){return this._listener==null&&(this._listener=new Rp.AudioListener),this._listener}_listener=null;awake(){ce.registerWaitForAllowAudio(()=>{let e=this.listener;if(e==null||e.parent)return;let t=A.getComponentInParent(this.gameObject,he);t?t.cam.add(e):this.gameObject.add(e)})}};import{GLTFLoader as Ov}from"three/examples/jsm/loaders/GLTFLoader";import*as Ga from"three";var ys=B("debugavatar"),hr=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))}},Cn=class{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){let r=new Be;i=A.instantiate(Qn(t,e.scene),r)}}else i=t;if(!i)return null;let n=this.findAvatar(i);return n.isValid?(ys&&console.log("[Custom Avatar] valid config",t,ys?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,ys?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(ys&&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 Pa(t,t,0,"no url here go away",!0),!r)?null:(await nt().parseSync(e,r,null,0))?.scene??null}let i=new Ov;return za(i,e),new Promise((n,r)=>{let o=this.avatarRegistryUrl+"/"+t;i.load(o,async s=>{await nt().createBuiltinComponents(e,o,s,null,void 0),n(s.scene)},s=>{ys&&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","hand"]),o=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;let l=new Ga.Vector3;new Ga.Box3().setFromObject(n).getSize(l);let d=Math.max(l.x,l.y,l.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 hr(t,n,r,o)}findAvatarPart(e,t){let i=e.name.toLowerCase(),n=!0;for(let r of t){if(!n)break;i.indexOf(r)===-1&&(n=!1)}if(n)return e;if(e.children)for(let r of e.children){let o=this.findAvatarPart(r,t);if(o)return o}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}};import{AxesHelper as kv}from"three";var Ui=class extends D{length=1;depthTest=!0;isGizmo=!0;_axes=null;onEnable(){if(this.isGizmo&&!si)return;this._axes||(this._axes=new kv(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([O()],Ui.prototype,"length",2),k([O()],Ui.prototype,"depthTest",2),k([O()],Ui.prototype,"isGizmo",2);import*as Sp from"three";var io=class extends D{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 Sp.Vector3;s.crossVectors(o,n),s.crossVectors(n,s),s.normalize();let l=i*.5,d=Math.max(this.desiredDistance,l),a=Math.sqrt(d*d-l*l),u=s.clone();u.multiplyScalar(a),u.add(r),oe(this.gameObject,u);let h=r.clone();h.sub(s),this.gameObject.lookAt(h)}};import*as Vi from"three";import*as gi from"three";var Av=new gi.BoxGeometry(1,1,1);function Wa(c=null){let e=new gi.Color(c??14540253),t=new gi.EdgesGeometry(Av);return new gi.LineSegments(t,new gi.LineBasicMaterial({color:e}))}var Mv=B("gizmos"),qa=class extends D{box=null;testBox=new Vi.Box3;_lastMatrixUpdateFrame=-1;isInBox(e){if(!!e){if(this.box||(this.box=new Vi.Box3),this.updateBox(!1),e.type==="Mesh")this.testBox.setFromObject(e);else{let t=q(e,qa._position),i=na(e,qa._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 Vi.Box3),(e||this.context.time.frameCount!=this._lastMatrixUpdateFrame)&&(this._lastMatrixUpdateFrame=this.context.time.frameCount,this.box.setFromCenterAndSize(new Vi.Vector3(0,0,0),new Vi.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(!(!Mv&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=Wa(e),this.gameObject.add(this._helper)}}},ot=qa;z(ot,"_position",new Vi.Vector3),z(ot,"_size",new Vi.Vector3(.01,.01,.01));import*as ur from"three";import{Vector3 as Pp}from"three";var Rn=class extends D{mass=1;set isKinematic(e){this._isKinematic=e,this._body&&(this._body.type=e?U.KINEMATIC:U.DYNAMIC)}get isKinematic(){return this._isKinematic}_isKinematic=!1;drag=0;angularDrag=1;detectCollisions=!0;sleepThreshold=.01;get body(){return this._body===null&&this.initialize(),this._body}_body=null;currentVelocity;_smoothedVelocity;lastWorldPosition;_ignoreChange=!1;_dirty=!1;_positionWatch;_matrixWatch;_setMatrix;constructor(){super(),this._setMatrix=new ur.Matrix4}awake(){this._body=null,this.currentVelocity=new ur.Vector3,this._smoothedVelocity=new ur.Vector3,this.lastWorldPosition=q(this.gameObject).clone(),this._matrixWatch=void 0,this._positionWatch=void 0}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._positionWatch||(this._positionWatch=new hn(this.gameObject.position,["x","y","z"])),this._positionWatch.subscribeWrite(e=>{!this.context.physics.isUpdating&&!this._ignoreChange&&(this._dirty=!0,this._setMatrix.copy(this.gameObject.matrix),this._setMatrix.setPosition(this.gameObject.position))})}onDisable(){this._body&&this.context.physics.removeBody(this.gameObject,this._body,!1)}onDestroy(){this._body&&this.context.physics.removeBody(this.gameObject,this._body)}onBeforeRender(){this._ignoreChange=!0,this.updateVelocity(),this._dirty&&(this._dirty=!1,this._setMatrix.decompose(this.gameObject.position,this.gameObject.quaternion,this.gameObject.scale),this.setBodyFromGameObject()),this._ignoreChange=!1}initialize(){if(this._body)return;let e=new ba;e.drag=this.drag,e.angularDrag=this.angularDrag,e.mass=this.mass,e.kinematic=this.isKinematic,e.physicsEvents=this.detectCollisions,e.sleepThreshold=this.sleepThreshold,this._body=this.context.physics.createBody(this.gameObject,e)}wakeUp(){this.body?.wakeUp()}applyForce(e,t){let i=new _(e.x,e.y,e.z);i.scale(1/this.context.time.deltaTime,i),this.body?.applyForce(i,t?new _(t.x,t.y,t.z):void 0)}setForce(e,t,i){this.body?.force.set(e,t,i)}getVelocity(){return this.body?Rn.tempPosition.set(this.body?.velocity.x,this.body?.velocity.y,this.body?.velocity.z):Rn.tempPosition.set(0,0,0)}setVelocity(e,t,i){if(!!this.body){if(e instanceof Pp){let n=e;e=n.x,t=n.y,i=n.z}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}}getTorque(){return this.body?Rn.tempPosition.set(this.body?.torque.x,this.body?.torque.y,this.body?.torque.z):Rn.tempPosition.set(0,0,0)}setTorque(e,t,i){if(!!this.body){if(e instanceof Pp){let n=e;e=n.x,t=n.y,i=n.z}this.body.torque.x=e/this.context.time.deltaTime,this.body.torque.y=t/this.context.time.deltaTime,this.body.torque.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.body&&this.gameObject&&!this.destroyed){this._ignoreChange=!0;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){Rn.copyVector3.set(e.x,e.y,e.z),this._smoothedVelocity.lerp(Rn.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}this._ignoreChange=!1}}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)}}},se=Rn;z(se,"tempPosition",new ur.Vector3),z(se,"copyVector3",new ur.Vector3),k([O()],se.prototype,"mass",2),k([O()],se.prototype,"isKinematic",1),k([O()],se.prototype,"drag",2),k([O()],se.prototype,"angularDrag",2),k([O()],se.prototype,"detectCollisions",2),k([O()],se.prototype,"sleepThreshold",2);import{Vector3 as no}from"three";var bi=class extends D{attachedRigidbody=null;isTrigger=!1;_shape=null;awake(){super.awake(),this._shape=null}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(se))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(se))}onDisable(){this._shape}};k([O(se)],bi.prototype,"attachedRigidbody",2),k([O()],bi.prototype,"isTrigger",2);var Sn=class extends bi{radius=.5;center=new no(0,0,0);onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addSphereCollider(this.gameObject,this.center,this.radius,this.attachedRigidbody))}};k([O()],Sn.prototype,"radius",2),k([O(no)],Sn.prototype,"center",2);var Pn=class extends bi{size=new no(1,1,1);center=new no(0,0,0);onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addBoxCollider(this.gameObject,this.isTrigger,this.center,this.size,this.attachedRigidbody))}};k([O(no)],Pn.prototype,"size",2),k([O(no)],Pn.prototype,"center",2);var It=class extends D{canGrab=!0;onPointerClick(e){}},Mt=class extends D{isUsed=!0;usedBy=null};var pr=class extends ot{},ro=class extends D{deleteBoxes=[];awake(){this.deleteBoxes=A.findObjectsOfType(pr,this.context)}update(){for(let e of this.deleteBoxes){let t=this.gameObject;e.isInBox(t)===!0&&(A.getComponentInParent(this.gameObject,Mt)||qr(this.gameObject,this.context.connection))}}};var fr=class extends D{visibleOn;onEnable(){this.apply()}apply(){this.test()||A.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:Dv()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}};k([O()],fr.prototype,"visibleOn",2);var Xa;function Dv(){if(Xa===!0||Xa===!1)return Xa;let c=!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)))&&(c=!0)}(navigator.userAgent||navigator.vendor||window.opera),Xa=c,c}import*as Gi from"three";var Te=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 oo=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Te).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Te).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Te).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,n,r,o,s,l,d,a){return e.prep(4,36),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(d),e.writeFloat32(l),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 Dt=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 Dt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+4),(t||new Dt).__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 oo).__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 On=B("debugsync"),so="STRS";$r(so,Dt.getRootAsSyncedTransformModel);var vi=new ut;function Wc(c,e,t=!0){vi.clear();let i=vi.createString(c);Dt.startSyncedTransformModel(vi),Dt.addGuid(vi,i),Dt.addFast(vi,t);let n=e.worldPosition,r=e.worldEuler,o=e.gameObject.scale;Dt.addTransform(vi,oo.createTransform(vi,n.x,n.y,n.z,r.x,r.y,r.z,o.x,o.y,o.z));let s=Dt.endSyncedTransformModel(vi);return vi.finish(s,so),vi.asUint8Array()}var ft=class extends D{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(){On&&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(){On&&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=A.getComponentInChildren(this.gameObject,se),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new yn(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(so,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Au(this.guid,this.context.connection),this._model=null,this.context.connection.stopListening("joined-room",this.joinedRoomCallback),this.context.connection.stopListenBinary(so,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){On&&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){re.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)&&Eu(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){On&&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:(On&&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),re.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 l=this.worldPosition;l.lerp(this._targetPosition,o),this.worldPosition=l,s=!0}if(this.interpolateRotation&&this._targetRotation){let l=this.worldQuaternion;l.slerp(this._targetRotation,o),this.worldQuaternion=l,s=!0}s&&re.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&&(On&&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&&(On&&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)){On&&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=Wc(this.guid,this,!!n);this.context.connection.sendBinary(r)}}};import*as ee from"three";var Qa=class{static createButton(e,t={}){let i=document.createElement("button");function n(){if(t.domOverlay===void 0){var l=document.createElement("div");l.style.display="none",document.body.appendChild(l);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(){u.end()}),l.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:l}}t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("local-floor"),t.optionalFeatures.push("hand-tracking"),t.optionalFeatures.push("layers");let u=null;async function h(E){E.addEventListener("end",m),await e.xr.setSession(E),i.textContent="STOP AR",t.domOverlay.root.style.display="",u=E}function m(){u.removeEventListener("end",m),i.textContent="START AR",t.domOverlay.root.style.display="none",u=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(){u===null?navigator.xr.requestSession("immersive-ar",t).then(h):u.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(l){l.style.position="absolute",l.style.bottom="20px",l.style.padding="12px 6px",l.style.border="1px solid #fff",l.style.borderRadius="4px",l.style.background="rgba(0,0,0,0.1)",l.style.color="#fff",l.style.font="normal 13px sans-serif",l.style.textAlign="center",l.style.opacity="0.5",l.style.outline="none",l.style.zIndex="999"}if("xr"in navigator)return i.id="ARButton",i.style.display="none",s(i),navigator.xr.isSessionSupported("immersive-ar").then(function(l){l?n():o()}).catch(o),i;{let l=document.createElement("a");return window.isSecureContext===!1?(l.href=document.location.href.replace(/^http:/,"https:"),l.innerHTML="WEBXR NEEDS HTTPS"):(l.href="https://immersiveweb.dev/",l.innerHTML="WEBXR NOT AVAILABLE"),l.style.left="calc(50% - 90px)",l.style.width="180px",l.style.textDecoration="none",s(l),l}}};var Ya=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 l=null;async function d(u){u.addEventListener("end",a),await e.xr.setSession(u),i.textContent="EXIT VR",l=u}function a(){l.removeEventListener("end",a),i.textContent="ENTER VR",l=null}i.style.display="",i.style.cursor="pointer",i.style.left="calc(50% - 50px)",i.style.width="100px",i.textContent="ENTER VR",i.onmouseenter=function(){i.style.opacity="1.0"},i.onmouseleave=function(){i.style.opacity="0.5"},i.onclick=function(){if(l===null){let u={optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};navigator.xr.requestSession("immersive-vr",u).then(d)}else l.end()}}function r(){i.disabled=!0,i.style.display="",i.style.cursor="auto",i.style.left="calc(50% - 75px)",i.style.width="150px",i.onmouseenter=null,i.onmouseleave=null,i.onclick=null}function o(){r(),i.textContent="VR NOT SUPPORTED"}function s(l){l.style.position="absolute",l.style.bottom="20px",l.style.padding="12px 6px",l.style.border="1px solid #fff",l.style.borderRadius="4px",l.style.background="rgba(0,0,0,0.1)",l.style.color="#fff",l.style.font="normal 13px sans-serif",l.style.textAlign="center",l.style.opacity="0.5",l.style.outline="none",l.style.zIndex="999"}if("xr"in navigator)return i.id="VRButton",i.style.display="none",s(i),navigator.xr.isSessionSupported("immersive-vr").then(function(l){l?n():o(),Ya.xrSessionIsGranted&&(console.log("XR session is granted - will enter immersive web now"),i.click())}),i;{let l=document.createElement("a");return window.isSecureContext===!1?(l.href=document.location.href.replace(/^http:/,"https:"),l.innerHTML="WEBXR NEEDS HTTPS"):(l.href="https://immersiveweb.dev/",l.innerHTML="WEBXR NOT AVAILABLE"),l.style.left="calc(50% - 90px)",l.style.width="180px",l.style.textDecoration="none",s(l),l}}static registerSessionGrantedListener(){if("xr"in navigator)try{navigator.xr.addEventListener("sessiongranted",()=>{console.log("Received session granted event"),Ya.xrSessionIsGranted=!0})}catch(e){console.error(e)}}},lo=Ya;z(lo,"xrSessionIsGranted",!1);lo.registerSessionGrantedListener();import*as ve from"three";import{Matrix4 as Xv,Vector3 as Qv}from"three";import*as Ka from"three";var Op=Ls(xa(),1);import{AudioAnalyser as Lv}from"three";var co="noVoip",st=B("debugvoip"),Hv=B("voip");var qc=class{id;constructor(e){this.id=e}};var Xc=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(){st&&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 Je.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}st&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),st&&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=>{st&&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){st&&console.log("call closed",e)}},Qc=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,ce.userInteractionRegistered||st&&console.log("Incoming call, waiting for user interaction before opening audio"),ce.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){st&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);let t=new Ka.AudioListener;this.audio=new Ka.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}}}),st&&console.log("call is setup, you should hear something now"),this.analyzer=new Lv(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()}},Je=class extends D{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(B(co)){console.log("VOIP is disabled by url parameter: "+co);return}if(this.requireParam&&!Hv){console.debug("VOIP must be enabled explicitly by url parameter");return}this.peer=new Op.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 Xc(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];st&&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){st&&console.log("Peer connection established and received id"),this.model=new qc(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){st&&console.log("CONNECTION",t),t.on("data",function(i){st&&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(),st&&console.log("received call"),await Je.HasMicrophonePermissions()){let o=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(o)}else e.answer(null);this.currentIncomingCalls[i]=new Qc(this,this.gameObject,e),e.on("stream",o=>{st&&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 ho=B("debugflags");var Yc=class{Mask=17;Has(e){let t=this.Mask&e;return ho&&console.log("HAS",e,this.Mask,"Result="+t),t!==0}Set(e){this.Mask=e,Ce.Apply()}Enable(e){this.Mask|=e,Ce.Apply()}Disable(e){this.Mask&=~e,Ce.Apply()}Toggle(e){this.Mask^=e,Ce.Apply()}EnableAll(){this.Mask=-1,Ce.Apply()}DisableAll(){this.Mask=0,Ce.Apply()}},mt=Yc;z(mt,"Global",new Yc);var yi=class extends D{static Apply(){for(let e of this.registry)e.UpdateVisible(mt.Global)}awake(){yi.registry.push(this)}onEnable(){yi.firstApply||(yi.firstApply=!0,yi.Apply())}onDestroy(){let e=yi.registry.indexOf(this);e>=0&&yi.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),ho&&console.log(i),yi.buffer.Mask=i,e=yi.buffer);let n=e;if(n?(ho&&console.log("use passed in mask"),t=n.Has(this.visibleIn)):(ho&&console.log("use global mask"),mt.Global.Has(this.visibleIn)),t!==void 0)if(t)ho&&console.trace("is visible",this.name,this.gameObject.uuid),A.setActive(this.gameObject,!0);else{if(ho&&console.trace("is not visible",this.name,this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},Ce=yi;z(Ce,"registry",[]),z(Ce,"firstApply"),z(Ce,"buffer",new mt);import*as $ from"three";import{XRControllerModelFactory as Vv}from"three/examples/jsm/webxr/XRControllerModelFactory.js";import{OculusHandModel as Gv}from"three/examples/jsm/webxr/OculusHandModel.js";import{OculusHandPointerModel as Wv}from"three/examples/jsm/webxr/OculusHandPointerModel.js";import*as Ip from"three";import*as ei from"three";var kn=B("debugavatar"),$t=class extends D{static getAvatar(e){return e>=0&&e<$t.instances.length?$t.instances[e]:null}static onAvatarMarkerCreated(e){return $t._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return $t._onAvatarMarkerDestroyed.push(e),e}connectionId;avatar;awake(){$t.instances.push(this),kn&&console.log(this);for(let e of $t._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){$t.instances.splice($t.instances.indexOf(this),1);for(let e of $t._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):A.setActive(this.avatar,e))}},ue=$t;z(ue,"instances",[]),z(ue,"_onNewAvatarMarkerAdded",[]),z(ue,"_onAvatarMarkerDestroyed",[]);var Es=class{_isVisible=!0;setVisible(e){this._isVisible=e,this.updateVisibility()}get isWebXRAvatar(){return!0}guid;root=null;head=null;handLeft=null;handRight=null;lastUpdate=-1;isLocalAvatar=!1;flags=null;headScale=new ei.Vector3(1,1,1);handLeftScale=new ei.Vector3(1,1,1);handRightScale=new ei.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 ei.Object3D;_handLeftTarget=new ei.Object3D;_handRightTarget=new ei.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)){let i=this.webxr.IsInAR?"handheld":"headset",n=this.head;this.context.players.setPlayerView(e.guid,n,i),re.markDirty(this.head),this._canInterpolate=!0;let r=this.isLocalAvatar?this.head:this._headTarget;if(r.position.set(e.position.x,e.position.y,e.position.z),r.quaternion.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),r.scale.set(e.scale,e.scale,e.scale),r.scale.multiply(this.headScale),this.handLeft){let o=this.isLocalAvatar?this.handLeft:this._handLeftTarget;o.position.set(e.posLeftHand.x,e.posLeftHand.y,e.posLeftHand.z),o.quaternion.set(e.rotLeftHand._x,e.rotLeftHand._y,e.rotLeftHand._z,e.rotLeftHand._w),o.quaternion.multiply(Es.invertRotation),o.scale.set(e.scale,e.scale,e.scale),o.scale.multiply(this.handLeftScale),re.markDirty(this.handLeft)}if(this.handRight){let o=this.isLocalAvatar?this.handRight:this._handRightTarget;o.position.set(e.posRightHand.x,e.posRightHand.y,e.posRightHand.z),o.quaternion.set(e.rotRightHand._x,e.rotRightHand._y,e.rotRightHand._z,e.rotRightHand._w),o.quaternion.multiply(Es.invertRotation),o.scale.set(e.scale,e.scale,e.scale),o.scale.multiply(this.handRightScale),re.markDirty(this.handRight)}}}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(){kn&&console.log("Destroy avatar",this.guid),this.root?.removeFromParent(),this.avatarMarker?.destroy(),this.lastAvatarId=null,this.head&&Ee.Remove(this.context,this.head)}updateVisibility(){let e=this.root;e&&A.setActive(e,this._isVisible)}async setupCustomAvatar(e){if(kn&&console.log("LOAD",e,this),!e||typeof e=="string"&&e.length<=0)return!1;this.head&&Ee.Remove(this.context,this.head);let t=e;if(t?.loadAssetAsync!==void 0){await t.loadAssetAsync();let n=t.asset;A.setActive(n,!1),e=A.instantiate(n),A.setActive(e,!0)}kn&&console.log(e);let i=await Es.loader.getOrCreateNewAvatarInstance(this.context,e);if(kn&&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=A.addNewComponent(this.root,ue),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&&Ee.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(...A.getComponentsInChildren(this.root,Ce)),this.flags.length<=0&&this.head){let n=A.addNewComponent(this.head,Ce);n.visibleIn=20,this.flags.push(n),kn&&console.log("Added flag to head: "+n.visibleIn,this.head.name)}return kn&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return kn&&console.warn("build avatar failed"),!1}},Lt=Es;z(Lt,"loader",new Cn),z(Lt,"invertRotation",new ei.Quaternion().setFromAxisAngle(new ei.Vector3(0,1,0),Math.PI));var Ee=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(Ee,"Pois",[]),z(Ee,"LastChangeTime",0);var Kc=class{guid;position=new Ip.Vector3},Wi=class extends D{set controlledTarget(e){this.target=e;let t=L.get("MoveRandom");if(t&&this.target){let i=A.getComponent(this.target,t);i&&i.destroy()}}target=null;avatar=null;_model=null;_targetModel=new Kc;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=A.getComponentInParent(this.gameObject,ue),this.avatar){let e=A.getComponentInParent(this.gameObject,ue);this._model=new yn(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&&oe(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(Ee.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Ee.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){let t=q(this._currentTargetObject);oe(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=Ee.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}}}}};import*as Ja from"three-mesh-ui";import{OrbitControls as Bv}from"three/examples/jsm/controls/OrbitControls";import{Object3D as jv}from"three";var qi=class extends D{constraintActive=!0;locked=!1;sources=[]};k([O(jv)],qi.prototype,"sources",2);import*as ws from"three";var gt=class extends D{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;_startedListeningToKeyEvents=!1;awake(){this._lookTargetPosition=new ws.Vector3,this._startedListeningToKeyEvents=!1}onEnable(){this._enableTime=this.context.time.time;let t=A.getComponent(this.gameObject,he)?.cam;this._controls||(console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t),this._controls=new Bv(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,this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body)))}onDisable(){this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1)}onDestroy(){this._controls?.dispose()}start(){if(this._controls){let e=A.getComponent(this.gameObject,he);if(e&&!this.setFromTargetPosition()){this.debugLog&&console.log("NO TARGET");let t=new ws.Vector3(0,0,-1).applyMatrix4(e.cam.matrixWorld);this.setTarget(t,!0)}}this.startCoroutine(this.startRaycastDelayed())}*startRaycastDelayed(){if(yield,!this.setFromTargetPosition()){let e=new _e;e.screenPoint=new ws.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&&A.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([O(qi)],gt.prototype,"lookAtConstraint",2);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 Nv}from"three";var zv=B("debugeventsystem"),Ei=class extends D{static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Ei.systems.length<=0&&Ei.systems.push(...A.findObjectsOfType(Ei,e)));for(let i of Ei.systems)if(i.context===e)return;let t=new Nv;A.addNewComponent(t,Ei),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(),Ei.systems.push(this)}onDestroy(){Ei.systems.splice(Ei.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)}_selectStartFn;_selectEndFn;_selectUpdateFn;onEnable(){this._selectStartFn??=(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)},this._selectEndFn??=(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)};let e=new _e;this._selectUpdateFn??=t=>{e.ray=t.getRay();let i=this.performRaycast(e);if(!i)return;let n=new ti;n.inputSource=t,this.handleIntersections(i,n)},ie.addEventListener("select-start",this._selectStartFn),ie.addEventListener("select-end",this._selectEndFn),ie.addEventListener("update",this._selectUpdateFn),this.context.pre_update_callbacks.push(this.onBeforeUpdate.bind(this)),this.context.input.addEventListener("pointerdown",this.onPointerDown.bind(this))}onDisable(){ie.removeEventListener("select-start",this._selectStartFn),ie.removeEventListener("select-end",this._selectEndFn),ie.removeEventListener("update",this._selectUpdateFn)}onPointerDown(){this.onBeforeUpdate()}lastPointerEvent=null;objectsHoveredThisFrame=[];objectsHoveredLastFrame=[];raisedPointerDownEvents=[];_didMove=!1;onBeforeUpdate(){if(this.objectsHoveredThisFrame.length=0,this.resetMeshUIStates(),Q.IsInWebXR||this.context.input.isKeyPressed("Alt"))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=A.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=A.getComponentsInParent(t,D,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=[];out={};handleEvents(e,t){if(!this.testIsVisible(e))return t.isClicked&&zv&&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[bt]){let l=i[bt].gameObject;if(l){if(!ni.isInteractable(l,this.out))return this.out.canvasGroup?.interactable??!1;o=this.out.canvasGroup??null;let a=this.handleMeshUIIntersection(e,s);e=l,n=!0}}if(!n&&this.handleMeshUiObjectWithoutShadowDom(i,s))return!0}if(r&&console.log(this.context.time.frame,e),this.objectsHoveredThisFrame.push(e),o===null||o.interactable){let s=this.objectsHoveredLastFrame.indexOf(e)>=0;this.handleEventsArray.length=0;let l=A.getComponentsInParent(e,D,this.handleEventsArray);for(let d=0;d<l.length;d++){if(t.used)return!0;if(l[d].destroyed)continue;let a=l[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=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?A.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}},Ve=Ei;z(Ve,"didSearchEventSystem",!1),z(Ve,"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 Uv}from"three";var uo="./include";Ja.Block.prototype.interactable={get(){return this.interactive},set(c){this.interactable=c}};var bt=Symbol("shadowDomOwner"),Fe=class extends D{isRoot(){return this.Root?.gameObject===this.gameObject}markDirty(){Ve.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=A.getComponentInParent(this.gameObject,Xi)),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=A.getComponentInParent(i,Fe),!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[bt]=this,e.traverse(r=>{r[bt]===void 0&&(r[bt]=this)});let n=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{let r=this._parentComponent.shadowComponent;r&&(r?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),si&&e.add(new Uv(.5)),this.onAfterAddedToScene(),n&&Ja.update()}set(e){}traverseOwnedShadowComponents(e,t,i){if(!!e&&e[bt]===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)}},Xi=class extends Fe{awake(){super.awake()}};var ni=class{static getObject(e){let t=e[bt];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;let i=this.tryFindCanvasGroup(e);if(i?.isCanvasGroup===!0&&(t&&(t.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;let n=Pt(e,r=>{if(r.isGraphic===!0)return r},!1);return t&&n?.isGraphic===!0&&(t.graphic=n),n?.raycastTarget===!1?!1:(console.log(n),!0)}static tryFindCanvasGroup(e){if(!e)return null;let t=Pt(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)}};var Zc=B("debugwebxrcontroller");var mr=class extends D{},De=class extends D{static CreateRaycastLine(){let e=new $.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 $.SphereGeometry(.5,22,22),t=new $.MeshBasicMaterial({color:this.raycastColor}),i=new $.Mesh(e,t);return i.visible=!1,i.layers.set(1),i}static Create(e,t,i,n){let r=i?A.addNewComponent(i,De,!1):new De;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 Gv(r.hand)),r.hand.traverse(s=>s.layers.set(2)),r.handPointerModel=new Wv(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 u=d[a];u.parent||r.hand.add(u)}}}),r}static addEventListener(e,t){let i=this.eventSubs[e]??[];i.push(t),this.eventSubs[e]=i}static removeEventListener(e,t){if(!t)return;let i=this.eventSubs[e]??[],n=i.indexOf(t);n>=0&&i.splice(n,1),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 $.Quaternion),Pe(e).multiply(this._wristQuaternion.setFromEuler(new $.Euler(-Math.PI/4,0,0)))):null}movementVector=new $.Vector3;worldRot=new $.Quaternion;joystick=new $.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=De.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=De.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._raycastHitPoint.visible=!1,this.hand.add(this.handPointerModel),Zc&&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 $.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=De.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(Pe(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,oe(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)}Xe(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=!0,Xe(this.raycastLine,this.rayRotation),oe(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*De.MovementSpeedFactor,r=2,o=K.clamp01(this.joystick.length()*2),s=this.joystick.x>0?1:-1,l=Math.pow(this.joystick.x,r);l*=s,l*=o;let d=this.joystick.y>0?1:-1,a=Math.pow(this.joystick.y,r);a*=d,l*=o,t.getWorldQuaternion(this.worldRot),this.movementVector.set(l,0,a),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),this.movementVector.multiplyScalar(n*this.context.time.deltaTime),t.position.add(this.movementVector),this.isUsingHands&&this.runTeleport(t,i);break;case"right":let u=this.joystick.x,h=Math.abs(u);if(h<.4)this.didRotate=!1;else if(h>.5&&!this.didRotate){let m=u>0?-1:1;t.rotateY(K.toRadians(30*m)),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&&this.webXR.IsInVR,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 l=t[s];if(s===4)if(l.pressed&&!this.didChangeScale&&this.webXR.IsInVR){this.didChangeScale=!0;let d=this.webXR.Rig;if(d)if(r){r=!1,d.scale.set(1,1,1),o=1,De.MovementSpeedFactor=1;let a=this.context.mainCamera;De.PreviousCameraFarDistance&&(a.far=De.PreviousCameraFarDistance)}else{r=!0,n=!0,o=.1,De.MovementSpeedFactor=o*2;let a=this.context.mainCamera;De.PreviousCameraFarDistance=a.far,a.far/=o}}else l.pressed||(this.didChangeScale=!1)}if(n){if(!this.didTeleport){let s=this.raycast();if(this.didTeleport=!0,s&&s.length>0){let l=s[0];if(r||this.isValidTeleportTarget(l.object)){let d=l.point;oe(e,d)}}}}else i<.1&&(this.didTeleport=!1);o!==null&&(e.scale.set(o,o,o),e.updateMatrixWorld())}isValidTeleportTarget(e){return A.getComponentInParent(e,mr)!=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=De.raycastColor:n.color=De.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;let n=K.clamp(this.lastHit.distance*.01*i,.015,.1);this._raycastHitPoint.scale.set(n,n,n)}this._raycastHitPoint.visible=this.lastHit!==null&&this.lastHit!==void 0}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;this.lastSelectStartObject=n;let r={selected:n,grab:n},o=De.eventSubs["select-start"];if(o&&o.length>0)for(let s of o)s(this,r);r.grab!==n&&Zc&&console.log("Grabbed object changed","original",n,"new",r.grab),r.grab&&(this.grabbed=at.TryTake(this,r.grab,i,t));break}else{let i=De.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=De.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||A.isActiveInHierarchy(e)===!1||ni.isInteractable(e)===!1)}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 $.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 _e;e.layerMask=new $.Layers,e.layerMask.set(0),e.ray=this.getRay();let t=this.context.physics.raycast(e);for(let i=0;i<t.length;i++){let n=t[i],r=n.object;if(!this.testIsVisible(r)){t.splice(i,1),i--;continue}n.object=ni.getObject(r);break}return t}},ie=De;z(ie,"Factory",new Vv),z(ie,"raycastColor",new $.Color(.9,.3,.3)),z(ie,"raycastNoHitColor",new $.Color(.6,.6,.6)),z(ie,"geometry",new $.BufferGeometry().setFromPoints([new $.Vector3(0,0,0),new $.Vector3(0,0,-1)])),z(ie,"handModels",{}),z(ie,"eventSubs",{}),z(ie,"PreviousCameraFarDistance"),z(ie,"MovementSpeedFactor",1);var Ze=class{static AddEventListener(e,t){return Ze.Events[e]||(Ze.Events[e]=[]),Ze.Events[e].push(t),t}static RemoveEventListener(e,t){if(!t||!Ze.Events[e])return;let i=Ze.Events[e].indexOf(t);i>=0&&Ze.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=A.getComponentInParent(t,It);if(!r)return Zc&&console.warn("Prevented taking object that is not interactable",t),null;let o=t,s=A.getComponentInParent(t,ft);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 l=new Ze;return l.Take(e,o,t,s,r,i,n),l}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 l={controller:e,take:t,hit:i,sync:n,interactable:r};Ze.Events.WillTake?.forEach(m=>m(this,l));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=A.addNewComponent(this.selected,Mt),this.rigidbodies=A.getComponentsInChildren(this.selected,se),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 u=e.isUsingHands&&s?this.controller.getWristQuaternion().clone():e.rayRotation.clone();Pe(this.selected,this.localQuaternionToGrab).premultiply(u.invert());let h=this.controller.webXR.Rig;return h&&this.rigPositionLastFrame.copy(q(h)),Ee.Add(e.context,this.selected),Ze.Register(this),this.sync&&(this.sync.fastMode=!0),Ze.Events.DidTake?.forEach(m=>m(this,l)),this}free(){if(!this.selected)return;let e={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};Ze.Events.WillFree?.forEach(n=>n(this,e)),Ee.Remove(this.controller.context,this.selected),Ze.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,Ze.Events.DidFree?.forEach(n=>n(this,e))}grabPoint=new $.Vector3;localPositionOffsetToGrab=null;localPositionOffsetToGrab_worldSpace=new $.Vector3;localQuaternionToGrab=new $.Quaternion(0,0,0,1);targetDir=null;quaternionLerp=null;controllerDir=new $.Vector3;controllerWorldPos=new $.Vector3;lastControllerWorldPos=new $.Vector3;controllerPosDelta=new $.Vector3;totalChangeAlongDirection=0;rigPositionLastFrame=new $.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 $.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),Xe(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)),oe(this.selected,i)}if(this.rigidbodies!=null)for(let e of this.rigidbodies)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0});re.markDirty(this.selected,!0)}}},at=Ze;z(at,"Events",{}),z(at,"Current",[]);import*as po from"three";var Ht=class extends D{webAR=null;get rig(){return this.webAR?.webxr.Rig}invertForward=!1;get arScale(){return this._arScale}set arScale(e){e!==this._arScale&&(this._arScale=e,this.setScale(e))}_initalMatrix=new po.Matrix4;_selectStartFn=this.onSelectStart.bind(this);_selectEndFn=this.onSelectEnd.bind(this);start(){let e=A.findObjectOfType(Q);e&&(e.Rig.updateMatrix(),this._initalMatrix.copy(e.Rig.matrix))}_arScale=5;_rig=null;_startPose=null;_placementPose=null;_isTouching=!1;_rigStartPose=null;onBegin(e){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose=this.gameObject.matrix.clone(),this._rigStartPose=this.rig?.matrix.clone(),e.addEventListener("selectstart",this._selectStartFn),e.addEventListener("selectend",this._selectEndFn),this.gameObject.visible=!1,this.rig&&(this.rig.matrixAutoUpdate=!0,this._initalMatrix.decompose(this.rig.position,this.rig.quaternion,this.rig.scale))}onUpdate(e,t,i){return i&&!this._placementPose&&this._isTouching?(this.webAR&&this.webAR.setReticleActive(!1),this.placeAt(e,new po.Matrix4().fromArray(i.transform.matrix).invert()),!0):!1}placeAt(e,t){if(this._placementPose||(this._placementPose=new po.Matrix4),this._placementPose.copy(t),e){if(this.invertForward){let i=new po.Matrix4().makeRotationY(Math.PI);this._placementPose.premultiply(i)}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.gameObject.matrixAutoUpdate=!1,this._startPose&&this.gameObject.matrix.copy(this._startPose),e&&(e.matrixAutoUpdate=!0,this._rigStartPose&&this._rigStartPose.decompose(e.position,e.quaternion,e.scale)),re.markDirty(this.gameObject,!0),setTimeout(()=>{this.gameObject.matrixAutoUpdate=!0,this.gameObject.visible=!0},100)}onSelectStart(){this._isTouching=!0}onSelectEnd(){this._isTouching=!1}setScale(e){let t=this._rig;!t||!this._placementPose||(this._rigStartPose||(this._rigStartPose=t.matrix.clone()),t.matrixAutoUpdate=!1,t.matrix.multiplyMatrices(new po.Matrix4().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld(),console.log("Place",t.position))}};k([O()],Ht.prototype,"invertForward",2),k([O()],Ht.prototype,"arScale",1);var An=class extends D{awake(){}};import*as vt from"three";var wi=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 ke=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 ke).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+4),(t||new ke).__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 Te).__init(this.bb_pos+t,this.bb):null}rotation(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new wi).__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 Te).__init(this.bb_pos+t,this.bb):null}posRightHand(e){let t=this.bb.__offset(this.bb_pos,18);return t?(e||new Te).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){let t=this.bb.__offset(this.bb_pos,20);return t?(e||new wi).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){let t=this.bb.__offset(this.bb_pos,22);return t?(e||new wi).__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 Dp=B("debugxr"),_s=B("debugavatar");var ed="VRUS";$r(ed,ke.getRootAsVrUserStateBuffer);function $c(){return new Date().getTime()}function qv(c){let e=c&4294967295,t=c/Math.pow(2,32)&1048575;return Ue.create(e,t)}var xs=class{guid;time;avatarId;position=new vt.Vector3;rotation=new vt.Vector4;scale=1;posLeftHand=new vt.Vector3;posRightHand=new vt.Vector3;rotLeftHand=new vt.Quaternion;rotRightHand=new vt.Quaternion;constructor(e){this.guid=e}update(e,t,i,n,r){this.time=$c(),this.avatarId=r,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let o=xs.quat0,s=xs.quat1;o.set(i.x,i.y,i.z,i.w),o=o.multiplyQuaternions(o,xs.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 l=n.LeftController?.controllerGrip;l&&(l.getWorldPosition(this.posLeftHand),l.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);ke.startVrUserStateBuffer(e),ke.addGuid(e,i),ke.addTime(e,qv(this.time)),ke.addAvatarId(e,n),ke.addPosition(e,Te.createVec3(e,this.position.x,this.position.y,this.position.z)),ke.addRotation(e,wi.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),ke.addScale(e,this.scale),ke.addPosLeftHand(e,Te.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),ke.addPosRightHand(e,Te.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),ke.addRotLeftHand(e,wi.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),ke.addRotRightHand(e,wi.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));let r=ke.endVrUserStateBuffer(e);e.finish(r,ed);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 l=t.rotLeftHand();l&&this.rotLeftHand.set(l.x(),l.y(),l.z(),l.w());let d=t.rotRightHand();d&&this.rotRightHand.set(d.x(),d.y(),d.z(),d.w()),this.scale=t.scale()}},jt=xs;z(jt,"invertRotation",new vt.Quaternion().setFromAxisAngle(new vt.Vector3(0,1,0),Math.PI)),z(jt,"quat0",new vt.Quaternion),z(jt,"quat1",new vt.Quaternion);var Qi=class extends D{webXR=null;debugAvatarUser=null;voip=null;async awake(){if(this.webXR||(this.webXR=A.getComponent(this.gameObject,Q)),this.webXR||(this.webXR=A.findObjectOfType(Q,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=A.findObjectOfType(Q,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=A.findObjectOfType(Je,this.context)),_s){let e="debug-avatar-"+_s,t=new Lt(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof _s=="string"&&_s.length>0)if(await t.setAvatarOverride(_s)){let i=new jt(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=A.getComponent(this.gameObject,Q),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),Q.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),Q.addEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),Q.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(ed,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 jt("");onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;let i=new Date().getTime()-t;if(i>5e3)return Dp&&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),Q.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),Q.removeEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),Q.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}update(){let e=$c();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=$c();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(){Dp&&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 ut(1024);onXRSessionUpdate(e){this.xrState??=new jt(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership??=new yn(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,l=o.orientation;this.xrState.update(n,s,l,this.webXR,this.getAvatarId()),this.localAvatar&&(this.context.connection.connectionId&&(this.localAvatar.guid=this.context.connection.connectionId),this.localAvatar.tryUpdate(this.xrState,0)),!(this.ownership&&!this.ownership.hasOwnership&&this.context.connection.isConnected&&(this.context.time.frameCount%120===0&&this.ownership.requestOwnership(),!this.ownership.hasOwnership))&&(!this.context.connection.isConnected||!this.context.connection.connectionId||this.xrState.sendAsBuffer(this.builder,this.context.connection))}getAvatarId(){return B("avatar")??null}};async function Yv(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function Kv(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}var td=!1,id=!1;Yv().then(c=>td=c);Kv().then(c=>id=c);var Le=class extends D{enableVR=!0;enableAR=!0;defaultAvatar;createVRButton=!0;createARButton=!0;static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(td||id)}static get IsARSupported(){return td}static get IsVRSupported(){return id}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){Le.XRSupported||console.warn("WebXR is not supported on this device");let i=lo.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={};i&&(n.domOverlay={root:i},n.optionalFeatures=["hit-test","dom-overlay"]);let r=Qa.createButton(e.context.renderer,n);return r.classList.add("webxr-ar-button"),r.classList.add("webxr-button"),Le.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||this.ensureRig(),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}get IsInVR(){return this._isInVR}get IsInAR(){return this._isInAR}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=Ke.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!A.findObjectOfType(Qi,this.context)){let e=A.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 In(this);let e=Le.XRSupported,t,i,n=document.createElement("div");n.classList.add("webxr-buttons"),this.context.domElement.append(n),this.enableAR&&this.createARButton&&(t=Le.createARButton(this),this._arButton=t,n.appendChild(t)),this.createVRButton&&this.enableVR&&(e||!this.enableAR)&&(i=Le.createVRButton(this),this._vrButton=i,n.appendChild(i)),setTimeout(()=>{Le.resetButtonStyles(i),Le.resetButtonStyles(t)},1e3)}_transformOrientation=new ve.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)}Le._isInXr===!1&&t&&this.onEnterXR(t,e),Le.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++)ie.Create(this,e,this.gameObject,0);Le.events.dispatchEvent({type:"requestVRSession"})}}captureCameraState(){this.context.mainCamera&&(this._originalCameraPosition.copy(q(this.context.mainCamera)),this._originalCameraRotation.copy(Pe(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent)}ensureRig(){if(!this.rig){let e=A.findObjectOfType(An,this.context);e?(this.rig=e.gameObject,this.rig.rotateY(Math.PI)):(this.rig=new ve.Group,this.rig.rotateY(Math.PI),this.rig.name="XRRig",this.context.scene.add(this.rig))}}_originalCameraParent=null;_originalCameraPosition=new ve.Vector3;_originalCameraRotation=new ve.Quaternion;onEnterXR(e,t){console.log("[XR] session begin",e),Le._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 l=new ve.Quaternion(s.x,s.y,s.z,s.w),d=new ve.Euler().setFromQuaternion(l);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(mt.Global.Set(r),r){case 2:this.context.xrSessionMode="immersive-ar",this._isInAR=!0,this.webAR?.onBegin(e);break;case 4:this.context.xrSessionMode="immersive-vr",this._isInVR=!0,this.onEnterVR(e);break}e.addEventListener("end",()=>{console.log("[XR] session end"),Le._isInXr=!1,this.onExitXR(e)}),this.onEnterXR_HandleMirrorWindow(e),Le.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.context.xrSessionMode=void 0,this.xrMirrorWindow&&(this.xrMirrorWindow.close(),this.xrMirrorWindow=null),this.destroyControllers(),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),oe(this.context.mainCamera,this._originalCameraPosition),Xe(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),mt.Global.Set(17),Le.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){!B("mirror")||setTimeout(()=>{if(!Le.IsInWebXR)return;let t=new URL(window.location.href);jr(t.searchParams,co,1),jr(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=()=>{Le.IsInWebXR&&e.end()})})},1e3)}},Q=Le;z(Q,"_isInXr",!1),z(Q,"events",new ve.EventDispatcher),k([O(Ke)],Q.prototype,"defaultAvatar",2);var fo=class{get webxr(){return this._webxr}_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;noHitTestAvailable=!1;didPlaceARSessionRoot=!1;getAROverlayContainer(){return this.arDomOverlay=this.webxr.context.domElement,this.arOverlayElement=this.arDomOverlay.getAROverlayContainer(),this.arOverlayElement}setReticleActive(e){this.reticleActive=e}async onBegin(e){let t=this.webxr.context;this.reticleActive=!0,this.didPlaceARSessionRoot=!1;let i=navigator.userAgent?.includes("OculusBrowser")?0:1;for(let n=0;n<4;n++)ie.Create(this.webxr,n,this.webxr.gameObject,i);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=A.findObjectOfType(Ht,t)),this.previousBackground=t.scene.background,this.previousEnvironment=t.scene.environment,t.scene.background=null,e.requestReferenceSpace("viewer").then(n=>{e.requestHitTestSource({space:n}).then(r=>{this.hitTestSource=r}).catch(r=>{this.noHitTestAvailable=!0,console.warn("WebXR: Hit test not supported")})}),!this.reticle&&this.sessionRoot&&(this.reticle=new ve.Mesh(new ve.RingGeometry(.07,.09,32).rotateX(-Math.PI/2),new ve.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,fo.tempWebXRObject||(fo.tempWebXRObject=new ve.Object3D),this.context.scene.add(fo.tempWebXRObject),A.addComponent(fo.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),A.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.noHitTestAvailable===!0){if(this.reticle&&(this.reticle.visible=!1),!this.didPlaceARSessionRoot){this.didPlaceARSessionRoot=!0;let n=this.webxr.Rig,r=Jv.clone();if(n){let o=new Qv(0,0,0).add(n.position).divideScalar(this.sessionRoot?.arScale??1);r.multiply(new Xv().makeTranslation(o.x,o.y,o.z))}this.sessionRoot?.placeAt(n,r)}return}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){let s=this.sessionRoot.onUpdate(this.webxr.Rig,e,o);this.didPlaceARSessionRoot=s}if(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)}},In=fo;z(In,"tempWebXRObject");var Jv=new ve.Matrix4().identity().makeTranslation(0,-.5,0);var nd=!1;var mo=class extends It{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)||Q.IsInWebXR)return;let t=A.getComponentInParent(e.object,mo);!t||t!==this||(mo.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){!this.allowEdit(this.gameObject)||Q.IsInWebXR||mo.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}_waitingForDragStart=null;onPointerDown(e){!this.allowEdit(this.gameObject)||Q.IsInWebXR||(this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation())}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&(Q.IsInWebXR||(this.onDragEnd(e),e.StopPropagation()))}update(){if(!Q.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 Za(this.context.mainCamera);else return;if(!e||!e.object)return;let t=A.getComponentInParent(e.object,mo);if(!t||t!==this)return;let i=e.object;this.transformSelf&&(i=this.gameObject);let n={selected:i,attached:i};for(let l of this.selectStartEventListener)l(this,n);if(!n.attached)return;n.attached,i=n.attached,this._isDragging=!0,this._dragHelper.setSelected(i,this.context);let r=A.getComponentInChildren(i,ft);nd&&console.log("DRAG START",r,i),r&&(r.fastMode=!0,r?.requestOwnership()),this._marker=A.addNewComponent(i,Mt),this._draggingRigidbodies.length=0;let o=A.getComponentsInChildren(i,se);o&&this._draggingRigidbodies.push(...o);let s=Ol();A.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(nd&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context),e?.object){let n=A.getComponentInChildren(e.object,ft);n&&(n.fastMode=!1),this._marker&&this._marker.destroy()}for(let n of this.selectEndEventListener)n(this);let i=Ol();A.invokeOnChildren(t,i("onDragEnd"))}},_i=mo;z(_i,"_active",null),z(_i,"lastHovered");var rd=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(rd.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&&Ee.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}Ee.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this._rbs=A.getComponentsInChildren(this._selected,se),this.onUpdateScreenSpacePlane()}}_groundOffsetVector=new ee.Vector3(0,1,0);_requireUpdateGroundPlane=!0;_didDragOnGroundPlaneLastFrame=!1;onUpdate(e){if(!this._context)return;let t=" ",i="d",n="s",r=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(i),o=this._context.input.getTouchesPressedCount()>=2||r;if(o){let l=this._context.input.getPointerPositionDelta(0);l&&(this._groundOffsetVector.set(0,1,0),this._selected?.rotateOnWorldAxis(this._groundOffsetVector,l.x*this._context.time.deltaTime))}let s=this._context.input.getPointerPositionRC(0);if(!!s&&(this._raycaster.setFromCamera(s,this._camera),this._selected)){nd&&console.log("UPDATE DRAG",this._selected),this._groundOffsetVector.set(0,1,0);let l=q(this._camera).clone().sub(q(this._selected)).normalize(),d=Math.abs(l.dot(this._groundOffsetVector)),a=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(i),u=!o&&d>.2&&!a&&this._context.input.getPointerPressedCount()<=1,h=this._didDragOnGroundPlaneLastFrame!==u;if(this._didDragOnGroundPlaneLastFrame=u,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!u||h)&&this.onUpdateGroundPlane(),this._requireUpdateGroundPlane=!1,this._hasGroundPlane)if(this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection)){let m=this._intersection.y;if(this._groundPlanePoint.copy(this._intersection).sub(this._groundOffset),this._groundPlanePoint.y=m,u){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);h&&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(oe(this._selected,e),oe(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),oe(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 _e;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(){re.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}},Za=rd;z(Za,"geometry",new ee.BufferGeometry().setFromPoints([new ee.Vector3(0,0,0),new ee.Vector3(0,-1,0)]));var Mn=class extends D{filesBackendUrl;localhost;_dragOver;_drop;onEnable(){this.filesBackendUrl=this.filesBackendUrl?ht.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 hp(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 up(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 _e;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:t}))}};k([O()],Mn.prototype,"filesBackendUrl",2),k([O()],Mn.prototype,"localhost",2);import{Vector3 as Zv,Quaternion as $v,Object3D as Hp}from"three";var xi=class extends It{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 Zv(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new $v(0,0,0,1)}let e=A.getComponentInParent(this.gameObject,_i);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),ie.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 Be;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=A.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([O(Hp)],xi.prototype,"parent",2),k([O(Hp)],xi.prototype,"object",2),k([O()],xi.prototype,"limitCount",2),k([O()],xi.prototype,"limitInterval",2);var Ti=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)}}},ey=c=>/^[A-Z]*$/.test(c),gr=class extends Event{args},Re=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&&ey(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 gr(this.key);i.args=e,t.call(this.target,i)}}}finally{this._isInvoking=!1}}addEventListener(e){return this.methods.push(new Ti(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 go=class extends D{};import{FlyControls as ty}from"three/examples/jsm/controls/FlyControls";var bo=class extends D{_controls=null;onEnable(){let e=A.getComponent(this.gameObject,he)?.cam;this._controls=new ty(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 jp from"three";import{Color as iy}from"three";var Yi=class extends D{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!si||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new jp.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=Wa(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([O()],Yi.prototype,"objectBounds",2),k([O(iy)],Yi.prototype,"color",2),k([O()],Yi.prototype,"isGizmo",2);import{GLTFExporter as Iy}from"three/examples/jsm/exporters/GLTFExporter.js";import{BufferAttribute as od,Matrix4 as ny,Vector3 as Bp,Quaternion as ry}from"three";var Ts=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 ny,s=new Array,l=new Array,d=new Array;for(let m=0;m<e.count;m++){e.getMatrixAt(m,o);let E=new Bp,b=new ry,y=new Bp;o.decompose(E,b,y),s.push(E.x,E.y,E.z),l.push(b.x,b.y,b.z,b.w),d.push(y.x,y.y,y.z)}let a=new Float32Array(s),u=new Float32Array(l),h=new Float32Array(d);r.attributes={TRANSLATION:i.processAccessor(new od(a,3)),ROTATION:i.processAccessor(new od(u,4)),SCALE:i.processAccessor(new od(h,3))},n[this.name]=!0}};import*as Ci from"three";import*as Cs from"three";var Ki=class{get lightmap(){return this.lightmapTexture}set lightmap(e){e!==this.lightmapTexture&&(this.lightmapTexture=e,this.setupLightmap())}lightmapIndex=-1;lightmapScaleOffset=new Cs.Vector4(1,1,0,0);context;gameObject;lightmapTexture=null;lightmapScaleOffsetUniform={value:new Cs.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 Cs.ShaderMaterial({vertexShader:`
123
+ #endif`);Kt.UniformsLib.lightmap.lightmapScaleOffset={value:new Kt.Vector4(1,1,0,0)};var Yb=H("debugplayerview");var wc=class{userId;context;viewDevice="browser";get currentObject(){return this._object}set currentObject(e){this._object=e}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}removed=!1;_object;constructor(e,t){this.userId=e,this.context=t}},ia=class{context;playerViews=new Map;constructor(e){this.context=e}setPlayerView(e,t,i){let n=this.playerViews.get(e);n||(n=new wc(e,this.context),this.playerViews.set(e,n)),n.viewDevice=i,n.currentObject=t,n.removed=!1}getPlayerView(e){if(!e)return;if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}removePlayerView(e,t){let i=this.playerViews.get(e);i?.viewDevice===t&&(Yb&&console.log("REMOVE",e),i.removed=!0,this.playerViews.delete(e))}};var ev=H("debugSetup"),tv=H("stats"),na={};function Ms(l,e){if(!l)return;let t=e?.new_scripts??J.Current.new_scripts;t.includes(l)||t.push(l)}var vt=class{static get Current(){return this._current}static set Current(e){this._current=e}name;alias;isManagedExternally=!1;domElement;get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(e){if(e!==this._resolutionScaleFactor&&typeof e=="number"){if(e<=0){console.error("Invalid resolution scale factor",e);return}this._resolutionScaleFactor=e,this.updateSize()}}_resolutionScaleFactor=1;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||!1}xrSessionMode=void 0;get xrSession(){return this.renderer.xr?.getSession()}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;players;_sizeChanged=!1;_isCreated=!1;_stats=tv?hp.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=H("postfx");this.renderer=new Jb({antialias:!0}),this.renderer.toneMappingExposure=1,this.renderer.toneMapping=_e.NoToneMapping,this.renderer.setClearColor(new _e.Color("lightgrey"),0),this.renderer.antialias=!0,this.renderer.alpha=!1,this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=_e.PCFSoftShadowMap,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputEncoding=_e.sRGBEncoding,this.renderer.physicallyCorrectLights=!0,this.composer=i?new Zb(this.renderer):null}this.scene=new _e.Scene,this.application=new ea(this),this.time=new Bs,this.input=new os(this),this.physics=new js(this),this.connection=new Gs(this),this.assets=new Ys,this.rendererData=new Zs(this),this.addressables=new $s(this),this.lightmaps=new ta(this),this.players=new ia(this),window.addEventListener("resize",()=>this._sizeChanged=!0),new ResizeObserver(i=>this._sizeChanged=!0).observe(this.domElement)}updateSize(){if(!this.isManagedExternally&&!this.renderer.xr.isPresenting){this._sizeChanged=!1;let e=this.resolutionScaleFactor,t=this.domWidth*e,i=this.domHeight*e,n=this.mainCamera;this.updateAspect(n),this.renderer.setSize(t,i),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.composer&&(this.composer.setSize(t,i),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,Rt(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()}removeCamera(e){if(!e)return;let t=this._cameraStack.indexOf(e);if(t>=0&&this._cameraStack.splice(t,1),this.mainCameraComponent===e&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){let i=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(i)}}_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 u=0;u<a.length;u++){let h=a[u];h(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{vt.Current=this,e&&await e(this,t)}catch(n){console.error(n),i=!1}if(!!i){this.isManagedExternally||this.domElement.prepend(this.renderer.domElement),_u(this),wu(this),rp(this),vt._current=this;for(let n=0;n<this.new_scripts.length;n++){let r=this.new_scripts[n];if(r.gameObject!==void 0&&r.gameObject!==null){r.gameObject.userData===void 0&&(r.gameObject.userData={}),r.gameObject.userData.components===void 0&&(r.gameObject.userData.components=[]);let o=r.gameObject.userData.components;o.includes(r)||o.push(r)}}if(this.post_setup_callbacks)for(let n=0;n<this.post_setup_callbacks.length;n++)vt._current=this,await this.post_setup_callbacks[n](this);if(this.mainCamera,vt._current=this,yi(this),!this.isManagedExternally&&this.composer&&this.mainCamera){let n=new $b(this.scene,this.mainCamera);this.renderer.setSize(this.domWidth,this.domHeight),this.composer.addPass(n),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)),ev&&ao(this.scene,!0)}}render(e,t){for(this._stats?.begin(),vt._current=this,this.time.update(),yi(this),uu(),Cs(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&&(vt._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&&(vt._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&&(vt._current=this,n.lateUpdate())}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&&(vt._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&&(vt._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 _e.WebGLRenderTarget(this.domWidth,this.domHeight),this._requireDepthTexture){let i=new Kb(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new _e.Texture,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=_e.NearestFilter,this._renderTarget.texture.magFilter=_e.NearestFilter,this._renderTarget.texture.format=_e.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 u=s[s.length-1].next();if(u.done&&s.pop(),t(u)&&(r.chained||(r.chained=[]),r.chained.push(u.value)),!u.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)}}},J=vt;N(J,"_current");var _n="ar",iv="quit-ar",ra=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(`.${_n}`).forEach(o=>{!o||o!==this.arContainer&&(this._reparentedObjects.push({el:o,previousParent:o.parentElement}),this.arContainer?.appendChild(o))});let r=t.getElementsByClassName(iv);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(_n))return e;if(e.children){for(let i of e.children)if(!(!i||!i.classList)&&i.classList.contains(_n))return i}let t=document.createElement("div");return t.classList.add(_n),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 _c={};$d(_c,{Behaviour:()=>D,Component:()=>Ot,GameObject:()=>A});import*as We from"three";var A=class extends We.Object3D{guid;static setActive(e,t,i=!0){!e||(e.visible=t,Bi(e),t&&i&&Cs(J.Current,e))}static isActiveSelf(e){return rr(e)}static isActiveInHierarchy(e){return Lu(e)}static markAsInstancedRendered(e,t){Hu(e,t)}static isUsingInstancing(e){return Ls(e)}static foreachComponent(e,t,i=!0){return gt(e,t,i)}static instantiateSynced(e,t){return e?Os(e,t):null}static instantiate(e,t=null){return vn(e,t)}static destroySynced(e,t,i=!0){if(!e)return;let n=e;t=t??J.Current,Ps(n,t.connection,i)}static destroy(e,t=!0,i=!0){return Rt(e,t,i)}static add(e,t,i){if(!(!e||!t)){if(e===t){console.warn("Can not add object to self",e);return}i||(i=J.Current),t.add(e),Bi(e),i?A.foreachComponent(e,n=>{Ql(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),A.foreachComponent(e,t=>{hu(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 ho(e,n,i),n}static addComponent(e,t){if(t.gameObject==null)throw new Error("Did you mean to create a new component? Use addNewComponent");Ou(e,t)}static removeComponent(e){return Is(e.gameObject,e),e}static getOrAddComponent(e,t){return As(e,t)}static getComponent(e,t){return e===null?null:yn(e,t)}static getComponents(e,t,i=null){return e===null?i??[]:sr(e,t,i)}static findByGuid(e,t){return bn(e,t)}static findObjectOfType(e,t,i=!0){return Au(e,t??J.Current,i)}static findObjectsOfType(e,t){let i=[];return Mu(e,i,t),i}static getComponentInChildren(e,t){return Fi(e,t)}static getComponentsInChildren(e,t,i=null){return ar(e,t,i??void 0)}static getComponentInParent(e,t){return or(e,t)}static getComponentsInParent(e,t,i=null){return uo(e,t,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]}},Pt=class{get isComponent(){return!0}__context;get context(){return this.__context??J.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[Xt];return e===void 0?!0:e}set __isActiveInHierarchy(e){!this.gameObject||(this.gameObject[Xt]=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||this.__internalDestroy()}__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,this.__internalResetsCachedPhysicsData()}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(){return this.__didEnable?!1:(this.__didEnable=!0,this.onEnable(),!0)}__internalDisable(){!this.__didEnable||(this.__didEnable=!1,this._collisionExitRoutine=void 0,this.onDisable(),this._collisions?.clear())}__internalDestroy(){this.__destroyed||(this.__destroyed=!0,this.destroy?.call(this),ku(this))}get enabled(){return this.__isEnabled??!0}set enabled(e){typeof e=="number"&&(e>=.5?e=!0:e=!1),this.__didAwake&&(e?this.__internalEnable():this.__internalDisable())}constructor(){this.__internalNewInstanceCreated()}_collisionExitRoutine;_collisions=null;_triggerExitRoutine;_triggerCollisions=null;get collisionsCount(){return this._collisions?.size??0}__internalResetsCachedPhysicsData(){this._collisionExitRoutine=null,this._collisions=null,this._triggerExitRoutine=null,this._triggerCollisions=null}__internalHandleCollision(e,t){if(t){if(!this.onTriggerEnter&&!this.onTriggerStay&&!this.onTriggerExit)return}else if(!this.onCollisionEnter&&!this.onCollisionStay&&!this.onCollisionExit)return;let i=e.gameObject;t&&!this._triggerCollisions?this._triggerCollisions=new Map:this._collisions||(this._collisions=new Map);let n=t?this._triggerCollisions:this._collisions;if(n.has(i)){let r=n.get(i);r.frame=this.context.time.frameCount,r.col=e,t?this.onTriggerStay?.(e):this.onCollisionStay?.call(this,e)}else{let r={col:e,frame:this.context.time.frameCount};n.set(i,r),t?this.onTriggerEnter?.(e):this.onCollisionEnter?.call(this,e)}}__internalHandleExitCollisionEvent(e,t){if(t){if(!this._triggerCollisions)return}else if(!this._collisions)return;let n=(t?this._triggerCollisions:this._collisions).get(e);!n||(n.exitFrame=this.context.time.frameCount,this.__waitForCollisionExit(t),t||this.onCollisionExitRaw?.call(this,n.col))}__waitForCollisionExit(e){if(e?this._triggerExitRoutine:this._collisionExitRoutine)return;let i=e?this._triggerCollisions:this._collisions,n=this,r=10;function*o(){for(;i&&i.size>0;){for(let c of i.keys()){let d=i.get(c);d.frame!==void 0&&n.context.time.frameCount-d.frame>=r&&(i.delete(c),e?n.onTriggerExit?.(d.col):n.onCollisionExit?.call(n,d.col))}for(let c=0;c<r;c++)yield}e?n._triggerExitRoutine=void 0:n._collisionExitRoutine=null}let s=this.startCoroutine(o(),4);e?this._triggerExitRoutine=s:this._collisionExitRoutine=s}_worldPosition=void 0;_worldQuaternion=void 0;_worldEuler=void 0;_worldRotation=void 0;get worldPosition(){return this._worldPosition||(this._worldPosition=new We.Vector3),G(this.gameObject,this._worldPosition),this._worldPosition}set worldPosition(e){ne(this.gameObject,e)}setWorldPosition(e,t,i){Pt._worldPositionBuffer.set(e,t,i),this.worldPosition=Pt._worldPositionBuffer}get worldQuaternion(){return this._worldQuaternion||(this._worldQuaternion=new We.Quaternion),we(this.gameObject,this._worldQuaternion)}set worldQuaternion(e){Ue(this.gameObject,e)}setWorldQuaternion(e,t,i,n){Pt._worldQuaternionBuffer.set(e,t,i,n),this.worldQuaternion=Pt._worldQuaternionBuffer}get worldEuler(){return this._worldEuler||(this._worldEuler=new We.Euler),this._worldEuler.setFromQuaternion(this.worldQuaternion),this._worldEuler}set worldEuler(e){this._worldQuaternion||(this._worldQuaternion=new We.Quaternion),this._worldQuaternion?.setFromEuler(e),this.worldQuaternion=this._worldQuaternion}get worldRotation(){let e=this.worldEuler;this._worldRotation||(this._worldRotation=new We.Vector3);let t=this._worldRotation;return t.set(e.x,e.y,e.z),t.x=K.toDegrees(t.x),t.y=K.toDegrees(t.y),t.z=K.toDegrees(t.z),t}set worldRotation(e){this.setWorldRotation(e.x,e.y,e.z,!0)}setWorldRotation(e,t,i,n=!0){n&&(e=K.toRadians(e),t=K.toRadians(t),i=K.toRadians(i)),Pt._worldEulerBuffer.set(e,t,i),Pt._worldQuaternionBuffer.setFromEuler(Pt._worldEulerBuffer),this.worldQuaternion=Pt._worldQuaternionBuffer}get forward(){return Pt._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=Pt;N(Ot,"_worldPositionBuffer",new We.Vector3),N(Ot,"_worldQuaternionBuffer",new We.Quaternion),N(Ot,"_worldEulerBuffer",new We.Euler),N(Ot,"_tempQuaternionBuffer2",new We.Quaternion),N(Ot,"_forward",new We.Vector3);var D=class extends Ot{};var nv=H("debugloadingbar");function xc(l){return l.index/l.count+l.progress.loaded/l.progress.total/l.count}var oa=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=xc(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;nv&&(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=K.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"),this._loadingElement.style.width="100%";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=30;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 K.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)",o.style.justifyContent="center",this._loadingElement.appendChild(o),this._loadingElement}};import{DRACOLoader as Tc}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as up}from"three/examples/jsm/loaders/KTX2Loader.js";var bo=H("debugdecoders"),kt,Wi;function Cc(l){l!==void 0&&typeof l=="string"&&(kt||(kt=new Tc),bo&&console.log("Setting draco decoder path to",l),kt.setDecoderPath(l))}function Rc(l){l!==void 0&&typeof l=="string"&&(kt||(kt=new Tc),bo&&console.log("Setting draco decoder type to",l),kt.setDecoderConfig({type:l}))}function Sc(l){l!==void 0&&typeof l=="string"&&(Wi||(Wi=new up),bo&&console.log("Setting ktx2 transcoder path to",l),Wi.setTranscoderPath(l))}function sa(l,e){kt||(kt=new Tc,kt.setDecoderPath("./include/draco/"),kt.setDecoderConfig({type:"js"}),bo&&console.log("Setting draco decoder path to","./include/draco/")),Wi||(Wi=new up,Wi.setTranscoderPath("./include/ktx2/"),bo&&console.log("Setting ktx2 transcoder path to","./include/ktx2/"),e.renderer&&Wi.detectSupport(e.renderer)),l.setDRACOLoader(kt),l.setKTX2Loader(Wi)}var xn=H("debugwebcomponent"),Pc=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||A.destroySynced(this.previouslyAdded)),this.previouslyAdded=null,t||this.context.connection.send(this.networkEvent,e),this.previousSource=e,J.Current=this.context;let n=await Ze().loadSync(this.context,e,this.getHashFromString(e),!1);i||yi(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}},ov="needle-engine",sv="vr",av="desktop",lv=[_n,sv,av],Oc=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=A;GameObject=A;_context=null;_overlay_ar;_loadingProgress01=0;_watcher;_loadingView;constructor(){super(),this._overlay_ar=new ra}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 J({name:i,domElement:this,alias:r}),this._watcher=new Pc(this.getAttribute("id")??r??"",this._context),i&&i.length>0){if(!n)for(;Object.keys(na).length<=0;){if(!this.isConnected)return;await sh(10)}let o=na[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=!1,d=this.dispatchEvent(new CustomEvent("loadstart",{detail:{context:this._context,alias:r},cancelable:c}));!this._loadingView&&d&&(this._loadingView=new oa(this)),d&&this._loadingView?.onLoadingBegin("begin load");let a=(h,f)=>{this._loadingProgress01=xc(h),d&&this._loadingView?.onLoadingUpdate(h,f),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:a});let u=t();u&&u!==s&&await this._watcher.onSourceChanged(u,!0,!0),this._loadingProgress01=1,d&&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',na)}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&&(xn&&console.log(e+" attribute changed",i),this.registerEventFromAttribute(e,i));break;case"dracoDecoderPath":xn&&console.log("dracoDecoderPath",i),Cc(i);break;case"dracoDecoderType":i==="wasm"||i==="js"?(xn&&console.log("dracoDecoderType",i),Rc(i)):console.error("Invalid dracoDecoderType",i,"expected js or wasm");break;case"ktx2DecoderPath":xn&&console.log("ktx2DecoderPath",i),Sc(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,_n))}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 lv)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&&(xn&&console.log("using custom draco decoder path",e),Cc(e));let t=this.getAttribute("dracoDecoderType");t&&(xn&&console.log("using custom draco decoder type",t),Rc(t));let i=this.getAttribute("ktx2DecoderPath");i&&(xn&&console.log("using custom ktx2 decoder path",i),Sc(i))}};window.customElements.define(ov,Oc);var O=function(l){if(l===void 0&&(l=null),!Array.isArray(l))l=pp(l);else for(let e=0;e<l.length;e++){let t=l[e];l[e]=pp(t)}return function(e,t){Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});let i=e.$serializedTypes=e.$serializedTypes||{};i[t]=l}};function pp(l){switch(l?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return l}var Vd={};$d(Vd,{AlignmentConstraint:()=>hr,Animation:()=>ur,AnimationCurve:()=>vo,AnimationTrackHandler:()=>Gr,Animator:()=>Zt,AnimatorController:()=>Ei,AttachedObject:()=>wt,AudioListener:()=>wi,AudioSource:()=>le,AudioTrackHandler:()=>qr,AvatarBlink_Simple:()=>on,AvatarEyeLook_Rotation:()=>sn,AvatarLoader:()=>mr,AvatarMarker:()=>he,AvatarModel:()=>_o,Avatar_Brain_LookAt:()=>Rn,Avatar_MouthShapes:()=>Ur,Avatar_MustacheShake:()=>$a,Avatar_POI:()=>Te,AxesHelper:()=>Tn,BaseUIComponent:()=>Ge,BasicIKConstraint:()=>da,BoxCollider:()=>vr,BoxGizmo:()=>kn,BoxHelperComponent:()=>yt,Button:()=>hi,CallInfo:()=>Ji,Camera:()=>de,Canvas:()=>Qe,CanvasGroup:()=>Gn,Collider:()=>Ti,ColorAdjustments:()=>zr,ControlTrackHandler:()=>Nn,Deletable:()=>pa,DeleteBox:()=>xo,DeviceFlag:()=>To,DragControls:()=>Yi,DropListener:()=>kr,Duplicatable:()=>Ki,EmissionModule:()=>Ma,EventList:()=>Ae,EventListEvent:()=>Io,EventSystem:()=>tt,EventTrigger:()=>Ea,FieldWithDefault:()=>xa,FlyControls:()=>wa,GltfExport:()=>di,GltfExportBox:()=>Sa,Graphic:()=>Nt,GraphicRaycaster:()=>cl,GridHelper:()=>Dn,GridLayoutGroup:()=>ll,GroundProjectedEnv:()=>Ln,HorizontalLayoutGroup:()=>al,Image:()=>Wn,InputField:()=>zt,Interactable:()=>ei,Keyboard:()=>ol,LODGroup:()=>Ar,LODModel:()=>$i,LayoutGroup:()=>Xn,Light:()=>it,LogStats:()=>el,LookAtConstraint:()=>Sn,MainModule:()=>Aa,MaskableGraphic:()=>Vn,MeshRenderer:()=>Ho,NavMesh:()=>ka,NavMeshAgent:()=>Ia,NestedGltf:()=>jo,Networking:()=>Oi,ObjectRaycaster:()=>Zo,OffsetConstraint:()=>en,OrbitControls:()=>Ri,ParticleSystem:()=>La,ParticleSystemRenderer:()=>Bo,PlayableDirector:()=>Un,PlayerColor:()=>ki,PointerEventData:()=>Si,RGBAColor:()=>xe,RawImage:()=>Qo,Raycaster:()=>Jo,Rect:()=>Xo,RectTransform:()=>xt,RemoteSkybox:()=>Hr,Renderer:()=>be,RendererLightmap:()=>In,Rigidbody:()=>ae,ScreenCapture:()=>Mr,ShadowCatcher:()=>Lr,ShapeModule:()=>Da,SignalAsset:()=>Wo,SignalReceiver:()=>Fn,SignalReceiverEvent:()=>Go,SignalTrackHandler:()=>zn,Size:()=>nl,SkinnedMeshRenderer:()=>Ta,SmoothFollow:()=>tn,SpatialHtml:()=>dl,SpatialTrigger:()=>jn,SpatialTriggerReceiver:()=>Ft,SpectatorCamera:()=>za,SphereCollider:()=>br,SpringJoint:()=>Ua,Sprite:()=>No,SpriteRenderer:()=>Bn,SyncedCamera:()=>Br,SyncedRoom:()=>Ii,SyncedTransform:()=>Mt,TeleportTarget:()=>Po,TestRunner:()=>Xa,TestSimulateUserData:()=>Qa,Text:()=>je,ToneMapping:()=>Nr,TransformGizmo:()=>zo,UIRaycastUtils:()=>Pi,UIRootComponent:()=>Pn,UsageMarker:()=>ti,VRUserState:()=>li,VerticalLayoutGroup:()=>sl,VideoPlayer:()=>Me,Voip:()=>st,Volume:()=>Uo,VolumeComponent:()=>rn,VolumeParameter:()=>Ka,VolumeProfile:()=>Fr,WebAR:()=>Pr,WebARSessionRoot:()=>si,WebXR:()=>Y,WebXRAvatar:()=>ri,WebXRController:()=>ce,WebXRSync:()=>On,XRFlag:()=>Oe,XRGrabModel:()=>Vo,XRGrabRendering:()=>Ja,XRRig:()=>Rr,XRState:()=>Dt,__Ignore:()=>Ud});import{Vector3 as cv}from"three";var hr=class extends D{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new cv}update(){if(!this.from||!this.to)return;let e=G(this.from).clone(),t=G(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),ne(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(G(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}};k([O(A)],hr.prototype,"from",2),k([O(A)],hr.prototype,"to",2);import*as pr from"three";var ur=class extends D{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&&ie.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?pr.LoopRepeat:pr.LoopOnce),e.play();let r=new kc(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 pr.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([O()],ur.prototype,"playAutomatically",2),k([O()],ur.prototype,"randomStartTime",2);var kc=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}};var Jt=class{time;value;inTangent;inWeight;outTangent;outWeight;weightedMode};k([O()],Jt.prototype,"time",2),k([O()],Jt.prototype,"value",2),k([O()],Jt.prototype,"inTangent",2),k([O()],Jt.prototype,"inWeight",2),k([O()],Jt.prototype,"outTangent",2),k([O()],Jt.prototype,"outWeight",2),k([O()],Jt.prototype,"weightedMode",2);var vo=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 K.lerp(t.value,i.value,(e-t.time)/(i.time-t.time));t=i}return this.keys[this.keys.length-1].value}};k([O(Jt)],vo.prototype,"keys",2);import{AnimationClip as dv,MathUtils as hv}from"three";var fr=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 fp(l,e){return{name:"",isLooping:!1,guid:e?.generateUUID()??hv.generateUUID(),index:-1,clip:new dv(l,1,[])}}import{AnimationClip as uv,AnimationMixer as pv,AxesHelper as fv,Euler as mp,LoopOnce as mv,Quaternion as It,Vector3 as yo}from"three";import*as la from"three";var Gi=H("debuganimatorcontroller"),Ic=H("debugrootmotion"),Ei=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){Gi&&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){Gi&&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 pv(this.animator.gameObject),this.createActions(this.animator)}clone(){let e=Jr(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 Ei(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,Gi&&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()&&(Gi&&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){Gi&&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,Gi&&(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 fr(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,u=new fr(this._activeState,a,d,this._speed);for(let h of this._activeState.behaviours)h.instance?.onStateExit?.call(h.instance,this.animator,u,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(mv,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 fr(e,i,d,this._speed);for(let u of this._activeState.behaviours)u.instance?.onStateEnter?.call(u.instance,this.animator,a,n)}}else console.warn("No action",e.motion,this);Gi&&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 Ac(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=fp(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 uv;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=Zr.get(o.typeName),c=new s;c.isStateMachineBehaviour&&(c._context=this.context??void 0,rs(c,o.properties),o.instance=c),Gi&&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},aa=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}},ye=class{set action(e){this._action=e}get action(){return this._action}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new yo;rotationChange=new It;constructor(e,t,i,n,r){if(this.context=e,this.root=t,this.clip=i,ye.firstKeyframeRotation[i.uuid]||(ye.firstKeyframeRotation[i.uuid]=new la.Quaternion),r){let o=r.values;ye.firstKeyframeRotation[i.uuid].set(o[0],o[1],o[2],o[3])}ye.spaceRotation[i.uuid]||(ye.spaceRotation[i.uuid]=new It),ye.effectiveSpaceRotation[i.uuid]||(ye.effectiveSpaceRotation[i.uuid]=new It),ye.clipOffsetRotation[i.uuid]=new It,r&&ye.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=ye.lastObjRotation[this.root.uuid];ye.spaceRotation[this.clip.uuid].copy(t);{let i=new la.Euler().setFromQuaternion(t);console.log("START",this.clip.name,K.toDegrees(i.y))}}getClipRotationOffset(){return ye.clipOffsetRotation[this.clip.uuid]}handlePosition(e,t){if(t){let i=this.root;Ic&&i.add(new fv),ye.lastObjPosition[i.uuid]||(ye.lastObjPosition[i.uuid]=new yo);let n=new yo,r=new yo,o=0;this.positionWrapper=new aa(t,(s,c)=>{let d=this.action.getEffectiveWeight();if(Ic&&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(ye.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(Ic){let s=t.values,c=new mp().setFromQuaternion(new It(s[0],s[1],s[2],s[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",K.toDegrees(c.y));let d=t.values.length-4,a=new It().set(s[d],s[d+1],s[d+2],s[d+3]),u=new mp().setFromQuaternion(a);console.log(e.name,t.name,"LAST ROTATION IN TRACK",K.toDegrees(u.y))}let i=this.root;ye.lastObjRotation[i.uuid]||(ye.lastObjRotation[i.uuid]=new It);let n=0,r=new It,o=new It;this.rotationWrapper=new aa(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(ye.identityQuaternion,1-e)}},At=ye;N(At,"lastObjPosition",{}),N(At,"lastObjRotation",{}),N(At,"firstKeyframeRotation",{}),N(At,"spaceRotation",{}),N(At,"effectiveSpaceRotation",{}),N(At,"clipOffsetRotation",{}),N(At,"identityQuaternion",new It);var Ac=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 At(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 yo;summedRotation=new It;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),At.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 gv=H("debuganimator"),Zt=class extends D{applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof Ei?this._animatorController=e:this._animatorController=new Ei(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=K.lerp(e.x,e.y,Math.random())}set minMaxOffsetNormalized(e){this.normalizedStartOffset=K.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}gv&&console.log("ANIMATOR",this.name,this)}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.Reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}};k([O()],Zt.prototype,"applyRootMotion",2),k([O()],Zt.prototype,"hasRootMotion",2),k([O()],Zt.prototype,"keepAnimatorControllerStateOnDisable",2),k([O()],Zt.prototype,"runtimeAnimatorController",1);import*as bp from"three";import*as Eo from"three";import{PositionalAudioHelper as bv}from"three/examples/jsm/helpers/PositionalAudioHelper.js";var $e=H("debugaudio");var Pe=class extends D{static get userInteractionRegistered(){return Pe._didCallBeginWaitForUserInteraction||(Pe._didCallBeginWaitForUserInteraction=!0,Pe._beginWaitForUserInteraction()),Pe._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),Pe._didCallBeginWaitForUserInteraction||(Pe._didCallBeginWaitForUserInteraction=!0,Pe._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);let i=(()=>{if(i!=null&&!Pe._userInteractionRegistered){Pe._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&&($e&&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&&Pe._userInteractionRegistered){let e=A.getComponent(this.context.mainCamera,wi)??A.findObjectOfType(wi,this.context);e?.listener&&(this.sound=new Eo.PositionalAudio(e.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}_focusCallback;awake(){this.audioLoader=new Eo.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&&Pe._userInteractionRegistered&&this.play()},this.context.application.addEventListener("application-visible",this._focusCallback)}onDestroy(){this.context.application.removeEventListener("application-visible",this._focusCallback)}onEnable(){Pe._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Pe._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){$e&&console.log("audio buffer loaded"),Pe.registerWaitForAllowAudio(()=>{$e&&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(),$e&&console.log(this.name,this.shouldPlay,Pe.userInteractionRegistered,this),this.shouldPlay&&Pe._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($e&&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?$e&&!this.helper&&(this.helper=new bv(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&($e&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new Eo.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){$e&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,$e&&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,$e&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying&&this.sound.play()}pause(){$e&&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(){$e&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&(this._lastContextTime=this.sound?.context.currentTime,$e&&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,$e&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},le=Pe;N(le,"_didCallBeginWaitForUserInteraction",!1),N(le,"callbacks",[]),N(le,"_userInteractionRegistered",!1),k([O()],le.prototype,"clip",2),k([O()],le.prototype,"playOnAwake",2),k([O()],le.prototype,"loop",1),k([O()],le.prototype,"spatialBlend",1),k([O()],le.prototype,"minDistance",1),k([O()],le.prototype,"maxDistance",1),k([O()],le.prototype,"volume",1),k([O()],le.prototype,"rollOffMode",2);import*as _i from"three";import{Color as vv}from"three";var xe=class extends vv{alpha=1;get isRGBAColor(){return!0}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=K.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 Ev}from"three";var gp=H("debugcam"),de=class extends D{get aspect(){return this._cam instanceof Ev?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 _i.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){e!==this._clearFlags&&(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(){gp&&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 _i.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),t.fov=this.fieldOfView;else{let i=this.orthographicSize*100;t=new _i.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.environmentIsTransparent()&&(!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.environmentIsTransparent()&&(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}}environmentIsTransparent(){let e=this.context.renderer.xr?.getSession();if(!e)return!1;let t=e.environmentBlendMode,i=t==="additive"||t==="alpha-blend";return t==="opaque"&&navigator.userAgent?.includes("OculusBrowser")&&this.context.xrSessionMode==="immersive-ar"?!0:i}enableSkybox(){this._skybox||(this._skybox=new Mc(this)),this._skybox.enable()}};k([O()],de.prototype,"fieldOfView",1),k([O()],de.prototype,"nearClipPlane",1),k([O()],de.prototype,"farClipPlane",1),k([O()],de.prototype,"clearFlags",1),k([O()],de.prototype,"orthographic",2),k([O()],de.prototype,"orthographicSize",2),k([O()],de.prototype,"ARBackgroundAlpha",2),k([O(xe)],de.prototype,"backgroundColor",1);var Mc=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?(gp&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=_i.sRGBEncoding,this._skybox.mapping=_i.EquirectangularReflectionMapping,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this)}};var wi=class extends D{get listener(){return this._listener==null&&(this._listener=new bp.AudioListener),this._listener}_listener=null;awake(){le.registerWaitForAllowAudio(()=>{let e=this.listener;if(e==null||e.parent)return;let t=A.getComponentInParent(this.gameObject,de);t?t.cam.add(e):this.gameObject.add(e)})}};import{GLTFLoader as wv}from"three/examples/jsm/loaders/GLTFLoader";import*as ca from"three";var wo=H("debugavatar"),_o=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))}},mr=class{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){let r=new He;i=A.instantiate(ln(t,e.scene),r)}}else i=t;if(!i)return null;let n=this.findAvatar(i);return n.isValid?(wo&&console.log("[Custom Avatar] valid config",t,wo?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,wo?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(wo&&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 Xs(t,t,0,"no url here go away",!0),!r)?null:(await Ze().parseSync(e,r,null,0))?.scene??null}let i=new wv;return sa(i,e),new Promise((n,r)=>{let o=this.avatarRegistryUrl+"/"+t;i.load(o,async s=>{await Ze().createBuiltinComponents(e,o,s,null,void 0),n(s.scene)},s=>{wo&&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","hand"]),o=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;let c=new ca.Vector3;new ca.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 _o(t,n,r,o)}findAvatarPart(e,t){let i=e.name.toLowerCase(),n=!0;for(let r of t){if(!n)break;i.indexOf(r)===-1&&(n=!1)}if(n)return e;if(e.children)for(let r of e.children){let o=this.findAvatarPart(r,t);if(o)return o}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}};import{AxesHelper as _v}from"three";var Tn=class extends D{length=1;depthTest=!0;isGizmo=!0;_axes=null;onEnable(){if(this.isGizmo&&!Ut)return;this._axes||(this._axes=new _v(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([O()],Tn.prototype,"length",2),k([O()],Tn.prototype,"depthTest",2),k([O()],Tn.prototype,"isGizmo",2);import*as vp from"three";var da=class extends D{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=G(this.to).clone(),t=G(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=G(this.hint).clone();o.sub(r);let s=new vp.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),u=s.clone();u.multiplyScalar(a),u.add(r),ne(this.gameObject,u);let h=r.clone();h.sub(s),this.gameObject.lookAt(h)}};import*as xi from"three";import*as $t from"three";var xv=new $t.BoxGeometry(1,1,1);function ha(l=null){let e=new $t.Color(l??14540253),t=new $t.EdgesGeometry(xv);return new $t.LineSegments(t,new $t.LineBasicMaterial({color:e}))}var Cv=H("gizmos"),ua=class extends D{box=null;testBox=new xi.Box3;_lastMatrixUpdateFrame=-1;isInBox(e){if(!!e){if(this.box||(this.box=new xi.Box3),this.updateBox(!1),e.type==="Mesh")this.testBox.setFromObject(e);else{let t=G(e,ua._position),i=ws(e,ua._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 xi.Box3),(e||this.context.time.frameCount!=this._lastMatrixUpdateFrame)&&(this._lastMatrixUpdateFrame=this.context.time.frameCount,this.box.setFromCenterAndSize(new xi.Vector3(0,0,0),new xi.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(!(!Cv&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=ha(e),this.gameObject.add(this._helper)}}},yt=ua;N(yt,"_position",new xi.Vector3),N(yt,"_size",new xi.Vector3(.01,.01,.01));import*as Cn from"three";import{Vector3 as yp}from"three";var qi=class extends D{mass=1;set isKinematic(e){this._isKinematic=e,this._body&&(this._body.type=e?z.KINEMATIC:z.DYNAMIC)}get isKinematic(){return this._isKinematic}_isKinematic=!1;drag=0;angularDrag=1;detectCollisions=!0;sleepThreshold=.01;get body(){return this._body===null&&this.initialize(),this._body}_body=null;currentVelocity;_smoothedVelocity;lastWorldPosition;_ignoreChange=!1;_dirty=!1;_positionWatch;_matrixWatch;_setMatrix;constructor(){super(),this._setMatrix=new Cn.Matrix4}awake(){this._body=null,this.currentVelocity=new Cn.Vector3,this._smoothedVelocity=new Cn.Vector3,this.lastWorldPosition=G(this.gameObject).clone(),this._matrixWatch=void 0,this._positionWatch=void 0}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._positionWatch||(this._positionWatch=new Mi(this.gameObject.position,["x","y","z"])),this._positionWatch.subscribeWrite(e=>{!this.context.physics.isUpdating&&!this._ignoreChange&&(this._dirty=!0,this._setMatrix.copy(this.gameObject.matrix),this._setMatrix.setPosition(this.gameObject.position))})}onDisable(){this._body&&this.context.physics.removeBody(this.gameObject,this._body,!1)}onDestroy(){this._body&&this.context.physics.removeBody(this.gameObject,this._body)}onBeforeRender(){this._ignoreChange=!0,this.updateVelocity(),this._dirty&&(this._dirty=!1,this._setMatrix.decompose(this.gameObject.position,this.gameObject.quaternion,this.gameObject.scale),this.setBodyFromGameObject()),this._ignoreChange=!1}initialize(){if(this._body)return;let e=new Hs;e.drag=this.drag,e.angularDrag=this.angularDrag,e.mass=this.mass,e.kinematic=this.isKinematic,e.physicsEvents=this.detectCollisions,e.sleepThreshold=this.sleepThreshold,this._body=this.context.physics.createBody(this.gameObject,e)}wakeUp(){this.body?.wakeUp()}applyForce(e,t){let i=new _(e.x,e.y,e.z);i.scale(1/this.context.time.deltaTime,i),this.body?.applyForce(i,t?new _(t.x,t.y,t.z):void 0)}setForce(e,t,i){this.body?.force.set(e,t,i)}getVelocity(){return this.body?qi.tempPosition.set(this.body?.velocity.x,this.body?.velocity.y,this.body?.velocity.z):qi.tempPosition.set(0,0,0)}setVelocity(e,t,i){if(!!this.body){if(e instanceof yp){let n=e;e=n.x,t=n.y,i=n.z}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}}getTorque(){return this.body?qi.tempPosition.set(this.body?.torque.x,this.body?.torque.y,this.body?.torque.z):qi.tempPosition.set(0,0,0)}setTorque(e,t,i){if(!!this.body){if(e instanceof yp){let n=e;e=n.x,t=n.y,i=n.z}this.body.torque.x=e/this.context.time.deltaTime,this.body.torque.y=t/this.context.time.deltaTime,this.body.torque.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.body&&this.gameObject&&!this.destroyed){this._ignoreChange=!0;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){qi.copyVector3.set(e.x,e.y,e.z),this._smoothedVelocity.lerp(qi.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}this._ignoreChange=!1}}updateVelocity(){if(!!this.currentVelocity&&this.body&&this.gameObject){let e=G(this.gameObject);this.currentVelocity.subVectors(e,this.lastWorldPosition),this.lastWorldPosition.copy(e),this._smoothedVelocity.lerp(this.currentVelocity,this.context.time.deltaTime/.1)}}},ae=qi;N(ae,"tempPosition",new Cn.Vector3),N(ae,"copyVector3",new Cn.Vector3),k([O()],ae.prototype,"mass",2),k([O()],ae.prototype,"isKinematic",1),k([O()],ae.prototype,"drag",2),k([O()],ae.prototype,"angularDrag",2),k([O()],ae.prototype,"detectCollisions",2),k([O()],ae.prototype,"sleepThreshold",2);import{Vector3 as gr}from"three";var Dc=class{getCollider(e){return Fi(e,Ti)}};Fu(new Dc);var Ti=class extends D{get isCollider(){return!0}attachedRigidbody=null;isTrigger=!1;_shape=null;awake(){super.awake(),this._shape=null}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(ae))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(ae))}onDisable(){this._shape}};k([O(ae)],Ti.prototype,"attachedRigidbody",2),k([O()],Ti.prototype,"isTrigger",2);var br=class extends Ti{radius=.5;center=new gr(0,0,0);onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addSphereCollider(this.gameObject,this.center,this.radius,this.attachedRigidbody))}};k([O()],br.prototype,"radius",2),k([O(gr)],br.prototype,"center",2);var vr=class extends Ti{size=new gr(1,1,1);center=new gr(0,0,0);onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addBoxCollider(this.gameObject,this.isTrigger,this.center,this.size,this.attachedRigidbody))}};k([O(gr)],vr.prototype,"size",2),k([O(gr)],vr.prototype,"center",2);var ei=class extends D{canGrab=!0;onPointerClick(e){}},ti=class extends D{isUsed=!0;usedBy=null};var xo=class extends yt{},pa=class extends D{deleteBoxes=[];awake(){this.deleteBoxes=A.findObjectsOfType(xo,this.context)}update(){for(let e of this.deleteBoxes){let t=this.gameObject;e.isInBox(t)===!0&&(A.getComponentInParent(this.gameObject,ti)||Ps(this.gameObject,this.context.connection))}}};var To=class extends D{visibleOn;onEnable(){this.apply()}apply(){this.test()||A.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:Rv()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}};k([O()],To.prototype,"visibleOn",2);var fa;function Rv(){if(fa===!0||fa===!1)return fa;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),fa=l,l}import*as Ci from"three";var Ee=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 yr=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Ee).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Ee).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Ee).__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 Et=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 Et).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+4),(t||new Et).__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 yr).__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 Xi=H("debugsync"),Er="STRS";dr(Er,Et.getRootAsSyncedTransformModel);var ii=new nt;function Lc(l,e,t=!0){ii.clear();let i=ii.createString(l);Et.startSyncedTransformModel(ii),Et.addGuid(ii,i),Et.addFast(ii,t);let n=e.worldPosition,r=e.worldEuler,o=e.gameObject.scale;Et.addTransform(ii,yr.createTransform(ii,n.x,n.y,n.z,r.x,r.y,r.z,o.x,o.y,o.z));let s=Et.endSyncedTransformModel(ii);return ii.finish(s,Er),ii.asUint8Array()}var Mt=class extends D{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(){Xi&&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(){Xi&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new Ci.Vector3,this._targetRotation=new Ci.Quaternion,this.lastWorldPos=new Ci.Vector3,this.lastWorldRotation=new Ci.Quaternion,this.rb=A.getComponentInChildren(this.gameObject,ae),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new zi(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(Er,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Eu(this.guid,this.context.connection),this._model=null,this.context.connection.stopListening("joined-room",this.joinedRoomCallback),this.context.connection.stopListenBinary(Er,this.receivedDataCallback)}tryGetLastState(){let e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new Ci.Euler;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){Xi&&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){ie.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)&&cu(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){Xi&&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:(Xi&&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),ie.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&&ie.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&&(Xi&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new Ci.Vector3(0,0,0))>1e3&&(Xi&&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)){Xi&&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=Lc(this.guid,this,!!n);this.context.connection.sendBinary(r)}}};import*as $ 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(){u.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 u=null;async function h(E){E.addEventListener("end",f),await e.xr.setSession(E),i.textContent="STOP AR",t.domOverlay.root.style.display="",u=E}function f(){u.removeEventListener("end",f),i.textContent="START AR",t.domOverlay.root.style.display="none",u=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(){u===null?navigator.xr.requestSession("immersive-ar",t).then(h):u.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 ga=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(u){u.addEventListener("end",a),await e.xr.setSession(u),i.textContent="EXIT VR",c=u}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 u={optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};navigator.xr.requestSession("immersive-vr",u).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(),ga.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"),ga.xrSessionIsGranted=!0})}catch(e){console.error(e)}}},wr=ga;N(wr,"xrSessionIsGranted",!1);wr.registerSessionGrantedListener();import*as ge from"three";import{Matrix4 as zv,Vector3 as Uv}from"three";import*as ba from"three";var Ep=$o(Us(),1);import{AudioAnalyser as Sv}from"three";var _r="noVoip",et=H("debugvoip"),Pv=H("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(){et&&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 st.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}et&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),et&&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=>{et&&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){et&&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,le.userInteractionRegistered||et&&console.log("Incoming call, waiting for user interaction before opening audio"),le.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){et&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);let t=new ba.AudioListener;this.audio=new ba.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}}}),et&&console.log("call is setup, you should hear something now"),this.analyzer=new Sv(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()}},st=class extends D{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(H(_r)){console.log("VOIP is disabled by url parameter: "+_r);return}if(this.requireParam&&!Pv){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 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];et&&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){et&&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){et&&console.log("CONNECTION",t),t.on("data",function(i){et&&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(),et&&console.log("received call"),await st.HasMicrophonePermissions()){let o=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(o)}else e.answer(null);this.currentIncomingCalls[i]=new Bc(this,this.gameObject,e),e.on("stream",o=>{et&&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 xr=H("debugflags");var Fc=class{Mask=17;Has(e){let t=this.Mask&e;return xr&&console.log("HAS",e,this.Mask,"Result="+t),t!==0}Set(e){this.Mask=e,Oe.Apply()}Enable(e){this.Mask|=e,Oe.Apply()}Disable(e){this.Mask&=~e,Oe.Apply()}Toggle(e){this.Mask^=e,Oe.Apply()}EnableAll(){this.Mask=-1,Oe.Apply()}DisableAll(){this.Mask=0,Oe.Apply()}},Dt=Fc;N(Dt,"Global",new Fc);var ni=class extends D{static Apply(){for(let e of this.registry)e.UpdateVisible(Dt.Global)}awake(){ni.registry.push(this)}onEnable(){ni.firstApply||(ni.firstApply=!0,ni.Apply())}onDestroy(){let e=ni.registry.indexOf(this);e>=0&&ni.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),xr&&console.log(i),ni.buffer.Mask=i,e=ni.buffer);let n=e;if(n?(xr&&console.log("use passed in mask"),t=n.Has(this.visibleIn)):(xr&&console.log("use global mask"),Dt.Global.Has(this.visibleIn)),t!==void 0)if(t)xr&&console.trace("is visible",this.name,this.gameObject.uuid),A.setActive(this.gameObject,!0);else{if(xr&&console.trace("is not visible",this.name,this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},Oe=ni;N(Oe,"registry",[]),N(Oe,"firstApply"),N(Oe,"buffer",new Dt);import*as Z from"three";import{XRControllerModelFactory as jv}from"three/examples/jsm/webxr/XRControllerModelFactory.js";import{OculusHandModel as Bv}from"three/examples/jsm/webxr/OculusHandModel.js";import{OculusHandPointerModel as Fv}from"three/examples/jsm/webxr/OculusHandPointerModel.js";import*as xp from"three";import*as Ht from"three";var Qi=H("debugavatar"),Lt=class extends D{static getAvatar(e){return e>=0&&e<Lt.instances.length?Lt.instances[e]:null}static onAvatarMarkerCreated(e){return Lt._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return Lt._onAvatarMarkerDestroyed.push(e),e}connectionId;avatar;awake(){Lt.instances.push(this),Qi&&console.log(this);for(let e of Lt._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Lt.instances.splice(Lt.instances.indexOf(this),1);for(let e of Lt._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):A.setActive(this.avatar,e))}},he=Lt;N(he,"instances",[]),N(he,"_onNewAvatarMarkerAdded",[]),N(he,"_onAvatarMarkerDestroyed",[]);var Ro=class{_isVisible=!0;setVisible(e){this._isVisible=e,this.updateVisibility()}get isWebXRAvatar(){return!0}guid;root=null;head=null;handLeft=null;handRight=null;lastUpdate=-1;isLocalAvatar=!1;flags=null;headScale=new Ht.Vector3(1,1,1);handLeftScale=new Ht.Vector3(1,1,1);handRightScale=new Ht.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 Ht.Object3D;_handLeftTarget=new Ht.Object3D;_handRightTarget=new Ht.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)){let i=this.webxr.IsInAR?"handheld":"headset",n=this.head;this.context.players.setPlayerView(e.guid,n,i),ie.markDirty(this.head),this._canInterpolate=!0;let r=this.isLocalAvatar?this.head:this._headTarget;if(r.position.set(e.position.x,e.position.y,e.position.z),r.quaternion.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),r.scale.set(e.scale,e.scale,e.scale),r.scale.multiply(this.headScale),this.handLeft){let o=this.isLocalAvatar?this.handLeft:this._handLeftTarget;o.position.set(e.posLeftHand.x,e.posLeftHand.y,e.posLeftHand.z),o.quaternion.set(e.rotLeftHand._x,e.rotLeftHand._y,e.rotLeftHand._z,e.rotLeftHand._w),o.quaternion.multiply(Ro.invertRotation),o.scale.set(e.scale,e.scale,e.scale),o.scale.multiply(this.handLeftScale),ie.markDirty(this.handLeft)}if(this.handRight){let o=this.isLocalAvatar?this.handRight:this._handRightTarget;o.position.set(e.posRightHand.x,e.posRightHand.y,e.posRightHand.z),o.quaternion.set(e.rotRightHand._x,e.rotRightHand._y,e.rotRightHand._z,e.rotRightHand._w),o.quaternion.multiply(Ro.invertRotation),o.scale.set(e.scale,e.scale,e.scale),o.scale.multiply(this.handRightScale),ie.markDirty(this.handRight)}}}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(){Qi&&console.log("Destroy avatar",this.guid),this.root?.removeFromParent(),this.avatarMarker?.destroy(),this.lastAvatarId=null,this.head&&Te.Remove(this.context,this.head)}updateVisibility(){let e=this.root;e&&A.setActive(e,this._isVisible)}async setupCustomAvatar(e){if(Qi&&console.log("LOAD",e,this),!e||typeof e=="string"&&e.length<=0)return!1;this.head&&Te.Remove(this.context,this.head);let t=e;if(t?.loadAssetAsync!==void 0){await t.loadAssetAsync();let n=t.asset;A.setActive(n,!1),e=A.instantiate(n),A.setActive(e,!0)}Qi&&console.log(e);let i=await Ro.loader.getOrCreateNewAvatarInstance(this.context,e);if(Qi&&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=A.addNewComponent(this.root,he),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&&Te.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(...A.getComponentsInChildren(this.root,Oe)),this.flags.length<=0&&this.head){let n=A.addNewComponent(this.head,Oe);n.visibleIn=20,this.flags.push(n),Qi&&console.log("Added flag to head: "+n.visibleIn,this.head.name)}return Qi&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return Qi&&console.warn("build avatar failed"),!1}},ri=Ro;N(ri,"loader",new mr),N(ri,"invertRotation",new Ht.Quaternion().setFromAxisAngle(new Ht.Vector3(0,1,0),Math.PI));var Te=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??J.Current?.time.time;return}}}};N(Te,"Pois",[]),N(Te,"LastChangeTime",0);var Nc=class{guid;position=new xp.Vector3},Rn=class extends D{set controlledTarget(e){this.target=e;let t=Zr.get("MoveRandom");if(t&&this.target){let i=A.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=A.getComponentInParent(this.gameObject,he),this.avatar){let e=A.getComponentInParent(this.gameObject,he);this._model=new zi(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&&ne(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(Te.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Te.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){let t=G(this._currentTargetObject);ne(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=Te.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}}}}};import*as va from"three-mesh-ui";import{OrbitControls as kv}from"three/examples/jsm/controls/OrbitControls";import{Object3D as Ov}from"three";var Sn=class extends D{constraintActive=!0;locked=!1;sources=[]};k([O(Ov)],Sn.prototype,"sources",2);import*as So from"three";var Tp=H("nocamlimits"),Ri=class extends D{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;_startedListeningToKeyEvents=!1;awake(){this._lookTargetPosition=new So.Vector3,this._startedListeningToKeyEvents=!1}onEnable(){this._enableTime=this.context.time.time;let t=A.getComponent(this.gameObject,de)?.cam;this._controls||(console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t),this._controls=new kv(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"?Tp||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):Tp||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body)))}onDisable(){this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1)}onDestroy(){this._controls?.dispose()}start(){if(this._controls){let e=A.getComponent(this.gameObject,de);if(e&&!this.setFromTargetPosition()){this.debugLog&&console.log("NO TARGET");let t=new So.Vector3(0,0,-1).applyMatrix4(e.cam.matrixWorld);this.setTarget(t,!0)}}this.startCoroutine(this.startRaycastDelayed())}*startRaycastDelayed(){if(yield,!this.setFromTargetPosition()){let e=new Se;e.screenPoint=new So.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&&A.isActiveInHierarchy(t.object)){if(this._lookTargetPosition.copy(t.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;let i=G(this.context.mainCamera);this._cameraTargetPosition=i.clone().sub(this.controls.target).add(this._lookTargetPosition)}break}}};k([O(Sn)],Ri.prototype,"lookAtConstraint",2);var Si=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 Mv}from"three";var Dv=H("debugeventsystem"),oi=class extends D{static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,oi.systems.length<=0&&oi.systems.push(...A.findObjectsOfType(oi,e)));for(let i of oi.systems)if(i.context===e)return;let t=new Mv;A.addNewComponent(t,oi),e.scene.add(t)}static ensureUpdateMeshUI(e,t){jt.update(e,t)}static markUIDirty(e){jt.markDirty()}static get instance(){return this.systems[0]}orbitControl=null;orbitControlWasEnabled=!1;raycaster=[];constructor(){super(),oi.systems.push(this)}onDestroy(){oi.systems.splice(oi.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)}_selectStartFn;_selectEndFn;_selectUpdateFn;onEnable(){this._selectStartFn??=(t,i)=>{if(!i.grab)return;jt.resetLastSelected();let n=new Si;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)},this._selectEndFn??=(t,i)=>{if(!i.grab)return;let n=new Si;n.inputSource=t,n.isDown=t.selectionDown,n.isUp=t.selectionUp,n.isPressed=t.selectionPressed,n.isClicked=t.selectionClick,this.handleEvents(i.grab,n)};let e=new Se;this._selectUpdateFn??=t=>{e.ray=t.getRay();let i=this.performRaycast(e);if(!i)return;let n=new Si;n.inputSource=t,this.handleIntersections(i,n)},ce.addEventListener("select-start",this._selectStartFn),ce.addEventListener("select-end",this._selectEndFn),ce.addEventListener("update",this._selectUpdateFn),this.context.pre_update_callbacks.push(this.onBeforeUpdate.bind(this)),this.context.input.addEventListener("pointerdown",this.onPointerDown.bind(this))}onDisable(){ce.removeEventListener("select-start",this._selectStartFn),ce.removeEventListener("select-end",this._selectEndFn),ce.removeEventListener("update",this._selectUpdateFn)}onPointerDown(){this.onBeforeUpdate()}lastPointerEvent=null;objectsHoveredThisFrame=[];objectsHoveredLastFrame=[];raisedPointerDownEvents=[];_didMove=!1;onBeforeUpdate(){if(this.objectsHoveredThisFrame.length=0,this.resetMeshUIStates(),Y.IsInWebXR||this.context.input.isKeyPressed("Alt"))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 Si(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=A.getComponent(this.context.mainCameraComponent.gameObject,Ri)??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=A.getComponentsInParent(t,D,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=[];out={};handleEvents(e,t){if(!this.testIsVisible(e))return t.isClicked&&Dv&&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[at]){let c=i[at].gameObject;if(c){if(!Pi.isInteractable(c,this.out))return this.out.canvasGroup?.interactable??!1;o=this.out.canvasGroup??null;let a=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=A.getComponentsInParent(e,D,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=jt.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&jt.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){let t=this.currentActiveMeshUIComponents[e];jt.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?A.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}},tt=oi;N(tt,"didSearchEventSystem",!1),N(tt,"systems",[]);var jt=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}};N(jt,"lastSelected",null),N(jt,"lastUpdateFrame",[]),N(jt,"needsUpdate",!1);import{AxesHelper as Hv}from"three";var Tr="./include";va.Block.prototype.interactable={get(){return this.interactive},set(l){this.interactable=l}};var at=Symbol("shadowDomOwner"),Ge=class extends D{isRoot(){return this.Root?.gameObject===this.gameObject}markDirty(){tt.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=A.getComponentInParent(this.gameObject,Pn)),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=A.getComponentInParent(i,Ge),!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[at]=this,e.traverse(r=>{r[at]===void 0&&(r[at]=this)});let n=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{let r=this._parentComponent.shadowComponent;r&&(r?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),Ut&&e.add(new Hv(.5)),this.onAfterAddedToScene(),n&&va.update()}set(e){}traverseOwnedShadowComponents(e,t,i){if(!!e&&e[at]===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)}},Pn=class extends Ge{awake(){super.awake()}};var Pi=class{static getObject(e){let t=e[at];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;let i=this.tryFindCanvasGroup(e);if(i?.isCanvasGroup===!0&&(t&&(t.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;let n=gt(e,r=>{if(r.isGraphic===!0)return r},!1);return t&&n?.isGraphic===!0&&(t.graphic=n),n?.raycastTarget!==!1}static tryFindCanvasGroup(e){if(!e)return null;let t=gt(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)}};var zc=H("debugwebxrcontroller");var Po=class extends D{},ke=class extends D{static CreateRaycastLine(){let e=new Z.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 Z.SphereGeometry(.5,22,22),t=new Z.MeshBasicMaterial({color:this.raycastColor}),i=new Z.Mesh(e,t);return i.visible=!1,i.layers.set(1),i}static Create(e,t,i,n){let r=i?A.addNewComponent(i,ke,!1):new ke;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 Bv(r.hand)),r.hand.traverse(s=>s.layers.set(2)),r.handPointerModel=new Fv(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 u=d[a];u.parent||r.hand.add(u)}}}),r}static addEventListener(e,t){let i=this.eventSubs[e]??[];i.push(t),this.eventSubs[e]=i}static removeEventListener(e,t){if(!t)return;let i=this.eventSubs[e]??[],n=i.indexOf(t);n>=0&&i.splice(n,1),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 Z.Quaternion),we(e).multiply(this._wristQuaternion.setFromEuler(new Z.Euler(-Math.PI/4,0,0)))):null}movementVector=new Z.Vector3;worldRot=new Z.Quaternion;joystick=new Z.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=ke.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=ke.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._raycastHitPoint.visible=!1,this.hand.add(this.handPointerModel),zc&&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 Z.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=ke.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(we(this.controller),this.useSmoothing?t:1);let i=G(this.controller);if(this.raycastLine)if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed,ne(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)}Ue(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=!0,Ue(this.raycastLine,this.rayRotation),ne(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*ke.MovementSpeedFactor,r=2,o=K.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),this.movementVector.multiplyScalar(n*this.context.time.deltaTime),t.position.add(this.movementVector),this.isUsingHands&&this.runTeleport(t,i);break;case"right":let u=this.joystick.x,h=Math.abs(u);if(h<.4)this.didRotate=!1;else if(h>.5&&!this.didRotate){let f=u>0?-1:1;t.rotateY(K.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&&this.webXR.IsInVR,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.webXR.IsInVR){this.didChangeScale=!0;let d=this.webXR.Rig;if(d)if(r){r=!1,d.scale.set(1,1,1),o=1,ke.MovementSpeedFactor=1;let a=this.context.mainCamera;ke.PreviousCameraFarDistance&&(a.far=ke.PreviousCameraFarDistance)}else{r=!0,n=!0,o=.1,ke.MovementSpeedFactor=o*2;let a=this.context.mainCamera;ke.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;ne(e,d)}}}}else i<.1&&(this.didTeleport=!1);o!==null&&(e.scale.set(o,o,o),e.updateMatrixWorld())}isValidTeleportTarget(e){return A.getComponentInParent(e,Po)!=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=ke.raycastColor:n.color=ke.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;let n=K.clamp(this.lastHit.distance*.01*i,.015,.1);this._raycastHitPoint.scale.set(n,n,n)}this._raycastHitPoint.visible=this.lastHit!==null&&this.lastHit!==void 0}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;this.lastSelectStartObject=n;let r={selected:n,grab:n},o=ke.eventSubs["select-start"];if(o&&o.length>0)for(let s of o)s(this,r);r.grab!==n&&zc&&console.log("Grabbed object changed","original",n,"new",r.grab),r.grab&&(this.grabbed=wt.TryTake(this,r.grab,i,t));break}else{let i=ke.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=ke.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||A.isActiveInHierarchy(e)===!1||Pi.isInteractable(e)===!1)}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 Z.Ray;return e.origin.copy(G(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=G(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){let e=new Se;e.layerMask=new Z.Layers,e.layerMask.set(0),e.ray=this.getRay();let t=this.context.physics.raycast(e);for(let i=0;i<t.length;i++){let n=t[i],r=n.object;if(!this.testIsVisible(r)){t.splice(i,1),i--;continue}n.object=Pi.getObject(r);break}return t}},ce=ke;N(ce,"Factory",new jv),N(ce,"raycastColor",new Z.Color(.9,.3,.3)),N(ce,"raycastNoHitColor",new Z.Color(.6,.6,.6)),N(ce,"geometry",new Z.BufferGeometry().setFromPoints([new Z.Vector3(0,0,0),new Z.Vector3(0,0,-1)])),N(ce,"handModels",{}),N(ce,"eventSubs",{}),N(ce,"PreviousCameraFarDistance"),N(ce,"MovementSpeedFactor",1);var qe=class{static AddEventListener(e,t){return qe.Events[e]||(qe.Events[e]=[]),qe.Events[e].push(t),t}static RemoveEventListener(e,t){if(!t||!qe.Events[e])return;let i=qe.Events[e].indexOf(t);i>=0&&qe.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=A.getComponentInParent(t,ei);if(!r)return zc&&console.warn("Prevented taking object that is not interactable",t),null;let o=t,s=A.getComponentInParent(t,Mt);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 qe;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};qe.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=A.addNewComponent(this.selected,ti),this.rigidbodies=A.getComponentsInChildren(this.selected,ae),G(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 u=e.isUsingHands&&s?this.controller.getWristQuaternion().clone():e.rayRotation.clone();we(this.selected,this.localQuaternionToGrab).premultiply(u.invert());let h=this.controller.webXR.Rig;return h&&this.rigPositionLastFrame.copy(G(h)),Te.Add(e.context,this.selected),qe.Register(this),this.sync&&(this.sync.fastMode=!0),qe.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};qe.Events.WillFree?.forEach(n=>n(this,e)),Te.Remove(this.controller.context,this.selected),qe.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,qe.Events.DidFree?.forEach(n=>n(this,e))}grabPoint=new Z.Vector3;localPositionOffsetToGrab=null;localPositionOffsetToGrab_worldSpace=new Z.Vector3;localQuaternionToGrab=new Z.Quaternion(0,0,0,1);targetDir=null;quaternionLerp=null;controllerDir=new Z.Vector3;controllerWorldPos=new Z.Vector3;lastControllerWorldPos=new Z.Vector3;controllerPosDelta=new Z.Vector3;totalChangeAlongDirection=0;rigPositionLastFrame=new Z.Vector3;controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),G(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=G(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 Z.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),Ue(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(G(this.selected)),i.sub(this.localPositionOffsetToGrab_worldSpace)),ne(this.selected,i)}if(this.rigidbodies!=null)for(let e of this.rigidbodies)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0});ie.markDirty(this.selected,!0)}}},wt=qe;N(wt,"Events",{}),N(wt,"Current",[]);import*as Cr from"three";var si=class extends D{webAR=null;get rig(){return this.webAR?.webxr.Rig}invertForward=!1;get arScale(){return this._arScale}set arScale(e){e!==this._arScale&&(this._arScale=e,this.setScale(e))}_initalMatrix=new Cr.Matrix4;_selectStartFn=this.onSelectStart.bind(this);_selectEndFn=this.onSelectEnd.bind(this);start(){let e=A.findObjectOfType(Y);e&&(e.Rig.updateMatrix(),this._initalMatrix.copy(e.Rig.matrix))}_arScale=5;_rig=null;_startPose=null;_placementPose=null;_isTouching=!1;_rigStartPose=null;onBegin(e){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose=this.gameObject.matrix.clone(),this._rigStartPose=this.rig?.matrix.clone(),e.addEventListener("selectstart",this._selectStartFn),e.addEventListener("selectend",this._selectEndFn),this.gameObject.visible=!1,this.rig&&(this.rig.matrixAutoUpdate=!0,this._initalMatrix.decompose(this.rig.position,this.rig.quaternion,this.rig.scale))}onUpdate(e,t,i){return i&&!this._placementPose&&this._isTouching?(this.webAR&&this.webAR.setReticleActive(!1),this.placeAt(e,new Cr.Matrix4().fromArray(i.transform.matrix).invert()),!0):!1}placeAt(e,t){if(this._placementPose||(this._placementPose=new Cr.Matrix4),this._placementPose.copy(t),e){if(this.invertForward){let i=new Cr.Matrix4().makeRotationY(Math.PI);this._placementPose.premultiply(i)}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.gameObject.matrixAutoUpdate=!1,this._startPose&&this.gameObject.matrix.copy(this._startPose),e&&(e.matrixAutoUpdate=!0,this._rigStartPose&&this._rigStartPose.decompose(e.position,e.quaternion,e.scale)),ie.markDirty(this.gameObject,!0),setTimeout(()=>{this.gameObject.matrixAutoUpdate=!0,this.gameObject.visible=!0},100)}onSelectStart(){this._isTouching=!0}onSelectEnd(){this._isTouching=!1}setScale(e){let t=this._rig;!t||!this._placementPose||(this._rigStartPose||(this._rigStartPose=t.matrix.clone()),t.matrixAutoUpdate=!1,t.matrix.multiplyMatrices(new Cr.Matrix4().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld(),console.log("Place",t.position))}};k([O()],si.prototype,"invertForward",2),k([O()],si.prototype,"arScale",1);var Rr=class extends D{awake(){}};import*as lt from"three";var ai=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 Ce=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 Ce).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+4),(t||new Ce).__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 Ee).__init(this.bb_pos+t,this.bb):null}rotation(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new ai).__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 Ee).__init(this.bb_pos+t,this.bb):null}posRightHand(e){let t=this.bb.__offset(this.bb_pos,18);return t?(e||new Ee).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){let t=this.bb.__offset(this.bb_pos,20);return t?(e||new ai).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){let t=this.bb.__offset(this.bb_pos,22);return t?(e||new ai).__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 Cp=H("debugxr"),Oo=H("debugavatar");var Vc="VRUS";dr(Vc,Ce.getRootAsVrUserStateBuffer);function Uc(){return new Date().getTime()}function Nv(l){let e=l&4294967295,t=l/Math.pow(2,32)&1048575;return Fe.create(e,t)}var ko=class{guid;time;avatarId;position=new lt.Vector3;rotation=new lt.Vector4;scale=1;posLeftHand=new lt.Vector3;posRightHand=new lt.Vector3;rotLeftHand=new lt.Quaternion;rotRightHand=new lt.Quaternion;constructor(e){this.guid=e}update(e,t,i,n,r){this.time=Uc(),this.avatarId=r,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let o=ko.quat0,s=ko.quat1;o.set(i.x,i.y,i.z,i.w),o=o.multiplyQuaternions(o,ko.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);Ce.startVrUserStateBuffer(e),Ce.addGuid(e,i),Ce.addTime(e,Nv(this.time)),Ce.addAvatarId(e,n),Ce.addPosition(e,Ee.createVec3(e,this.position.x,this.position.y,this.position.z)),Ce.addRotation(e,ai.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),Ce.addScale(e,this.scale),Ce.addPosLeftHand(e,Ee.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),Ce.addPosRightHand(e,Ee.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),Ce.addRotLeftHand(e,ai.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),Ce.addRotRightHand(e,ai.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));let r=Ce.endVrUserStateBuffer(e);e.finish(r,Vc);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()}},li=ko;N(li,"invertRotation",new lt.Quaternion().setFromAxisAngle(new lt.Vector3(0,1,0),Math.PI)),N(li,"quat0",new lt.Quaternion),N(li,"quat1",new lt.Quaternion);var On=class extends D{webXR=null;debugAvatarUser=null;voip=null;async awake(){if(this.webXR||(this.webXR=A.getComponent(this.gameObject,Y)),this.webXR||(this.webXR=A.findObjectOfType(Y,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=A.findObjectOfType(Y,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=A.findObjectOfType(st,this.context)),Oo){let e="debug-avatar-"+Oo,t=new ri(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof Oo=="string"&&Oo.length>0)if(await t.setAvatarOverride(Oo)){let i=new li(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=A.getComponent(this.gameObject,Y),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),Y.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),Y.addEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),Y.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 li("");onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;let i=new Date().getTime()-t;if(i>5e3)return Cp&&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 ri(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),Y.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),Y.removeEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),Y.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}update(){let e=Uc();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=Uc();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 ri(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(){Cp&&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 nt(1024);onXRSessionUpdate(e){this.xrState??=new li(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership??=new zi(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 H("avatar")??null}};async function Vv(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function Wv(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}var Wc=!1,Gc=!1;Vv().then(l=>Wc=l);Wv().then(l=>Gc=l);var Ie=class extends D{enableVR=!0;enableAR=!0;defaultAvatar;createVRButton=!0;createARButton=!0;static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(Wc||Gc)}static get IsARSupported(){return Wc}static get IsVRSupported(){return Gc}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){Ie.XRSupported||console.warn("WebXR is not supported on this device");let i=wr.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={};i&&(n.domOverlay={root:i},n.optionalFeatures=["hit-test","dom-overlay"]);let r=ma.createButton(e.context.renderer,n);return r.classList.add("webxr-ar-button"),r.classList.add("webxr-button"),Ie.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||this.ensureRig(),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}get IsInVR(){return this._isInVR}get IsInAR(){return this._isInAR}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=ot.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!A.findObjectOfType(On,this.context)){let e=A.addNewComponent(this.gameObject,On,!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 Pr(this);let e=Ie.XRSupported,t,i,n=document.createElement("div");n.classList.add("webxr-buttons"),this.context.domElement.append(n),this.enableAR&&this.createARButton&&(t=Ie.createARButton(this),this._arButton=t,n.appendChild(t)),this.createVRButton&&this.enableVR&&(e||!this.enableAR)&&(i=Ie.createVRButton(this),this._vrButton=i,n.appendChild(i)),setTimeout(()=>{Ie.resetButtonStyles(i),Ie.resetButtonStyles(t)},1e3)}_transformOrientation=new ge.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)}Ie._isInXr===!1&&t&&this.onEnterXR(t,e),Ie.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++)ce.Create(this,e,this.gameObject,0);Ie.events.dispatchEvent({type:"requestVRSession"})}}captureCameraState(){this.context.mainCamera&&(this._originalCameraPosition.copy(G(this.context.mainCamera)),this._originalCameraRotation.copy(we(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent)}ensureRig(){if(!this.rig){let e=A.findObjectOfType(Rr,this.context);e?(this.rig=e.gameObject,this.rig.rotateY(Math.PI)):(this.rig=new ge.Group,this.rig.rotateY(Math.PI),this.rig.name="XRRig",this.context.scene.add(this.rig))}}_originalCameraParent=null;_originalCameraPosition=new ge.Vector3;_originalCameraRotation=new ge.Quaternion;onEnterXR(e,t){console.log("[XR] session begin",e),Ie._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 ge.Quaternion(s.x,s.y,s.z,s.w),d=new ge.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(Dt.Global.Set(r),r){case 2:this.context.xrSessionMode="immersive-ar",this._isInAR=!0,this.webAR?.onBegin(e);break;case 4:this.context.xrSessionMode="immersive-vr",this._isInVR=!0,this.onEnterVR(e);break}e.addEventListener("end",()=>{console.log("[XR] session end"),Ie._isInXr=!1,this.onExitXR(e)}),this.onEnterXR_HandleMirrorWindow(e),Ie.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.context.xrSessionMode=void 0,this.xrMirrorWindow&&(this.xrMirrorWindow.close(),this.xrMirrorWindow=null),this.destroyControllers(),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),ne(this.context.mainCamera,this._originalCameraPosition),Ue(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),Dt.Global.Set(17),Ie.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){!H("mirror")||setTimeout(()=>{if(!Ie.IsInWebXR)return;let t=new URL(window.location.href);Kn(t.searchParams,_r,1),Kn(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=()=>{Ie.IsInWebXR&&e.end()})})},1e3)}},Y=Ie;N(Y,"_isInXr",!1),N(Y,"events",new ge.EventDispatcher),k([O(ot)],Y.prototype,"defaultAvatar",2);var Sr=class{get webxr(){return this._webxr}_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;noHitTestAvailable=!1;didPlaceARSessionRoot=!1;getAROverlayContainer(){return this.arDomOverlay=this.webxr.context.domElement,this.arDomOverlay.getAROverlayContainer?this.arOverlayElement=this.arDomOverlay.getAROverlayContainer():this.arOverlayElement=this.arDomOverlay,this.arOverlayElement}setReticleActive(e){this.reticleActive=e}async onBegin(e){let t=this.webxr.context;this.reticleActive=!0,this.didPlaceARSessionRoot=!1;let i=navigator.userAgent?.includes("OculusBrowser")?0:1;for(let n=0;n<4;n++)ce.Create(this.webxr,n,this.webxr.gameObject,i);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=A.findObjectOfType(si,t)),this.previousBackground=t.scene.background,this.previousEnvironment=t.scene.environment,t.scene.background=null,e.requestReferenceSpace("viewer").then(n=>{e.requestHitTestSource({space:n}).then(r=>{this.hitTestSource=r}).catch(r=>{this.noHitTestAvailable=!0,console.warn("WebXR: Hit test not supported")})}),!this.reticle&&this.sessionRoot&&(this.reticle=new ge.Mesh(new ge.RingGeometry(.07,.09,32).rotateX(-Math.PI/2),new ge.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,Sr.tempWebXRObject||(Sr.tempWebXRObject=new ge.Object3D),this.context.scene.add(Sr.tempWebXRObject),A.addComponent(Sr.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),A.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.noHitTestAvailable===!0){if(this.reticle&&(this.reticle.visible=!1),!this.didPlaceARSessionRoot){this.didPlaceARSessionRoot=!0;let n=this.webxr.Rig,r=Gv.clone();if(n){let o=new Uv(0,0,0).add(n.position).divideScalar(this.sessionRoot?.arScale??1);r.multiply(new zv().makeTranslation(o.x,o.y,o.z))}this.sessionRoot?.placeAt(n,r)}return}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){let s=this.sessionRoot.onUpdate(this.webxr.Rig,e,o);this.didPlaceARSessionRoot=s}if(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)}},Pr=Sr;N(Pr,"tempWebXRObject");var Gv=new ge.Matrix4().identity().makeTranslation(0,-.5,0);var qc=!1;var Or=class extends ei{static get HasAnySelected(){return this._active!==null}transformSelf=!0;selectStartEventListener=[];selectEndEventListener=[];constructor(){super(),this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new $.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)||Y.IsInWebXR)return;let t=A.getComponentInParent(e.object,Or);!t||t!==this||(Or.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){!this.allowEdit(this.gameObject)||Y.IsInWebXR||Or.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}_waitingForDragStart=null;onPointerDown(e){!this.allowEdit(this.gameObject)||Y.IsInWebXR||(this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation())}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&(Y.IsInWebXR||(this.onDragEnd(e),e.StopPropagation()))}update(){if(!Y.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 ya(this.context.mainCamera);else return;if(!e||!e.object)return;let t=A.getComponentInParent(e.object,Or);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=A.getComponentInChildren(i,Mt);qc&&console.log("DRAG START",r,i),r&&(r.fastMode=!0,r?.requestOwnership()),this._marker=A.addNewComponent(i,ti),this._draggingRigidbodies.length=0;let o=A.getComponentsInChildren(i,ae);o&&this._draggingRigidbodies.push(...o);let s=bl();A.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(qc&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context),e?.object){let n=A.getComponentInChildren(e.object,Mt);n&&(n.fastMode=!1),this._marker&&this._marker.destroy()}for(let n of this.selectEndEventListener)n(this);let i=bl();A.invokeOnChildren(t,i("onDragEnd"))}},Yi=Or;N(Yi,"_active",null),N(Yi,"lastHovered");var Xc=class{get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}_selected=null;_context=null;_camera;_cameraPlane=new $.Plane;_hasGroundPlane=!1;_groundPlane=new $.Plane;_groundOffset=new $.Vector3;_groundOffsetFactor=0;_groundDistance=0;_groundPlanePoint=new $.Vector3;_raycaster=new $.Raycaster;_cameraPlaneOffset=new $.Vector3;_intersection=new $.Vector3;_worldPosition=new $.Vector3;_inverseMatrix=new $.Matrix4;_rbs=[];_groundLine;_groundMarker;constructor(e){this._camera=e;let t=new $.Line(Xc.geometry),i=t.material;i.color=new $.Color(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;let n=new $.SphereGeometry(.5,22,22),r=new $.MeshBasicMaterial({color:i.color}),o=new $.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&&Te.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}Te.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this._rbs=A.getComponentsInChildren(this._selected,ae),this.onUpdateScreenSpacePlane()}}_groundOffsetVector=new $.Vector3(0,1,0);_requireUpdateGroundPlane=!0;_didDragOnGroundPlaneLastFrame=!1;onUpdate(e){if(!this._context)return;let t=" ",i="d",n="s",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)){qc&&console.log("UPDATE DRAG",this._selected),this._groundOffsetVector.set(0,1,0);let c=G(this._camera).clone().sub(G(this._selected)).normalize(),d=Math.abs(c.dot(this._groundOffsetVector)),a=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(i),u=!o&&d>.2&&!a&&this._context.input.getPointerPressedCount()<=1,h=this._didDragOnGroundPlaneLastFrame!==u;if(this._didDragOnGroundPlaneLastFrame=u,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!u||h)&&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,u){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);h&&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=G(this._selected);n.y=e.y,e=n}if(ne(this._selected,e),ne(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=t!==null,t){let n=G(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(n,n,n),ne(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=G(this._selected),t=new $.Ray(new $.Vector3(0,.1,0).add(e),new $.Vector3(0,-1,0)),i=new Se;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 $.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(){ie.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}},ya=Xc;N(ya,"geometry",new $.BufferGeometry().setFromPoints([new $.Vector3(0,0,0),new $.Vector3(0,-1,0)]));function Sp(l=window.location.hostname){return new RegExp("[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}|localhost","gm").test(l)===!0}var Oi=class extends D{url=null;urlParameterName=null;localhost=null;awake(){this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?Oi.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){let r=H(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=Oi.IsLocalNetwork()&&t;return n&&(i=t),e?.startsWith("/")&&(i=(n?i:window.location.origin)+e),i}static IsLocalNetwork(e=window.location.hostname){return Sp(e)}};var kr=class extends D{filesBackendUrl;localhost;_dragOver;_drop;onEnable(){this.filesBackendUrl=this.filesBackendUrl?Oi.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 ip(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 np(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 Se;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:t}))}};k([O()],kr.prototype,"filesBackendUrl",2),k([O()],kr.prototype,"localhost",2);import{Vector3 as qv,Quaternion as Xv,Object3D as Pp}from"three";var Ki=class extends ei{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 qv(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new Xv(0,0,0,1)}let e=A.getComponentInParent(this.gameObject,Yi);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),ce.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 He;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=A.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([O(Pp)],Ki.prototype,"parent",2),k([O(Pp)],Ki.prototype,"object",2),k([O()],Ki.prototype,"limitCount",2),k([O()],Ki.prototype,"limitInterval",2);var Ji=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)}}},Qv=l=>/^[A-Z]*$/.test(l),Io=class extends Event{args},Ae=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&&Qv(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 Io(this.key);i.args=e,t.call(this.target,i)}}}finally{this._isInvoking=!1}}addEventListener(e){return this.methods.push(new Ji(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 Ea=class extends D{};import{FlyControls as Yv}from"three/examples/jsm/controls/FlyControls";var wa=class extends D{_controls=null;onEnable(){let e=A.getComponent(this.gameObject,de)?.cam;this._controls=new Yv(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 Kv}from"three";var kn=class extends D{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!Ut||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new Op.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=ha(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([O()],kn.prototype,"objectBounds",2),k([O(Kv)],kn.prototype,"color",2),k([O()],kn.prototype,"isGizmo",2);import{GLTFExporter as Ry}from"three/examples/jsm/exporters/GLTFExporter.js";import{BufferAttribute as Qc,Matrix4 as Jv,Vector3 as kp,Quaternion as Zv}from"three";var Ao=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 Jv,s=new Array,c=new Array,d=new Array;for(let f=0;f<e.count;f++){e.getMatrixAt(f,o);let E=new kp,b=new Zv,y=new kp;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),u=new Float32Array(c),h=new Float32Array(d);r.attributes={TRANSLATION:i.processAccessor(new Qc(a,3)),ROTATION:i.processAccessor(new Qc(u,4)),SCALE:i.processAccessor(new Qc(h,3))},n[this.name]=!0}};import*as ci from"three";import*as Mo from"three";var In=class{get lightmap(){return this.lightmapTexture}set lightmap(e){e!==this.lightmapTexture&&(this.lightmapTexture=e,this.setupLightmap())}lightmapIndex=-1;lightmapScaleOffset=new Mo.Vector4(1,1,0,0);context;gameObject;lightmapTexture=null;lightmapScaleOffsetUniform={value:new Mo.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 Mo.ShaderMaterial({vertexShader:`
119
124
  attribute vec2 uv2;
120
125
  varying vec2 vUv2;
121
126
  void main()
@@ -147,9 +152,9 @@ irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
147
152
  // gl_FragColor = vec4(vUv2.xy, 0, 1);
148
153
  gl_FragColor = lightMapTexel;
149
154
  }
150
- `,defines:{USE_LIGHTMAP:""}})}};import{Vector4 as Ry}from"three";import{NeverStencilFunc as oy,LessStencilFunc as sy,EqualStencilFunc as ay,LessEqualStencilFunc as ly,GreaterStencilFunc as cy,NotEqualStencilFunc as dy,GreaterEqualStencilFunc as hy,AlwaysStencilFunc as uy,ZeroStencilOp as py,KeepStencilOp as fy,ReplaceStencilOp as my,IncrementStencilOp as gy,DecrementStencilOp as by,IncrementWrapStencilOp as vy,DecrementWrapStencilOp as yy,InvertStencilOp as Ey}from"three";var sd=B("debugstencil");function wy(c,e){return(c&1<<e.layer)!=0}var br=class{static applyStencil(e){if(!e)return;let t=e.sourceId;if(sd&&console.log(t,br.stencils),!t)return;let i=br.stencils[t];if(!!i)for(let n=i.length-1;n>=0;n--){let r=i[n];if(wy(r.layer,e)){sd&&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[xy];if(i){sd&&console.log(i);let n=i.stencil;if(n&&Array.isArray(n))for(let r of n){let o={...r};o.compareFunc=_y(o.compareFunc),o.passOp=ad(o.passOp),o.failOp=ad(o.failOp),o.zFailOp=ad(o.zFailOp),br.stencils[this.source]||(br.stencils[this.source]=[]),br.stencils[this.source].push(o)}}}return null}},Rs=br;z(Rs,"stencils",{});function ad(c){switch(c){case 0:return fy;case 1:return py;case 2:return my;case 3:return gy;case 4:return by;case 6:return vy;case 7:return yy;case 5:return Ey}return 0}function _y(c){switch(c){case 1:return oy;case 2:return sy;case 3:return ay;case 4:return ly;case 5:return cy;case 6:return dy;case 7:return hy;case 8:return uy}return 0}var xy="NEEDLE_render_objects";import{TextureLoader as Ty}from"three";import{GLTFLoader as Cy}from"three/examples/jsm/loaders/GLTFLoader";var ld="NEEDLE_deferred_texture",Bt=B("debugdeferredtextures"),Ss=class{static assignTextureLOD(e,t,i,n=0){if(!!i)for(let r of Object.keys(i)){let o=i[r];o?.isTexture===!0&&(Bt&&console.log(`-----------
151
- `,"FIND",i.name,r,o?.name,o?.userData,o),Ss.getOrLoadTexture(e,t,i,r,o,n).then(s=>{s?.isTexture===!0&&(s.needsUpdate=!0,Bt&&console.log("Assign LOD",i.name,r,s.name,s.guid,i,"Prev:",o,"Now:",s,`
152
- --------------`),i[r]=s,i.needsUpdate=!0)}))}}get name(){return ld}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}_loading=[];afterRoot(e){return Bt&&console.log("AFTER",this.sourceId,e),this.parser.json.textures?.forEach((t,i)=>{if(t?.extensions){let n=t?.extensions[ld];if(n){let r=this.parser.getDependency("texture",i);this._loading.splice(this._loading.indexOf(i),1),r.then(o=>{Bt&&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,o){let s=r.uuid,l=Ss.cache.get(s);if(l){Bt&&console.log(s,l.uri,l.guid);let d=un(t,l.uri);if(d.endsWith(".glb")||d.endsWith(".gltf")){if(!l.guid)return console.warn("missing pointer for glb/gltf texture",l),null;let a=d+"_"+l.guid;if(this.resolved[a])return Bt&&console.log("Texture has already been loaded: "+a,i.name,n,r.name),this.resolved[a];let u=new Cy;za(u,e),Bt&&console.log("Load "+d,i.name,n,l.guid);let h=await u.loadAsync(d),m=h.parser;Bt&&console.log("Loading finished "+d,i.name,n,l.guid);let E=-1,b=!1;for(let g of h.parser.json.textures)if(E++,g?.extensions){let p=g?.extensions[ld];if(p?.guid&&p.guid===l.guid){b=!0;break}}if(!b)return null;let y=await m.getDependency("texture",E);return y&&(y.guid=l.guid),this.resolved[a]=y,Bt&&console.log(i.name,n,'change "'+r.name+'" \u2192 "'+y.name+'"',d,E,y,i,a),y}else{Bt&&console.log("Load texture from uri: "+d);let u=await new Ty().loadAsync(d);return u&&Bt?console.log(l,u):console.warn("failed loading",d),u}}else Bt&&console.warn("unknown uuid",r.name,r.uuid,r);return null}},vr=Ss;z(vr,"cache",new Map),z(vr,"resolved",{});var Fp=B("noInstancing"),Np=!!B("debuglightmaps"),Sy=B("debuginstancing"),Py=B("debugprogressiveload"),Oy=B("noprogressiveload"),vo=class{path=null;asset=null;default};var cd=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}},pd=class extends D{receiveShadows=!1;shadowCastingMode=dd.Off;lightmapIndex=-1;lightmapScaleOffset=new Ci.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 cd(this)),this._sharedMaterials}static get shouldSuppressInstancing(){return Fp}_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}awake(){this.clearInstancingState();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"||A.getComponent(n,pd))){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 Ki(this.gameObject,this.context);this._lightmaps.push(i),i.init(this.lightmapIndex,this.lightmapScaleOffset,t,Np)}}else if(e==="Group"){for(let i of this.gameObject.children)if(!i.material?.isMeshBasicMaterial){let n=new Ki(i,this.context);this._lightmaps.push(n),n.init(this.lightmapIndex,this.lightmapScaleOffset,t,Np),n.bindOnBeforeRender()}}}}}_isInstancingEnabled=!1;handles=void 0;prevLayers=void 0;clearInstancingState(){this._isInstancingEnabled=!1,this.handles=void 0,this.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=ky.setup(this.gameObject,this.context,null,{rend:this,foundMeshes:0}),this.handles)return A.markAsInstancedRendered(this.gameObject,!0),!0}else if(this.handles!==null){for(let t of this.handles)t.updateInstanceMatrix(!0),t.add();return A.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&&!Fp&&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(){Rs.applyStencil(this)}onBeforeRenderThree(e,t,i,n,r,o){if(!Oy&&r._didRequestTextureLOD===void 0&&(r._didRequestTextureLOD=0,Py?(console.log("Load material LOD (with delay)",r.name),setTimeout(()=>{vr.assignTextureLOD(this.context,this.sourceId,r)},2e3)):vr.assignTextureLOD(this.context,this.sourceId,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[sa]===!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[sa],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&&A.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==dd.On?e.castShadow=!0:e.castShadow=!1}},pe=pd;k([O()],pe.prototype,"receiveShadows",2),k([O()],pe.prototype,"shadowCastingMode",2),k([O()],pe.prototype,"lightmapIndex",2),k([O(Ry)],pe.prototype,"lightmapScaleOffset",2),k([O()],pe.prototype,"enableInstancing",2),k([O()],pe.prototype,"renderOrder",2),k([O()],pe.prototype,"allowOcclusionWhenDynamic",2);var yr=class extends pe{},yo=class extends yr{awake(){super.awake(),this.allowOcclusionWhenDynamic=!1}},dd=(n=>(n[n.Off=0]="Off",n[n.On=1]="On",n[n.TwoSided=2]="TwoSided",n[n.ShadowsOnly=3]="ShadowsOnly",n))(dd||{}),hd=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 l of e.children)i=this.setup(l,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 l=new $a(e.name,o,s,200,t);return this.objs.push(l),l.addInstance(r)}return null}},ky=new hd,ud=class{get name(){return this.object.name}instanceIndex=-1;object;instancer;constructor(e,t,i){this.instanceIndex=e,this.object=t,this.instancer=i,A.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)}},fd=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,Sy&&(i=new Ci.MeshBasicMaterial({color:this.randomColor()})),this.inst=new Ci.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 Ci.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 ud(-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,fd.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}},$a=fd;z($a,"nullMatrix",new Ci.Matrix4);import{Object3D as My,Vector3 as Dy}from"three";var Dn=tt,el="$___Export_Components",Ay="NEEDLE_components",md=class{[ir]},gd=class{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}},tl=class{get name(){return Ay}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[el]=i)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Dn&&console.log("DONE",JSON.stringify(t)),e[el]===void 0)return;let i=e[el];delete e[el],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 gd(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){Dn&&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 l=new md;r.extensions=r.extensions||{},r.extensions[this.name]=l,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 u=nt().writeBuiltinComponentData(a,this.context);u!==null&&d.push(u)}d.length>0&&(l[ir]=d,Dn&&console.log("DID WRITE",n,"nodeIndex",o,d))}}beforeRoot(){return Dn&&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];Dn&&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 l=await t.getDependency("node",s);this.nodeToObjectMap[s]=l}for(let s=0;s<o.length;s++){let l=o[s],d=s,a=l.extensions;if(!a)continue;let u=a[this.name];if(!u)continue;Dn&&console.log("NODE",l);let h=this.nodeToObjectMap[d];if(!h){console.error("Could not find object for node index: "+d,l,t);continue}ma(h),r.push(this.createComponents(h,u))}}await Promise.all(r)}async createComponents(e,t){if(!t)return;let i=t[ir];if(i){Dn&&console.log(e.name,i);for(let n in i){let r=i[n];Dn&&console.log("Serialized data",JSON.parse(JSON.stringify(r))),r&&this.parser&&await Bs(this.parser,r),e.userData=e.userData||{},e.userData[ir]=e.userData[ir]||[],e.userData[ir].push(r)}}}};var Eo=class extends ot{sceneRoot;start(){this.startCoroutine(this.updateGltfBox())}*updateGltfBox(){for(;;)for(let e=0;e<10;e++)yield}},Ft=class extends D{binary=!0;objects=[];exporter;ext;async exportNow(e){console.log("DO EXPORT",this.objects);let t={binary:this.binary,pivot:Ft.calculateCenter(this.objects)},i=await this.export(this.objects,t);this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?Ft.saveArrayBuffer(i,e):Ft.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 Iy,this.exporter.register(s=>new Ts(s)),this.ext=new tl,this.ext.registerExport(this.exporter)),Ft.filterTopmostParent(e);let i={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:t?.binary??!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:Ft.collectAnimations(e)},n=new My;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),A.getComponentsInChildren(s,pe).forEach(l=>{A.isActiveInHierarchy(l.gameObject)&&l.setInstancingEnabled(!1)}))});let r=new Fs(n);return this.ext.context=r,new Promise((s,l)=>{try{this.exporter?.parse(n,d=>{o(),s(d)},d=>{o(),l(d)},i)}catch(d){console.error(d),l(d)}finally{console.log("FINALLY")}});function o(){e.forEach(s=>{!s||(s.matrixAutoUpdate=!0,A.getComponentsInChildren(s,pe).forEach(l=>{A.isActiveInHierarchy(l.gameObject)&&l.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 Dy;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 il,GridHelper as Ly}from"three";var Ji=class extends D{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!si)return;let e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new Ly(e,t,this.color0??new il(.4,.4,.4),this.color1??new il(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset),this.gameObject.add(this.gridHelper))}};k([O()],Ji.prototype,"isGizmo",2),k([O(il)],Ji.prototype,"color0",2),k([O(il)],Ji.prototype,"color1",2);import{GroundProjectedEnv as Hy}from"three/examples/jsm/objects/GroundProjectedEnv.js";var Zi=class extends D{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 hn(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 Hy(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([O()],Zi.prototype,"scale",1),k([O()],Zi.prototype,"radius",1),k([O()],Zi.prototype,"height",1);import*as $e from"three";import{Color as jy}from"three";function bd(c){return c*Math.PI/180}var zp=300,Up=B("debuglights");var Ge=class extends D{type=0;range=1;spotAngle=1;innerSpotAngle=1;color=new $e.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 $e.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=Q.addEventListener("xrStarted",this.onWebXRStarted.bind(this)),this._webXREndedListener=Q.addEventListener("xrStopped",this.onWebXREnded.bind(this)))}onDisable(){Q.removeEventListener("xrStarted",this._webXRStartedListener),Q.removeEventListener("xrStopped",this._webXREndedListener)}_webXRStartedListener;_webXREndedListener;_webARRoot;onWebXRStarted(){this._webARRoot=A.getComponentInParent(this.gameObject,Ht)??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 $e.DirectionalLight(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-zp*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),Vr(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Up){let o=new $e.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(o)}break;case 0:let i=new $e.SpotLight(this.color,this.intensity*Math.PI,this.range,bd(this.spotAngle/2),1-bd(this.innerSpotAngle/2)/bd(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 $e.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=r;break}if(this.light!==void 0){this._intensity=this.light.intensity,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=zp*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,Up&&this.context.scene.add(new $e.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([O()],Ge.prototype,"type",2),k([O(jy)],Ge.prototype,"color",2),k([O()],Ge.prototype,"shadowNearPlane",1),k([O()],Ge.prototype,"shadowBias",1),k([O()],Ge.prototype,"shadowNormalBias",1),k([O()],Ge.prototype,"shadows",1),k([O()],Ge.prototype,"lightmapBakeType",2),k([O()],Ge.prototype,"intensity",1),k([O()],Ge.prototype,"shadowDistance",1),k([O()],Ge.prototype,"shadowResolution",1);var AI=new $e.Vector3(0,0,0);import*as nl from"three";import{Vector3 as By}from"three";var wo=B("debugLODs"),Fy=B("noLODs");var Ri=class{screenRelativeTransitionHeight;distance;renderers};k([O()],Ri.prototype,"screenRelativeTransitionHeight",2),k([O()],Ri.prototype,"distance",2),k([O()],Ri.prototype,"renderers",2);var vd=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):wo&&console.warn("Renderer not found: "+i,e.gameObject)}}findRenderer(e,t){let i=A.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}},Ln=class extends D{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(!Fy&&!this._lodsHandler&&!!this.gameObject&&(wo&&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 vd(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 nl.LOD;this._lodsHandler.push(r),this.gameObject.add(r)}let i=new nl.Object3D;wo&&console.log(t);for(let n=0;n<t.length;n++){let r=t[n],o=this._lodsHandler[n],s=r.gameObject,l=0,d=0;wo&&console.log(n,s.name);for(let u of this._lods){let h=null;u.renderers.includes(r)?h=s:h=i,wo&&console.log("add",u.model.distance,h.name);let m=u.model.distance;d=m-l,l=Math.max(m,l),this.onAddLodLevel(o,h,m)}let a=l+d;wo&&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([O(By)],Ln.prototype,"localReferencePoint",2),k([O(Ri)],Ln.prototype,"lodModels",2);var _o=class extends D{},xo=class extends D{};var yd=B("debugnestedgltf"),Er=class extends D{filePath;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){this.filePath?.preload()}async start(){if(this._isLoadingOrDoneLoading)return;yd&&console.log(this,this.guid);let e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;let t=new Be;t.idProvider=new Qe(this.hash(this.guid)),t.parent=e,this.gameObject.updateMatrix();let i=this.gameObject.matrix;yd&&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(),yd&&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([O(Ke)],Er.prototype,"filePath",2);import{Quaternion as Ny,Euler as zy,Vector3 as wr,Plane as Uy}from"three";var Si=class extends D{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new wr(0,0,0);rotationOffset=new wr(0,0,0);offset=new wr(0,0,0);update(){if(!this.from)return;var e=q(this.from),t=Pe(this.from);this.offset.copy(this.positionOffset);let i=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(i),e.add(this.offset),this.levelPosition&&this.referenceSpace){let s=new Uy(this.gameObject.up,0),l=q(this.referenceSpace);s.setFromNormalAndCoplanarPoint(this.gameObject.up,l);let d=new wr(0,0,0);s.projectPoint(e,d),e.copy(d)}this.affectPosition&&oe(this.gameObject,e);let n=new zy(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),r=new Ny().setFromEuler(n);this.affectRotation&&Xe(this.gameObject,t.multiply(r));let o=new wr;this.from.getWorldDirection(o).multiplyScalar(50),this.levelLookDirection&&(o.y=0),this.alignLookDirection&&this.gameObject.lookAt(o)}};k([O(A)],Si.prototype,"referenceSpace",2),k([O(A)],Si.prototype,"from",2),k([O(wr)],Si.prototype,"positionOffset",2),k([O(wr)],Si.prototype,"rotationOffset",2);import*as we from"three";import*as ri from"three";var To=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 ri.Color(1,1,1);startColor1=new ri.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 ri.Vector2(0,1);cullingMode=0},Co=class{burstCount=0;enabled=!0;rate=10;rateMutliplier=1;rateOverDistance=0;rateOverDistanceMultiplier=0;rateOverTime=0;rateOverTimeMultiplier=0},Ro=class{shapeType=Ed.Box;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcmode=0;box=new ri.Vector3(1,1,1);boxThickness=new ri.Vector3(0,0,0);position=new ri.Vector3(0,0,0);rotation=new ri.Vector3(0,0,0);scale=new ri.Vector3(1,1,1);radius=1;sphericalDirectionAmount=0},Ed=(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))(Ed||{});var Gy=B("debugparticles"),wd=class{age=0;lifetime=0;position;velocity;color},_r=class extends D{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(){Gy&&console.log(this)}},So=class extends D{main;emission;shape;renderer;geometry;material;particlesMesh;positions;positionsArray;particleStates=[];activeCount=0;shapeRotation=new we.Quaternion;tempVec3=new we.Vector3;tempQuat=new we.Quaternion;awake(){this.renderer=A.getComponent(this.gameObject,_r),console.log(this)}onEnable(){if(this.geometry)return;this.particleStates=[],this.shapeRotation.setFromEuler(new we.Euler(this.shape.rotation.x,this.shape.rotation.y,this.shape.rotation.z)),this.geometry=new we.BufferGeometry,this.positionsArray=new Float32Array(this.main.maxParticles*3),this.positions=new we.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 we.Float32BufferAttribute(e,3);this.geometry.setAttribute("color",t),this.material=new we.PointsMaterial({size:this.main.startSize,color:16777215,vertexColors:!0}),this.material.map=this.renderer.mainTexture,this.particlesMesh=new we.Points(this.geometry,this.material),this.particlesMesh.layers.enable(2),this.gameObject.add(this.particlesMesh),this.activeCount=this.main.prewarm?this.main.maxParticles:0}emit(e){let t=this.activeCount;for(let i=0;i<t;i+=1){if(i>=this.particleStates.length){let r=new wd;r.lifetime=this.main.startLifetime??1,r.position=new we.Vector3,r.velocity=new we.Vector3,r.color=new we.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 we.Vector3(0,1,0);t.copy(i);break;case 10:this.tempQuat.setFromAxisAngle(this.tempVec3.set(0,0,1),Math.random()*K.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 Gp from"three";function*Vp(c,e=null){let t=e?e.time:Z.Current.time,i=t.time;for(;t.time-i<c;)yield}var lt=class extends D{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 Vp(.2),!this.tryAssignColor()););}tryAssignColor(){let e=A.getComponentInParent(this.gameObject,ue);return e&&e.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(e.connectionId),!0):!1}assignUserColor(e){let t=lt.hashCode(e),i=lt.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),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 Gp.Color(t/255,i/255,n/255)}};import*as ol from"three";import{Object3D as Yy,ShaderMaterial as Ky,Texture as Jy,Vector2 as xd,Vector4 as Zy}from"three";function Wy(){return new Promise((c,e)=>{let i=()=>{i!=null&&(document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i),c())};document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)})}async function Wp(c){await Wy(),c()}import{PlaneGeometry as qy,MeshBasicMaterial as Xy,Mesh as Qy}from"three";var rl=class{static createPrimitive(e,t){let i;switch(e){case 0:let n=new qy(1,1,1,1),r=t?.material??new Xy({color:16777215});i=new Qy(n,r)}return t?.name&&(i.name=t.name),i}};var _d=B("debugvideo");var qp=(n=>(n[n.CameraFarPlane=0]="CameraFarPlane",n[n.CameraNearPlane=1]="CameraNearPlane",n[n.RenderTexture=2]="RenderTexture",n[n.MaterialOverride=3]="MaterialOverride",n))(qp||{}),Se=class extends D{renderer=null;playOnAwake=!0;playOnEnable;aspectMode=0;renderMode;targetMaterialProperty;targetMaterialRenderer;targetTexture;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"))}get videoTexture(){return this._videoTexture}_crossOrigin="anonymous";audioOutputMode=1;source;clip=null;url=null;videoElement=null;_videoTexture=null;videoMaterial=null;_isPlaying=!1;wasPlaying=!1;setVideo(e){this.clip=e,this.source=0,this.videoElement?(this.videoElement.srcObject=e,this._isPlaying&&this.videoElement.play(),this.updateAspect()):this.create(!0)}setClipURL(e){this.url!==e&&(this.url=e,this.source=1,_d&&console.log("set url",e),this.videoElement?(this.videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(!0))}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),this.screenspace?this._overlay?.start():this._overlay?.stop()}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(),Wp(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],B("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}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)}),_d&&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}if(!!t){if(this.videoElement||(this.videoElement=this.createVideoElement(),this.context.domElement?.prepend(this.videoElement),this.updateVideoElementStyles()),typeof t=="string"){this.videoElement.src=t;let i=this.videoElement.captureStream?.call(this.videoElement);this.clip=i}else this.videoElement.srcObject=t;this._videoTexture||(this._videoTexture=new ol.VideoTexture(this.videoElement)),this._videoTexture.flipY=!1,this._videoTexture.encoding=ol.sRGBEncoding,this.handleBeginPlaying(e),console.log(this)}}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}_overlay=null;get screenspace(){return this._overlay?.enabled??!1}set screenspace(e){if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new Td(this.context)),this._overlay.add(this._videoTexture)}else this._overlay?.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}_targetObjects;createVideoElement(){let e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),_d&&console.log("create video elment",e),e}handleBeginPlaying(e){if(!this.enabled||!this.videoElement)return;this._targetObjects.length=0;let t=this.gameObject;switch(this.renderMode){case 3:t=this.targetMaterialRenderer?.gameObject,t||(t=A.getComponent(this.gameObject,pe)?.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!t){console.error("Missing target for video material renderer",this.name,qp[this.renderMode],this);return}let i=t.material;if(i)if(this._targetObjects.push(t),i!==this.videoMaterial&&(this.videoMaterial=i.clone(),t.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",this.updateAspect())}_updateAspectRoutineId=-1;*updateAspectImpl(){let e=++this._updateAspectRoutineId,t=void 0,i=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&i===this.clip&&this._isPlaying;){if(!i||typeof i=="string")return;let n;for(let r of i.getVideoTracks()){let o=r.getSettings();if(o&&o.width&&o.height){n=o.width/o.height;break}else n=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(n===void 0){for(let r=0;r<10;r++)yield;if(!this.isPlaying)break;continue}if(t===n){yield;continue}for(let r of this._targetObjects){let o=1;if(r.parent){let s=na(r.parent);o=s.x/s.y}switch(this.aspectMode){case 1:r.scale.y=1/n*r.scale.x*o;break;case 2:r.scale.x=n*r.scale.y*o;break}}for(let r=0;r<3;r++)yield}}};k([O(Yy)],Se.prototype,"renderer",2),k([O()],Se.prototype,"playOnAwake",2),k([O()],Se.prototype,"playOnEnable",2),k([O()],Se.prototype,"aspectMode",2),k([O()],Se.prototype,"renderMode",2),k([O()],Se.prototype,"targetMaterialProperty",2),k([O(pe)],Se.prototype,"targetMaterialRenderer",2),k([O(Jy)],Se.prototype,"targetTexture",2),k([O()],Se.prototype,"time",2),k([O()],Se.prototype,"playbackSpeed",1),k([O()],Se.prototype,"isLooping",1);var Td=class{context;constructor(e){this.context=e,this._input=new Cd(this)}get enabled(){return this._isInScreenspaceMode}set enabled(e){e?this.start():this.stop()}add(e){this._videos.indexOf(e)===-1&&this._videos.push(e)}remove(e){if(!e)return;let t=this._videos.indexOf(e);t>=0&&this._videos.splice(t,1)}start(){if(this._isInScreenspaceMode||this._videos.length<0)return;let e=this._videos[this._videos.length-1];if(!e)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=rl.createPrimitive(0,{material:new Rd(e)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}let t=this._screenspaceModeQuad;this.context.scene.add(t),this.updateScreenspaceMaterialUniforms();let i=t.material;i?.reset(),this._input?.enable(i)}stop(){this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&(this._input?.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){let e=this._screenspaceModeQuad?.material;!e||(e.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}_videos=[];_screenspaceModeQuad;_isInScreenspaceMode=!1;_input},Cd=class{_onResizeScreenFn;_onKeyUpFn;_onMouseWheelFn;context;overlay;constructor(e){this.overlay=e,this.context=e.context}_material;enable(e){this._material=e,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=n=>{n.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=n=>{this.overlay.enabled&&(e.zoom+=n.deltaY*5e-4,n.preventDefault())},{passive:!1});let t=new xd;window.addEventListener("mousemove",n=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){let r=new xd(n.movementX,n.movementY);r.x/=this.context.domElement.clientWidth,r.y/=this.context.domElement.clientHeight,t.set(r.x,r.y),t.multiplyScalar(e.zoom/-this.context.time.deltaTime*.01),e.offset=e.offset.add(t)}}),window.addEventListener("pointermove",n=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(t.set(n.movementX,n.movementY),t.multiplyScalar(e.zoom*-this.context.time.deltaTime*.05),e.offset=e.offset.add(t))});let i=0;window.addEventListener("touchstart",n=>{if(n.touches.length<2){this.context.time.time-i<.3&&this.overlay.stop(),i=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",n=>{if(!this._isPinching||!this._material)return;let r=n.touches[0],o=n.touches[1],s=r.clientX-o.clientX,l=r.clientY-o.clientY,d=Math.sqrt(s*s+l*l);if(this._lastPinch!==0){let a=d-this._lastPinch;this._material.zoom-=a*.004}this._lastPinch=d}),window.addEventListener("touchend",()=>{this._isPinching=!1})}_isPinching=!1;_lastPinch=0;disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}},Rd=class extends Ky{set screenAspect(e){this.uniforms.screenAspect.value=e,this.needsUpdate=!0}set offset(e){let t=this.uniforms.offsetScale.value;t.x=e.x,t.y=e.y,this.uniforms.offsetScale.value=t,this.needsUpdate=!0}_offset=new xd;get offset(){let e=this.uniforms.offsetScale.value;return this._offset.set(e.x,e.y),this._offset}set zoom(e){let t=this.uniforms.offsetScale.value;e<.001&&(e=.001),t.z=e,this.needsUpdate=!0}get zoom(){return this.uniforms.offsetScale.value.z}reset(){this.offset=this.offset.set(0,0),this.zoom=1,this.needsUpdate=!0}constructor(e){super(),this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new Zy(0,0,1,1)}},this.vertexShader=`
155
+ `,defines:{USE_LIGHTMAP:""}})}};import{Vector4 as Ey}from"three";import{NeverStencilFunc as $v,LessStencilFunc as ey,EqualStencilFunc as ty,LessEqualStencilFunc as iy,GreaterStencilFunc as ny,NotEqualStencilFunc as ry,GreaterEqualStencilFunc as oy,AlwaysStencilFunc as sy,ZeroStencilOp as ay,KeepStencilOp as ly,ReplaceStencilOp as cy,IncrementStencilOp as dy,DecrementStencilOp as hy,IncrementWrapStencilOp as uy,DecrementWrapStencilOp as py,InvertStencilOp as fy}from"three";var Yc=H("debugstencil");function my(l,e){return(l&1<<e.layer)!=0}var An=class{static applyStencil(e){if(!e)return;let t=e.sourceId;if(Yc&&console.log(t,An.stencils),!t)return;let i=An.stencils[t];if(!!i)for(let n=i.length-1;n>=0;n--){let r=i[n];if(my(r.layer,e)){Yc&&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[by];if(i){Yc&&console.log(i);let n=i.stencil;if(n&&Array.isArray(n))for(let r of n){let o={...r};o.compareFunc=gy(o.compareFunc),o.passOp=Kc(o.passOp),o.failOp=Kc(o.failOp),o.zFailOp=Kc(o.zFailOp),An.stencils[this.source]||(An.stencils[this.source]=[]),An.stencils[this.source].push(o)}}}return null}},Do=An;N(Do,"stencils",{});function Kc(l){switch(l){case 0:return ly;case 1:return ay;case 2:return cy;case 3:return dy;case 4:return hy;case 6:return uy;case 7:return py;case 5:return fy}return 0}function gy(l){switch(l){case 1:return $v;case 2:return ey;case 3:return ty;case 4:return iy;case 5:return ny;case 6:return ry;case 7:return oy;case 8:return sy}return 0}var by="NEEDLE_render_objects";import{TextureLoader as vy}from"three";import{GLTFLoader as yy}from"three/examples/jsm/loaders/GLTFLoader";var Jc="NEEDLE_deferred_texture",_t=H("debugdeferredtextures"),Lo=class{static assignTextureLOD(e,t,i,n=0){if(!!i)for(let r of Object.keys(i)){let o=i[r];o?.isTexture===!0&&(_t&&console.log(`-----------
156
+ `,"FIND",i.name,r,o?.name,o?.userData,o),Lo.getOrLoadTexture(e,t,i,r,o,n).then(s=>{s?.isTexture===!0&&(s.needsUpdate=!0,_t&&console.log("Assign LOD",i.name,r,s.name,s.guid,i,"Prev:",o,"Now:",s,`
157
+ --------------`),i[r]=s,i.needsUpdate=!0)}))}}get name(){return Jc}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}_loading=[];afterRoot(e){return _t&&console.log("AFTER",this.sourceId,e),this.parser.json.textures?.forEach((t,i)=>{if(t?.extensions){let n=t?.extensions[Jc];if(n){let r=this.parser.getDependency("texture",i);this._loading.splice(this._loading.indexOf(i),1),r.then(o=>{_t&&console.log("register texture",o.name,o.uuid,n),o.userData.deferred=n,Lo.cache.set(o.uuid,n)})}}}),null}static async getOrLoadTexture(e,t,i,n,r,o){let s=r.uuid,c=Lo.cache.get(s);if(c){_t&&console.log(s,c.uri,c.guid);let d=Di(t,c.uri);if(d.endsWith(".glb")||d.endsWith(".gltf")){if(!c.guid)return console.warn("missing pointer for glb/gltf texture",c),null;let a=d+"_"+c.guid;if(this.resolved[a])return _t&&console.log("Texture has already been loaded: "+a,i.name,n,r.name),this.resolved[a];let u=new yy;sa(u,e),_t&&console.log("Load "+d,i.name,n,c.guid);let h=await u.loadAsync(d),f=h.parser;_t&&console.log("Loading finished "+d,i.name,n,c.guid);let E=-1,b=!1;for(let g of h.parser.json.textures)if(E++,g?.extensions){let p=g?.extensions[Jc];if(p?.guid&&p.guid===c.guid){b=!0;break}}if(!b)return null;let y=await f.getDependency("texture",E);return y&&(y.guid=c.guid),this.resolved[a]=y,_t&&console.log(i.name,n,'change "'+r.name+'" \u2192 "'+y.name+'"',d,E,y,i,a),y}else{_t&&console.log("Load texture from uri: "+d);let u=await new vy().loadAsync(d);return u&&_t?console.log(c,u):console.warn("failed loading",d),u}}else _t&&console.warn("unknown uuid",r.name,r.uuid,r);return null}},Mn=Lo;N(Mn,"cache",new Map),N(Mn,"resolved",{});var Ip=H("noInstancing"),Ap=!!H("debuglightmaps"),wy=H("debuginstancing"),_y=H("debugprogressiveload"),xy=H("noprogressiveload"),xa=class{path=null;asset=null;default};var Zc=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}},id=class extends D{receiveShadows=!1;shadowCastingMode=$c.Off;lightmapIndex=-1;lightmapScaleOffset=new ci.Vector4(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;_lightmaps;get mesh(){if(this.gameObject.type==="Mesh")return this.gameObject;if(this.gameObject.type==="Group")return this.gameObject.children[0]}get material(){return this.sharedMaterials[0]}set material(e){this.sharedMaterials[0]=e}_sharedMaterials;get sharedMaterials(){return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._sharedMaterials=new Zc(this)),this._sharedMaterials}static get shouldSuppressInstancing(){return Ip}_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}awake(){this.clearInstancingState();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"||A.getComponent(n,id))){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 In(this.gameObject,this.context);this._lightmaps.push(i),i.init(this.lightmapIndex,this.lightmapScaleOffset,t,Ap)}}else if(e==="Group"){for(let i of this.gameObject.children)if(!i.material?.isMeshBasicMaterial){let n=new In(i,this.context);this._lightmaps.push(n),n.init(this.lightmapIndex,this.lightmapScaleOffset,t,Ap),n.bindOnBeforeRender()}}}}}_isInstancingEnabled=!1;handles=void 0;prevLayers=void 0;clearInstancingState(){this._isInstancingEnabled=!1,this.handles=void 0,this.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=Ty.setup(this.gameObject,this.context,null,{rend:this,foundMeshes:0}),this.handles)return A.markAsInstancedRendered(this.gameObject,!0),!0}else if(this.handles!==null){for(let t of this.handles)t.updateInstanceMatrix(!0),t.add();return A.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&&!Ip&&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(){Do.applyStencil(this)}onBeforeRenderThree(e,t,i,n,r,o){if(!xy&&r._didRequestTextureLOD===void 0&&(r._didRequestTextureLOD=0,_y?(console.log("Load material LOD (with delay)",r.name),setTimeout(()=>{Mn.assignTextureLOD(this.context,this.sourceId,r)},2e3)):Mn.assignTextureLOD(this.context,this.sourceId,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[Ts]===!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[Ts],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&&A.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==$c.On?e.castShadow=!0:e.castShadow=!1}},be=id;k([O()],be.prototype,"receiveShadows",2),k([O()],be.prototype,"shadowCastingMode",2),k([O()],be.prototype,"lightmapIndex",2),k([O(Ey)],be.prototype,"lightmapScaleOffset",2),k([O()],be.prototype,"enableInstancing",2),k([O()],be.prototype,"renderOrder",2),k([O()],be.prototype,"allowOcclusionWhenDynamic",2);var Ho=class extends be{},Ta=class extends Ho{awake(){super.awake(),this.allowOcclusionWhenDynamic=!1}},$c=(n=>(n[n.Off=0]="Off",n[n.On=1]="On",n[n.TwoSided=2]="TwoSided",n[n.ShadowsOnly=3]="ShadowsOnly",n))($c||{}),ed=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 _a(e.name,o,s,200,t);return this.objs.push(c),c.addInstance(r)}return null}},Ty=new ed,td=class{get name(){return this.object.name}instanceIndex=-1;object;instancer;constructor(e,t,i){this.instanceIndex=e,this.object=t,this.instancer=i,A.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)}},nd=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,wy&&(i=new ci.MeshBasicMaterial({color:this.randomColor()})),this.inst=new ci.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 ci.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 td(-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,nd.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}},_a=nd;N(_a,"nullMatrix",new ci.Matrix4);import{Object3D as Sy,Vector3 as Py}from"three";var Zi=Ke,Ca="$___Export_Components",Cy="NEEDLE_components",rd=class{[gn]},od=class{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}},Ra=class{get name(){return Cy}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[Ca]=i)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Zi&&console.log("DONE",JSON.stringify(t)),e[Ca]===void 0)return;let i=e[Ca];delete e[Ca],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 od(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){Zi&&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 rd;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 u=Ze().writeBuiltinComponentData(a,this.context);u!==null&&d.push(u)}d.length>0&&(c[gn]=d,Zi&&console.log("DID WRITE",n,"nodeIndex",o,d))}}beforeRoot(){return Zi&&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];Zi&&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 u=a[this.name];if(!u)continue;Zi&&console.log("NODE",c);let h=this.nodeToObjectMap[d];if(!h){console.error("Could not find object for node index: "+d,c,t);continue}Ds(h),r.push(this.createComponents(h,u))}}await Promise.all(r)}async createComponents(e,t){if(!t)return;let i=t[gn];if(i){Zi&&console.log(e.name,i);for(let n in i){let r=i[n];Zi&&console.log("Serialized data",JSON.parse(JSON.stringify(r))),r&&this.parser&&await is(this.parser,r),e.userData=e.userData||{},e.userData[gn]=e.userData[gn]||[],e.userData[gn].push(r)}}}};var Sa=class extends yt{sceneRoot;start(){this.startCoroutine(this.updateGltfBox())}*updateGltfBox(){for(;;)for(let e=0;e<10;e++)yield}},di=class extends D{binary=!0;objects=[];exporter;ext;async exportNow(e){console.log("DO EXPORT",this.objects);let t={binary:this.binary,pivot:di.calculateCenter(this.objects)},i=await this.export(this.objects,t);this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?di.saveArrayBuffer(i,e):di.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 Ry,this.exporter.register(s=>new Ao(s)),this.ext=new Ra,this.ext.registerExport(this.exporter)),di.filterTopmostParent(e);let i={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:t?.binary??!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:di.collectAnimations(e)},n=new Sy;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),A.getComponentsInChildren(s,be).forEach(c=>{A.isActiveInHierarchy(c.gameObject)&&c.setInstancingEnabled(!1)}))});let r=new ns(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,A.getComponentsInChildren(s,be).forEach(c=>{A.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 Py;return i.set(0,0,0),e.forEach(n=>{i.add(G(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 Pa,GridHelper as Oy}from"three";var Dn=class extends D{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!Ut)return;let e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new Oy(e,t,this.color0??new Pa(.4,.4,.4),this.color1??new Pa(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset),this.gameObject.add(this.gridHelper))}};k([O()],Dn.prototype,"isGizmo",2),k([O(Pa)],Dn.prototype,"color0",2),k([O(Pa)],Dn.prototype,"color1",2);import{GroundProjectedEnv as ky}from"three/examples/jsm/objects/GroundProjectedEnv.js";var Ln=class extends D{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 Mi(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 ky(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([O()],Ln.prototype,"scale",1),k([O()],Ln.prototype,"radius",1),k([O()],Ln.prototype,"height",1);import*as Xe from"three";import{Color as Iy}from"three";function sd(l){return l*Math.PI/180}var Mp=300,Dp=H("debuglights");var it=class extends D{type=0;range=1;spotAngle=1;innerSpotAngle=1;color=new Xe.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 Xe.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=Y.addEventListener("xrStarted",this.onWebXRStarted.bind(this)),this._webXREndedListener=Y.addEventListener("xrStopped",this.onWebXREnded.bind(this)))}onDisable(){Y.removeEventListener("xrStarted",this._webXRStartedListener),Y.removeEventListener("xrStopped",this._webXREndedListener)}_webXRStartedListener;_webXREndedListener;_webARRoot;onWebXRStarted(){this._webARRoot=A.getComponentInParent(this.gameObject,si)??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 Xe.DirectionalLight(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-Mp*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),ir(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Dp){let o=new Xe.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(o)}break;case 0:let i=new Xe.SpotLight(this.color,this.intensity*Math.PI,this.range,sd(this.spotAngle/2),1-sd(this.innerSpotAngle/2)/sd(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 Xe.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=r;break}if(this.light!==void 0){this._intensity=this.light.intensity,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=Mp*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,Dp&&this.context.scene.add(new Xe.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([O()],it.prototype,"type",2),k([O(Iy)],it.prototype,"color",2),k([O()],it.prototype,"shadowNearPlane",1),k([O()],it.prototype,"shadowBias",1),k([O()],it.prototype,"shadowNormalBias",1),k([O()],it.prototype,"shadows",1),k([O()],it.prototype,"lightmapBakeType",2),k([O()],it.prototype,"intensity",1),k([O()],it.prototype,"shadowDistance",1),k([O()],it.prototype,"shadowResolution",1);var PI=new Xe.Vector3(0,0,0);import*as Oa from"three";import{Vector3 as Ay}from"three";var Ir=H("debugLODs"),My=H("noLODs");var $i=class{screenRelativeTransitionHeight;distance;renderers};k([O()],$i.prototype,"screenRelativeTransitionHeight",2),k([O()],$i.prototype,"distance",2),k([O()],$i.prototype,"renderers",2);var ad=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):Ir&&console.warn("Renderer not found: "+i,e.gameObject)}}findRenderer(e,t){let i=A.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}},Ar=class extends D{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(!My&&!this._lodsHandler&&!!this.gameObject&&(Ir&&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 ad(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 Oa.LOD;this._lodsHandler.push(r),this.gameObject.add(r)}let i=new Oa.Object3D;Ir&&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;Ir&&console.log(n,s.name);for(let u of this._lods){let h=null;u.renderers.includes(r)?h=s:h=i,Ir&&console.log("add",u.model.distance,h.name);let f=u.model.distance;d=f-c,c=Math.max(f,c),this.onAddLodLevel(o,h,f)}let a=c+d;Ir&&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([O(Ay)],Ar.prototype,"localReferencePoint",2),k([O($i)],Ar.prototype,"lodModels",2);var ka=class extends D{},Ia=class extends D{};var ld=H("debugnestedgltf"),jo=class extends D{filePath;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){this.filePath?.preload()}async start(){if(this._isLoadingOrDoneLoading)return;ld&&console.log(this,this.guid);let e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;let t=new He;t.idProvider=new Ve(this.hash(this.guid)),t.parent=e,this.gameObject.updateMatrix();let i=this.gameObject.matrix;ld&&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(),ld&&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([O(ot)],jo.prototype,"filePath",2);import{Quaternion as Dy,Euler as Ly,Vector3 as Hn,Plane as Hy}from"three";var en=class extends D{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new Hn(0,0,0);rotationOffset=new Hn(0,0,0);offset=new Hn(0,0,0);update(){if(!this.from)return;var e=G(this.from),t=we(this.from);this.offset.copy(this.positionOffset);let i=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(i),e.add(this.offset),this.levelPosition&&this.referenceSpace){let s=new Hy(this.gameObject.up,0),c=G(this.referenceSpace);s.setFromNormalAndCoplanarPoint(this.gameObject.up,c);let d=new Hn(0,0,0);s.projectPoint(e,d),e.copy(d)}this.affectPosition&&ne(this.gameObject,e);let n=new Ly(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),r=new Dy().setFromEuler(n);this.affectRotation&&Ue(this.gameObject,t.multiply(r));let o=new Hn;this.from.getWorldDirection(o).multiplyScalar(50),this.levelLookDirection&&(o.y=0),this.alignLookDirection&&this.gameObject.lookAt(o)}};k([O(A)],en.prototype,"referenceSpace",2),k([O(A)],en.prototype,"from",2),k([O(Hn)],en.prototype,"positionOffset",2),k([O(Hn)],en.prototype,"rotationOffset",2);import*as ve from"three";import*as Bt from"three";var Aa=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 Bt.Color(1,1,1);startColor1=new Bt.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 Bt.Vector2(0,1);cullingMode=0},Ma=class{burstCount=0;enabled=!0;rate=10;rateMutliplier=1;rateOverDistance=0;rateOverDistanceMultiplier=0;rateOverTime=0;rateOverTimeMultiplier=0},Da=class{shapeType=cd.Box;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcmode=0;box=new Bt.Vector3(1,1,1);boxThickness=new Bt.Vector3(0,0,0);position=new Bt.Vector3(0,0,0);rotation=new Bt.Vector3(0,0,0);scale=new Bt.Vector3(1,1,1);radius=1;sphericalDirectionAmount=0},cd=(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))(cd||{});var By=H("debugparticles"),dd=class{age=0;lifetime=0;position;velocity;color},Bo=class extends D{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(){By&&console.log(this)}},La=class extends D{main;emission;shape;renderer;geometry;material;particlesMesh;positions;positionsArray;particleStates=[];activeCount=0;shapeRotation=new ve.Quaternion;tempVec3=new ve.Vector3;tempQuat=new ve.Quaternion;awake(){this.renderer=A.getComponent(this.gameObject,Bo),console.log(this)}onEnable(){if(this.geometry)return;this.particleStates=[],this.shapeRotation.setFromEuler(new ve.Euler(this.shape.rotation.x,this.shape.rotation.y,this.shape.rotation.z)),this.geometry=new ve.BufferGeometry,this.positionsArray=new Float32Array(this.main.maxParticles*3),this.positions=new ve.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 ve.Float32BufferAttribute(e,3);this.geometry.setAttribute("color",t),this.material=new ve.PointsMaterial({size:this.main.startSize,color:16777215,vertexColors:!0}),this.material.map=this.renderer.mainTexture,this.particlesMesh=new ve.Points(this.geometry,this.material),this.particlesMesh.layers.enable(2),this.gameObject.add(this.particlesMesh),this.activeCount=this.main.prewarm?this.main.maxParticles:0}emit(e){let t=this.activeCount;for(let i=0;i<t;i+=1){if(i>=this.particleStates.length){let r=new dd;r.lifetime=this.main.startLifetime??1,r.position=new ve.Vector3,r.velocity=new ve.Vector3,r.color=new ve.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 ve.Vector3(0,1,0);t.copy(i);break;case 10:this.tempQuat.setFromAxisAngle(this.tempVec3.set(0,0,1),Math.random()*K.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*Lp(l,e=null){let t=e?e.time:J.Current.time,i=t.time;for(;t.time-i<l;)yield}var ki=class extends D{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 Lp(.2),!this.tryAssignColor()););}tryAssignColor(){let e=A.getComponentInParent(this.gameObject,he);return e&&e.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(e.connectionId),!0):!1}assignUserColor(e){let t=ki.hashCode(e),i=ki.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),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 ja from"three";import{Object3D as Vy,ShaderMaterial as Wy,Texture as Gy,Vector2 as ud,Vector4 as qy}from"three";function Fy(){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 Fy(),l()}import{PlaneGeometry as Ny,MeshBasicMaterial as zy,Mesh as Uy}from"three";var Ha=class{static createPrimitive(e,t){let i;switch(e){case 0:let n=new Ny(1,1,1,1),r=t?.material??new zy({color:16777215});i=new Uy(n,r)}return t?.name&&(i.name=t.name),i}};var hd=H("debugvideo");var Bp=(n=>(n[n.CameraFarPlane=0]="CameraFarPlane",n[n.CameraNearPlane=1]="CameraNearPlane",n[n.RenderTexture=2]="RenderTexture",n[n.MaterialOverride=3]="MaterialOverride",n))(Bp||{}),Me=class extends D{renderer=null;playOnAwake=!0;playOnEnable;aspectMode=0;renderMode;targetMaterialProperty;targetMaterialRenderer;targetTexture;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"))}get videoTexture(){return this._videoTexture}_crossOrigin="anonymous";audioOutputMode=1;source;clip=null;url=null;videoElement=null;_videoTexture=null;videoMaterial=null;_isPlaying=!1;wasPlaying=!1;setVideo(e){this.clip=e,this.source=0,this.videoElement?(this.videoElement.srcObject=e,this._isPlaying&&this.videoElement.play(),this.updateAspect()):this.create(!0)}setClipURL(e){this.url!==e&&(this.url=e,this.source=1,hd&&console.log("set url",e),this.videoElement?(this.videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(!0))}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),this.screenspace?this._overlay?.start():this._overlay?.stop()}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()}),this._targetObjects=[],H("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}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)}),hd&&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}if(!!t){if(this.videoElement||(this.videoElement=this.createVideoElement(),this.context.domElement?.prepend(this.videoElement),this.updateVideoElementStyles()),typeof t=="string"){this.videoElement.src=t;let i=this.videoElement.captureStream?.call(this.videoElement);this.clip=i}else this.videoElement.srcObject=t;this._videoTexture||(this._videoTexture=new ja.VideoTexture(this.videoElement)),this._videoTexture.flipY=!1,this._videoTexture.encoding=ja.sRGBEncoding,this.handleBeginPlaying(e),console.log(this)}}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}_overlay=null;get screenspace(){return this._overlay?.enabled??!1}set screenspace(e){if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new pd(this.context)),this._overlay.add(this._videoTexture)}else this._overlay?.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}_targetObjects;createVideoElement(){let e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),hd&&console.log("create video elment",e),e}handleBeginPlaying(e){if(!this.enabled||!this.videoElement)return;this._targetObjects.length=0;let t=this.gameObject;switch(this.renderMode){case 3:t=this.targetMaterialRenderer?.gameObject,t||(t=A.getComponent(this.gameObject,be)?.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!t){console.error("Missing target for video material renderer",this.name,Bp[this.renderMode],this);return}let i=t.material;if(i)if(this._targetObjects.push(t),i!==this.videoMaterial&&(this.videoMaterial=i.clone(),t.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",this.updateAspect())}_updateAspectRoutineId=-1;*updateAspectImpl(){let e=++this._updateAspectRoutineId,t=void 0,i=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&i===this.clip&&this._isPlaying;){if(!i||typeof i=="string")return;let n;for(let r of i.getVideoTracks()){let o=r.getSettings();if(o&&o.width&&o.height){n=o.width/o.height;break}else n=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(n===void 0){for(let r=0;r<10;r++)yield;if(!this.isPlaying)break;continue}if(t===n){yield;continue}for(let r of this._targetObjects){let o=1;if(r.parent){let s=ws(r.parent);o=s.x/s.y}switch(this.aspectMode){case 1:r.scale.y=1/n*r.scale.x*o;break;case 2:r.scale.x=n*r.scale.y*o;break}}for(let r=0;r<3;r++)yield}}};k([O(Vy)],Me.prototype,"renderer",2),k([O()],Me.prototype,"playOnAwake",2),k([O()],Me.prototype,"playOnEnable",2),k([O()],Me.prototype,"aspectMode",2),k([O()],Me.prototype,"renderMode",2),k([O()],Me.prototype,"targetMaterialProperty",2),k([O(be)],Me.prototype,"targetMaterialRenderer",2),k([O(Gy)],Me.prototype,"targetTexture",2),k([O()],Me.prototype,"time",2),k([O()],Me.prototype,"playbackSpeed",1),k([O()],Me.prototype,"isLooping",1);var pd=class{context;constructor(e){this.context=e,this._input=new fd(this)}get enabled(){return this._isInScreenspaceMode}set enabled(e){e?this.start():this.stop()}add(e){this._videos.indexOf(e)===-1&&this._videos.push(e)}remove(e){if(!e)return;let t=this._videos.indexOf(e);t>=0&&this._videos.splice(t,1)}start(){if(this._isInScreenspaceMode||this._videos.length<0)return;let e=this._videos[this._videos.length-1];if(!e)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=Ha.createPrimitive(0,{material:new md(e)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}let t=this._screenspaceModeQuad;this.context.scene.add(t),this.updateScreenspaceMaterialUniforms();let i=t.material;i?.reset(),this._input?.enable(i)}stop(){this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&(this._input?.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){let e=this._screenspaceModeQuad?.material;!e||(e.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}_videos=[];_screenspaceModeQuad;_isInScreenspaceMode=!1;_input},fd=class{_onResizeScreenFn;_onKeyUpFn;_onMouseWheelFn;context;overlay;constructor(e){this.overlay=e,this.context=e.context}_material;enable(e){this._material=e,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=n=>{n.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=n=>{this.overlay.enabled&&(e.zoom+=n.deltaY*5e-4,n.preventDefault())},{passive:!1});let t=new ud;window.addEventListener("mousemove",n=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){let r=new ud(n.movementX,n.movementY);r.x/=this.context.domElement.clientWidth,r.y/=this.context.domElement.clientHeight,t.set(r.x,r.y),t.multiplyScalar(e.zoom/-this.context.time.deltaTime*.01),e.offset=e.offset.add(t)}}),window.addEventListener("pointermove",n=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(t.set(n.movementX,n.movementY),t.multiplyScalar(e.zoom*-this.context.time.deltaTime*.05),e.offset=e.offset.add(t))});let i=0;window.addEventListener("touchstart",n=>{if(n.touches.length<2){this.context.time.time-i<.3&&this.overlay.stop(),i=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",n=>{if(!this._isPinching||!this._material)return;let r=n.touches[0],o=n.touches[1],s=r.clientX-o.clientX,c=r.clientY-o.clientY,d=Math.sqrt(s*s+c*c);if(this._lastPinch!==0){let a=d-this._lastPinch;this._material.zoom-=a*.004}this._lastPinch=d}),window.addEventListener("touchend",()=>{this._isPinching=!1})}_isPinching=!1;_lastPinch=0;disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}},md=class extends Wy{set screenAspect(e){this.uniforms.screenAspect.value=e,this.needsUpdate=!0}set offset(e){let t=this.uniforms.offsetScale.value;t.x=e.x,t.y=e.y,this.uniforms.offsetScale.value=t,this.needsUpdate=!0}_offset=new ud;get offset(){let e=this.uniforms.offsetScale.value;return this._offset.set(e.x,e.y),this._offset}set zoom(e){let t=this.uniforms.offsetScale.value;e<.001&&(e=.001),t.z=e,this.needsUpdate=!0}get zoom(){return this.uniforms.offsetScale.value.z}reset(){this.offset=this.offset.set(0,0),this.zoom=1,this.needsUpdate=!0}constructor(e){super(),this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new qy(0,0,1,1)}},this.vertexShader=`
153
158
  uniform sampler2D map;
154
159
  uniform float screenAspect;
155
160
  uniform vec4 offsetScale;
@@ -199,7 +204,7 @@ irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
199
204
  else
200
205
  gl_FragColor = texture2D(map, vUv);
201
206
  }
202
- `}};var Qp=Ls(xa(),1);import*as Xp from"three";import{Color as $y,Object3D as eE}from"three";var Pd=class extends Di{constructor(){super([$y,ye])}onDeserialize(e){if(e!=null)return e.a!==void 0?new ye(e.r,e.g,e.b,e.a):e.alpha!==void 0?new ye(e.r,e.g,e.b,e.alpha):new Xp.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}}},U1=new Pd,Od=class extends Di{constructor(){super(eE)}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){let i=t.objectToNode[e.uuid];return tt&&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 tt&&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=A.findByGuid(e.guid,n)),i||(i=A.findByGuid(e.guid,t.context.scene)),i?tt&&console.log("Deserialized object reference?",e,i,t?.nodeToObject):console.warn("could not resolve reference",e,t.target,t.path,t.context.scene),i}}}},tE=new Od,kd=class extends Di{constructor(){super([dt,D])}onSerialize(e,t){if(e?.guid)return{guid:e.guid}}onDeserialize(e,t){if(e?.guid){tt&&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){if(t.guid===e)return t;let i=A.foreachComponent(t,n=>{if(n.guid===e)return n},!1);if(i!==void 0)return i;for(let n=0;n<t.children.length;n++){let r=t.children[n],o=this.findObjectForGuid(e,r);if(o)return o}}},Sd=new kd,Ad=class extends Di{constructor(){super([Re])}onSerialize(e,t){console.log("TODO: SERIALIZE EVENT")}onDeserialize(e,t){if(e&&e.type==="EventList"){tt&&console.log("DESERIALIZE EVENT",e);let i=new Array;for(let o of e.calls){tt&&console.log(o);let s=Sd.findObjectForGuid(o.target,t.root);!s&&t.context?.scene&&(s=Sd.findObjectForGuid(o.target,t.context?.scene));let l=o.method?.length>0;if(s&&l){let h=()=>console.warn(`Could not find method ${o.method} on object ${s.name}`,s,typeof s[o.method]);if(typeof s[o.method]!="function"){let m=!1;o.method.startsWith("set_")&&o.method.length>4&&(o.method=o.method.substring(4),s[o.method]!==void 0&&(m=!0)),m||h()}}let d,a=o.argument;o.argument!==void 0?(typeof a=="object"&&(a=tE.onDeserialize(o.argument,t),a||(a=Sd.onDeserialize(o.argument,t))),d=new Ti(l?(...h)=>u(...h):void 0,o.enabled)):d=new Ti(l?(...h)=>u(...h):void 0,o.enabled);let u=(...h)=>{let m=s[o.method];typeof m=="function"?a!==void 0?m?.call(s,a):m?.call(s,...h):s[o.method]=a};if(d.method||(d.__debuginfo=t.object?.name),!s||!d.method){let h=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,h,e)}else i.push(d)}let n=new Re(i);tt&&console.log(n);let r=t.target;return r!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,r),n}}},V1=new Ad;import{EventDispatcher as Hd}from"three";var nE=B("debugscreenshare");function sl(c){if(!!c)for(let e of c.getTracks())e.stop()}var Hn=class extends D{onPointerClick(){if(this.isReceiving){this.videoPlayer&&(this.videoPlayer.screenspace=!this.videoPlayer.screenspace);return}if(this.isSending){this.close();return}this.share()}videoPlayer;device=0;get currentScream(){return this._currentStream}get currentMode(){return this._currentMode}get isSending(){return this._currentStream?.active&&this._currentMode===1}get isReceiving(){if(this._currentMode===2){if(!this._currentStream||this._currentStream.active===!1)return!1;let e=this._currentStream.getTracks();for(let t of e)if(t.readyState==="live")return!0}return!1}_net;_requestOpen=!1;_currentStream=null;_currentMode=0;awake(){console.log(this),ce.registerWaitForAllowAudio(()=>{this.videoPlayer&&this._currentStream&&this._currentMode===2&&this.videoPlayer.setVideo(this._currentStream)})}start(){if(this.videoPlayer||(this.videoPlayer=A.getComponent(this.gameObject,Se)??void 0),!this.videoPlayer){console.error("Screencapture did not find a VideoPlayer component");return}let e=al.getOrCreate(this.context,this.guid);this._net=new Ld(this.context,e),this._net.enable(),this._net.addEventListener(Yp.ReceiveVideo,this.onReceiveVideo.bind(this))}async share(){this._requestOpen=!0;try{if(this.videoPlayer){let e={echoCancellation:!0,autoGainControl:!1},t={video:e,audio:e};switch(this.device){case 1:this.tryShareUserCamera(t);break;case 0:if(!navigator.mediaDevices.getDisplayMedia){console.error("No getDisplayMedia support");return}let i=await navigator.mediaDevices.getDisplayMedia(t);this._requestOpen?this.setVideo(i,1):sl(i);break;case 2:let n=0,r=this.context.renderer.domElement.captureStream(n);this.setVideo(r,1);break}}}catch(e){if(e.name==="NotAllowedError"){console.log("Selection cancelled"),this._requestOpen=!1;return}console.error("Error opening video",e)}}close(){this._requestOpen=!1,this._currentStream&&(console.warn("Close current stream / disposing resources"),this._net?.stopSendingVideo(this._currentStream),sl(this._currentStream),this._currentMode=0,this._currentStream=null)}setVideo(e,t){if(e===this._currentStream||(this.close(),!e||!this.videoPlayer))return;this._currentStream=e,this._requestOpen=!0,this._currentMode=t,this.videoPlayer.setVideo(e),t===1&&this._net?.startSendingVideo(e),e.addEventListener("ended",()=>{this.close()})}onReceiveVideo(e){this.setVideo(e.stream,2)}async tryShareUserCamera(e){let t=(await navigator.mediaDevices.enumerateDevices()).filter(i=>i.kind==="videoinput");console.log("Request camera",t);for(let i of t)try{if(!this._requestOpen)break;if(i.kind!=="videoinput")continue;let n=i.deviceId;e.video!==!1&&((typeof e.video>"u"||typeof e.video=="boolean")&&(e.video={}),e.video.deviceId=n);let r=await navigator.mediaDevices.getUserMedia(e);this._requestOpen?this.setVideo(r,1):sl(r),console.log("Selected camera",i);break}catch(n){console.warn(n)}}};k([O(Se)],Hn.prototype,"videoPlayer",2),k([O()],Hn.prototype,"device",2);var Yp=(i=>(i.Connected="peer-user-connected",i.ReceiveVideo="receive-video",i.Disconnected="peer-user-disconnected",i))(Yp||{}),Id=class{type="receive-video";stream;target;constructor(e,t){this.stream=e,this.target=t}},Md=class{guid;peerId;dontSave=!0;constructor(e,t){this.guid=e.id,this.peerId=t}};var Dd=class extends Hd{userId;direction;call;get stream(){return this._stream}_stream=null;_isDisposed=!1;close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),sl(this._stream))}get isOpen(){return this.call.peerConnection?.connectionState==="connected"}get isClosed(){return!this.isOpen}constructor(e,t,i){super(),this.userId=e,this.call=t,this.direction=i,this._stream=null,t.on("stream",n=>{if(console.log("Receive video",n.getAudioTracks(),n.getVideoTracks()),this._stream=n,i==="incoming"){let r=new Id(n,this);this.dispatchEvent(r)}})}},Po=class extends Hd{static getOrCreate(e,t){if(Po.instances.has(t))return Po.instances.get(t);let i=new Po(e,t);return Po.instances.set(t,i),i}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(e){return this.id+"-"+e}getUserIdFromPeerId(e){return e.substring(this.id.length+1)}makeCall(e,t){let i={metadata:{userId:this.context.connection.connectionId}},n=this._peer?.call(e,t,i);if(n)return this.registerCall(n,"outgoing")}get peer(){return this._peer}id;context;_peer;_incomingCalls=[];_outgoingCalls=[];constructor(e,t){super(),this.context=e,this.id=t,this.setupPeer(),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia}_enabled=!1;_enabledPeer=!1;onConnectRoomFn=this.onConnectRoom.bind(this);onUserJoinedOrLeftRoomFn=this.onUserJoinedOrLeftRoom.bind(this);onPeerConnectFn=this.onPeerConnect.bind(this);onPeerReceiveCallFn=this.onPeerReceivingCall.bind(this);enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen("joined-room",this.onConnectRoomFn),this.context.connection.beginListen("user-joined-room",this.onUserJoinedOrLeftRoomFn),this.context.connection.beginListen("user-left-room",this.onUserJoinedOrLeftRoomFn),this.subscribePeerEvents())}disable(){!this._enabled||(this._enabled=!1,this.context.connection.stopListening("joined-room",this.onConnectRoomFn),this.context.connection.stopListening("user-joined-room",this.onUserJoinedOrLeftRoomFn),this.context.connection.stopListening("user-left-room",this.onUserJoinedOrLeftRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}onUserJoinedOrLeftRoom(e){}setupPeer(){if(!!this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){let e=this.getMyPeerId();this._peer=new Qp.default(e)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){!this._peer||(this._peer.on("open",this.onPeerConnectFn),this._peer.on("call",this.onPeerReceiveCallFn))}unsubscribePeerEvents(){}onPeerConnect(e){nE&&console.log("Peer connected as",e),this.context.connection.send("peer-user-connected",new Md(this,e))}onPeerReceivingCall(e){e.answer(),this.registerCall(e,"incoming")}registerCall(e,t){let i=e.metadata;(!i||!i.userId)&&console.error("Missing call metadata",e);let n=i.userId;console.log(t==="incoming"?"Receive call from":"Make call to",e.metadata);let r=t==="incoming"?this._incomingCalls:this._outgoingCalls,o=new Dd(n,e,t);return r.push(o),e.on("error",s=>{console.error("Call error",s)}),e.on("close",()=>{console.log("Call ended",e.metadata),e.close();let s=r.indexOf(o);s!==-1&&r.splice(s,1)}),t==="incoming"&&(o.addEventListener("receive-video",s=>{this.dispatchEvent(s)}),e.on("stream",()=>{let s=setInterval(()=>{o.isOpen||(clearInterval(s),o.close())},2e3)})),o}},al=Po;z(al,"instances",new Map);var Ld=class extends Hd{context;peer;_sendingVideoStreams=new Map;constructor(e,t){super(),this.context=e,this.peer=t}startSendingVideo(e){this._sendingVideoStreams.has(e)||(this._sendingVideoStreams.set(e,[]),this.updateSendingCalls())}stopSendingVideo(e){if(e){let t=this._sendingVideoStreams.get(e);if(t){console.log("Closing calls",t);for(let i of t)i.close()}this._sendingVideoStreams.delete(e),t&&console.log("Currently sending",this._sendingVideoStreams)}}onConnectRoomFn=this.onConnectRoom.bind(this);onUserConnectedFn=this.onUserConnected.bind(this);onUserLeftFn=this.onUserLeft.bind(this);enable(){this.peer.enable(),this.context.connection.beginListen("peer-user-connected",this.onUserConnectedFn),this.peer.addEventListener("receive-video",this.onReceiveVideo.bind(this))}disable(){this.peer.disable()}onReceiveVideo(e){console.log("RECEIVE VIDEO",e),this.dispatchEvent({type:"receive-video",target:this,stream:e.stream,userId:e.userId})}onConnectRoom(){}onUserConnected(e){if(this.peer.id===e.guid){console.log("USER CONNECTED",e);let t=this._sendingVideoStreams.keys().next().value;this.peer.makeCall(e.peerId,t)}}onUserLeft(e){this.stopCallsToUsersThatAreNotInTheRoomAnymore()}updateSendingCalls(){let e=!1;for(let t of this._sendingVideoStreams.keys()){let i=this._sendingVideoStreams.get(t)||[];for(let n of this.context.connection.usersInRoom()){if(n===this.context.connection.connectionId)continue;if(!i.find(o=>o.userId===n)){let o=this.peer.makeCall(this.peer.getPeerIdFromUserId(n),t);o&&(e=!0,i.push(o))}}this._sendingVideoStreams.set(t,i)}this.stopCallsToUsersThatAreNotInTheRoomAnymore(),e&&console.log("Currently sending",this._sendingVideoStreams)}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(let e of this._sendingVideoStreams.keys()){let t=this._sendingVideoStreams.get(e);if(!!t)for(let i=t.length-1;i>=0;i--){let n=t[i];this.context.connection.userIsInRoom(n.userId)||(n.close(),t.splice(i,1))}}}};import{ShadowMaterial as rE,AdditiveBlending as oE}from"three";var jn=class extends D{mode=0;shadowColor=new ye(0,0,0,1);awake(){switch(this.mode){case 0:this.applyShadowMaterial();break;case 1:this.applyLightBlendMaterial();break}}applyLightBlendMaterial(){let e=A.getComponent(this.gameObject,pe);if(e){let t=e.material;t.blending=oE,this.applyMaterialOptions(t),t.onBeforeCompile=i=>{i.fragmentShader=i.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
207
+ `}};var Np=$o(Us(),1);import*as Fp from"three";import{Color as Xy,Object3D as Qy}from"three";var bd=class extends pi{constructor(){super([Xy,xe])}onDeserialize(e){if(e!=null)return e.a!==void 0?new xe(e.r,e.g,e.b,e.a):e.alpha!==void 0?new xe(e.r,e.g,e.b,e.alpha):new Fp.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}}},FA=new bd,vd=class extends pi{constructor(){super(Qy)}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){let i=t.objectToNode[e.uuid];return Ke&&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 Ke&&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=A.findByGuid(e.guid,n)),i||(i=A.findByGuid(e.guid,t.context.scene)),i?Ke&&console.log("Deserialized object reference?",e,i,t?.nodeToObject):console.warn("could not resolve reference",e,t.target,t.path,t.context.scene),i}}}},Yy=new vd,yd=class extends pi{constructor(){super([Ot,D])}onSerialize(e,t){if(e?.guid)return{guid:e.guid}}onDeserialize(e,t){if(e?.guid){Ke&&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){if(t.guid===e)return t;let i=A.foreachComponent(t,n=>{if(n.guid===e)return n},!1);if(i!==void 0)return i;for(let n=0;n<t.children.length;n++){let r=t.children[n],o=this.findObjectForGuid(e,r);if(o)return o}}},gd=new yd,Ed=class extends pi{constructor(){super([Ae])}onSerialize(e,t){console.log("TODO: SERIALIZE EVENT")}onDeserialize(e,t){if(e&&e.type==="EventList"){Ke&&console.log("DESERIALIZE EVENT",e);let i=new Array;for(let o of e.calls){Ke&&console.log(o);let s=gd.findObjectForGuid(o.target,t.root);!s&&t.context?.scene&&(s=gd.findObjectForGuid(o.target,t.context?.scene));let c=o.method?.length>0;if(s&&c){let h=()=>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||h()}}let d,a=o.argument;o.argument!==void 0?(typeof a=="object"&&(a=Yy.onDeserialize(o.argument,t),a||(a=gd.onDeserialize(o.argument,t))),d=new Ji(c?(...h)=>u(...h):void 0,o.enabled)):d=new Ji(c?(...h)=>u(...h):void 0,o.enabled);let u=(...h)=>{let f=s[o.method];typeof f=="function"?a!==void 0?f?.call(s,a):f?.call(s,...h):s[o.method]=a};if(d.method||(d.__debuginfo=t.object?.name),!s||!d.method){let h=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,h,e)}else i.push(d)}let n=new Ae(i);Ke&&console.log(n);let r=t.target;return r!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,r),n}}},NA=new Ed;import{EventDispatcher as Cd}from"three";var Jy=H("debugscreenshare");function Ba(l){if(!!l)for(let e of l.getTracks())e.stop()}var Mr=class extends D{onPointerClick(){if(this.isReceiving){this.videoPlayer&&(this.videoPlayer.screenspace=!this.videoPlayer.screenspace);return}if(this.isSending){this.close();return}this.share()}videoPlayer;device=0;get currentScream(){return this._currentStream}get currentMode(){return this._currentMode}get isSending(){return this._currentStream?.active&&this._currentMode===1}get isReceiving(){if(this._currentMode===2){if(!this._currentStream||this._currentStream.active===!1)return!1;let e=this._currentStream.getTracks();for(let t of e)if(t.readyState==="live")return!0}return!1}_net;_requestOpen=!1;_currentStream=null;_currentMode=0;awake(){console.log(this),le.registerWaitForAllowAudio(()=>{this.videoPlayer&&this._currentStream&&this._currentMode===2&&this.videoPlayer.setVideo(this._currentStream)})}start(){if(this.videoPlayer||(this.videoPlayer=A.getComponent(this.gameObject,Me)??void 0),!this.videoPlayer){console.error("Screencapture did not find a VideoPlayer component");return}let e=Fa.getOrCreate(this.context,this.guid);this._net=new Td(this.context,e),this._net.enable(),this._net.addEventListener(zp.ReceiveVideo,this.onReceiveVideo.bind(this))}async share(){this._requestOpen=!0;try{if(this.videoPlayer){let e={echoCancellation:!0,autoGainControl:!1},t={video:e,audio:e};switch(this.device){case 1:this.tryShareUserCamera(t);break;case 0:if(!navigator.mediaDevices.getDisplayMedia){console.error("No getDisplayMedia support");return}let i=await navigator.mediaDevices.getDisplayMedia(t);this._requestOpen?this.setVideo(i,1):Ba(i);break;case 2:let n=0,r=this.context.renderer.domElement.captureStream(n);this.setVideo(r,1);break}}}catch(e){if(e.name==="NotAllowedError"){console.log("Selection cancelled"),this._requestOpen=!1;return}console.error("Error opening video",e)}}close(){this._requestOpen=!1,this._currentStream&&(console.warn("Close current stream / disposing resources"),this._net?.stopSendingVideo(this._currentStream),Ba(this._currentStream),this._currentMode=0,this._currentStream=null)}setVideo(e,t){if(e===this._currentStream||(this.close(),!e||!this.videoPlayer))return;this._currentStream=e,this._requestOpen=!0,this._currentMode=t,this.videoPlayer.setVideo(e),t===1&&this._net?.startSendingVideo(e),e.addEventListener("ended",()=>{this.close()})}onReceiveVideo(e){this.setVideo(e.stream,2)}async tryShareUserCamera(e){let t=(await navigator.mediaDevices.enumerateDevices()).filter(i=>i.kind==="videoinput");console.log("Request camera",t);for(let i of t)try{if(!this._requestOpen)break;if(i.kind!=="videoinput")continue;let n=i.deviceId;e.video!==!1&&((typeof e.video>"u"||typeof e.video=="boolean")&&(e.video={}),e.video.deviceId=n);let r=await navigator.mediaDevices.getUserMedia(e);this._requestOpen?this.setVideo(r,1):Ba(r),console.log("Selected camera",i);break}catch(n){console.warn(n)}}};k([O(Me)],Mr.prototype,"videoPlayer",2),k([O()],Mr.prototype,"device",2);var zp=(i=>(i.Connected="peer-user-connected",i.ReceiveVideo="receive-video",i.Disconnected="peer-user-disconnected",i))(zp||{}),wd=class{type="receive-video";stream;target;constructor(e,t){this.stream=e,this.target=t}},_d=class{guid;peerId;dontSave=!0;constructor(e,t){this.guid=e.id,this.peerId=t}};var xd=class extends Cd{userId;direction;call;get stream(){return this._stream}_stream=null;_isDisposed=!1;close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),Ba(this._stream))}get isOpen(){return this.call.peerConnection?.connectionState==="connected"}get isClosed(){return!this.isOpen}constructor(e,t,i){super(),this.userId=e,this.call=t,this.direction=i,this._stream=null,t.on("stream",n=>{if(console.log("Receive video",n.getAudioTracks(),n.getVideoTracks()),this._stream=n,i==="incoming"){let r=new wd(n,this);this.dispatchEvent(r)}})}},Dr=class extends Cd{static getOrCreate(e,t){if(Dr.instances.has(t))return Dr.instances.get(t);let i=new Dr(e,t);return Dr.instances.set(t,i),i}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(e){return this.id+"-"+e}getUserIdFromPeerId(e){return e.substring(this.id.length+1)}makeCall(e,t){let i={metadata:{userId:this.context.connection.connectionId}},n=this._peer?.call(e,t,i);if(n)return this.registerCall(n,"outgoing")}get peer(){return this._peer}id;context;_peer;_incomingCalls=[];_outgoingCalls=[];constructor(e,t){super(),this.context=e,this.id=t,this.setupPeer(),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia}_enabled=!1;_enabledPeer=!1;onConnectRoomFn=this.onConnectRoom.bind(this);onUserJoinedOrLeftRoomFn=this.onUserJoinedOrLeftRoom.bind(this);onPeerConnectFn=this.onPeerConnect.bind(this);onPeerReceiveCallFn=this.onPeerReceivingCall.bind(this);enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen("joined-room",this.onConnectRoomFn),this.context.connection.beginListen("user-joined-room",this.onUserJoinedOrLeftRoomFn),this.context.connection.beginListen("user-left-room",this.onUserJoinedOrLeftRoomFn),this.subscribePeerEvents())}disable(){!this._enabled||(this._enabled=!1,this.context.connection.stopListening("joined-room",this.onConnectRoomFn),this.context.connection.stopListening("user-joined-room",this.onUserJoinedOrLeftRoomFn),this.context.connection.stopListening("user-left-room",this.onUserJoinedOrLeftRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}onUserJoinedOrLeftRoom(e){}setupPeer(){if(!!this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){let e=this.getMyPeerId();this._peer=new Np.default(e)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){!this._peer||(this._peer.on("open",this.onPeerConnectFn),this._peer.on("call",this.onPeerReceiveCallFn))}unsubscribePeerEvents(){}onPeerConnect(e){Jy&&console.log("Peer connected as",e),this.context.connection.send("peer-user-connected",new _d(this,e))}onPeerReceivingCall(e){e.answer(),this.registerCall(e,"incoming")}registerCall(e,t){let i=e.metadata;(!i||!i.userId)&&console.error("Missing call metadata",e);let n=i.userId;console.log(t==="incoming"?"Receive call from":"Make call to",e.metadata);let r=t==="incoming"?this._incomingCalls:this._outgoingCalls,o=new xd(n,e,t);return r.push(o),e.on("error",s=>{console.error("Call error",s)}),e.on("close",()=>{console.log("Call ended",e.metadata),e.close();let s=r.indexOf(o);s!==-1&&r.splice(s,1)}),t==="incoming"&&(o.addEventListener("receive-video",s=>{this.dispatchEvent(s)}),e.on("stream",()=>{let s=setInterval(()=>{o.isOpen||(clearInterval(s),o.close())},2e3)})),o}},Fa=Dr;N(Fa,"instances",new Map);var Td=class extends Cd{context;peer;_sendingVideoStreams=new Map;constructor(e,t){super(),this.context=e,this.peer=t}startSendingVideo(e){this._sendingVideoStreams.has(e)||(this._sendingVideoStreams.set(e,[]),this.updateSendingCalls())}stopSendingVideo(e){if(e){let t=this._sendingVideoStreams.get(e);if(t){console.log("Closing calls",t);for(let i of t)i.close()}this._sendingVideoStreams.delete(e),t&&console.log("Currently sending",this._sendingVideoStreams)}}onConnectRoomFn=this.onConnectRoom.bind(this);onUserConnectedFn=this.onUserConnected.bind(this);onUserLeftFn=this.onUserLeft.bind(this);enable(){this.peer.enable(),this.context.connection.beginListen("peer-user-connected",this.onUserConnectedFn),this.peer.addEventListener("receive-video",this.onReceiveVideo.bind(this))}disable(){this.peer.disable()}onReceiveVideo(e){console.log("RECEIVE VIDEO",e),this.dispatchEvent({type:"receive-video",target:this,stream:e.stream,userId:e.userId})}onConnectRoom(){}onUserConnected(e){if(this.peer.id===e.guid){console.log("USER CONNECTED",e);let t=this._sendingVideoStreams.keys().next().value;this.peer.makeCall(e.peerId,t)}}onUserLeft(e){this.stopCallsToUsersThatAreNotInTheRoomAnymore()}updateSendingCalls(){let e=!1;for(let t of this._sendingVideoStreams.keys()){let i=this._sendingVideoStreams.get(t)||[];for(let n of this.context.connection.usersInRoom()){if(n===this.context.connection.connectionId)continue;if(!i.find(o=>o.userId===n)){let o=this.peer.makeCall(this.peer.getPeerIdFromUserId(n),t);o&&(e=!0,i.push(o))}}this._sendingVideoStreams.set(t,i)}this.stopCallsToUsersThatAreNotInTheRoomAnymore(),e&&console.log("Currently sending",this._sendingVideoStreams)}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(let e of this._sendingVideoStreams.keys()){let t=this._sendingVideoStreams.get(e);if(!!t)for(let i=t.length-1;i>=0;i--){let n=t[i];this.context.connection.userIsInRoom(n.userId)||(n.close(),t.splice(i,1))}}}};import{ShadowMaterial as Zy,AdditiveBlending as $y}from"three";var Lr=class extends D{mode=0;shadowColor=new xe(0,0,0,1);awake(){switch(this.mode){case 0:this.applyShadowMaterial();break;case 1:this.applyLightBlendMaterial();break}}applyLightBlendMaterial(){let e=A.getComponent(this.gameObject,be);if(e){let t=e.material;t.blending=$y,this.applyMaterialOptions(t),t.onBeforeCompile=i=>{i.fragmentShader=i.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
203
208
 
204
209
  // diffuse-only lighting with overdrive to somewhat compensate
205
210
  // for the loss of indirect lighting and to make it more visible.
@@ -210,8 +215,8 @@ irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
210
215
  // be blended onto the scene.
211
216
  gl_FragColor = vec4(direct, max);
212
217
  return;
213
- `)}}}applyShadowMaterial(){let e=A.getComponent(this.gameObject,pe);if(e)if(e.material?.type!=="ShadowMaterial"){let t=new rE;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([O()],jn.prototype,"mode",2),k([O(ye)],jn.prototype,"shadowColor",2);import{RGBELoader as lE}from"three/examples/jsm/loaders/RGBELoader.js";import{EXRLoader as cE}from"three/examples/jsm/loaders/EXRLoader";import{EquirectangularRefractionMapping as dE}from"three";var Kp=B("debugautosync"),jd=class{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];let t=new Bd(e);return this._syncers[e.guid]=t,t}},Jp=new jd,Bd=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 sE(c,e){let t=e!==c;if(!t&&c&&e){if(Array.isArray(c)&&Array.isArray(e))t=!0;else if(typeof c=="object"&&typeof e=="object"){for(let i of Object.keys(c))if(c[i]!==e[i]){t=!0;break}}}return t}function aE(c){if(c.__autoPropertySyncHandler)return c.__autoPropertySyncHandler;let e=Jp.getOrCreateSyncer(c);return e?.init(c),c.__autoPropertySyncHandler=e,e}var ll=function(c){return function(e,t){let i=null,n=c?e[c]:void 0,r=e,o=r.__internalAwake;Kp&&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=Jp.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,t)?.set===void 0&&Object.defineProperty(this,t,{set:function(d){let a=this[s];this[s]=d,sE(d,a)&&n?.call(this,d,a)!==!1&&aE(this)?.notifyChanged(t,d)},get:function(){return this[s]},configurable:!0,enumerable:!0}),i?.init(this)}}};var Bn=class extends D{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 cE:new lE}let t=await this._loader.loadAsync(e);if(!t||!this.enabled)return;this.url=e,t.mapping=dE,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([ll("setSkybox"),O()],Bn.prototype,"url",2),k([O()],Bn.prototype,"allowDrop",2);import*as Oo from"three";import{Object3D as hE}from"three";var Fd=class extends D{target=null;followFactor=.1;rotateFactor=.1;flipForward=!1;_firstUpdate=!0;onEnable(){let e=A.getComponentInChildren(this.gameObject,he);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 Oo.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:K.clamp01(this.context.time.deltaTime*this.followFactor);this.worldPosition=this.worldPosition.lerp(t,i)}if(this.rotateFactor>0){let t=Pe(this.target);this.flipForward&&t.premultiply(Fd._invertForward);let i=this._firstUpdate||e?1:K.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(t,i)}this._firstUpdate=!1}}},Pi=Fd;z(Pi,"_invertForward",new Oo.Quaternion().setFromAxisAngle(new Oo.Vector3(0,1,0),Math.PI)),k([O(hE)],Pi.prototype,"target",2);import{Layers as ef}from"three";var cl=B("debugspatialtrigger"),Zp=new ef,$p=new ef;function uE(c,e){return Zp.mask=c,$p.mask=e,Zp.test($p)}var yt=class extends D{triggerMask=0;onEnter;onStay;onExit;start(){cl&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(let e of $i.triggers)uE(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){cl&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),this.onEnter?.invoke(this,e)}onExitTrigger(e){cl&&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([O()],yt.prototype,"triggerMask",2),k([O(Re)],yt.prototype,"onEnter",2),k([O(Re)],yt.prototype,"onStay",2),k([O(Re)],yt.prototype,"onExit",2);var Ps=class extends D{triggerMask;boxHelper;start(){cl&&console.log(this.name,this.triggerMask,this)}onEnable(){Ps.triggers.push(this),this.boxHelper||(this.boxHelper=A.addNewComponent(this.gameObject,ot),this.boxHelper?.showHelper())}onDisable(){Ps.triggers.splice(Ps.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){A.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof yt&&t.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){A.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof yt&&t.onStayTrigger(this)},!1)}raiseOnExitEvent(e){A.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof yt&&t.onExitTrigger(this)},!1)}},$i=Ps;z($i,"triggers",[]),k([O()],$i.prototype,"triggerMask",2);import*as Fn from"three";var Et=B("debugspectator"),ko=class extends D{cam=null;_mode=0;get mode(){return this._mode}set mode(e){this._mode=e}get isSpectating(){return this._handler?.currentTarget!==void 0}isSpectatingUser(e){return this.target?.userId===e}isFollowedBy(e){return this.followers?.includes(e)}get followers(){return this._networking.followers}stopSpectating(){if(this.context.isInXR){this.followSelf();return}this.target=void 0}set target(e){if(this._handler){let t=this._handler.currentTarget?.userId,i=this.context.players.getPlayerView(this.context.connection.connectionId);e===void 0||this.context.isInXR===!1&&i?.currentObject===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),A.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,t)):this._handler.currentTarget!==e&&(this._handler.set(e),A.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,t))}}get target(){return this._handler?.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){return this.isSpectating&&this.target?.currentObject===this.context.players.getPlayerView(this.context.connection.connectionId)?.currentObject}orbit=null;_handler;eventSub_WebXRRequestStartEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;_debug;_networking;awake(){if(this._debug=new zd(this.context,this),this._networking=new Gd(this.context,this),this._networking.awake(),A.setActive(this.gameObject,!1),this.cam=A.getComponent(this.gameObject,he),!this.cam){console.error("Spectator camera needs camera component",this);return}!this._handler&&this.cam&&(this._handler=new Nd(this.context,this.cam,this)),this.eventSub_WebXRRequestStartEvent=this.onXRSessionRequestStart.bind(this),this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),Q.addEventListener("requestVRSession",this.eventSub_WebXRRequestStartEvent),Q.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),Q.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.orbit=A.getComponent(this.context.mainCamera,gt)}onDestroy(){this.stopSpectating(),Q.removeEventListener("requestVRSession",this.eventSub_WebXRStartEvent),Q.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),Q.removeEventListener("xrStopped",this.eventSub_WebXREndEvent),this._handler?.destroy(),this._networking.destroy()}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.isSupportedPlatform()||A.setActive(this.gameObject,!0)}onXRSessionStart(e){!this.isSupportedPlatform()||(Et&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onXRSessionEnded(e){this.context.removeCamera(this.cam),A.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._handler?.set(void 0),this._handler?.disable(),this.isSpectatingSelf&&this.stopSpectating()}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),Et&&console.log("Follow self",this.target)}onAfterRender(){if(!this.cam)return;let e=this.context.renderer,t=e.xr.enabled;if(!e.xr.isPresenting&&!this._handler?.currentTarget)return;this._handler?.update(this._mode);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();let r=this.context.mainCameraComponent;if(r){let l=r.backgroundColor;l&&e.setClearColor(l,l.alpha),this.cam.backgroundColor=l,this.cam.clearFlags=r.clearFlags,this.cam.nearClipPlane=r.nearClipPlane,this.cam.farClipPlane=r.farClipPlane}else e.setClearColor(new Fn.Color(1,1,1));e.setRenderTarget(null),e.xr.enabled=!1;let o=this.cam?.cam;this.context.updateAspect(o);let s=e.xr.isPresenting;e.xr.isPresenting=!1,e.setSize(this.context.domWidth,this.context.domHeight),e.render(this.context.scene,o),e.xr.isPresenting=s,e.xr.enabled=t,i?e.setRenderTarget(i):e.state.bindXRFramebuffer(n),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){let e=this._mode===0;for(let t of ue.instances)if(t.avatar&&"isLocalAvatar"in t.avatar){let i=4294967295;this.isSpectatingSelf&&(i=e&&t.avatar.isLocalAvatar?8:16);let n=t.avatar.flags;if(!n)continue;for(let r of n)r.UpdateVisible(i)}}resetAvatarFlags(){for(let e of ue.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)}}},Nd=class{context;cam;spectator;follow;target;view;currentObject;get currentTarget(){return this.view}constructor(e,t,i){this.context=e,this.cam=t,this.spectator=i}set(e){let t=e?.currentObject;if(!t){this.spectator.stopSpectating();return}t!==this.currentObject&&(this.currentObject=t,this.view=e,this.follow||(this.follow=A.addNewComponent(this.cam.gameObject,Pi)),this.target||(this.target=new Fn.Object3D),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Et&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Et&&console.log("STOP FOLLOW",this.currentObject),this.view=void 0,this.currentObject=void 0,this.context.removeCamera(this.cam),this.follow&&(this.follow.enabled=!1)}destroy(){this.target?.removeFromParent(),this.follow&&A.destroy(this.follow)}update(e){if(this.currentTarget?.isConnected===!1||this.currentTarget?.removed===!0){Et&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&this.currentTarget?.currentObject!==this.currentObject&&(Et&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));let t=this.context.mainCamera;t&&(this.cam.cam.near!==t.near||this.cam.cam.far!==t.far)&&(this.cam.cam.near=t.near,this.cam.cam.far=t.far,this.cam.cam.updateProjectionMatrix());let i=this.follow?.target;if(!(!i||!this.follow)){switch(e){case 0:this.view?.viewDevice!=="browser"?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),i.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,i.position.set(0,.5,1.5);break}this.follow.flipForward=!1,this.view?.viewDevice!=="browser"?i.quaternion.copy(pE):i.quaternion.identity()}}},pE=new Fn.Quaternion().setFromAxisAngle(new Fn.Vector3(0,1,0),Math.PI),zd=class{context;spectator;constructor(e,t){this.context=e,this.spectator=t,console.log("Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),window.addEventListener("keydown",n=>{n.key==="Escape"&&this.spectator.stopSpectating()});let i=0;this.context.input.addEventListener("pointerdown",n=>{i=this.context.time.time}),this.context.input.addEventListener("pointerup",n=>{let r=this.context.time.time-i;r>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&r<.3&&this.trySelectObject()})}trySelectObject(){let e=new _e;e.setMask(16777215);let t=this.context.physics.raycast(e);if(Et&&console.log(...t),t?.length)for(let i of t){if(i.distance<.2)continue;let n=i.object,r=A.getComponentInParent(n,ue),o=r?.connectionId;if(o){let s=this.context.players.getPlayerView(o);this.spectator.target=s,Et&&console.log("spectate",o,r);break}}}},Ud=class{guid;dontSave=!0;targetUserId;stoppedFollowing;constructor(e,t,i){this.guid=e,this.targetUserId=t,this.stoppedFollowing=i}},Vd=class{guid;userId;constructor(e,t){this.guid=e.guid,this.userId=t}},Gd=class{followers=[];context;spectator;_followerEventMethod;_requestFollowMethod;_joinedRoomMethod;constructor(e,t){this.context=e,this.spectator=t,this._followerEventMethod=this.onFollowerEvent.bind(this),this._requestFollowMethod=this.onRequestFollowEvent.bind(this),this._joinedRoomMethod=this.onUserJoinedRoom.bind(this)}awake(){this.context.connection.beginListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.beginListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.beginListen("joined-room",this._joinedRoomMethod),document.addEventListener("keydown",e=>{e.key==="f"?this.onRequestFollowMe():e.key==="Escape"&&this.onRequestFollowMe(!0)})}destroy(){this.context.connection.stopListening("spectator-follower-changed",this._followerEventMethod),this.context.connection.stopListening("spectator-request-follow",this._requestFollowMethod),this.context.connection.stopListening("joined-room",this._joinedRoomMethod)}onSpectatedObjectChanged(e,t){if(Et&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",e,t),this.context.connection.connectionId){let i=e?.userId===void 0,n=i?t:e?.userId,r=new Ud(this.context.connection.connectionId,n,i);this.context.connection.send("spectator-follower-changed",r)}}onRequestFollowMe(e=!1){if(Et&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();let t=e?void 0:this.context.connection.connectionId,i=new Vd(this.spectator,t);this.context.connection.send("spectator-request-follow",i)}}onUserJoinedRoom(){B("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){let t=e.targetUserId,i=e.guid;if(Et&&console.log(e),t===this.context.connection.connectionId)if(e.stoppedFollowing){let n=this.followers.indexOf(i);n!==-1&&(this.followers.splice(n,1),this.removeDisconnectedFollowers(),console.log(i,"unfollows you",this.followers.length))}else this.followers.includes(i)||(this.followers.push(i),this.removeDisconnectedFollowers(),console.log(i,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let e=this.followers.length-1;e>=0;e--){let t=this.followers[e];this.context.connection.userIsInRoom(t)===!1&&this.followers.splice(e,1)}}_lastRequestFollowUser;onRequestFollowEvent(e){if(this._lastRequestFollowUser=e,e.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(e.userId===void 0)this.spectator.stopSpectating();else{let t=this.context.players.getPlayerView(e.userId);if(t)this.spectator.target=t;else return Et&&console.warn("Could not find view",e.userId),this.enforceFollow(),!1}return!0}_enforceFollowInterval;enforceFollow(){this._enforceFollowInterval||(this._enforceFollowInterval=setInterval(()=>{this._lastRequestFollowUser===void 0||this._lastRequestFollowUser.userId&&this.spectator.isFollowedBy(this._lastRequestFollowUser.userId)?(clearInterval(this._enforceFollowInterval),this._enforceFollowInterval=void 0):(Et&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}};var Ao=class extends D{anchor=null;connectedBody=null;connectedAnchor=null;spring=10;damper=.2;rb=null;awake(){if(this.rb=A.getComponent(this.gameObject,se),!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 Zs(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 wt from"three";import{Material as fE,Texture as mE}from"three";var xr=class{texture;triangles;uv;vertices;_geometry};k([O(mE)],xr.prototype,"texture",2);var dl=class{static getOrCreateGeometry(e){if(e._geometry)return e._geometry;let t=new wt.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 wt.BufferAttribute(i,3)),t.setAttribute("uv",new wt.BufferAttribute(n,2)),t}},en=class extends D{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=dl.getOrCreateGeometry(this.sprite),this._currentSprite.material.map=this.sprite.texture;else{let e=new wt.MeshBasicMaterial({color:16777215,side:wt.DoubleSide});if(!e)return;if(this.color&&(e.color||(e.color=new wt.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 wt.Mesh(dl.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([O()],en.prototype,"drawMode",2),k([O(ye)],en.prototype,"color",2),k([O(fE)],en.prototype,"sharedMaterial",2);var _t=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 _t).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+4),(t||new _t).__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 Te).__init(this.bb_pos+t,this.bb):null}rot(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new Te).__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 gE}from"three";var hl="SCAM";$r(hl,_t.getRootAsSyncedCameraModel);var xt=new ut,Wd=class{userId;guid;constructor(e,t){this.guid=t,this.userId=e}send(e,t){if(e){xt.clear();let i=xt.createString(this.guid),n=xt.createString(this.userId);_t.startSyncedCameraModel(xt),_t.addGuid(xt,i),_t.addUserId(xt,n);let r=q(e),o=ra(e);_t.addPos(xt,Te.createVec3(xt,r.x,r.y,r.z)),_t.addRot(xt,Te.createVec3(xt,o.x,o.y,o.z));let s=_t.endSyncedCameraModel(xt);xt.finish(s,hl),t.sendBinary(xt.asUint8Array())}}},ul=class extends D{getCameraObject(e){let t=this.userToCamMap[e];return t?this.remoteCams[t].obj: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))}onEnable(){this._receiveCallback=this.context.connection.beginListenBinrary(hl,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(hl,this._receiveCallback)}update(){for(let n in this.remoteCams){let r=this.remoteCams[n],o=this.context.time.realtimeSinceStartup-r.lastUpdate;if(!r||o>this._camTimeoutInSeconds){console.log("Remote cam timeout",r,o),r?.obj&&A.destroy(r.obj),delete this.remoteCams[n],r&&delete this.userToCamMap[r.userId],ul.instances.push(r),this.context.players.removePlayerView(r.userId,"browser");continue}}if(Q.IsInWebXR)return;let e=this.context.mainCamera;if(e===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new Wd(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));let t=q(e),i=Pe(e);(t.distanceTo(this._lastWorldPosition)>.001||i.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(t),this._lastWorldQuaternion.copy(i),!((!this._needsUpdate||this.context.time.frameCount%2!==0)&&!(this.context.time.realtimeSinceStartup-this._lastUpdateTime>this._camTimeoutInSeconds*.5))&&(this._lastUpdateTime=this.context.time.realtimeSinceStartup,this._needsUpdate=!1,this._model.send(e,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,e,"browser"))}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 l=new Be;l.context=this.context;let d=A.instantiate(this.cameraPrefab,l);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,ul.instances.push(n);let a=A.getOrAddComponent(d,ue);a.connectionId=i,a.avatar=d}else return;let r=n.obj;this.context.players.setPlayerView(i,r,"browser"),n.lastUpdate=this.context.time.realtimeSinceStartup,re.markDirty(r);let o=e.pos();o&&Vr(r,o.x(),o.y(),o.z());let s=e.rot();s&&oa(r,s.x(),s.y(),s.z())}},Nn=ul;z(Nn,"instances",[]),k([O([gE,Ke])],Nn.prototype,"cameraPrefab",2);var qd="view",tf=B("debugsyncedroom"),oi=class extends D{roomName;urlParameterName;joinRandomRoom=!0;requireRoomParameter=!1;autoRejoin=!0;_roomPrefix;awake(){this._roomPrefix===void 0&&(this._roomPrefix=this.roomName,this.roomName="")}onEnable(){let e=B(qd);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){e===void 0&&(e=0);let t=!1;if(this.urlParameterName){let i=B(this.urlParameterName);if(i&&typeof i=="string"){t=!0;let n=gh(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?(tf&&console.log('No required room parameter "'+this.urlParameterName+'" in url - will not connect to networking backend.'),!1):!this.roomName||this.roomName.length<=0?(tf&&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=B(qd);return e||B(this.urlParameterName)}setRandomRoomUrlParameter(){let e=Al(),t=this.generateRoomName();B(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),ph(t,e)}generateRoomName(){return mh()+"_"+fh(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(qd,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}};k([O()],oi.prototype,"roomName",2),k([O()],oi.prototype,"urlParameterName",2),k([O()],oi.prototype,"joinRandomRoom",2),k([O()],oi.prototype,"requireRoomParameter",2),k([O()],oi.prototype,"autoRejoin",2);function nf(){let c=B("testwindowcount")||0;c&&c>0&&bE(c)}function bE(c){if(B("testwindow"))return null;let e=new URL(window.location.href);jr(e.searchParams,co,1),jr(e.searchParams,"testwindow",1);let t=e.toString(),i=[];window.onbeforeunload=()=>{for(let l of i)l.close()};let n=.05,r=128,o=0,s=0;for(let l=0;l<c;l++){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 u=window.open(t,"test window "+l,`popup=yes width=${r} height=${r} top=${a} left=${d}`);if(!u){console.warn("Failed to open window");continue}i.push(u),u.onload=()=>{u.onbeforeunload=()=>{for(let h=0;h<i.length;h++){let m=i[h];m!==u&&m.close()}i.length=0}}}return i}import{Vector3 as yE}from"three";var Io=class extends D{awake(){nf()}},Mo=class extends D{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinrary(so,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new pl(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 ut(1024));let e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();let i=Wc(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)}}}},pl=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(pl,"temp",new yE);import{MathUtils as EE}from"three";import{TransformControls as wE}from"three/examples/jsm/controls/TransformControls";import{OrbitControls as _E}from"three/examples/jsm/controls/OrbitControls";var Tr=class extends D{isGizmo=!0;control;orbit;awake(){this.isGizmo&&!si||!this.context.mainCamera||(this.control=new wE(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=A.getComponentInParent(this.context.mainCamera,_E)??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=A.getComponentInParent(this.gameObject,ft);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(EE.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([O()],Tr.prototype,"isGizmo",2);import{LinearToneMapping as rf,ACESFilmicToneMapping as xE,ReinhardToneMapping as TE}from"three";var fl=B("debugvolume"),sf=(i=>(i[i.None=0]="None",i[i.Neutral=1]="Neutral",i[i.ACES=2]="ACES",i))(sf||{}),Do=class{overrideState=!1;value=0},Oi=class{active=!1;parameters},Un=class extends Oi{mode;get isToneMapping(){return!0}},Vn=class extends Oi{postExposure};function CE(c){return"mode"in c?Un:"postExposure"in c?Vn:Oi}var of=Symbol("volumeprofile"),zn=class{components;apply(e){this.onUpdate(e,!1)}unapply(e){this.onUpdate(e,!0)}onUpdate(e,t){if(!this.components)return;let i=e.renderer,r=i[of]!==void 0;if(t){if(!r)return}else i[of]=this;for(let o of this.components)if(o instanceof Un){let s=o;if(!o.active||t){e.renderer.toneMapping=rf;continue}switch(fl&&console.log("VOLUME:",sf[s.mode?.value??0]),s.mode?.value??0){case 0:e.renderer.toneMapping=rf;break;case 1:e.renderer.toneMapping=TE;break;case 2:e.renderer.toneMapping=xE;break}}else if(o instanceof Vn){let s=o;fl&&console.log(s.postExposure);let l=Math.pow(2,s.postExposure?.value??0),d=s.postExposure?.overrideState&&!t;e.renderer.toneMappingExposure=d?l:1}}};k([O([c=>CE(c),Oi])],zn.prototype,"components",2);var Cr=class extends D{sharedProfile;awake(){fl&&(console.log(this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",e=>{e.key==="p"&&(console.log("Toggle volume: "+this.name,!this.enabled),this.enabled=!this.enabled)}))}onEnable(){fl&&console.log("APPLY VOLUME",this),this.sharedProfile?.apply(this.context)}onDisable(){this.sharedProfile?.unapply(this.context)}};k([O(zn)],Cr.prototype,"sharedProfile",2);import*as af from"three";var Rr=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}},Lo=class extends D{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=at.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),at.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=A.instantiate(this.prefab);if(i.visible=!0,this._instances[e.guid]={instance:i,model:e},e.userId){let n=A.getComponentsInChildren(i,lt);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]&&(A.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<at.Current.length;e++){let t=at.Current[e];if(!t.controller||!t.selected)continue;this._grabModels.length<=e&&(this._grabModels.push(new Rr),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 af.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),oe(i,o)}}};import{Object3D as RE}from"three";var ki=class extends D{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=A.getComponentInParent(this.gameObject,Ce)}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([O(RE)],ki.prototype,"eyes",2),k([O()],ki.prototype,"lastBlinkTime",2),k([O()],ki.prototype,"blinkLength",2),k([O()],ki.prototype,"eyesOpen",2);import*as ml from"three";import{Object3D as Xd}from"three";var Qd=class extends D{head=null;eyes=null;target=null;brain=null;awake(){this.brain||(this.brain=A.getComponentInParent(this.gameObject,Wi)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=A.addNewComponent(this.gameObject,Wi)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new ml.Vector3;currentTargetPoint=new ml.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=Qd.forward;if(o.set(0,0,1),o.applyQuaternion(Pe(this.head)),o.dot(r)>.45)for(let l=0;l<t.length;l++)t[l].lookAt(this.currentTargetPoint)}}}},Ai=Qd;z(Ai,"forward",new ml.Vector3(0,0,1)),k([O(Xd)],Ai.prototype,"head",2),k([O(Xd)],Ai.prototype,"eyes",2),k([O(Xd)],Ai.prototype,"target",2);import{Object3D as lf}from"three";var SE=B("debugmouth"),Gn=class extends D{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){setTimeout(()=>{this.voip=A.findObjectOfType(Je,this.context),this.marker||(this.marker=A.getComponentInParent(this.gameObject,ue))},3e3)}update(){if(!this.voip||this.context.time.frameCount%10!==0)return;let e=this.marker?.connectionId??null;if(!e){SE&&(e=null);return}let t=this.voip.getFrequency(e)??0;this.updateLips(t)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;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)}}}};k([O(lf)],Gn.prototype,"idle",2),k([O(lf)],Gn.prototype,"talking",2);var Ho=class extends D{voip=null;marker=null;_startPosition=null;awake(){this.voip=A.findObjectOfType(Je,this.context),this.marker=A.getComponentInParent(this.gameObject,ue)}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 $d={};dh($d,{AlignmentConstraint:()=>_n,Animation:()=>xn,AnimationCurve:()=>dr,AnimationTrackHandler:()=>Wn,Animator:()=>At,AnimatorController:()=>Jt,AttachedObject:()=>at,AudioListener:()=>Zt,AudioSource:()=>ce,AudioTrackHandler:()=>qn,AvatarBlink_Simple:()=>ki,AvatarEyeLook_Rotation:()=>Ai,AvatarLoader:()=>Cn,AvatarMarker:()=>ue,AvatarModel:()=>hr,Avatar_Brain_LookAt:()=>Wi,Avatar_MouthShapes:()=>Gn,Avatar_MustacheShake:()=>Ho,Avatar_POI:()=>Ee,AxesHelper:()=>Ui,BaseUIComponent:()=>Fe,BasicIKConstraint:()=>io,BoxCollider:()=>Pn,BoxGizmo:()=>Yi,BoxHelperComponent:()=>ot,Button:()=>Nt,CallInfo:()=>Ti,Camera:()=>he,Canvas:()=>Ne,CanvasGroup:()=>ln,Collider:()=>bi,ColorAdjustments:()=>Vn,ControlTrackHandler:()=>nn,Deletable:()=>ro,DeleteBox:()=>pr,DeviceFlag:()=>fr,DragControls:()=>_i,DropListener:()=>Mn,Duplicatable:()=>xi,EmissionModule:()=>Co,EventList:()=>Re,EventListEvent:()=>gr,EventSystem:()=>Ve,EventTrigger:()=>go,FieldWithDefault:()=>vo,FlyControls:()=>bo,GltfExport:()=>Ft,GltfExportBox:()=>Eo,Graphic:()=>Tt,GraphicRaycaster:()=>Xo,GridHelper:()=>Ji,GridLayoutGroup:()=>qo,GroundProjectedEnv:()=>Zi,HorizontalLayoutGroup:()=>Wo,Image:()=>an,InputField:()=>Ct,Interactable:()=>It,Keyboard:()=>Vo,LODGroup:()=>Ln,LODModel:()=>Ri,LayoutGroup:()=>cn,Light:()=>Ge,LogStats:()=>jo,LookAtConstraint:()=>qi,MainModule:()=>To,MaskableGraphic:()=>sn,MeshRenderer:()=>yr,NavMesh:()=>_o,NavMeshAgent:()=>xo,NestedGltf:()=>Er,Networking:()=>ht,ObjectRaycaster:()=>Mr,OffsetConstraint:()=>Si,OrbitControls:()=>gt,ParticleSystem:()=>So,ParticleSystemRenderer:()=>_r,PlayableDirector:()=>on,PlayerColor:()=>lt,PointerEventData:()=>ti,RGBAColor:()=>ye,RawImage:()=>kr,Raycaster:()=>Ir,Rect:()=>Or,RectTransform:()=>ct,RemoteSkybox:()=>Bn,Renderer:()=>pe,RendererLightmap:()=>Ki,Rigidbody:()=>se,ScreenCapture:()=>Hn,ShadowCatcher:()=>jn,ShapeModule:()=>Ro,SignalAsset:()=>Sr,SignalReceiver:()=>tn,SignalReceiverEvent:()=>Pr,SignalTrackHandler:()=>rn,Size:()=>zo,SkinnedMeshRenderer:()=>yo,SmoothFollow:()=>Pi,SpatialHtml:()=>Qo,SpatialTrigger:()=>$i,SpatialTriggerReceiver:()=>yt,SpectatorCamera:()=>ko,SphereCollider:()=>Sn,SpringJoint:()=>Ao,Sprite:()=>xr,SpriteRenderer:()=>en,SyncedCamera:()=>Nn,SyncedRoom:()=>oi,SyncedTransform:()=>ft,TeleportTarget:()=>mr,TestRunner:()=>Io,TestSimulateUserData:()=>Mo,Text:()=>Ae,ToneMapping:()=>Un,TransformGizmo:()=>Tr,UIRaycastUtils:()=>ni,UIRootComponent:()=>Xi,UsageMarker:()=>Mt,VRUserState:()=>jt,VerticalLayoutGroup:()=>Go,VideoPlayer:()=>Se,Voip:()=>Je,Volume:()=>Cr,VolumeComponent:()=>Oi,VolumeParameter:()=>Do,VolumeProfile:()=>zn,WebAR:()=>In,WebARSessionRoot:()=>Ht,WebXR:()=>Q,WebXRAvatar:()=>Lt,WebXRController:()=>ie,WebXRSync:()=>Qi,XRFlag:()=>Ce,XRGrabModel:()=>Rr,XRGrabRendering:()=>Lo,XRRig:()=>An,XRState:()=>mt,__Ignore:()=>Is});var PE=B("logstats"),jo=class extends D{onEnable(){console.log(this),PE&&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 hf from"three";var Sr=class{guid},Pr=class{signal;reaction;$serializedTypes={signal:Sr,reaction:Re}},tn=class extends D{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([O(Pr)],tn.prototype,"events",2);import*as ne from"three";import{Quaternion as OE,Vector3 as kE}from"three";var Bo=B("debugtimeline"),Fo=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}},Yd=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";Bo&&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 ne.Vector3().fromArray(o.values,0),this.rootEndPosition=new ne.Vector3().fromArray(o.values,o.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),Bo&&console.log(this.rootPositionOffset);else if(o.name.endsWith(r)&&(this.rootStartQuaternion=new ne.Quaternion().fromArray(o.values,0),this.rootEndQuaternion=new ne.Quaternion().fromArray(o.values,o.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),Bo)){let s=new ne.Euler().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",s)}}}},Wn=class extends Fo{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,l=!1;for(let d of t.tracks)d.name.endsWith(r)?(s=!0,this.createPositionInterpolant(t,e,d)):d.name.endsWith(o)&&(l=!0,this.createRotationInterpolant(t,e,d));if(!s||!l){let d=this.mixer?.getRoot(),a=t.tracks[0],u=a.name.lastIndexOf("."),h=a.name.substring(0,u),m=h.substring(h.lastIndexOf(".")+1),E=d.getObjectByName(m);if(E)if(s){if(!l){let b=t.tracks[0].name.substring(0,u)+".quaternion";Bo&&console.warn("Create quaternion track",m,E);let y=E.quaternion,g=new ne.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=h+".position";Bo&&console.warn("Create position track",m,E);let y=E.position,g=new ne.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,Bo&&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 Yd(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 kE(i.x,i.y,i.z)),n.isQuaternion||(t.rotation=new OE(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 ne.Vector3(e.x,e.y,e.z)));let t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new ne.Quaternion(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new ne.Vector3;_totalOffsetRotation=new ne.Quaternion;_totalOffsetPosition2=new ne.Vector3;_totalOffsetRotation2=new ne.Quaternion;_summedPos=new ne.Vector3;_tempPos=new ne.Vector3;_summedRot=new ne.Quaternion;_tempRot=new ne.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],l=o.asset;s.weight=0;let d=e>=o.start&&e<=o.end,a=o.postExtrapolationMode,u=d;if(!u&&!n&&o.end<e&&o.postExtrapolationMode!==0){let h=r<this.clips.length-1?this.models[r+1]:null;(!h||h.start>e)&&(u=!0,n=!0)}if(u){let h=1;h*=this.evaluateWeight(e,r,this.models,u);let m=this.getClipTime(e,o),E=0,b=l.duration;if(d){if(l.loop)for(E+=Math.floor(m/(b+1e-6));m>b;)m-=b}else if(!d)switch(a){case 2:m%=b;break;case 3:let p=Math.floor(m/b)%2!==0;m%=b,p&&(m=b-m);break}s.time=m,s.timeScale=0;let y=h*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-h),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=l.rotation,C=new ne.Quaternion;C.slerp(T,h);let R=this._actionOffsets[r];if(R.hasOffsets)for(let P=0;P<E;P++)R.rootPositionOffset?v.copy(R.rootPositionOffset):v.set(0,0,0),v.applyQuaternion(w).applyQuaternion(C),R.rootQuaternionOffset&&(x.copy(R.rootQuaternionOffset),w.multiply(x)),f.add(v);p.multiply(C),p.multiply(w),f.add(l.position),g.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 ne.Quaternion;this.ensureTrackOffsets();let o=this.trackOffset?.rotation;i.createInterpolant=()=>{let s=n(),l=s.evaluate.bind(s);return s.evaluate=d=>{let a=l(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 ne.Vector3;this.ensureTrackOffsets();let o=this.trackOffset?.rotation,s=this.trackOffset?.position,l;i.createInterpolant=()=>{let d=n(),a=d.evaluate.bind(d);return d.evaluate=u=>{let h=a(u);return r.set(h[0],h[1],h[2]),t.removeStartOffset&&(l===void 0?(l=null,l=this._actionOffsets.find(m=>m.clip===e)?.rootStartPosition?.clone()):l?.isVector3&&r.sub(l)),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),h[0]=r.x,h[1]=r.y,h[2]=r.z,h},d}}},qn=class extends Fo{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;getAudioFilePath(e){let t=this.director.sourceId;return un(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 ne.Audio(this.listener);i.setVolume(e.asset.volume);let n=new ne.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}}},rn=class extends Fo{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)}}},Os=class extends Fo{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;Os.resolved[r]?n.sourceObject=Os.resolved[r]:(n.sourceObject=A.findByGuid(r,e.scene),Os.resolved[r]=n.sourceObject)}if(n.sourceObject){let r=A.getComponent(n.sourceObject,on);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)}}}}},nn=Os;z(nn,"resolved",{});var df=B("debugtimeline");var gl=class extends D{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(){df&&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=Zo(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=A.findByGuid(n,e);r===null||typeof r!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(df&&console.log("Resolved binding",n,"to",r),t.outputs[i]=r)}else if(n===null){if(t.outputs.splice(i,1),gl.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=gl.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 l=new Wn;l.trackOffset=t.trackOffset,l.director=this,l.track=t;for(let d=0;d<t.clips.length;d++){let a=t.clips[d],u=a.asset;if(!u){console.error("MISSING anim model?","clip#"+d,a,t,this.playableAsset,this.name);continue}let h=u.clip,m=h;if((typeof m=="string"||typeof m=="number")&&(m=s.find(b=>b.name===h)),!m){console.warn("Could not find animationClip for model",a,t.name,this.name,this.playableAsset?.name);continue}l.mixer||(l.mixer=new hf.AnimationMixer(o.gameObject)),l.clips.push(m),l.mixer.uncacheAction(m),l.createHooks(a.asset,m);let E=l.mixer.clipAction(m);l.actions.push(E),l.models.push(a)}this._animationTracks.push(l)}}}else if(t.type==="AudioTrack"){if(t.clips.length<=0)continue;e.push(t)}else if(t.type==="MarkerTrack"){let r=new rn;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=A.getComponent(this.gameObject,tn);o&&(r.receivers.push(o),this._signalTracks.push(r))}}else if(t.type==="SignalTrack"){let r=new rn;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 nn;r.director=this,r.track=t;for(let o of t.clips)r.models.push(o);r.resolveSourceObjects(this.context),this._controlTracks.push(r)}}ce.registerWaitForAllowAudio(()=>{let t=A.findObjectOfType(Zt,this.context);if(!!t)for(let i of e){let n=new qn;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)}},on=gl;z(on,"createTrackFunctions",{});import{Color as DE,Texture as bf}from"three";import*as Jd from"three-mesh-ui";import{Matrix4 as IE,Object3D as ME,Vector2 as mf,Vector3 as Kd}from"three";import{FrontSide as uf,DoubleSide as pf}from"three";function No(c,e){if(!c)return;let t=c.material;t?.isMaterial===!0&&(t.depthTest=!e.renderOnTop,t.side=e.doubleSided??!0?pf:uf,t.depthWrite=e.depthWrite??!1,t.shadowSide=e.doubleSided?pf:uf,c.castShadow=e.castShadows?e.castShadows:!1,c.receiveShadow=e.receiveShadows?e.receiveShadows:!1);for(let i of c.children)No(i,e)}function bl(c,e,t){c[e]===void 0&&console.warn("Field",e,"is undefined on",c);let i=Proxy.revocable(c[e],{set(o,s,l,d){let a=o[s],u=Reflect.set(o,s,l,d);return t(l,a),u}}),n=i.revoke,r=c[e];return i.revoke=()=>{c[e]=r,n()},c[e]=i.proxy,i}function ff(c,e,t=3){let i=c.__scheduledActions;i||(i=c.__scheduledActions={});let n=e.name;i[t]||(i[t]={});let r=i[t];if(r[n])return;function*s(){e?.call(c),r[n]=null}let l=c.startCoroutine(s(),t);r[n]=l}var gf=B("debugui"),zo=class{width;height},Or=class{x;y;width;height},ct=class extends Fe{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 Kd),this._anchoredPosition}rect;sizeDelta;anchoredPosition3D;pivot;lastMatrix;rectBlock;_transformNeedsUpdate=!1;awake(){super.awake(),this.lastMatrix=new IE,this.rectBlock=new ME,this.rectBlock.position.z=.1,this.rectBlock.name=this.name,this._anchoredPosition||(this._anchoredPosition=new Kd),bl(this,"_anchoredPosition",()=>{this._transformNeedsUpdate=!0})}onEnable(){super.onEnable(),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0}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)&&(gf&&console.log("updating",this.name),this.applyTransform()),Ve.ensureUpdateMeshUI(Jd,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},gf&&console.log(this.name,e);let t=new Jd.Block(e);return this._createdBlocks.push(t),t}};k([O(Or)],ct.prototype,"rect",2),k([O(mf)],ct.prototype,"sizeDelta",2),k([O(Kd)],ct.prototype,"anchoredPosition3D",2),k([O(mf)],ct.prototype,"pivot",2);var Tt=class extends Fe{get isGraphic(){return!0}get color(){return this._color||(this._color=new ye(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 ye(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=A.getComponent(this.gameObject,ct)),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(),bl(this,"_color",()=>ff(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(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}};k([O(ye)],Tt.prototype,"color",1),k([O()],Tt.prototype,"raycastTarget",2);var sn=class extends Tt{onAfterCreated(){this.uiObject&&(this.uiObject.scale.y*=-1)}};var vl=class{texture;rect};k([O(bf)],vl.prototype,"texture",2);var an=class extends sn{sprite;isBuiltinSprite(){switch(this.sprite?.texture?.name){case"InputFieldBackground":case"UISprite":case"Background":return!0}return this.sprite?.texture?.image?.width===32&&this.sprite?.texture?.image?.height===32}onBeforeCreate(e){this.isBuiltinSprite()&&(e.borderRadius=5,e.borderColor=new DE(.4,.4,.4),e.borderOpacity=this.color.alpha,e.borderWidth=.3)}onAfterCreated(){super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture)}};k([O(vl)],an.prototype,"sprite",2);var kr=class extends sn{mainTexture;onAfterCreated(){super.onAfterCreated(),this.setTexture(this.mainTexture)}};k([O(bf)],kr.prototype,"mainTexture",2);var Uo=B("debugbutton");var Nt=class extends D{onClick;_isHovered=!1;onPointerEnter(e){Uo&&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(){Uo&&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){Uo&&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){Uo&&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){Uo&&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(),Uo&&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=A.getComponent(this.gameObject,an),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 l=this.getFinalColor(e.color,this.colors?.selectedColor),d={state:"selected",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(d);let a=this.getFinalColor(e.color,this.colors?.disabledColor),u={state:"disabled",attributes:{backgroundColor:a,backgroundOpacity:a.alpha}};e.setupState(u)}getFinalColor(e,t){return t?e.clone().multiply(t):e.clone()}};k([O(Re)],Nt.prototype,"onClick",2),k([O()],Nt.prototype,"colors",2),k([O()],Nt.prototype,"transition",2),k([O()],Nt.prototype,"animationTriggers",2),k([O(At)],Nt.prototype,"animator",2),k([O()],Nt.prototype,"interactable",1);var Zd=class extends Xi{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 Zd||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}_scaleFactor=1;get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}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(),No(this.shadowComponent,this);for(let e of A.getComponentsInChildren(this.gameObject,Fe))No(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(K.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}}},Ne=Zd;k([O()],Ne.prototype,"renderOnTop",1),k([O()],Ne.prototype,"depthWrite",1),k([O()],Ne.prototype,"doubleSided",1),k([O()],Ne.prototype,"castShadows",1),k([O()],Ne.prototype,"receiveShadows",1),k([O()],Ne.prototype,"renderMode",1),k([O(Ne)],Ne.prototype,"rootCanvas",1),k([O()],Ne.prototype,"scaleFactor",1);var ln=class extends D{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}_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 A.getComponentsInChildren(this.gameObject,Tt,this._buffer)){let t=e.color;t.alpha=this._alpha,e.color=t}}};k([O()],ln.prototype,"alpha",1),k([O()],ln.prototype,"interactable",2),k([O()],ln.prototype,"blocksRaycasts",2);import*as vf from"three-mesh-ui";import{Color as F}from"three";var LE=B("debugtext");var Ae=class extends Tt{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){LE&&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=this.fontSize,t={content:this.text,fontColor:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.font=this.font?.toLocaleLowerCase(),this.setFont(t,this.fontStyle),t}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[bt]===void 0&&(e[bt]=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 vf.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||(No(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 ks(e,{fontColor:t.fontColor});if(i.push(n),e.type.length>6){let r=e.type.substring(6);t.fontColor=HE(r)}else t.fontColor=new F(1,1,1)}else if(e.type=="b"){let n=new ks(e,{fontFamily:t.fontFamily,fontTexture:t.fontTexture});i.push(n),this.setFont(t,1)}else if(e.type=="i"){let n=new ks(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=un(this.sourceId,this.font),this.font):null}};k([O(Ne)],Ae.prototype,"canvas",2),k([O()],Ae.prototype,"alignment",2),k([O()],Ae.prototype,"verticalOverflow",2),k([O()],Ae.prototype,"horizontalOverflow",2),k([O()],Ae.prototype,"lineSpacing",2),k([O()],Ae.prototype,"supportRichText",2),k([O()],Ae.prototype,"font",2),k([O()],Ae.prototype,"fontStyle",2),k([O()],Ae.prototype,"text",1),k([O()],Ae.prototype,"fontSize",1);var ks=class{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}};function HE(c){if(c.startsWith("#")){let t=c.substring(1);var e=parseInt(t,16);let i=e>>16&255,n=e>>8&255,r=e&255;return new F(i/255,n/255,r/255)}switch(c){case"black":return new F(0,0,0);case"white":return new F(1,1,1);case"red":return new F(1,0,0);case"lime":return new F(0,1,0);case"blue":return new F(0,0,1);case"yellow":return new F(1,1,0);case"cyan":return new F(0,1,1);case"magenta":return new F(1,0,1);case"silver":return new F(.75,.75,.75);case"gray":return new F(.5,.5,.5);case"maroon":return new F(.5,0,0);case"olive":return new F(.5,.5,0);case"green":return new F(0,.5,0);case"purple":return new F(.5,0,.5);case"teal":return new F(0,.5,.5);case"navy":return new F(0,0,.5);case"darkred":return new F(.54,0,0);case"brown":return new F(.55,.27,0);case"firebrick":return new F(.69,.13,.13);case"crimson":return new F(.86,.08,.24);case"tomato":return new F(1,.39,.28);case"coral":return new F(1,.49,.31);case"indianred":return new F(.6,.31,.51);case"lightcoral":return new F(.94,.5,.5);case"darkorange":return new F(1,.55,0);case"orange":return new F(1,.65,0);case"gold":return new F(1,.84,0);case"darkgoldenrod":return new F(.72,.53,.04);case"goldenrod":return new F(.85,.65,.13);case"palegoldenrod":return new F(.93,.87,.67);case"darkkhaki":return new F(.74,.7,.42);case"khaki":return new F(.94,.9,.55);case"yellowgreen":return new F(.6,.8,.19);case"darkolivegreen":return new F(.33,.42,.18);case"olivedrab":return new F(.42,.56,.14);case"lawngreen":return new F(.49,.99,0);case"chartreuse":return new F(.5,1,0);case"greenyellow":return new F(.68,1,.18);case"darkgreen":return new F(0,.39,0);case"forestgreen":return new F(.13,.55,.13);case"limegreen":return new F(.19,.8,.19);case"lightgreen":return new F(.56,.93,.56);case"palegreen":return new F(.59,.98,.59);case"darkseagreen":return new F(.56,.74,.56);case"mediumspringgreen":return new F(0,.98,.6);case"springgreen":return new F(0,1,.5);case"seagreen":return new F(.18,.31,.31);case"mediumaquamarine":return new F(.4,.8,.66);case"mediumseagreen":return new F(.24,.7,.44);case"lightseagreen":return new F(.13,.7,.67);case"darkslategray":return new F(.18,.31,.31);case"darkcyan":return new F(0,.55,.55);case"aqua":return new F(0,1,1);case"lightcyan":return new F(.8,1,1);case"darkturquoise":return new F(0,.81,.82);case"turquoise":return new F(0,.82,.82);case"mediumturquoise":return new F(.28,.82,.8);case"paleturquoise":return new F(.68,1,.93);case"aquamarine":return new F(.5,1,.83);case"powderblue":return new F(.69,.88,.9);case"cadetblue":return new F(.37,.62,.63);case"steelblue":return new F(.27,.51,.71);case"cornflowerblue":return new F(.39,.58,.93);case"deepskyblue":return new F(0,.7,1);case"dodgerblue":return new F(.12,.56,1);case"lightblue":return new F(.68,.85,.9);case"skyblue":return new F(.53,.81,.92);case"lightskyblue":return new F(.53,.81,.98);case"midnightblue":return new F(.18,.18,.31);case"darkblue":return new F(0,0,.55);case"mediumblue":return new F(0,0,.82);case"royalblue":return new F(.25,.41,.88);case"blueviolet":return new F(.54,.17,.89);case"indigo":return new F(.29,0,.51);case"darkslateblue":return new F(.28,.24,.55);case"slateblue":return new F(.42,.35,.8);case"mediumslateblue":return new F(.48,.41,.9);case"mediumpurple":return new F(.58,.44,.86);case"darkmagenta":return new F(.55,0,.55);case"darkviolet":return new F(.58,0,.83);case"darkorchid":return new F(.6,.2,.8);case"mediumorchid":return new F(.73,.33,.83);case"thistle":return new F(.84,.75,.85);case"plum":return new F(.87,.63,.87);case"violet":return new F(.93,.51,.93);case"fuchsia":return new F(1,0,1);case"orchid":return new F(.85,.44,.84);case"mediumvioletred":return new F(.78,.08,.52);case"palevioletred":return new F(.86,.44,.58);case"hotpink":return new F(1,.4,.71);case"deeppink":return new F(1,.08,.58);case"lightpink":return new F(1,.71,.76);case"pink":return new F(1,.75,.78);case"antiquewhite":return new F(.98,.92,.84);case"beige":return new F(.96,.96,.86);case"bisque":return new F(1,.89,.77);case"blanchedalmond":return new F(1,.92,.82);case"wheat":return new F(.96,.87,.87);case"cornsilk":return new F(1,.97,.86);case"lemonchiffon":return new F(1,.98,.8);case"lightgoldenrodyellow":return new F(.98,.98,.82);case"lightyellow":return new F(1,1,.8);case"saddlebrown":return new F(.55,.27,.07);case"sienna":return new F(.63,.32,.18);case"chocolate":return new F(.82,.41,.12);case"peru":return new F(.82,.52,.25);case"sandybrown":return new F(.96,.64,.38);case"burlywood":return new F(.87,.72,.53);case"tan":return new F(.82,.71,.55);case"rosybrown":return new F(.74,.56,.56);case"moccasin":return new F(1,.89,.71);case"navajowhite":return new F(1,.87,.68);case"peachpuff":return new F(1,.85,.73);case"mistyrose":return new F(1,.89,.88);case"lavenderblush":return new F(1,.94,.93);case"linen":return new F(.98,.94,.9);case"oldlace":return new F(.99,.96,.9);case"papayawhip":return new F(1,.94,.84);case"seashell":return new F(1,.96,.93);case"mintcream":return new F(.98,1,.98);case"slategray":return new F(.44,.5,.56);case"lightslategray":return new F(.47,.53,.6);case"lightsteelblue":return new F(.69,.77,.87);case"lavender":return new F(.9,.9,.98);case"floralwhite":return new F(1,.98,.98);case"aliceblue":return new F(.94,.97,1);case"ghostwhite":return new F(.97,.97,1);case"honeydew":return new F(.94,1,.94);case"ivory":return new F(1,1,.94);case"azure":return new F(.94,1,1);case"snow":return new F(1,.98,.98);case"dimgray":return new F(.4,.4,.4);case"darkgray":return new F(.66,.66,.66);case"lightgray":return new F(.83,.83,.83);case"gainsboro":return new F(.86,.86,.86);case"whitesmoke":return new F(.96,.96,.96)}return new F(1,1,1)}var Ar=B("debuginputfield"),Y=class extends D{get text(){return this.textComponent?.text??""}get isFocused(){return Y.active===this}textComponent;placeholder;onValueChanged;onEndEdit;inputEventFn;start(){Ar&&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&&A.setActive(this.placeholder.gameObject,!1)}onDisable(){Y.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected()}onPointerClick(e){Ar&&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&&(Ar&&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&&A.setActive(this.placeholder.gameObject,!1),Y.htmlField)){if(Y.htmlField.value=this.textComponent?.text||"",Ar&&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,Ar&&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)&&A.setActive(this.placeholder.gameObject,!0),this.onEndEdit?.invoke())}onInput(e){if(Y.active===this){if(Ar&&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&&A.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&Y.htmlField){if(this.textComponent.text!==Y.htmlField.value){Ar&&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([O(Ae)],Ct.prototype,"textComponent",2),k([O(Ae)],Ct.prototype,"placeholder",2),k([O(Re)],Ct.prototype,"onValueChanged",2),k([O(Re)],Ct.prototype,"onEndEdit",2);import*as yf from"three-mesh-ui";import*as As from"three";var Ef=(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))(Ef||{}),Vo=class extends Fe{font;text;keymap;padding;margin;fontSize;borderRadius;colors={keyboardBack:8750469,panelBack:2500134,button:3552822,hovered:1842204,selected:1088605};awake(){super.awake();let e=Ef[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=A.getComponent(this.gameObject,ct);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:uo+"/"+t+"-msdf.json",fontTexture:uo+"/"+t+".png",fontSize:this.fontSize||6,backgroundColor:new As.Color(this.colors.keyboardBack),backspaceTexture:uo+"/backspace.png",shiftTexture:uo+"/shift.png",enterTexture:uo+"/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 yf.Keyboard(n),this.gameObject.scale.set(1,1,1),this.keyboard.keys.forEach(o=>{o.setupState({state:"normal",attributes:{offset:.003,backgroundColor:new As.Color(this.colors.button),backgroundOpacity:1}}),o.setState("normal"),o.setupState({state:"hovered",attributes:{offset:.3,backgroundColor:new As.Color(this.colors.hovered),backgroundOpacity:1}}),o.setupState({state:"pressed",attributes:{offset:.1,backgroundColor:new As.Color(this.colors.selected),backgroundOpacity:1},onSet:()=>{let s=o.info.input,l=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||l=="switch"||l=="shift"||l=="switch-set"){this._lastKeyPressedTime=this.context.time.time;return}if(this._lastKeyPressedTime=this.context.time.time,this._lastKeyPressed=s,l)switch(l){case"switch":this.keyboard.setNextPanel();break;case"switch-set":this.keyboard.setNextCharset();break;case"enter":this.tryAppend(`
214
- `);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 cn=class extends D{reverseArrangement=!1},Go=class extends cn{},Wo=class extends cn{},qo=class extends cn{};var Ir=class extends D{awake(){Ve.createIfNoneExists(this.context)}onEnable(){Ve.instance?.register(this)}onDisable(){Ve.instance?.unregister(this)}performRaycast(e=null){return null}},Mr=class extends Ir{targets=null;raycastHits=[];start(){this.targets=[this.gameObject]}performRaycast(e=null){return this.targets?(e??=new _e,e.targets=this.targets,e.results=this.raycastHits,this.context.physics.raycast(e)):null}},Xo=class extends Mr{eventCamera=null;ignoreReversedGraphics=!1;rootRaycaster=null};import*as wf from"three";import{HTMLMesh as jE}from"three/examples/jsm/interactive/HTMLMesh.js";import{InteractiveGroup as BE}from"three/examples/jsm/interactive/InteractiveGroup.js";var Qo=class extends D{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 BE(this.context.renderer,this.context.mainCamera);this.gameObject.add(t);let i=new jE(e);t.add(i),i.visible=!1,console.log(i);let n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;let r=ra(this.gameObject).clone();oa(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();let o=new wf.Box3;o.setFromObject(t),this.setWorldRotation(r.x,r.y,r.z);let s=o.max.x-o.min.x,l=o.max.y-o.min.y;if(this.keepAspect){let a=s/l;s>l?i.scale.set(1/s,1/l/a,1):i.scale.set(1/s*a,1/l,1)}else i.scale.set(1/s,1/l,1);let d=this.gameObject.scale;i.scale.multiply(d)},1)}};var Is=class{};var yl=class extends D{toggleKey="p";update(){this.context.input.isKeyDown("p")&&this.context.domElement.classList.toggle("presentation-mode")}};import*as _f from"three";import{Raycaster as zE,Vector3 as UE}from"three";import*as El from"three";import{MeshLine as FE,MeshLineMaterial as NE}from"three.meshline";var eh=class{id=0;points=[];line=new FE;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 El.Mesh(this.line,this.material),e.add(this.mesh)}appendPoint(e){let t=eh.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 NE({color:10066329,lineWidth:.01})},Yo=eh;z(Yo,"wp",new El.Vector3);var Dr=class extends D{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=A.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 Yo(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 VE}from"three.meshline";var wl=class{isDrawing;lastHit;currentHandle;maxDistance;prevDistance;lastParent;constructor(){this.isDrawing=!1,this.lastHit=new UE,this.currentHandle=null,this.maxDistance=0,this.prevDistance=0,this.lastParent=null}},_l=class extends D{lines;colliders;alignToSurface=!0;addToPaintedObject=!0;orbit;start(){this.lines||(this.lines=A.getComponent(this.gameObject,Dr),this.lines||(this.lines=A.addNewComponent(this.gameObject,Dr))),this.orbit=A.findObjectOfType(gt,this.context)??void 0,this._states.mouse=new wl;let e={};ie.addEventListener("select-start",(t,i)=>{e[t.controller.uuid]=!0}),ie.addEventListener("update",(t,i)=>{if(e[t.controller.uuid]===!0){let n=t.getRay();this.updateLine(t.controller.uuid,n,!0,!1,!1)}}),ie.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);_l._raycaster.setFromCamera(t,this.context.mainCamera);let i=_l._raycaster.ray;this.updateLine("mouse",i,this.context.input.getPointerPressed(0),this.context.input.getPointerUp(0),e||this.context.input.isKeyPressed("Alt"))}updateLine(e,t,i,n,r=!1){let o=this._states[e];if(o||(this._states[e]=new wl,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),l=null,d=o.prevDistance;if(s)o.currentHandle||(o.maxDistance=s.distance),l=s.point,l.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 u=q(this.context.mainCamera);a=o.lastHit.distanceTo(u)}l=t.origin.add(t.direction.multiplyScalar(o.maxDistance)),o.prevDistance=o.maxDistance}if(l){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;l=t.origin.add(t.direction.multiplyScalar(a)),o.prevDistance=a}if(o.lastHit&&o.lastHit.distanceTo(l)<o.prevDistance*.01)return o;this.lines.updateLine(o.currentHandle,{point:l}),o.lastHit.copy(l)}o.isDrawing=o.currentHandle!==null}return o}_raycastOptions=new _e;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(!!A.isActiveInHierarchy(i.object))return i}return null}createRandomMaterial(){let e;return this.context.connection.connectionId?e=lt.colorFromHashCode(lt.hashCode(this.context.connection.connectionId)):e=new _f.Color("hsl("+(Math.random()*100).toFixed(0)+", 80%, 30%)"),new VE({color:e,lineWidth:K.lerp(.005,.01,Math.random())})}},Ms=_l;z(Ms,"_raycaster",new zE);import{Object3D as GE}from"three";var Ds=class extends D{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=A.getComponent(t,Ii);i&&(i.owner=this.context.connection.connectionId)}}watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=Ii.all.length-1;t>=0;t--){let i=Ii.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};k([O(Ke)],Ds.prototype,"asset",2);var zt=class extends D{static get all(){return zt._all}static get local(){return zt._local}static isLocalPlayer(e){return e instanceof GE?A.getComponentInParent(e,zt)?.isLocalPlayer??!1:e instanceof dt?A.getComponentInParent(e.gameObject,zt)?.isLocalPlayer??!1:!1}owner;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}awake(){this.isLocalPlayer&&zt.local.push(this),zt.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(){qr(this.gameObject,this.context.connection)}onDestroy(){if(zt.all.splice(zt.all.indexOf(this),1),this.isLocalPlayer){let e=zt._local.indexOf(this);e>=0&&zt._local.splice(e,1)}}},Ii=zt;z(Ii,"_all",[]),z(Ii,"_local",[]),k([ll(),O()],Ii.prototype,"owner",2);L.add("AlignmentConstraint",_n);L.add("Animation",xn);L.add("AnimationCurve",dr);L.add("Animator",At);L.add("AnimatorController",Jt);L.add("AudioListener",Zt);L.add("AudioSource",ce);L.add("AvatarModel",hr);L.add("AvatarLoader",Cn);L.add("AxesHelper",Ui);L.add("BasicIKConstraint",io);L.add("BoxHelperComponent",ot);L.add("Camera",he);L.add("Collider",bi);L.add("SphereCollider",Sn);L.add("BoxCollider",Pn);L.add("DeleteBox",pr);L.add("Deletable",ro);L.add("DeviceFlag",fr);L.add("DragControls",_i);L.add("DropListener",Mn);L.add("Duplicatable",xi);L.add("CallInfo",Ti);L.add("EventListEvent",gr);L.add("EventList",Re);L.add("EventTrigger",go);L.add("FlyControls",bo);L.add("BoxGizmo",Yi);L.add("GltfExportBox",Eo);L.add("GltfExport",Ft);L.add("GridHelper",Ji);L.add("GroundProjectedEnv",Zi);L.add("Interactable",It);L.add("UsageMarker",Mt);L.add("Light",Ge);L.add("LODModel",Ri);L.add("LODGroup",Ln);L.add("LookAtConstraint",qi);L.add("NavMesh",_o);L.add("NavMeshAgent",xo);L.add("NestedGltf",Er);L.add("Networking",ht);L.add("OffsetConstraint",Si);L.add("OrbitControls",gt);L.add("ParticleSystemRenderer",_r);L.add("ParticleSystem",So);L.add("MainModule",To);L.add("EmissionModule",Co);L.add("ShapeModule",Ro);L.add("PlayerColor",lt);L.add("FieldWithDefault",vo);L.add("Renderer",pe);L.add("MeshRenderer",yr);L.add("SkinnedMeshRenderer",yo);L.add("RendererLightmap",Ki);L.add("Rigidbody",se);L.add("ScreenCapture",Hn);L.add("ShadowCatcher",jn);L.add("RemoteSkybox",Bn);L.add("SmoothFollow",Pi);L.add("SpatialTriggerReceiver",yt);L.add("SpatialTrigger",$i);L.add("SpectatorCamera",ko);L.add("SpringJoint",Ao);L.add("Sprite",xr);L.add("SpriteRenderer",en);L.add("SyncedCamera",Nn);L.add("SyncedRoom",oi);L.add("SyncedTransform",ft);L.add("TestRunner",Io);L.add("TestSimulateUserData",Mo);L.add("TransformGizmo",Tr);L.add("VideoPlayer",Se);L.add("Voip",Je);L.add("VolumeParameter",Do);L.add("VolumeComponent",Oi);L.add("ToneMapping",Un);L.add("ColorAdjustments",Vn);L.add("VolumeProfile",zn);L.add("Volume",Cr);L.add("WebARSessionRoot",Ht);L.add("WebXR",Q);L.add("WebAR",In);L.add("AvatarMarker",ue);L.add("WebXRAvatar",Lt);L.add("TeleportTarget",mr);L.add("WebXRController",ie);L.add("AttachedObject",at);L.add("XRGrabModel",Rr);L.add("XRGrabRendering",Lo);L.add("XRRig",An);L.add("VRUserState",jt);L.add("WebXRSync",Qi);L.add("XRState",mt);L.add("XRFlag",Ce);L.add("AvatarBlink_Simple",ki);L.add("AvatarEyeLook_Rotation",Ai);L.add("Avatar_POI",Ee);L.add("Avatar_Brain_LookAt",Wi);L.add("Avatar_MouthShapes",Gn);L.add("Avatar_MustacheShake",Ho);L.add("__Ignore",Is);L.add("LogStats",jo);L.add("RGBAColor",ye);L.add("PlayableDirector",on);L.add("SignalAsset",Sr);L.add("SignalReceiverEvent",Pr);L.add("SignalReceiver",tn);L.add("AnimationTrackHandler",Wn);L.add("AudioTrackHandler",qn);L.add("SignalTrackHandler",rn);L.add("ControlTrackHandler",nn);L.add("BaseUIComponent",Fe);L.add("UIRootComponent",Xi);L.add("Button",Nt);L.add("Canvas",Ne);L.add("CanvasGroup",ln);L.add("EventSystem",Ve);L.add("Graphic",Tt);L.add("MaskableGraphic",sn);L.add("Image",an);L.add("RawImage",kr);L.add("InputField",Ct);L.add("Keyboard",Vo);L.add("LayoutGroup",cn);L.add("VerticalLayoutGroup",Go);L.add("HorizontalLayoutGroup",Wo);L.add("GridLayoutGroup",qo);L.add("PointerEventData",ti);L.add("Raycaster",Ir);L.add("ObjectRaycaster",Mr);L.add("GraphicRaycaster",Xo);L.add("UIRaycastUtils",ni);L.add("Size",zo);L.add("Rect",Or);L.add("RectTransform",ct);L.add("SpatialHtml",Qo);L.add("Text",Ae);L.add("PresentationMode",yl);L.add("LinesDrawer",Ms);L.add("LineInstanceHandler",Yo);L.add("LinesManager",Dr);L.add("PlayerSync",Ds);L.add("PlayerState",Ii);import*as WE from"three";var th={Context:Z};globalThis.Needle=th;function xf(c){for(let e in c)th[e]=c[e]}xf(mc);xf($d);for(let c of Object.getOwnPropertyNames(A))switch(c){case"prototype":case"constructor":case"length":case"name":continue;default:th[c]=A[c];break}globalThis.THREE?console.warn("Threejs is already imported"):globalThis.THREE=WE;export{_n as AlignmentConstraint,xn as Animation,dr as AnimationCurve,Wn as AnimationTrackHandler,At as Animator,Jt as AnimatorController,at as AttachedObject,Zt as AudioListener,ce as AudioSource,qn as AudioTrackHandler,ki as AvatarBlink_Simple,Ai as AvatarEyeLook_Rotation,Cn as AvatarLoader,ue as AvatarMarker,hr as AvatarModel,Wi as Avatar_Brain_LookAt,Gn as Avatar_MouthShapes,Ho as Avatar_MustacheShake,Ee as Avatar_POI,Ui as AxesHelper,Fe as BaseUIComponent,io as BasicIKConstraint,D as Behaviour,Pn as BoxCollider,Yi as BoxGizmo,ot as BoxHelperComponent,Nt as Button,Ti as CallInfo,he as Camera,Ne as Canvas,ln as CanvasGroup,bi as Collider,Gr as Collision,Vn as ColorAdjustments,nn as ControlTrackHandler,ro as Deletable,pr as DeleteBox,fr as DeviceFlag,_i as DragControls,Mn as DropListener,xi as Duplicatable,Co as EmissionModule,Re as EventList,gr as EventListEvent,Ve as EventSystem,go as EventTrigger,vo as FieldWithDefault,bo as FlyControls,A as GameObject,Ft as GltfExport,Eo as GltfExportBox,Tt as Graphic,Xo as GraphicRaycaster,Ji as GridHelper,qo as GridLayoutGroup,Zi as GroundProjectedEnv,Db as HideFlags,Wo as HorizontalLayoutGroup,an as Image,Ct as InputField,re as InstancingUtil,Be as InstantiateOptions,It as Interactable,Vo as Keyboard,Ln as LODGroup,Ri as LODModel,cn as LayoutGroup,Ge as Light,jo as LogStats,qi as LookAtConstraint,To as MainModule,sn as MaskableGraphic,yr as MeshRenderer,_o as NavMesh,xo as NavMeshAgent,Er as NestedGltf,ht as Networking,Mr as ObjectRaycaster,Si as OffsetConstraint,gt as OrbitControls,So as ParticleSystem,_r as ParticleSystemRenderer,on as PlayableDirector,lt as PlayerColor,ti as PointerEventData,ye as RGBAColor,kr as RawImage,Ir as Raycaster,Or as Rect,ct as RectTransform,Bn as RemoteSkybox,pe as Renderer,Ki as RendererLightmap,se as Rigidbody,Hn as ScreenCapture,jn as ShadowCatcher,Ro as ShapeModule,Sr as SignalAsset,tn as SignalReceiver,Pr as SignalReceiverEvent,rn as SignalTrackHandler,zo as Size,yo as SkinnedMeshRenderer,Pi as SmoothFollow,Qo as SpatialHtml,$i as SpatialTrigger,yt as SpatialTriggerReceiver,ko as SpectatorCamera,Sn as SphereCollider,Ao as SpringJoint,xr as Sprite,en as SpriteRenderer,Nn as SyncedCamera,oi as SyncedRoom,ft as SyncedTransform,mr as TeleportTarget,Io as TestRunner,Mo as TestSimulateUserData,Ae as Text,Un as ToneMapping,Tr as TransformGizmo,ni as UIRaycastUtils,Xi as UIRootComponent,Mt as UsageMarker,jt as VRUserState,Go as VerticalLayoutGroup,Se as VideoPlayer,Je as Voip,Cr as Volume,Oi as VolumeComponent,Do as VolumeParameter,zn as VolumeProfile,In as WebAR,Ht as WebARSessionRoot,Q as WebXR,Lt as WebXRAvatar,ie as WebXRController,Qi as WebXRSync,Ce as XRFlag,Rr as XRGrabModel,Lo as XRGrabRendering,An as XRRig,mt as XRState,Is as __Ignore,ds as addNewComponentInstance,ma as apply,Gt as destroy,Nu as destroyComponentInstance,nr as findByGuid,Uu as findObjectOfType,Vu as findObjectsOfType,Pt as foreachComponent,or as getComponent,Yr as getComponentInChildren,Xr as getComponentInParent,Qr as getComponents,Kr as getComponentsInChildren,hs as getComponentsInParent,pa as getOrAddComponent,rr as instantiate,Wu as isActiveInHierarchy,Wr as isActiveSelf,ga as isUsingInstancing,qu as markAsInstancedRendered,Fu as moveComponentInstance,zu as onGetComponent,ua as removeComponent,O as serializeable};
218
+ `)}}}applyShadowMaterial(){let e=A.getComponent(this.gameObject,be);if(e)if(e.material?.type!=="ShadowMaterial"){let t=new Zy;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([O()],Lr.prototype,"mode",2),k([O(xe)],Lr.prototype,"shadowColor",2);import{RGBELoader as iE}from"three/examples/jsm/loaders/RGBELoader.js";import{EXRLoader as nE}from"three/examples/jsm/loaders/EXRLoader";import{EquirectangularRefractionMapping as rE}from"three";var Up=H("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}},Vp=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)){Up&&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 eE(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 tE(l){if(l.__autoPropertySyncHandler)return l.__autoPropertySyncHandler;let e=Vp.getOrCreateSyncer(l);return e?.init(l),l.__autoPropertySyncHandler=e,e}var Wp=function(l){return function(e,t){let i=null,n=l?e[l]:void 0,r=e,o=r.__internalAwake;Up&&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=Vp.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,t)?.set===void 0&&Object.defineProperty(this,t,{set:function(d){let a=this[s];this[s]=d,eE(d,a)&&n?.call(this,d,a)!==!1&&tE(this)?.notifyChanged(t,d)},get:function(){return this[s]},configurable:!0,enumerable:!0}),i?.init(this)}}};var Hr=class extends D{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 nE:new iE}let t=await this._loader.loadAsync(e);if(!t||!this.enabled)return;this.url=e,t.mapping=rE,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([Wp("setSkybox"),O()],Hr.prototype,"url",2),k([O()],Hr.prototype,"allowDrop",2);import*as jr from"three";import{Object3D as oE}from"three";var Pd=class extends D{target=null;followFactor=.1;rotateFactor=.1;flipForward=!1;_firstUpdate=!0;onEnable(){let e=A.getComponentInChildren(this.gameObject,de);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 jr.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=G(this.target),i=this._firstUpdate||e?1:K.clamp01(this.context.time.deltaTime*this.followFactor);this.worldPosition=this.worldPosition.lerp(t,i)}if(this.rotateFactor>0){let t=we(this.target);this.flipForward&&t.premultiply(Pd._invertForward);let i=this._firstUpdate||e?1:K.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(t,i)}this._firstUpdate=!1}}},tn=Pd;N(tn,"_invertForward",new jr.Quaternion().setFromAxisAngle(new jr.Vector3(0,1,0),Math.PI)),k([O(oE)],tn.prototype,"target",2);import{Layers as Xp}from"three";var Na=H("debugspatialtrigger"),Gp=new Xp,qp=new Xp;function sE(l,e){return Gp.mask=l,qp.mask=e,Gp.test(qp)}var Ft=class extends D{triggerMask=0;onEnter;onStay;onExit;start(){Na&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(let e of jn.triggers)sE(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){Na&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),this.onEnter?.invoke(this,e)}onExitTrigger(e){Na&&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([O()],Ft.prototype,"triggerMask",2),k([O(Ae)],Ft.prototype,"onEnter",2),k([O(Ae)],Ft.prototype,"onStay",2),k([O(Ae)],Ft.prototype,"onExit",2);var Fo=class extends D{triggerMask;boxHelper;start(){Na&&console.log(this.name,this.triggerMask,this)}onEnable(){Fo.triggers.push(this),this.boxHelper||(this.boxHelper=A.addNewComponent(this.gameObject,yt),this.boxHelper?.showHelper())}onDisable(){Fo.triggers.splice(Fo.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){A.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof Ft&&t.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){A.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof Ft&&t.onStayTrigger(this)},!1)}raiseOnExitEvent(e){A.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof Ft&&t.onExitTrigger(this)},!1)}},jn=Fo;N(jn,"triggers",[]),k([O()],jn.prototype,"triggerMask",2);import*as nn from"three";var ct=H("debugspectator"),za=class extends D{cam=null;_mode=0;get mode(){return this._mode}set mode(e){this._mode=e}get isSpectating(){return this._handler?.currentTarget!==void 0}isSpectatingUser(e){return this.target?.userId===e}isFollowedBy(e){return this.followers?.includes(e)}get followers(){return this._networking.followers}stopSpectating(){if(this.context.isInXR){this.followSelf();return}this.target=void 0}set target(e){if(this._handler){let t=this._handler.currentTarget?.userId,i=this.context.players.getPlayerView(this.context.connection.connectionId);e===void 0||this.context.isInXR===!1&&i?.currentObject===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),A.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,t)):this._handler.currentTarget!==e&&(this._handler.set(e),A.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,t))}}get target(){return this._handler?.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){return this.isSpectating&&this.target?.currentObject===this.context.players.getPlayerView(this.context.connection.connectionId)?.currentObject}orbit=null;_handler;eventSub_WebXRRequestStartEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;_debug;_networking;awake(){if(this._debug=new kd(this.context,this),this._networking=new Md(this.context,this),this._networking.awake(),A.setActive(this.gameObject,!1),this.cam=A.getComponent(this.gameObject,de),!this.cam){console.error("Spectator camera needs camera component",this);return}!this._handler&&this.cam&&(this._handler=new Od(this.context,this.cam,this)),this.eventSub_WebXRRequestStartEvent=this.onXRSessionRequestStart.bind(this),this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),Y.addEventListener("requestVRSession",this.eventSub_WebXRRequestStartEvent),Y.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),Y.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.orbit=A.getComponent(this.context.mainCamera,Ri)}onDestroy(){this.stopSpectating(),Y.removeEventListener("requestVRSession",this.eventSub_WebXRStartEvent),Y.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),Y.removeEventListener("xrStopped",this.eventSub_WebXREndEvent),this._handler?.destroy(),this._networking.destroy()}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.isSupportedPlatform()||A.setActive(this.gameObject,!0)}onXRSessionStart(e){!this.isSupportedPlatform()||(ct&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onXRSessionEnded(e){this.context.removeCamera(this.cam),A.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._handler?.set(void 0),this._handler?.disable(),this.isSpectatingSelf&&this.stopSpectating()}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),ct&&console.log("Follow self",this.target)}onAfterRender(){if(!this.cam)return;let e=this.context.renderer,t=e.xr.enabled;if(!e.xr.isPresenting&&!this._handler?.currentTarget)return;this._handler?.update(this._mode);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();let r=this.context.mainCameraComponent;if(r){let c=r.backgroundColor;c&&e.setClearColor(c,c.alpha),this.cam.backgroundColor=c,this.cam.clearFlags=r.clearFlags,this.cam.nearClipPlane=r.nearClipPlane,this.cam.farClipPlane=r.farClipPlane}else e.setClearColor(new nn.Color(1,1,1));e.setRenderTarget(null),e.xr.enabled=!1;let o=this.cam?.cam;this.context.updateAspect(o);let s=e.xr.isPresenting;e.xr.isPresenting=!1,e.setSize(this.context.domWidth,this.context.domHeight),e.render(this.context.scene,o),e.xr.isPresenting=s,e.xr.enabled=t,i?e.setRenderTarget(i):e.state.bindXRFramebuffer(n),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){let e=this._mode===0;for(let t of he.instances)if(t.avatar&&"isLocalAvatar"in t.avatar){let i=4294967295;this.isSpectatingSelf&&(i=e&&t.avatar.isLocalAvatar?8:16);let n=t.avatar.flags;if(!n)continue;for(let r of n)r.UpdateVisible(i)}}resetAvatarFlags(){for(let e of he.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)}}},Od=class{context;cam;spectator;follow;target;view;currentObject;get currentTarget(){return this.view}constructor(e,t,i){this.context=e,this.cam=t,this.spectator=i}set(e){let t=e?.currentObject;if(!t){this.spectator.stopSpectating();return}t!==this.currentObject&&(this.currentObject=t,this.view=e,this.follow||(this.follow=A.addNewComponent(this.cam.gameObject,tn)),this.target||(this.target=new nn.Object3D),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,ct&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){ct&&console.log("STOP FOLLOW",this.currentObject),this.view=void 0,this.currentObject=void 0,this.context.removeCamera(this.cam),this.follow&&(this.follow.enabled=!1)}destroy(){this.target?.removeFromParent(),this.follow&&A.destroy(this.follow)}update(e){if(this.currentTarget?.isConnected===!1||this.currentTarget?.removed===!0){ct&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&this.currentTarget?.currentObject!==this.currentObject&&(ct&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));let t=this.context.mainCamera;t&&(this.cam.cam.near!==t.near||this.cam.cam.far!==t.far)&&(this.cam.cam.near=t.near,this.cam.cam.far=t.far,this.cam.cam.updateProjectionMatrix());let i=this.follow?.target;if(!(!i||!this.follow)){switch(e){case 0:this.view?.viewDevice!=="browser"?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),i.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,i.position.set(0,.5,1.5);break}this.follow.flipForward=!1,this.view?.viewDevice!=="browser"?i.quaternion.copy(aE):i.quaternion.identity()}}},aE=new nn.Quaternion().setFromAxisAngle(new nn.Vector3(0,1,0),Math.PI),kd=class{context;spectator;constructor(e,t){this.context=e,this.spectator=t,console.log("Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),window.addEventListener("keydown",n=>{n.key==="Escape"&&this.spectator.stopSpectating()});let i=0;this.context.input.addEventListener("pointerdown",n=>{i=this.context.time.time}),this.context.input.addEventListener("pointerup",n=>{let r=this.context.time.time-i;r>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&r<.3&&this.trySelectObject()})}trySelectObject(){let e=new Se;e.setMask(16777215);let t=this.context.physics.raycast(e);if(ct&&console.log(...t),t?.length)for(let i of t){if(i.distance<.2)continue;let n=i.object,r=A.getComponentInParent(n,he),o=r?.connectionId;if(o){let s=this.context.players.getPlayerView(o);this.spectator.target=s,ct&&console.log("spectate",o,r);break}}}},Id=class{guid;dontSave=!0;targetUserId;stoppedFollowing;constructor(e,t,i){this.guid=e,this.targetUserId=t,this.stoppedFollowing=i}},Ad=class{guid;userId;constructor(e,t){this.guid=e.guid,this.userId=t}},Md=class{followers=[];context;spectator;_followerEventMethod;_requestFollowMethod;_joinedRoomMethod;constructor(e,t){this.context=e,this.spectator=t,this._followerEventMethod=this.onFollowerEvent.bind(this),this._requestFollowMethod=this.onRequestFollowEvent.bind(this),this._joinedRoomMethod=this.onUserJoinedRoom.bind(this)}awake(){this.context.connection.beginListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.beginListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.beginListen("joined-room",this._joinedRoomMethod),document.addEventListener("keydown",e=>{e.key==="f"?this.onRequestFollowMe():e.key==="Escape"&&this.onRequestFollowMe(!0)})}destroy(){this.context.connection.stopListening("spectator-follower-changed",this._followerEventMethod),this.context.connection.stopListening("spectator-request-follow",this._requestFollowMethod),this.context.connection.stopListening("joined-room",this._joinedRoomMethod)}onSpectatedObjectChanged(e,t){if(ct&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",e,t),this.context.connection.connectionId){let i=e?.userId===void 0,n=i?t:e?.userId,r=new Id(this.context.connection.connectionId,n,i);this.context.connection.send("spectator-follower-changed",r)}}onRequestFollowMe(e=!1){if(ct&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();let t=e?void 0:this.context.connection.connectionId,i=new Ad(this.spectator,t);this.context.connection.send("spectator-request-follow",i)}}onUserJoinedRoom(){H("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){let t=e.targetUserId,i=e.guid;if(ct&&console.log(e),t===this.context.connection.connectionId)if(e.stoppedFollowing){let n=this.followers.indexOf(i);n!==-1&&(this.followers.splice(n,1),this.removeDisconnectedFollowers(),console.log(i,"unfollows you",this.followers.length))}else this.followers.includes(i)||(this.followers.push(i),this.removeDisconnectedFollowers(),console.log(i,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let e=this.followers.length-1;e>=0;e--){let t=this.followers[e];this.context.connection.userIsInRoom(t)===!1&&this.followers.splice(e,1)}}_lastRequestFollowUser;onRequestFollowEvent(e){if(this._lastRequestFollowUser=e,e.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(e.userId===void 0)this.spectator.stopSpectating();else{let t=this.context.players.getPlayerView(e.userId);if(t)this.spectator.target=t;else return ct&&console.warn("Could not find view",e.userId),this.enforceFollow(),!1}return!0}_enforceFollowInterval;enforceFollow(){this._enforceFollowInterval||(this._enforceFollowInterval=setInterval(()=>{this._lastRequestFollowUser===void 0||this._lastRequestFollowUser.userId&&this.spectator.isFollowedBy(this._lastRequestFollowUser.userId)?(clearInterval(this._enforceFollowInterval),this._enforceFollowInterval=void 0):(ct&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}};var Ua=class extends D{anchor=null;connectedBody=null;connectedAnchor=null;spring=10;damper=.2;rb=null;awake(){if(this.rb=A.getComponent(this.gameObject,ae),!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 gs(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 dt from"three";import{Material as lE,Texture as cE}from"three";var No=class{texture;triangles;uv;vertices;_geometry};k([O(cE)],No.prototype,"texture",2);var Va=class{static getOrCreateGeometry(e){if(e._geometry)return e._geometry;let t=new dt.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 dt.BufferAttribute(i,3)),t.setAttribute("uv",new dt.BufferAttribute(n,2)),t}},Bn=class extends D{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=Va.getOrCreateGeometry(this.sprite),this._currentSprite.material.map=this.sprite.texture;else{let e=new dt.MeshBasicMaterial({color:16777215,side:dt.DoubleSide});if(!e)return;if(this.color&&(e.color||(e.color=new dt.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 dt.Mesh(Va.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([O()],Bn.prototype,"drawMode",2),k([O(xe)],Bn.prototype,"color",2),k([O(lE)],Bn.prototype,"sharedMaterial",2);var ht=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 ht).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+4),(t||new ht).__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 Ee).__init(this.bb_pos+t,this.bb):null}rot(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new Ee).__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 dE}from"three";var Wa="SCAM";dr(Wa,ht.getRootAsSyncedCameraModel);var ut=new nt,Dd=class{userId;guid;constructor(e,t){this.guid=t,this.userId=e}send(e,t){if(e){ut.clear();let i=ut.createString(this.guid),n=ut.createString(this.userId);ht.startSyncedCameraModel(ut),ht.addGuid(ut,i),ht.addUserId(ut,n);let r=G(e),o=_s(e);ht.addPos(ut,Ee.createVec3(ut,r.x,r.y,r.z)),ht.addRot(ut,Ee.createVec3(ut,o.x,o.y,o.z));let s=ht.endSyncedCameraModel(ut);ut.finish(s,Wa),t.sendBinary(ut.asUint8Array())}}},Ga=class extends D{getCameraObject(e){let t=this.userToCamMap[e];return t?this.remoteCams[t].obj: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))}onEnable(){this._receiveCallback=this.context.connection.beginListenBinrary(Wa,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(Wa,this._receiveCallback)}update(){for(let n in this.remoteCams){let r=this.remoteCams[n],o=this.context.time.realtimeSinceStartup-r.lastUpdate;if(!r||o>this._camTimeoutInSeconds){console.log("Remote cam timeout",r,o),r?.obj&&A.destroy(r.obj),delete this.remoteCams[n],r&&delete this.userToCamMap[r.userId],Ga.instances.push(r),this.context.players.removePlayerView(r.userId,"browser");continue}}if(Y.IsInWebXR)return;let e=this.context.mainCamera;if(e===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new Dd(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));let t=G(e),i=we(e);(t.distanceTo(this._lastWorldPosition)>.001||i.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(t),this._lastWorldQuaternion.copy(i),!((!this._needsUpdate||this.context.time.frameCount%2!==0)&&!(this.context.time.realtimeSinceStartup-this._lastUpdateTime>this._camTimeoutInSeconds*.5))&&(this._lastUpdateTime=this.context.time.realtimeSinceStartup,this._needsUpdate=!1,this._model.send(e,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,e,"browser"))}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 He;c.context=this.context;let d=A.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,Ga.instances.push(n);let a=A.getOrAddComponent(d,he);a.connectionId=i,a.avatar=d}else return;let r=n.obj;this.context.players.setPlayerView(i,r,"browser"),n.lastUpdate=this.context.time.realtimeSinceStartup,ie.markDirty(r);let o=e.pos();o&&ir(r,o.x(),o.y(),o.z());let s=e.rot();s&&xs(r,s.x(),s.y(),s.z())}},Br=Ga;N(Br,"instances",[]),k([O([dE,ot])],Br.prototype,"cameraPrefab",2);var Ld="view",Qp=H("debugsyncedroom"),Ii=class extends D{roomName;urlParameterName;joinRandomRoom=!0;requireRoomParameter=!1;autoRejoin=!0;_roomPrefix;awake(){this._roomPrefix===void 0&&(this._roomPrefix=this.roomName,this.roomName="")}onEnable(){let e=H(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){e===void 0&&(e=0);let t=!1;if(this.urlParameterName){let i=H(this.urlParameterName);if(i&&typeof i=="string"){t=!0;let n=oh(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?(Qp&&console.log('No required room parameter "'+this.urlParameterName+'" in url - will not connect to networking backend.'),!1):!this.roomName||this.roomName.length<=0?(Qp&&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=H(Ld);return e||H(this.urlParameterName)}setRandomRoomUrlParameter(){let e=yl(),t=this.generateRoomName();H(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([O()],Ii.prototype,"roomName",2),k([O()],Ii.prototype,"urlParameterName",2),k([O()],Ii.prototype,"joinRandomRoom",2),k([O()],Ii.prototype,"requireRoomParameter",2),k([O()],Ii.prototype,"autoRejoin",2);function Yp(){let l=H("testwindowcount")||0;l&&l>0&&hE(l)}function hE(l){if(H("testwindow"))return null;let e=new URL(window.location.href);Kn(e.searchParams,_r,1),Kn(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 u=window.open(t,"test window "+c,`popup=yes width=${r} height=${r} top=${a} left=${d}`);if(!u){console.warn("Failed to open window");continue}i.push(u),u.onload=()=>{u.onbeforeunload=()=>{for(let h=0;h<i.length;h++){let f=i[h];f!==u&&f.close()}i.length=0}}}return i}import{Vector3 as pE}from"three";var Xa=class extends D{awake(){Yp()}},Qa=class extends D{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinrary(Er,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 nt(1024));let e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();let i=Lc(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}}};N(qa,"temp",new pE);import{MathUtils as fE}from"three";import{TransformControls as mE}from"three/examples/jsm/controls/TransformControls";import{OrbitControls as gE}from"three/examples/jsm/controls/OrbitControls";var zo=class extends D{isGizmo=!0;control;orbit;awake(){this.isGizmo&&!Ut||!this.context.mainCamera||(this.control=new mE(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=A.getComponentInParent(this.context.mainCamera,gE)??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=A.getComponentInParent(this.gameObject,Mt);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(fE.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([O()],zo.prototype,"isGizmo",2);import{LinearToneMapping as Kp,ACESFilmicToneMapping as bE,ReinhardToneMapping as vE}from"three";var Ya=H("debugvolume"),Zp=(i=>(i[i.None=0]="None",i[i.Neutral=1]="Neutral",i[i.ACES=2]="ACES",i))(Zp||{}),Ka=class{overrideState=!1;value=0},rn=class{active=!1;parameters},Nr=class extends rn{mode;get isToneMapping(){return!0}},zr=class extends rn{postExposure};function yE(l){return"mode"in l?Nr:"postExposure"in l?zr:rn}var Jp=Symbol("volumeprofile"),Fr=class{components;apply(e){this.onUpdate(e,!1)}unapply(e){this.onUpdate(e,!0)}onUpdate(e,t){if(!this.components)return;let i=e.renderer,r=i[Jp]!==void 0;if(t){if(!r)return}else i[Jp]=this;for(let o of this.components)if(o instanceof Nr){let s=o;if(!o.active||t){e.renderer.toneMapping=Kp;continue}switch(Ya&&console.log("VOLUME:",Zp[s.mode?.value??0]),s.mode?.value??0){case 0:e.renderer.toneMapping=Kp;break;case 1:e.renderer.toneMapping=vE;break;case 2:e.renderer.toneMapping=bE;break}}else if(o instanceof zr){let s=o;Ya&&console.log(s.postExposure);let c=Math.pow(2,s.postExposure?.value??0),d=s.postExposure?.overrideState&&!t;e.renderer.toneMappingExposure=d?c:1}}};k([O([l=>yE(l),rn])],Fr.prototype,"components",2);var Uo=class extends D{sharedProfile;awake(){Ya&&(console.log(this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",e=>{e.key==="p"&&(console.log("Toggle volume: "+this.name,!this.enabled),this.enabled=!this.enabled)}))}onEnable(){Ya&&console.log("APPLY VOLUME",this),this.sharedProfile?.apply(this.context)}onDisable(){this.sharedProfile?.unapply(this.context)}};k([O(Fr)],Uo.prototype,"sharedProfile",2);import*as $p from"three";var Vo=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}},Ja=class extends D{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=wt.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),wt.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=A.instantiate(this.prefab);if(i.visible=!0,this._instances[e.guid]={instance:i,model:e},e.userId){let n=A.getComponentsInChildren(i,ki);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]&&(A.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<wt.Current.length;e++){let t=wt.Current[e];if(!t.controller||!t.selected)continue;this._grabModels.length<=e&&(this._grabModels.push(new Vo),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 $p.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=G(i);this.temp.set(r.x,r.y,r.z),o.lerp(this.temp,e),ne(i,o)}}};import{Object3D as EE}from"three";var on=class extends D{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=A.getComponentInParent(this.gameObject,Oe)}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([O(EE)],on.prototype,"eyes",2),k([O()],on.prototype,"lastBlinkTime",2),k([O()],on.prototype,"blinkLength",2),k([O()],on.prototype,"eyesOpen",2);import*as Za from"three";import{Object3D as Hd}from"three";var jd=class extends D{head=null;eyes=null;target=null;brain=null;awake(){this.brain||(this.brain=A.getComponentInParent(this.gameObject,Rn)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=A.addNewComponent(this.gameObject,Rn)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new Za.Vector3;currentTargetPoint=new Za.Vector3;update(){let e=this.target;if(e&&this.head){let t=this.eyes;if(t){let i=G(e);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);let n=G(this.head),r=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(r.length()<.1)return;let o=jd.forward;if(o.set(0,0,1),o.applyQuaternion(we(this.head)),o.dot(r)>.45)for(let c=0;c<t.length;c++)t[c].lookAt(this.currentTargetPoint)}}}},sn=jd;N(sn,"forward",new Za.Vector3(0,0,1)),k([O(Hd)],sn.prototype,"head",2),k([O(Hd)],sn.prototype,"eyes",2),k([O(Hd)],sn.prototype,"target",2);import{Object3D as ef}from"three";var wE=H("debugmouth"),Ur=class extends D{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){setTimeout(()=>{this.voip=A.findObjectOfType(st,this.context),this.marker||(this.marker=A.getComponentInParent(this.gameObject,he))},3e3)}update(){if(!this.voip||this.context.time.frameCount%10!==0)return;let e=this.marker?.connectionId??null;if(!e){wE&&(e=null);return}let t=this.voip.getFrequency(e)??0;this.updateLips(t)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;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)}}}};k([O(ef)],Ur.prototype,"idle",2),k([O(ef)],Ur.prototype,"talking",2);var $a=class extends D{voip=null;marker=null;_startPosition=null;awake(){this.voip=A.findObjectOfType(st,this.context),this.marker=A.getComponentInParent(this.gameObject,he)}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 _E=H("logstats"),el=class extends D{onEnable(){console.log(this),_E&&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 rf from"three";var Wo=class{guid},Go=class{signal;reaction;$serializedTypes={signal:Wo,reaction:Ae}},Fn=class extends D{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([O(Go)],Fn.prototype,"events",2);import*as te from"three";import{Quaternion as xE,Vector3 as TE}from"three";var Vr=H("debugtimeline"),Wr=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}},Bd=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";Vr&&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 te.Vector3().fromArray(o.values,0),this.rootEndPosition=new te.Vector3().fromArray(o.values,o.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),Vr&&console.log(this.rootPositionOffset);else if(o.name.endsWith(r)&&(this.rootStartQuaternion=new te.Quaternion().fromArray(o.values,0),this.rootEndQuaternion=new te.Quaternion().fromArray(o.values,o.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),Vr)){let s=new te.Euler().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",s)}}}},Gr=class extends Wr{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],u=a.name.lastIndexOf("."),h=a.name.substring(0,u),f=h.substring(h.lastIndexOf(".")+1),E=d.getObjectByName(f);if(E)if(s){if(!c){let b=t.tracks[0].name.substring(0,u)+".quaternion";Vr&&console.warn("Create quaternion track",f,E);let y=E.quaternion,g=new te.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=h+".position";Vr&&console.warn("Create position track",f,E);let y=E.position,g=new te.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,Vr&&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 Bd(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 TE(i.x,i.y,i.z)),n.isQuaternion||(t.rotation=new xE(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 te.Vector3(e.x,e.y,e.z)));let t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new te.Quaternion(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new te.Vector3;_totalOffsetRotation=new te.Quaternion;_totalOffsetPosition2=new te.Vector3;_totalOffsetRotation2=new te.Quaternion;_summedPos=new te.Vector3;_tempPos=new te.Vector3;_summedRot=new te.Quaternion;_tempRot=new te.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,u=d;if(!u&&!n&&o.end<e&&o.postExtrapolationMode!==0){let h=r<this.clips.length-1?this.models[r+1]:null;(!h||h.start>e)&&(u=!0,n=!0)}if(u){let h=1;h*=this.evaluateWeight(e,r,this.models,u);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=h*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-h),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,C=new te.Quaternion;C.slerp(T,h);let R=this._actionOffsets[r];if(R.hasOffsets)for(let P=0;P<E;P++)R.rootPositionOffset?v.copy(R.rootPositionOffset):v.set(0,0,0),v.applyQuaternion(w).applyQuaternion(C),R.rootQuaternionOffset&&(x.copy(R.rootQuaternionOffset),w.multiply(x)),m.add(v);p.multiply(C),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 te.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 te.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=u=>{let h=a(u);return r.set(h[0],h[1],h[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),h[0]=r.x,h[1]=r.y,h[2]=r.z,h},d}}},qr=class extends Wr{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;getAudioFilePath(e){let t=this.director.sourceId;return Di(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 te.Audio(this.listener);i.setVolume(e.asset.volume);let n=new te.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}}},zn=class extends Wr{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)}}},qo=class extends Wr{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;qo.resolved[r]?n.sourceObject=qo.resolved[r]:(n.sourceObject=A.findByGuid(r,e.scene),qo.resolved[r]=n.sourceObject)}if(n.sourceObject){let r=A.getComponent(n.sourceObject,Un);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)}}}}},Nn=qo;N(Nn,"resolved",{});var nf=H("debugtimeline");var tl=class extends D{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(){nf&&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=Jr(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=A.findByGuid(n,e);r===null||typeof r!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(nf&&console.log("Resolved binding",n,"to",r),t.outputs[i]=r)}else if(n===null){if(t.outputs.splice(i,1),tl.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=tl.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 Gr;c.trackOffset=t.trackOffset,c.director=this,c.track=t;for(let d=0;d<t.clips.length;d++){let a=t.clips[d],u=a.asset;if(!u){console.error("MISSING anim model?","clip#"+d,a,t,this.playableAsset,this.name);continue}let h=u.clip,f=h;if((typeof f=="string"||typeof f=="number")&&(f=s.find(b=>b.name===h)),!f){console.warn("Could not find animationClip for model",a,t.name,this.name,this.playableAsset?.name);continue}c.mixer||(c.mixer=new rf.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 zn;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=A.getComponent(this.gameObject,Fn);o&&(r.receivers.push(o),this._signalTracks.push(r))}}else if(t.type==="SignalTrack"){let r=new zn;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 Nn;r.director=this,r.track=t;for(let o of t.clips)r.models.push(o);r.resolveSourceObjects(this.context),this._controlTracks.push(r)}}le.registerWaitForAllowAudio(()=>{let t=A.findObjectOfType(wi,this.context);if(!!t)for(let i of e){let n=new qr;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)}},Un=tl;N(Un,"createTrackFunctions",{});import{Color as PE,Texture as df}from"three";import*as Nd from"three-mesh-ui";import{Matrix4 as RE,Object3D as SE,Vector2 as lf,Vector3 as Fd}from"three";import{FrontSide as of,DoubleSide as sf}from"three";function Xr(l,e){if(!l)return;let t=l.material;t?.isMaterial===!0&&(t.depthTest=!e.renderOnTop,t.side=e.doubleSided??!0?sf:of,t.depthWrite=e.depthWrite??!1,t.shadowSide=e.doubleSided?sf:of,l.castShadow=e.castShadows?e.castShadows:!1,l.receiveShadow=e.receiveShadows?e.receiveShadows:!1);for(let i of l.children)Xr(i,e)}function il(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],u=Reflect.set(o,s,c,d);return t(c,a),u}}),n=i.revoke,r=l[e];return i.revoke=()=>{l[e]=r,n()},l[e]=i.proxy,i}function af(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 cf=H("debugui"),nl=class{width;height},Xo=class{x;y;width;height},xt=class extends Ge{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 Fd),this._anchoredPosition}rect;sizeDelta;anchoredPosition3D;pivot;lastMatrix;rectBlock;_transformNeedsUpdate=!1;awake(){super.awake(),this.lastMatrix=new RE,this.rectBlock=new SE,this.rectBlock.position.z=.1,this.rectBlock.name=this.name,this._anchoredPosition||(this._anchoredPosition=new Fd),il(this,"_anchoredPosition",()=>{this._transformNeedsUpdate=!0})}onEnable(){super.onEnable(),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0}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)&&(cf&&console.log("updating",this.name),this.applyTransform()),tt.ensureUpdateMeshUI(Nd,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},cf&&console.log(this.name,e);let t=new Nd.Block(e);return this._createdBlocks.push(t),t}};k([O(Xo)],xt.prototype,"rect",2),k([O(lf)],xt.prototype,"sizeDelta",2),k([O(Fd)],xt.prototype,"anchoredPosition3D",2),k([O(lf)],xt.prototype,"pivot",2);var Nt=class extends Ge{get isGraphic(){return!0}get color(){return this._color||(this._color=new xe(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 xe(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=A.getComponent(this.gameObject,xt)),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(),il(this,"_color",()=>af(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(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}};k([O(xe)],Nt.prototype,"color",1),k([O()],Nt.prototype,"raycastTarget",2);var Vn=class extends Nt{onAfterCreated(){this.uiObject&&(this.uiObject.scale.y*=-1)}};var rl=class{texture;rect};k([O(df)],rl.prototype,"texture",2);var Wn=class extends Vn{sprite;isBuiltinSprite(){switch(this.sprite?.texture?.name){case"InputFieldBackground":case"UISprite":case"Background":return!0}return this.sprite?.texture?.image?.width===32&&this.sprite?.texture?.image?.height===32}onBeforeCreate(e){this.isBuiltinSprite()&&(e.borderRadius=5,e.borderColor=new PE(.4,.4,.4),e.borderOpacity=this.color.alpha,e.borderWidth=.3)}onAfterCreated(){super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture)}};k([O(rl)],Wn.prototype,"sprite",2);var Qo=class extends Vn{mainTexture;onAfterCreated(){super.onAfterCreated(),this.setTexture(this.mainTexture)}};k([O(df)],Qo.prototype,"mainTexture",2);var Qr=H("debugbutton");var hi=class extends D{onClick;_isHovered=!1;onPointerEnter(e){Qr&&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(){Qr&&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){Qr&&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){Qr&&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){Qr&&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(),Qr&&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=A.getComponent(this.gameObject,Wn),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),u={state:"disabled",attributes:{backgroundColor:a,backgroundOpacity:a.alpha}};e.setupState(u)}getFinalColor(e,t){return t?e.clone().multiply(t):e.clone()}};k([O(Ae)],hi.prototype,"onClick",2),k([O()],hi.prototype,"colors",2),k([O()],hi.prototype,"transition",2),k([O()],hi.prototype,"animationTriggers",2),k([O(Zt)],hi.prototype,"animator",2),k([O()],hi.prototype,"interactable",1);var zd=class extends Pn{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 zd||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}_scaleFactor=1;get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}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(),Xr(this.shadowComponent,this);for(let e of A.getComponentsInChildren(this.gameObject,Ge))Xr(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(K.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}}},Qe=zd;k([O()],Qe.prototype,"renderOnTop",1),k([O()],Qe.prototype,"depthWrite",1),k([O()],Qe.prototype,"doubleSided",1),k([O()],Qe.prototype,"castShadows",1),k([O()],Qe.prototype,"receiveShadows",1),k([O()],Qe.prototype,"renderMode",1),k([O(Qe)],Qe.prototype,"rootCanvas",1),k([O()],Qe.prototype,"scaleFactor",1);var Gn=class extends D{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}_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 A.getComponentsInChildren(this.gameObject,Nt,this._buffer)){let t=e.color;t.alpha=this._alpha,e.color=t}}};k([O()],Gn.prototype,"alpha",1),k([O()],Gn.prototype,"interactable",2),k([O()],Gn.prototype,"blocksRaycasts",2);import*as hf from"three-mesh-ui";import{Color as B}from"three";var OE=H("debugtext");var je=class extends Nt{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){OE&&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=this.fontSize,t={content:this.text,fontColor:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.font=this.font?.toLocaleLowerCase(),this.setFont(t,this.fontStyle),t}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[at]===void 0&&(e[at]=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 hf.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||(Xr(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 Yo(e,{fontColor:t.fontColor});if(i.push(n),e.type.length>6){let r=e.type.substring(6);t.fontColor=kE(r)}else t.fontColor=new B(1,1,1)}else if(e.type=="b"){let n=new Yo(e,{fontFamily:t.fontFamily,fontTexture:t.fontTexture});i.push(n),this.setFont(t,1)}else if(e.type=="i"){let n=new Yo(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=Di(this.sourceId,this.font),this.font):null}};k([O(Qe)],je.prototype,"canvas",2),k([O()],je.prototype,"alignment",2),k([O()],je.prototype,"verticalOverflow",2),k([O()],je.prototype,"horizontalOverflow",2),k([O()],je.prototype,"lineSpacing",2),k([O()],je.prototype,"supportRichText",2),k([O()],je.prototype,"font",2),k([O()],je.prototype,"fontStyle",2),k([O()],je.prototype,"text",1),k([O()],je.prototype,"fontSize",1);var Yo=class{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}};function kE(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 qn=H("debuginputfield"),X=class extends D{get text(){return this.textComponent?.text??""}get isFocused(){return X.active===this}textComponent;placeholder;onValueChanged;onEndEdit;inputEventFn;start(){qn&&console.log(this.name,this)}onEnable(){X.htmlField||(X.htmlField=document.createElement("input"),X.htmlField.classList.add("ar"),document.body.appendChild(X.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),X.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&A.setActive(this.placeholder.gameObject,!1)}onDisable(){X.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected()}onPointerClick(e){qn&&console.log("CLICK",e,X.active),X.activeTime=this.context.time.time,X.active!==this&&this.startCoroutine(this.activeLoop(),2),this.selectInputField()}*activeLoop(){for(this.onSelected();X.active===this&&!(this.context.input.getPointerUp(0)&&this.context.time.time-X.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(X.active!==this&&(qn&&console.log("Select",this.name,this,X.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,X.htmlField?.value),X.active?.onDeselected(),X.active=this,this.placeholder&&A.setActive(this.placeholder.gameObject,!1),X.htmlField)){if(X.htmlField.value=this.textComponent?.text||"",qn&&console.log("set input field value",X.htmlField.value),this.context.isInXR){let e=this.context.arOverlayElement;e&&(X.htmlField.style.width="0px",X.htmlField.style.height="0px",e.append(X.htmlField))}this.selectInputField()}}onDeselected(){X.active===this&&(X.active=null,qn&&console.log("Deselect",this.name,this),X.htmlField&&(X.htmlField.blur(),document.body.append(X.htmlField),X.htmlField.style.width="",X.htmlField.style.height=""),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&A.setActive(this.placeholder.gameObject,!0),this.onEndEdit?.invoke())}onInput(e){if(X.active===this){if(qn&&console.log(e.code,e,X.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}X.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&A.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&X.htmlField){if(this.textComponent.text!==X.htmlField.value){qn&&console.log("VALUE CHANGED");let e=this.textComponent.text,t=X.htmlField.value;this.onValueChanged?.invoke(t,e)}this.textComponent.text=X.htmlField.value}}selectInputField(){X.htmlField&&(X.htmlField.setSelectionRange(X.htmlField.value.length,X.htmlField.value.length),X.htmlField.focus())}},zt=X;N(zt,"active",null),N(zt,"activeTime",-1),N(zt,"htmlField",null),k([O(je)],zt.prototype,"textComponent",2),k([O(je)],zt.prototype,"placeholder",2),k([O(Ae)],zt.prototype,"onValueChanged",2),k([O(Ae)],zt.prototype,"onEndEdit",2);import*as uf from"three-mesh-ui";import*as Ko from"three";var pf=(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))(pf||{}),ol=class extends Ge{font;text;keymap;padding;margin;fontSize;borderRadius;colors={keyboardBack:8750469,panelBack:2500134,button:3552822,hovered:1842204,selected:1088605};awake(){super.awake();let e=pf[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=A.getComponent(this.gameObject,xt);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:Tr+"/"+t+"-msdf.json",fontTexture:Tr+"/"+t+".png",fontSize:this.fontSize||6,backgroundColor:new Ko.Color(this.colors.keyboardBack),backspaceTexture:Tr+"/backspace.png",shiftTexture:Tr+"/shift.png",enterTexture:Tr+"/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 uf.Keyboard(n),this.gameObject.scale.set(1,1,1),this.keyboard.keys.forEach(o=>{o.setupState({state:"normal",attributes:{offset:.003,backgroundColor:new Ko.Color(this.colors.button),backgroundOpacity:1}}),o.setState("normal"),o.setupState({state:"hovered",attributes:{offset:.3,backgroundColor:new Ko.Color(this.colors.hovered),backgroundOpacity:1}}),o.setupState({state:"pressed",attributes:{offset:.1,backgroundColor:new Ko.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(`
219
+ `);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 Xn=class extends D{reverseArrangement=!1},sl=class extends Xn{},al=class extends Xn{},ll=class extends Xn{};var Jo=class extends D{awake(){tt.createIfNoneExists(this.context)}onEnable(){tt.instance?.register(this)}onDisable(){tt.instance?.unregister(this)}performRaycast(e=null){return null}},Zo=class extends Jo{targets=null;raycastHits=[];start(){this.targets=[this.gameObject]}performRaycast(e=null){return this.targets?(e??=new Se,e.targets=this.targets,e.results=this.raycastHits,this.context.physics.raycast(e)):null}},cl=class extends Zo{eventCamera=null;ignoreReversedGraphics=!1;rootRaycaster=null};import*as ff from"three";import{HTMLMesh as IE}from"three/examples/jsm/interactive/HTMLMesh.js";import{InteractiveGroup as AE}from"three/examples/jsm/interactive/InteractiveGroup.js";var dl=class extends D{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 AE(this.context.renderer,this.context.mainCamera);this.gameObject.add(t);let i=new IE(e);t.add(i),i.visible=!1,console.log(i);let n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;let r=_s(this.gameObject).clone();xs(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();let o=new ff.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 Ud=class{};import*as ME from"three";var Wd={Context:J};globalThis.Needle=Wd;function mf(l){for(let e in l)Wd[e]=l[e]}mf(_c);mf(Vd);for(let l of Object.getOwnPropertyNames(A))switch(l){case"prototype":case"constructor":case"length":case"name":continue;default:Wd[l]=A[l];break}globalThis.THREE?console.warn("Threejs is already imported"):globalThis.THREE=ME;export{hr as AlignmentConstraint,ur as Animation,vo as AnimationCurve,Gr as AnimationTrackHandler,Zt as Animator,Ei as AnimatorController,wt as AttachedObject,wi as AudioListener,le as AudioSource,qr as AudioTrackHandler,on as AvatarBlink_Simple,sn as AvatarEyeLook_Rotation,mr as AvatarLoader,he as AvatarMarker,_o as AvatarModel,Rn as Avatar_Brain_LookAt,Ur as Avatar_MouthShapes,$a as Avatar_MustacheShake,Te as Avatar_POI,Tn as AxesHelper,Ge as BaseUIComponent,da as BasicIKConstraint,D as Behaviour,vr as BoxCollider,kn as BoxGizmo,yt as BoxHelperComponent,hi as Button,Ji as CallInfo,de as Camera,Qe as Canvas,Gn as CanvasGroup,Ti as Collider,nr as Collision,zr as ColorAdjustments,Nn as ControlTrackHandler,pa as Deletable,xo as DeleteBox,To as DeviceFlag,Yi as DragControls,kr as DropListener,Ki as Duplicatable,Ma as EmissionModule,Ae as EventList,Io as EventListEvent,tt as EventSystem,Ea as EventTrigger,xa as FieldWithDefault,wa as FlyControls,A as GameObject,di as GltfExport,Sa as GltfExportBox,Nt as Graphic,cl as GraphicRaycaster,Dn as GridHelper,ll as GridLayoutGroup,Ln as GroundProjectedEnv,Rb as HideFlags,al as HorizontalLayoutGroup,Wn as Image,zt as InputField,ie as InstancingUtil,He as InstantiateOptions,ei as Interactable,ol as Keyboard,Ar as LODGroup,$i as LODModel,Xn as LayoutGroup,it as Light,el as LogStats,Sn as LookAtConstraint,Aa as MainModule,Vn as MaskableGraphic,Ho as MeshRenderer,ka as NavMesh,Ia as NavMeshAgent,jo as NestedGltf,Oi as Networking,Zo as ObjectRaycaster,en as OffsetConstraint,Ri as OrbitControls,La as ParticleSystem,Bo as ParticleSystemRenderer,Un as PlayableDirector,ki as PlayerColor,Si as PointerEventData,xe as RGBAColor,Qo as RawImage,Jo as Raycaster,Xo as Rect,xt as RectTransform,Hr as RemoteSkybox,be as Renderer,In as RendererLightmap,ae as Rigidbody,Mr as ScreenCapture,Lr as ShadowCatcher,Da as ShapeModule,Wo as SignalAsset,Fn as SignalReceiver,Go as SignalReceiverEvent,zn as SignalTrackHandler,nl as Size,Ta as SkinnedMeshRenderer,tn as SmoothFollow,dl as SpatialHtml,jn as SpatialTrigger,Ft as SpatialTriggerReceiver,za as SpectatorCamera,br as SphereCollider,Ua as SpringJoint,No as Sprite,Bn as SpriteRenderer,Br as SyncedCamera,Ii as SyncedRoom,Mt as SyncedTransform,Po as TeleportTarget,Xa as TestRunner,Qa as TestSimulateUserData,je as Text,Nr as ToneMapping,zo as TransformGizmo,Pi as UIRaycastUtils,Pn as UIRootComponent,ti as UsageMarker,li as VRUserState,sl as VerticalLayoutGroup,Me as VideoPlayer,st as Voip,Uo as Volume,rn as VolumeComponent,Ka as VolumeParameter,Fr as VolumeProfile,Pr as WebAR,si as WebARSessionRoot,Y as WebXR,ri as WebXRAvatar,ce as WebXRController,On as WebXRSync,Oe as XRFlag,Vo as XRGrabModel,Ja as XRGrabRendering,Rr as XRRig,Dt as XRState,Ud as __Ignore,ho as addNewComponentInstance,Ds as apply,Rt as destroy,ku as destroyComponentInstance,bn as findByGuid,Au as findObjectOfType,Mu as findObjectsOfType,gt as foreachComponent,yn as getComponent,Fi as getComponentInChildren,or as getComponentInParent,sr as getComponents,ar as getComponentsInChildren,uo as getComponentsInParent,As as getOrAddComponent,vn as instantiate,Lu as isActiveInHierarchy,rr as isActiveSelf,Ls as isUsingInstancing,Hu as markAsInstancedRendered,Ou as moveComponentInstance,Is as removeComponent,O as serializeable};
215
220
  /*!
216
221
  * Determine if an object is a Buffer
217
222
  *