@needle-tools/engine 2.51.0-pre → 2.52.0-pre

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/needle-engine.d.ts +56 -20
  3. package/dist/needle-engine.js +376 -377
  4. package/dist/needle-engine.js.map +4 -4
  5. package/dist/needle-engine.min.js +26 -27
  6. package/dist/needle-engine.min.js.map +4 -4
  7. package/lib/engine/engine_utils.d.ts +2 -0
  8. package/lib/engine/engine_utils.js +9 -0
  9. package/lib/engine/engine_utils.js.map +1 -1
  10. package/lib/engine/extensions/NEEDLE_deferred_texture.js +4 -3
  11. package/lib/engine/extensions/NEEDLE_deferred_texture.js.map +1 -1
  12. package/lib/engine-components/Camera.d.ts +8 -2
  13. package/lib/engine-components/Camera.js +39 -2
  14. package/lib/engine-components/Camera.js.map +1 -1
  15. package/lib/engine-components/EventTrigger.d.ts +10 -1
  16. package/lib/engine-components/EventTrigger.js +47 -0
  17. package/lib/engine-components/EventTrigger.js.map +1 -1
  18. package/lib/engine-components/Light.js +5 -2
  19. package/lib/engine-components/Light.js.map +1 -1
  20. package/lib/engine-components/ParticleSystemModules.js +0 -1
  21. package/lib/engine-components/ParticleSystemModules.js.map +1 -1
  22. package/lib/engine-components/Renderer.d.ts +1 -0
  23. package/lib/engine-components/Renderer.js +10 -3
  24. package/lib/engine-components/Renderer.js.map +1 -1
  25. package/lib/engine-components/ShadowCatcher.js +5 -6
  26. package/lib/engine-components/ShadowCatcher.js.map +1 -1
  27. package/lib/engine-components/Skybox.d.ts +1 -0
  28. package/lib/engine-components/Skybox.js +5 -0
  29. package/lib/engine-components/Skybox.js.map +1 -1
  30. package/lib/engine-components/SpriteRenderer.d.ts +19 -3
  31. package/lib/engine-components/SpriteRenderer.js +154 -41
  32. package/lib/engine-components/SpriteRenderer.js.map +1 -1
  33. package/lib/engine-components/WebXRRig.js +12 -0
  34. package/lib/engine-components/WebXRRig.js.map +1 -1
  35. package/lib/engine-components/codegen/components.d.ts +1 -0
  36. package/lib/engine-components/codegen/components.js +1 -0
  37. package/lib/engine-components/codegen/components.js.map +1 -1
  38. package/lib/engine-components/timeline/PlayableDirector.js +6 -0
  39. package/lib/engine-components/timeline/PlayableDirector.js.map +1 -1
  40. package/package.json +1 -1
  41. package/src/engine/codegen/register_types.js +2 -0
  42. package/src/engine/engine_utils.ts +13 -2
  43. package/src/engine/extensions/NEEDLE_deferred_texture.ts +9 -6
  44. package/src/engine-components/Camera.ts +36 -2
  45. package/src/engine-components/EventTrigger.ts +39 -19
  46. package/src/engine-components/Light.ts +4 -2
  47. package/src/engine-components/ParticleSystemModules.ts +0 -3
  48. package/src/engine-components/Renderer.ts +10 -4
  49. package/src/engine-components/ShadowCatcher.ts +5 -6
  50. package/src/engine-components/Skybox.ts +4 -0
  51. package/src/engine-components/SpriteRenderer.ts +140 -44
  52. package/src/engine-components/WebXRRig.ts +14 -1
  53. package/src/engine-components/codegen/components.ts +1 -0
  54. package/src/engine-components/timeline/PlayableDirector.ts +5 -0
@@ -1,4 +1,4 @@
1
- var og=Object.create;var ws=Object.defineProperty;var Ah=Object.getOwnPropertyDescriptor;var sg=Object.getOwnPropertyNames;var ag=Object.getPrototypeOf,lg=Object.prototype.hasOwnProperty;var cg=(o,e,t)=>e in o?ws(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var Cc=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+o+'" is not supported')});var Es=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),Dh=(o,e)=>{for(var t in e)ws(o,t,{get:e[t],enumerable:!0})},dg=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of sg(e))!lg.call(o,n)&&n!==t&&ws(o,n,{get:()=>e[n],enumerable:!(i=Ah(e,n))||i.enumerable});return o};var ba=(o,e,t)=>(t=o!=null?og(ag(o)):{},dg(e||!o||!o.__esModule?ws(t,"default",{value:o,enumerable:!0}):t,o));var _=(o,e,t,i)=>{for(var n=i>1?void 0:i?Ah(e,t):e,r=o.length-1,s;r>=0;r--)(s=o[r])&&(n=(i?s(e,t,n):s(n))||n);return i&&n&&ws(e,t,n),n};var A=(o,e,t)=>(cg(o,typeof e!="symbol"?e+"":e,t),t);var Ya=Es((Wp,ld)=>{parcelRequire=function(o,e,t,i){var n,r=typeof parcelRequire=="function"&&parcelRequire,s=typeof Cc=="function"&&Cc;function a(l,u){if(!e[l]){if(!o[l]){var h=typeof parcelRequire=="function"&&parcelRequire;if(!u&&h)return h(l,!0);if(r)return r(l,!0);if(s&&typeof l=="string")return s(l);var b=new Error("Cannot find module '"+l+"'");throw b.code="MODULE_NOT_FOUND",b}v.resolve=function(x){return o[l][1][x]||x},v.cache={};var w=e[l]=new a.Module(l);o[l][0].call(w.exports,v,w,w.exports,this)}return e[l].exports;function v(x){return a(v.resolve(x))}}a.isParcelRequire=!0,a.Module=function(l){this.id=l,this.bundle=a,this.exports={}},a.modules=o,a.cache=e,a.parent=r,a.register=function(l,u){o[l]=[function(h,b){b.exports=u},{}]};for(var c=0;c<t.length;c++)try{a(t[c])}catch(l){n||(n=l)}if(t.length){var d=a(t[t.length-1]);typeof Wp=="object"&&typeof ld<"u"?ld.exports=d:typeof define=="function"&&define.amd?define(function(){return d}):i&&(this[i]=d)}if(parcelRequire=a,n)throw n;return a}({EgBh:[function(o,e,t){var i={};i.useBlobBuilder=function(){try{return new Blob([]),!1}catch{return!0}}(),i.useArrayBufferView=!i.useBlobBuilder&&function(){try{return new Blob([new Uint8Array([])]).size===0}catch{return!0}}(),e.exports.binaryFeatures=i;var n=e.exports.BlobBuilder;function r(){this._pieces=[],this._parts=[]}typeof window<"u"&&(n=e.exports.BlobBuilder=window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder||window.BlobBuilder),r.prototype.append=function(s){typeof s=="number"?this._pieces.push(s):(this.flush(),this._parts.push(s))},r.prototype.flush=function(){if(this._pieces.length>0){var s=new Uint8Array(this._pieces);i.useArrayBufferView||(s=s.buffer),this._parts.push(s),this._pieces=[]}},r.prototype.getBuffer=function(){if(this.flush(),i.useBlobBuilder){for(var s=new n,a=0,c=this._parts.length;a<c;a++)s.append(this._parts[a]);return s.getBlob()}return new Blob(this._parts)},e.exports.BufferBuilder=r},{}],kdPp:[function(o,e,t){var i=o("./bufferbuilder").BufferBuilder,n=o("./bufferbuilder").binaryFeatures,r={unpack:function(l){return new s(l).unpack()},pack:function(l){var u=new a;return u.pack(l),u.getBuffer()}};function s(l){this.index=0,this.dataBuffer=l,this.dataView=new Uint8Array(this.dataBuffer),this.length=this.dataBuffer.byteLength}function a(){this.bufferBuilder=new i}function c(l){var u=l.charCodeAt(0);return u<=2047?"00":u<=65535?"000":u<=2097151?"0000":u<=67108863?"00000":"000000"}function d(l){return l.length>600?new Blob([l]).size:l.replace(/[^\u0000-\u007F]/g,c).length}e.exports=r,s.prototype.unpack=function(){var l,u=this.unpack_uint8();if(u<128)return u;if((224^u)<32)return(224^u)-32;if((l=160^u)<=15)return this.unpack_raw(l);if((l=176^u)<=15)return this.unpack_string(l);if((l=144^u)<=15)return this.unpack_array(l);if((l=128^u)<=15)return this.unpack_map(l);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 l=this.unpack_uint16(),this.unpack_string(l);case 217:return l=this.unpack_uint32(),this.unpack_string(l);case 218:return l=this.unpack_uint16(),this.unpack_raw(l);case 219:return l=this.unpack_uint32(),this.unpack_raw(l);case 220:return l=this.unpack_uint16(),this.unpack_array(l);case 221:return l=this.unpack_uint32(),this.unpack_array(l);case 222:return l=this.unpack_uint16(),this.unpack_map(l);case 223:return l=this.unpack_uint32(),this.unpack_map(l)}},s.prototype.unpack_uint8=function(){var l=255&this.dataView[this.index];return this.index++,l},s.prototype.unpack_uint16=function(){var l=this.read(2),u=256*(255&l[0])+(255&l[1]);return this.index+=2,u},s.prototype.unpack_uint32=function(){var l=this.read(4),u=256*(256*(256*l[0]+l[1])+l[2])+l[3];return this.index+=4,u},s.prototype.unpack_uint64=function(){var l=this.read(8),u=256*(256*(256*(256*(256*(256*(256*l[0]+l[1])+l[2])+l[3])+l[4])+l[5])+l[6])+l[7];return this.index+=8,u},s.prototype.unpack_int8=function(){var l=this.unpack_uint8();return l<128?l:l-256},s.prototype.unpack_int16=function(){var l=this.unpack_uint16();return l<32768?l:l-65536},s.prototype.unpack_int32=function(){var l=this.unpack_uint32();return l<Math.pow(2,31)?l:l-Math.pow(2,32)},s.prototype.unpack_int64=function(){var l=this.unpack_uint64();return l<Math.pow(2,63)?l:l-Math.pow(2,64)},s.prototype.unpack_raw=function(l){if(this.length<this.index+l)throw new Error("BinaryPackFailure: index is out of range "+this.index+" "+l+" "+this.length);var u=this.dataBuffer.slice(this.index,this.index+l);return this.index+=l,u},s.prototype.unpack_string=function(l){for(var u,h,b=this.read(l),w=0,v="";w<l;)(u=b[w])<128?(v+=String.fromCharCode(u),w++):(192^u)<32?(h=(192^u)<<6|63&b[w+1],v+=String.fromCharCode(h),w+=2):(h=(15&u)<<12|(63&b[w+1])<<6|63&b[w+2],v+=String.fromCharCode(h),w+=3);return this.index+=l,v},s.prototype.unpack_array=function(l){for(var u=new Array(l),h=0;h<l;h++)u[h]=this.unpack();return u},s.prototype.unpack_map=function(l){for(var u={},h=0;h<l;h++){var b=this.unpack(),w=this.unpack();u[b]=w}return u},s.prototype.unpack_float=function(){var l=this.unpack_uint32(),u=(l>>23&255)-127;return(l>>31===0?1:-1)*(8388607&l|8388608)*Math.pow(2,u-23)},s.prototype.unpack_double=function(){var l=this.unpack_uint32(),u=this.unpack_uint32(),h=(l>>20&2047)-1023;return(l>>31===0?1:-1)*((1048575&l|1048576)*Math.pow(2,h-20)+u*Math.pow(2,h-52))},s.prototype.read=function(l){var u=this.index;if(u+l<=this.length)return this.dataView.subarray(u,u+l);throw new Error("BinaryPackFailure: read index out of range")},a.prototype.getBuffer=function(){return this.bufferBuilder.getBuffer()},a.prototype.pack=function(l){var u=typeof l;if(u==="string")this.pack_string(l);else if(u==="number")Math.floor(l)===l?this.pack_integer(l):this.pack_double(l);else if(u==="boolean")l===!0?this.bufferBuilder.append(195):l===!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(l===null)this.bufferBuilder.append(192);else{var h=l.constructor;if(h==Array)this.pack_array(l);else if(h==Blob||h==File||l instanceof Blob||l instanceof File)this.pack_bin(l);else if(h==ArrayBuffer)n.useArrayBufferView?this.pack_bin(new Uint8Array(l)):this.pack_bin(l);else if("BYTES_PER_ELEMENT"in l)n.useArrayBufferView?this.pack_bin(new Uint8Array(l.buffer)):this.pack_bin(l.buffer);else if(h==Object||h.toString().startsWith("class"))this.pack_object(l);else if(h==Date)this.pack_string(l.toString());else{if(typeof l.toBinaryPack!="function")throw new Error('Type "'+h.toString()+'" not yet supported');this.bufferBuilder.append(l.toBinaryPack())}}}this.bufferBuilder.flush()},a.prototype.pack_bin=function(l){var u=l.length||l.byteLength||l.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(l)},a.prototype.pack_string=function(l){var u=d(l);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(l)},a.prototype.pack_array=function(l){var u=l.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(l[h])},a.prototype.pack_integer=function(l){if(l>=-32&&l<=127)this.bufferBuilder.append(255&l);else if(l>=0&&l<=255)this.bufferBuilder.append(204),this.pack_uint8(l);else if(l>=-128&&l<=127)this.bufferBuilder.append(208),this.pack_int8(l);else if(l>=0&&l<=65535)this.bufferBuilder.append(205),this.pack_uint16(l);else if(l>=-32768&&l<=32767)this.bufferBuilder.append(209),this.pack_int16(l);else if(l>=0&&l<=4294967295)this.bufferBuilder.append(206),this.pack_uint32(l);else if(l>=-2147483648&&l<=2147483647)this.bufferBuilder.append(210),this.pack_int32(l);else if(l>=-9223372036854776e3&&l<=9223372036854776e3)this.bufferBuilder.append(211),this.pack_int64(l);else{if(!(l>=0&&l<=18446744073709552e3))throw new Error("Invalid integer");this.bufferBuilder.append(207),this.pack_uint64(l)}},a.prototype.pack_double=function(l){var u=0;l<0&&(u=1,l=-l);var h=Math.floor(Math.log(l)/Math.LN2),b=l/Math.pow(2,h)-1,w=Math.floor(b*Math.pow(2,52)),v=Math.pow(2,32),x=u<<31|h+1023<<20|w/v&1048575,m=w%v;this.bufferBuilder.append(203),this.pack_int32(x),this.pack_int32(m)},a.prototype.pack_object=function(l){var u=Object.keys(l).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 l)l.hasOwnProperty(h)&&(this.pack(h),this.pack(l[h]))},a.prototype.pack_uint8=function(l){this.bufferBuilder.append(l)},a.prototype.pack_uint16=function(l){this.bufferBuilder.append(l>>8),this.bufferBuilder.append(255&l)},a.prototype.pack_uint32=function(l){var u=4294967295&l;this.bufferBuilder.append((4278190080&u)>>>24),this.bufferBuilder.append((16711680&u)>>>16),this.bufferBuilder.append((65280&u)>>>8),this.bufferBuilder.append(255&u)},a.prototype.pack_uint64=function(l){var u=l/Math.pow(2,32),h=l%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)},a.prototype.pack_int8=function(l){this.bufferBuilder.append(255&l)},a.prototype.pack_int16=function(l){this.bufferBuilder.append((65280&l)>>8),this.bufferBuilder.append(255&l)},a.prototype.pack_int32=function(l){this.bufferBuilder.append(l>>>24&255),this.bufferBuilder.append((16711680&l)>>>16),this.bufferBuilder.append((65280&l)>>>8),this.bufferBuilder.append(255&l)},a.prototype.pack_int64=function(l){var u=Math.floor(l/Math.pow(2,32)),h=l%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(o,e,t){"use strict";function i(f,p,g){return p in f?Object.defineProperty(f,p,{value:g,enumerable:!0,configurable:!0,writable:!0}):f[p]=g,f}function n(f){return(n=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(p){return typeof p}:function(p){return p&&typeof Symbol=="function"&&p.constructor===Symbol&&p!==Symbol.prototype?"symbol":typeof p})(f)}Object.defineProperty(t,"__esModule",{value:!0}),t.extractVersion=a,t.wrapPeerConnectionEvent=c,t.disableLog=d,t.disableWarnings=l,t.log=u,t.deprecated=h,t.detectBrowser=b,t.compactObject=v,t.walkStats=x,t.filterStats=m;var r=!0,s=!0;function a(f,p,g){var E=f.match(p);return E&&E.length>=g&&parseInt(E[g],10)}function c(f,p,g){if(f.RTCPeerConnection){var E=f.RTCPeerConnection.prototype,C=E.addEventListener;E.addEventListener=function(S,I){if(S!==p)return C.apply(this,arguments);var D=function(O){var j=g(O);j&&(I.handleEvent?I.handleEvent(j):I(j))};return this._eventMap=this._eventMap||{},this._eventMap[p]||(this._eventMap[p]=new Map),this._eventMap[p].set(I,D),C.apply(this,[S,D])};var T=E.removeEventListener;E.removeEventListener=function(S,I){if(S!==p||!this._eventMap||!this._eventMap[p])return T.apply(this,arguments);if(!this._eventMap[p].has(I))return T.apply(this,arguments);var D=this._eventMap[p].get(I);return this._eventMap[p].delete(I),this._eventMap[p].size===0&&delete this._eventMap[p],Object.keys(this._eventMap).length===0&&delete this._eventMap,T.apply(this,[S,D])},Object.defineProperty(E,"on"+p,{get:function(){return this["_on"+p]},set:function(S){this["_on"+p]&&(this.removeEventListener(p,this["_on"+p]),delete this["_on"+p]),S&&this.addEventListener(p,this["_on"+p]=S)},enumerable:!0,configurable:!0})}}function d(f){return typeof f!="boolean"?new Error("Argument type: "+n(f)+". Please use a boolean."):(r=f,f?"adapter.js logging disabled":"adapter.js logging enabled")}function l(f){return typeof f!="boolean"?new Error("Argument type: "+n(f)+". Please use a boolean."):(s=!f,"adapter.js deprecation warnings "+(f?"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(f,p){s&&console.warn(f+" is deprecated, please use "+p+" instead.")}function b(f){var p={browser:null,version:null};if(f===void 0||!f.navigator)return p.browser="Not a browser.",p;var{navigator:g}=f;if(g.mozGetUserMedia)p.browser="firefox",p.version=a(g.userAgent,/Firefox\/(\d+)\./,1);else if(g.webkitGetUserMedia||f.isSecureContext===!1&&f.webkitRTCPeerConnection&&!f.RTCIceGatherer)p.browser="chrome",p.version=a(g.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(g.mediaDevices&&g.userAgent.match(/Edge\/(\d+).(\d+)$/))p.browser="edge",p.version=a(g.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!f.RTCPeerConnection||!g.userAgent.match(/AppleWebKit\/(\d+)\./))return p.browser="Not a supported browser.",p;p.browser="safari",p.version=a(g.userAgent,/AppleWebKit\/(\d+)\./,1),p.supportsUnifiedPlan=f.RTCRtpTransceiver&&"currentDirection"in f.RTCRtpTransceiver.prototype}return p}function w(f){return Object.prototype.toString.call(f)==="[object Object]"}function v(f){return w(f)?Object.keys(f).reduce(function(p,g){var E=w(f[g]),C=E?v(f[g]):f[g],T=E&&!Object.keys(C).length;return C===void 0||T?p:Object.assign(p,i({},g,C))},{}):f}function x(f,p,g){p&&!g.has(p.id)&&(g.set(p.id,p),Object.keys(p).forEach(function(E){E.endsWith("Id")?x(f,f.get(p[E]),g):E.endsWith("Ids")&&p[E].forEach(function(C){x(f,f.get(C),g)})}))}function m(f,p,g){var E=g?"outbound-rtp":"inbound-rtp",C=new Map;if(p===null)return C;var T=[];return f.forEach(function(S){S.type==="track"&&S.trackIdentifier===p.id&&T.push(S)}),T.forEach(function(S){f.forEach(function(I){I.type===E&&I.trackId===S.id&&x(f,I,C)})}),C}},{}],s6SN:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetUserMedia=c;var i=r(o("../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 l=n();if(l&&l.has(d))return l.get(d);var u={},h=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var b in d)if(Object.prototype.hasOwnProperty.call(d,b)){var w=h?Object.getOwnPropertyDescriptor(d,b):null;w&&(w.get||w.set)?Object.defineProperty(u,b,w):u[b]=d[b]}return u.default=d,l&&l.set(d,u),u}function s(d){return(s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(l){return typeof l}:function(l){return l&&typeof Symbol=="function"&&l.constructor===Symbol&&l!==Symbol.prototype?"symbol":typeof l})(d)}var a=i.log;function c(d,l){var u=d&&d.navigator;if(u.mediaDevices){var h=function(x){if(s(x)!=="object"||x.mandatory||x.optional)return x;var m={};return Object.keys(x).forEach(function(f){if(f!=="require"&&f!=="advanced"&&f!=="mediaSource"){var p=s(x[f])==="object"?x[f]:{ideal:x[f]};p.exact!==void 0&&typeof p.exact=="number"&&(p.min=p.max=p.exact);var g=function(C,T){return C?C+T.charAt(0).toUpperCase()+T.slice(1):T==="deviceId"?"sourceId":T};if(p.ideal!==void 0){m.optional=m.optional||[];var E={};typeof p.ideal=="number"?(E[g("min",f)]=p.ideal,m.optional.push(E),(E={})[g("max",f)]=p.ideal,m.optional.push(E)):(E[g("",f)]=p.ideal,m.optional.push(E))}p.exact!==void 0&&typeof p.exact!="number"?(m.mandatory=m.mandatory||{},m.mandatory[g("",f)]=p.exact):["min","max"].forEach(function(C){p[C]!==void 0&&(m.mandatory=m.mandatory||{},m.mandatory[g(C,f)]=p[C])})}}),x.advanced&&(m.optional=(m.optional||[]).concat(x.advanced)),m},b=function(x,m){if(l.version>=61)return m(x);if((x=JSON.parse(JSON.stringify(x)))&&s(x.audio)==="object"){var f=function(C,T,S){T in C&&!(S in C)&&(C[S]=C[T],delete C[T])};f((x=JSON.parse(JSON.stringify(x))).audio,"autoGainControl","googAutoGainControl"),f(x.audio,"noiseSuppression","googNoiseSuppression"),x.audio=h(x.audio)}if(x&&s(x.video)==="object"){var p=x.video.facingMode;p=p&&(s(p)==="object"?p:{ideal:p});var g,E=l.version<66;if(p&&(p.exact==="user"||p.exact==="environment"||p.ideal==="user"||p.ideal==="environment")&&(!u.mediaDevices.getSupportedConstraints||!u.mediaDevices.getSupportedConstraints().facingMode||E)&&(delete x.video.facingMode,p.exact==="environment"||p.ideal==="environment"?g=["back","rear"]:p.exact!=="user"&&p.ideal!=="user"||(g=["front"]),g))return u.mediaDevices.enumerateDevices().then(function(C){var T=(C=C.filter(function(S){return S.kind==="videoinput"})).find(function(S){return g.some(function(I){return S.label.toLowerCase().includes(I)})});return!T&&C.length&&g.includes("back")&&(T=C[C.length-1]),T&&(x.video.deviceId=p.exact?{exact:T.deviceId}:{ideal:T.deviceId}),x.video=h(x.video),a("chrome: "+JSON.stringify(x)),m(x)});x.video=h(x.video)}return a("chrome: "+JSON.stringify(x)),m(x)},w=function(x){return l.version>=64?x:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[x.name]||x.name,message:x.message,constraint:x.constraint||x.constraintName,toString:function(){return this.name+(this.message&&": ")+this.message}}};if(u.getUserMedia=function(x,m,f){b(x,function(p){u.webkitGetUserMedia(p,m,function(g){f&&f(w(g))})})}.bind(u),u.mediaDevices.getUserMedia){var v=u.mediaDevices.getUserMedia.bind(u.mediaDevices);u.mediaDevices.getUserMedia=function(x){return b(x,function(m){return v(m).then(function(f){if(m.audio&&!f.getAudioTracks().length||m.video&&!f.getVideoTracks().length)throw f.getTracks().forEach(function(p){p.stop()}),new DOMException("","NotFoundError");return f},function(f){return Promise.reject(w(f))})})}}}}},{"../utils.js":"iSxC"}],VHa8:[function(o,e,t){"use strict";function i(n,r){n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||n.navigator.mediaDevices&&(typeof r=="function"?n.navigator.mediaDevices.getDisplayMedia=function(s){return r(s).then(function(a){var c=s.video&&s.video.width,d=s.video&&s.video.height,l=s.video&&s.video.frameRate;return s.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:a,maxFrameRate:l||3}},c&&(s.video.mandatory.maxWidth=c),d&&(s.video.mandatory.maxHeight=d),n.navigator.mediaDevices.getUserMedia(s)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetDisplayMedia=i},{}],uI5X:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimMediaStream=l,t.shimOnTrack=u,t.shimGetSendersWithDtmf=h,t.shimGetStats=b,t.shimSenderReceiverGetStats=w,t.shimAddTrackRemoveTrackWithNative=v,t.shimAddTrackRemoveTrack=x,t.shimPeerConnection=m,t.fixNegotiationNeeded=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=a(o("../utils.js")),n=o("./getusermedia"),r=o("./getdisplaymedia");function s(){if(typeof WeakMap!="function")return null;var p=new WeakMap;return s=function(){return p},p}function a(p){if(p&&p.__esModule)return p;if(p===null||typeof p!="object"&&typeof p!="function")return{default:p};var g=s();if(g&&g.has(p))return g.get(p);var E={},C=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var T in p)if(Object.prototype.hasOwnProperty.call(p,T)){var S=C?Object.getOwnPropertyDescriptor(p,T):null;S&&(S.get||S.set)?Object.defineProperty(E,T,S):E[T]=p[T]}return E.default=p,g&&g.set(p,E),E}function c(p,g,E){return g in p?Object.defineProperty(p,g,{value:E,enumerable:!0,configurable:!0,writable:!0}):p[g]=E,p}function d(p){return(d=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})(p)}function l(p){p.MediaStream=p.MediaStream||p.webkitMediaStream}function u(p){if(d(p)!=="object"||!p.RTCPeerConnection||"ontrack"in p.RTCPeerConnection.prototype)i.wrapPeerConnectionEvent(p,"track",function(E){return E.transceiver||Object.defineProperty(E,"transceiver",{value:{receiver:E.receiver}}),E});else{Object.defineProperty(p.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(E){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=E)},enumerable:!0,configurable:!0});var g=p.RTCPeerConnection.prototype.setRemoteDescription;p.RTCPeerConnection.prototype.setRemoteDescription=function(){var E=this;return this._ontrackpoly||(this._ontrackpoly=function(C){C.stream.addEventListener("addtrack",function(T){var S;S=p.RTCPeerConnection.prototype.getReceivers?E.getReceivers().find(function(D){return D.track&&D.track.id===T.track.id}):{track:T.track};var I=new Event("track");I.track=T.track,I.receiver=S,I.transceiver={receiver:S},I.streams=[C.stream],E.dispatchEvent(I)}),C.stream.getTracks().forEach(function(T){var S;S=p.RTCPeerConnection.prototype.getReceivers?E.getReceivers().find(function(D){return D.track&&D.track.id===T.id}):{track:T};var I=new Event("track");I.track=T,I.receiver=S,I.transceiver={receiver:S},I.streams=[C.stream],E.dispatchEvent(I)})},this.addEventListener("addstream",this._ontrackpoly)),g.apply(this,arguments)}}}function h(p){if(d(p)==="object"&&p.RTCPeerConnection&&!("getSenders"in p.RTCPeerConnection.prototype)&&"createDTMFSender"in p.RTCPeerConnection.prototype){var g=function(D,O){return{track:O,get dtmf(){return this._dtmf===void 0&&(O.kind==="audio"?this._dtmf=D.createDTMFSender(O):this._dtmf=null),this._dtmf},_pc:D}};if(!p.RTCPeerConnection.prototype.getSenders){p.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};var E=p.RTCPeerConnection.prototype.addTrack;p.RTCPeerConnection.prototype.addTrack=function(D,O){var j=E.apply(this,arguments);return j||(j=g(this,D),this._senders.push(j)),j};var C=p.RTCPeerConnection.prototype.removeTrack;p.RTCPeerConnection.prototype.removeTrack=function(D){C.apply(this,arguments);var O=this._senders.indexOf(D);O!==-1&&this._senders.splice(O,1)}}var T=p.RTCPeerConnection.prototype.addStream;p.RTCPeerConnection.prototype.addStream=function(D){var O=this;this._senders=this._senders||[],T.apply(this,[D]),D.getTracks().forEach(function(j){O._senders.push(g(O,j))})};var S=p.RTCPeerConnection.prototype.removeStream;p.RTCPeerConnection.prototype.removeStream=function(D){var O=this;this._senders=this._senders||[],S.apply(this,[D]),D.getTracks().forEach(function(j){var F=O._senders.find(function(W){return W.track===j});F&&O._senders.splice(O._senders.indexOf(F),1)})}}else if(d(p)==="object"&&p.RTCPeerConnection&&"getSenders"in p.RTCPeerConnection.prototype&&"createDTMFSender"in p.RTCPeerConnection.prototype&&p.RTCRtpSender&&!("dtmf"in p.RTCRtpSender.prototype)){var I=p.RTCPeerConnection.prototype.getSenders;p.RTCPeerConnection.prototype.getSenders=function(){var D=this,O=I.apply(this,[]);return O.forEach(function(j){return j._pc=D}),O},Object.defineProperty(p.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 b(p){if(p.RTCPeerConnection){var g=p.RTCPeerConnection.prototype.getStats;p.RTCPeerConnection.prototype.getStats=function(){var E=this,[C,T,S]=arguments;if(arguments.length>0&&typeof C=="function")return g.apply(this,arguments);if(g.length===0&&(arguments.length===0||typeof C!="function"))return g.apply(this,[]);var I=function(O){var j={};return O.result().forEach(function(F){var W={id:F.id,timestamp:F.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[F.type]||F.type};F.names().forEach(function(z){W[z]=F.stat(z)}),j[W.id]=W}),j},D=function(O){return new Map(Object.keys(O).map(function(j){return[j,O[j]]}))};return arguments.length>=2?g.apply(this,[function(O){T(D(I(O)))},C]):new Promise(function(O,j){g.apply(E,[function(F){O(D(I(F)))},j])}).then(T,S)}}}function w(p){if(d(p)==="object"&&p.RTCPeerConnection&&p.RTCRtpSender&&p.RTCRtpReceiver){if(!("getStats"in p.RTCRtpSender.prototype)){var g=p.RTCPeerConnection.prototype.getSenders;g&&(p.RTCPeerConnection.prototype.getSenders=function(){var S=this,I=g.apply(this,[]);return I.forEach(function(D){return D._pc=S}),I});var E=p.RTCPeerConnection.prototype.addTrack;E&&(p.RTCPeerConnection.prototype.addTrack=function(){var S=E.apply(this,arguments);return S._pc=this,S}),p.RTCRtpSender.prototype.getStats=function(){var S=this;return this._pc.getStats().then(function(I){return i.filterStats(I,S.track,!0)})}}if(!("getStats"in p.RTCRtpReceiver.prototype)){var C=p.RTCPeerConnection.prototype.getReceivers;C&&(p.RTCPeerConnection.prototype.getReceivers=function(){var S=this,I=C.apply(this,[]);return I.forEach(function(D){return D._pc=S}),I}),i.wrapPeerConnectionEvent(p,"track",function(S){return S.receiver._pc=S.srcElement,S}),p.RTCRtpReceiver.prototype.getStats=function(){var S=this;return this._pc.getStats().then(function(I){return i.filterStats(I,S.track,!1)})}}if("getStats"in p.RTCRtpSender.prototype&&"getStats"in p.RTCRtpReceiver.prototype){var T=p.RTCPeerConnection.prototype.getStats;p.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof p.MediaStreamTrack){var S,I,D,O=arguments[0];return this.getSenders().forEach(function(j){j.track===O&&(S?D=!0:S=j)}),this.getReceivers().forEach(function(j){return j.track===O&&(I?D=!0:I=j),j.track===O}),D||S&&I?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):S?S.getStats():I?I.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return T.apply(this,arguments)}}}}function v(p){p.RTCPeerConnection.prototype.getLocalStreams=function(){var S=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(function(I){return S._shimmedLocalStreams[I][0]})};var g=p.RTCPeerConnection.prototype.addTrack;p.RTCPeerConnection.prototype.addTrack=function(S,I){if(!I)return g.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var D=g.apply(this,arguments);return this._shimmedLocalStreams[I.id]?this._shimmedLocalStreams[I.id].indexOf(D)===-1&&this._shimmedLocalStreams[I.id].push(D):this._shimmedLocalStreams[I.id]=[I,D],D};var E=p.RTCPeerConnection.prototype.addStream;p.RTCPeerConnection.prototype.addStream=function(S){var I=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},S.getTracks().forEach(function(j){if(I.getSenders().find(function(F){return F.track===j}))throw new DOMException("Track already exists.","InvalidAccessError")});var D=this.getSenders();E.apply(this,arguments);var O=this.getSenders().filter(function(j){return D.indexOf(j)===-1});this._shimmedLocalStreams[S.id]=[S].concat(O)};var C=p.RTCPeerConnection.prototype.removeStream;p.RTCPeerConnection.prototype.removeStream=function(S){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[S.id],C.apply(this,arguments)};var T=p.RTCPeerConnection.prototype.removeTrack;p.RTCPeerConnection.prototype.removeTrack=function(S){var I=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},S&&Object.keys(this._shimmedLocalStreams).forEach(function(D){var O=I._shimmedLocalStreams[D].indexOf(S);O!==-1&&I._shimmedLocalStreams[D].splice(O,1),I._shimmedLocalStreams[D].length===1&&delete I._shimmedLocalStreams[D]}),T.apply(this,arguments)}}function x(p,g){if(p.RTCPeerConnection){if(p.RTCPeerConnection.prototype.addTrack&&g.version>=65)return v(p);var E=p.RTCPeerConnection.prototype.getLocalStreams;p.RTCPeerConnection.prototype.getLocalStreams=function(){var O=this,j=E.apply(this);return this._reverseStreams=this._reverseStreams||{},j.map(function(F){return O._reverseStreams[F.id]})};var C=p.RTCPeerConnection.prototype.addStream;p.RTCPeerConnection.prototype.addStream=function(O){var j=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},O.getTracks().forEach(function(W){if(j.getSenders().find(function(z){return z.track===W}))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[O.id]){var F=new p.MediaStream(O.getTracks());this._streams[O.id]=F,this._reverseStreams[F.id]=O,O=F}C.apply(this,[O])};var T=p.RTCPeerConnection.prototype.removeStream;p.RTCPeerConnection.prototype.removeStream=function(O){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},T.apply(this,[this._streams[O.id]||O]),delete this._reverseStreams[this._streams[O.id]?this._streams[O.id].id:O.id],delete this._streams[O.id]},p.RTCPeerConnection.prototype.addTrack=function(O,j){var F=this;if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var W=[].slice.call(arguments,1);if(W.length!==1||!W[0].getTracks().find(function(ue){return ue===O}))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(ue){return ue.track===O}))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var z=this._streams[j.id];if(z)z.addTrack(O),Promise.resolve().then(function(){F.dispatchEvent(new Event("negotiationneeded"))});else{var ne=new p.MediaStream([O]);this._streams[j.id]=ne,this._reverseStreams[ne.id]=j,this.addStream(ne)}return this.getSenders().find(function(ue){return ue.track===O})},["createOffer","createAnswer"].forEach(function(O){var j=p.RTCPeerConnection.prototype[O],F=c({},O,function(){var W=this,z=arguments;return arguments.length&&typeof arguments[0]=="function"?j.apply(this,[function(ne){var ue=D(W,ne);z[0].apply(null,[ue])},function(ne){z[1]&&z[1].apply(null,ne)},arguments[2]]):j.apply(this,arguments).then(function(ne){return D(W,ne)})});p.RTCPeerConnection.prototype[O]=F[O]});var S=p.RTCPeerConnection.prototype.setLocalDescription;p.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=(O=this,j=arguments[0],F=j.sdp,Object.keys(O._reverseStreams||[]).forEach(function(W){var z=O._reverseStreams[W],ne=O._streams[z.id];F=F.replace(new RegExp(z.id,"g"),ne.id)}),new RTCSessionDescription({type:j.type,sdp:F})),S.apply(this,arguments)):S.apply(this,arguments);var O,j,F};var I=Object.getOwnPropertyDescriptor(p.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(p.RTCPeerConnection.prototype,"localDescription",{get:function(){var O=I.get.apply(this);return O.type===""?O:D(this,O)}}),p.RTCPeerConnection.prototype.removeTrack=function(O){var j,F=this;if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!O._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(O._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{},Object.keys(this._streams).forEach(function(W){F._streams[W].getTracks().find(function(z){return O.track===z})&&(j=F._streams[W])}),j&&(j.getTracks().length===1?this.removeStream(this._reverseStreams[j.id]):j.removeTrack(O.track),this.dispatchEvent(new Event("negotiationneeded")))}}function D(O,j){var F=j.sdp;return Object.keys(O._reverseStreams||[]).forEach(function(W){var z=O._reverseStreams[W],ne=O._streams[z.id];F=F.replace(new RegExp(ne.id,"g"),z.id)}),new RTCSessionDescription({type:j.type,sdp:F})}}function m(p,g){!p.RTCPeerConnection&&p.webkitRTCPeerConnection&&(p.RTCPeerConnection=p.webkitRTCPeerConnection),p.RTCPeerConnection&&g.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(E){var C=p.RTCPeerConnection.prototype[E],T=c({},E,function(){return arguments[0]=new(E==="addIceCandidate"?p.RTCIceCandidate:p.RTCSessionDescription)(arguments[0]),C.apply(this,arguments)});p.RTCPeerConnection.prototype[E]=T[E]})}function f(p,g){i.wrapPeerConnectionEvent(p,"negotiationneeded",function(E){var C=E.target;if(!(g.version<72||C.getConfiguration&&C.getConfiguration().sdpSemantics==="plan-b")||C.signalingState==="stable")return E})}},{"../utils.js":"iSxC","./getusermedia":"s6SN","./getdisplaymedia":"VHa8"}],NZ1C:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterIceServers=s;var i=r(o("../utils"));function n(){if(typeof WeakMap!="function")return null;var a=new WeakMap;return n=function(){return a},a}function r(a){if(a&&a.__esModule)return a;if(a===null||typeof a!="object"&&typeof a!="function")return{default:a};var c=n();if(c&&c.has(a))return c.get(a);var d={},l=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var u in a)if(Object.prototype.hasOwnProperty.call(a,u)){var h=l?Object.getOwnPropertyDescriptor(a,u):null;h&&(h.get||h.set)?Object.defineProperty(d,u,h):d[u]=a[u]}return d.default=a,c&&c.set(a,d),d}function s(a,c){var d=!1;return(a=JSON.parse(JSON.stringify(a))).filter(function(l){if(l&&(l.urls||l.url)){var u=l.urls||l.url;l.url&&!l.urls&&i.deprecated("RTCIceServer.url","RTCIceServer.urls");var h=typeof u=="string";return h&&(u=[u]),u=u.filter(function(b){if(b.indexOf("stun:")===0)return!1;var w=b.startsWith("turn")&&!b.startsWith("turn:[")&&b.includes("transport=udp");return w&&!d?(d=!0,!0):w&&!d}),delete l.url,l.urls=h?u[0]:u,!!u.length}})}},{"../utils":"iSxC"}],YHvh:[function(o,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 pg=Object.create;var Ts=Object.defineProperty;var Uh=Object.getOwnPropertyDescriptor;var fg=Object.getOwnPropertyNames;var mg=Object.getPrototypeOf,gg=Object.prototype.hasOwnProperty;var bg=(o,e,t)=>e in o?Ts(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var Oc=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+o+'" is not supported')});var Rs=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),Gh=(o,e)=>{for(var t in e)Ts(o,t,{get:e[t],enumerable:!0})},vg=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of fg(e))!gg.call(o,n)&&n!==t&&Ts(o,n,{get:()=>e[n],enumerable:!(i=Uh(e,n))||i.enumerable});return o};var wa=(o,e,t)=>(t=o!=null?pg(mg(o)):{},vg(e||!o||!o.__esModule?Ts(t,"default",{value:o,enumerable:!0}):t,o));var y=(o,e,t,i)=>{for(var n=i>1?void 0:i?Uh(e,t):e,r=o.length-1,s;r>=0;r--)(s=o[r])&&(n=(i?s(e,t,n):s(n))||n);return i&&n&&Ts(e,t,n),n};var D=(o,e,t)=>(bg(o,typeof e!="symbol"?e+"":e,t),t);var el=Rs((Jp,pd)=>{parcelRequire=function(o,e,t,i){var n,r=typeof parcelRequire=="function"&&parcelRequire,s=typeof Oc=="function"&&Oc;function a(l,u){if(!e[l]){if(!o[l]){var h=typeof parcelRequire=="function"&&parcelRequire;if(!u&&h)return h(l,!0);if(r)return r(l,!0);if(s&&typeof l=="string")return s(l);var b=new Error("Cannot find module '"+l+"'");throw b.code="MODULE_NOT_FOUND",b}v.resolve=function(x){return o[l][1][x]||x},v.cache={};var w=e[l]=new a.Module(l);o[l][0].call(w.exports,v,w,w.exports,this)}return e[l].exports;function v(x){return a(v.resolve(x))}}a.isParcelRequire=!0,a.Module=function(l){this.id=l,this.bundle=a,this.exports={}},a.modules=o,a.cache=e,a.parent=r,a.register=function(l,u){o[l]=[function(h,b){b.exports=u},{}]};for(var c=0;c<t.length;c++)try{a(t[c])}catch(l){n||(n=l)}if(t.length){var d=a(t[t.length-1]);typeof Jp=="object"&&typeof pd<"u"?pd.exports=d:typeof define=="function"&&define.amd?define(function(){return d}):i&&(this[i]=d)}if(parcelRequire=a,n)throw n;return a}({EgBh:[function(o,e,t){var i={};i.useBlobBuilder=function(){try{return new Blob([]),!1}catch{return!0}}(),i.useArrayBufferView=!i.useBlobBuilder&&function(){try{return new Blob([new Uint8Array([])]).size===0}catch{return!0}}(),e.exports.binaryFeatures=i;var n=e.exports.BlobBuilder;function r(){this._pieces=[],this._parts=[]}typeof window<"u"&&(n=e.exports.BlobBuilder=window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder||window.BlobBuilder),r.prototype.append=function(s){typeof s=="number"?this._pieces.push(s):(this.flush(),this._parts.push(s))},r.prototype.flush=function(){if(this._pieces.length>0){var s=new Uint8Array(this._pieces);i.useArrayBufferView||(s=s.buffer),this._parts.push(s),this._pieces=[]}},r.prototype.getBuffer=function(){if(this.flush(),i.useBlobBuilder){for(var s=new n,a=0,c=this._parts.length;a<c;a++)s.append(this._parts[a]);return s.getBlob()}return new Blob(this._parts)},e.exports.BufferBuilder=r},{}],kdPp:[function(o,e,t){var i=o("./bufferbuilder").BufferBuilder,n=o("./bufferbuilder").binaryFeatures,r={unpack:function(l){return new s(l).unpack()},pack:function(l){var u=new a;return u.pack(l),u.getBuffer()}};function s(l){this.index=0,this.dataBuffer=l,this.dataView=new Uint8Array(this.dataBuffer),this.length=this.dataBuffer.byteLength}function a(){this.bufferBuilder=new i}function c(l){var u=l.charCodeAt(0);return u<=2047?"00":u<=65535?"000":u<=2097151?"0000":u<=67108863?"00000":"000000"}function d(l){return l.length>600?new Blob([l]).size:l.replace(/[^\u0000-\u007F]/g,c).length}e.exports=r,s.prototype.unpack=function(){var l,u=this.unpack_uint8();if(u<128)return u;if((224^u)<32)return(224^u)-32;if((l=160^u)<=15)return this.unpack_raw(l);if((l=176^u)<=15)return this.unpack_string(l);if((l=144^u)<=15)return this.unpack_array(l);if((l=128^u)<=15)return this.unpack_map(l);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 l=this.unpack_uint16(),this.unpack_string(l);case 217:return l=this.unpack_uint32(),this.unpack_string(l);case 218:return l=this.unpack_uint16(),this.unpack_raw(l);case 219:return l=this.unpack_uint32(),this.unpack_raw(l);case 220:return l=this.unpack_uint16(),this.unpack_array(l);case 221:return l=this.unpack_uint32(),this.unpack_array(l);case 222:return l=this.unpack_uint16(),this.unpack_map(l);case 223:return l=this.unpack_uint32(),this.unpack_map(l)}},s.prototype.unpack_uint8=function(){var l=255&this.dataView[this.index];return this.index++,l},s.prototype.unpack_uint16=function(){var l=this.read(2),u=256*(255&l[0])+(255&l[1]);return this.index+=2,u},s.prototype.unpack_uint32=function(){var l=this.read(4),u=256*(256*(256*l[0]+l[1])+l[2])+l[3];return this.index+=4,u},s.prototype.unpack_uint64=function(){var l=this.read(8),u=256*(256*(256*(256*(256*(256*(256*l[0]+l[1])+l[2])+l[3])+l[4])+l[5])+l[6])+l[7];return this.index+=8,u},s.prototype.unpack_int8=function(){var l=this.unpack_uint8();return l<128?l:l-256},s.prototype.unpack_int16=function(){var l=this.unpack_uint16();return l<32768?l:l-65536},s.prototype.unpack_int32=function(){var l=this.unpack_uint32();return l<Math.pow(2,31)?l:l-Math.pow(2,32)},s.prototype.unpack_int64=function(){var l=this.unpack_uint64();return l<Math.pow(2,63)?l:l-Math.pow(2,64)},s.prototype.unpack_raw=function(l){if(this.length<this.index+l)throw new Error("BinaryPackFailure: index is out of range "+this.index+" "+l+" "+this.length);var u=this.dataBuffer.slice(this.index,this.index+l);return this.index+=l,u},s.prototype.unpack_string=function(l){for(var u,h,b=this.read(l),w=0,v="";w<l;)(u=b[w])<128?(v+=String.fromCharCode(u),w++):(192^u)<32?(h=(192^u)<<6|63&b[w+1],v+=String.fromCharCode(h),w+=2):(h=(15&u)<<12|(63&b[w+1])<<6|63&b[w+2],v+=String.fromCharCode(h),w+=3);return this.index+=l,v},s.prototype.unpack_array=function(l){for(var u=new Array(l),h=0;h<l;h++)u[h]=this.unpack();return u},s.prototype.unpack_map=function(l){for(var u={},h=0;h<l;h++){var b=this.unpack(),w=this.unpack();u[b]=w}return u},s.prototype.unpack_float=function(){var l=this.unpack_uint32(),u=(l>>23&255)-127;return(l>>31===0?1:-1)*(8388607&l|8388608)*Math.pow(2,u-23)},s.prototype.unpack_double=function(){var l=this.unpack_uint32(),u=this.unpack_uint32(),h=(l>>20&2047)-1023;return(l>>31===0?1:-1)*((1048575&l|1048576)*Math.pow(2,h-20)+u*Math.pow(2,h-52))},s.prototype.read=function(l){var u=this.index;if(u+l<=this.length)return this.dataView.subarray(u,u+l);throw new Error("BinaryPackFailure: read index out of range")},a.prototype.getBuffer=function(){return this.bufferBuilder.getBuffer()},a.prototype.pack=function(l){var u=typeof l;if(u==="string")this.pack_string(l);else if(u==="number")Math.floor(l)===l?this.pack_integer(l):this.pack_double(l);else if(u==="boolean")l===!0?this.bufferBuilder.append(195):l===!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(l===null)this.bufferBuilder.append(192);else{var h=l.constructor;if(h==Array)this.pack_array(l);else if(h==Blob||h==File||l instanceof Blob||l instanceof File)this.pack_bin(l);else if(h==ArrayBuffer)n.useArrayBufferView?this.pack_bin(new Uint8Array(l)):this.pack_bin(l);else if("BYTES_PER_ELEMENT"in l)n.useArrayBufferView?this.pack_bin(new Uint8Array(l.buffer)):this.pack_bin(l.buffer);else if(h==Object||h.toString().startsWith("class"))this.pack_object(l);else if(h==Date)this.pack_string(l.toString());else{if(typeof l.toBinaryPack!="function")throw new Error('Type "'+h.toString()+'" not yet supported');this.bufferBuilder.append(l.toBinaryPack())}}}this.bufferBuilder.flush()},a.prototype.pack_bin=function(l){var u=l.length||l.byteLength||l.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(l)},a.prototype.pack_string=function(l){var u=d(l);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(l)},a.prototype.pack_array=function(l){var u=l.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(l[h])},a.prototype.pack_integer=function(l){if(l>=-32&&l<=127)this.bufferBuilder.append(255&l);else if(l>=0&&l<=255)this.bufferBuilder.append(204),this.pack_uint8(l);else if(l>=-128&&l<=127)this.bufferBuilder.append(208),this.pack_int8(l);else if(l>=0&&l<=65535)this.bufferBuilder.append(205),this.pack_uint16(l);else if(l>=-32768&&l<=32767)this.bufferBuilder.append(209),this.pack_int16(l);else if(l>=0&&l<=4294967295)this.bufferBuilder.append(206),this.pack_uint32(l);else if(l>=-2147483648&&l<=2147483647)this.bufferBuilder.append(210),this.pack_int32(l);else if(l>=-9223372036854776e3&&l<=9223372036854776e3)this.bufferBuilder.append(211),this.pack_int64(l);else{if(!(l>=0&&l<=18446744073709552e3))throw new Error("Invalid integer");this.bufferBuilder.append(207),this.pack_uint64(l)}},a.prototype.pack_double=function(l){var u=0;l<0&&(u=1,l=-l);var h=Math.floor(Math.log(l)/Math.LN2),b=l/Math.pow(2,h)-1,w=Math.floor(b*Math.pow(2,52)),v=Math.pow(2,32),x=u<<31|h+1023<<20|w/v&1048575,m=w%v;this.bufferBuilder.append(203),this.pack_int32(x),this.pack_int32(m)},a.prototype.pack_object=function(l){var u=Object.keys(l).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 l)l.hasOwnProperty(h)&&(this.pack(h),this.pack(l[h]))},a.prototype.pack_uint8=function(l){this.bufferBuilder.append(l)},a.prototype.pack_uint16=function(l){this.bufferBuilder.append(l>>8),this.bufferBuilder.append(255&l)},a.prototype.pack_uint32=function(l){var u=4294967295&l;this.bufferBuilder.append((4278190080&u)>>>24),this.bufferBuilder.append((16711680&u)>>>16),this.bufferBuilder.append((65280&u)>>>8),this.bufferBuilder.append(255&u)},a.prototype.pack_uint64=function(l){var u=l/Math.pow(2,32),h=l%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)},a.prototype.pack_int8=function(l){this.bufferBuilder.append(255&l)},a.prototype.pack_int16=function(l){this.bufferBuilder.append((65280&l)>>8),this.bufferBuilder.append(255&l)},a.prototype.pack_int32=function(l){this.bufferBuilder.append(l>>>24&255),this.bufferBuilder.append((16711680&l)>>>16),this.bufferBuilder.append((65280&l)>>>8),this.bufferBuilder.append(255&l)},a.prototype.pack_int64=function(l){var u=Math.floor(l/Math.pow(2,32)),h=l%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(o,e,t){"use strict";function i(f,p,g){return p in f?Object.defineProperty(f,p,{value:g,enumerable:!0,configurable:!0,writable:!0}):f[p]=g,f}function n(f){return(n=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(p){return typeof p}:function(p){return p&&typeof Symbol=="function"&&p.constructor===Symbol&&p!==Symbol.prototype?"symbol":typeof p})(f)}Object.defineProperty(t,"__esModule",{value:!0}),t.extractVersion=a,t.wrapPeerConnectionEvent=c,t.disableLog=d,t.disableWarnings=l,t.log=u,t.deprecated=h,t.detectBrowser=b,t.compactObject=v,t.walkStats=x,t.filterStats=m;var r=!0,s=!0;function a(f,p,g){var E=f.match(p);return E&&E.length>=g&&parseInt(E[g],10)}function c(f,p,g){if(f.RTCPeerConnection){var E=f.RTCPeerConnection.prototype,C=E.addEventListener;E.addEventListener=function(S,I){if(S!==p)return C.apply(this,arguments);var A=function(k){var j=g(k);j&&(I.handleEvent?I.handleEvent(j):I(j))};return this._eventMap=this._eventMap||{},this._eventMap[p]||(this._eventMap[p]=new Map),this._eventMap[p].set(I,A),C.apply(this,[S,A])};var T=E.removeEventListener;E.removeEventListener=function(S,I){if(S!==p||!this._eventMap||!this._eventMap[p])return T.apply(this,arguments);if(!this._eventMap[p].has(I))return T.apply(this,arguments);var A=this._eventMap[p].get(I);return this._eventMap[p].delete(I),this._eventMap[p].size===0&&delete this._eventMap[p],Object.keys(this._eventMap).length===0&&delete this._eventMap,T.apply(this,[S,A])},Object.defineProperty(E,"on"+p,{get:function(){return this["_on"+p]},set:function(S){this["_on"+p]&&(this.removeEventListener(p,this["_on"+p]),delete this["_on"+p]),S&&this.addEventListener(p,this["_on"+p]=S)},enumerable:!0,configurable:!0})}}function d(f){return typeof f!="boolean"?new Error("Argument type: "+n(f)+". Please use a boolean."):(r=f,f?"adapter.js logging disabled":"adapter.js logging enabled")}function l(f){return typeof f!="boolean"?new Error("Argument type: "+n(f)+". Please use a boolean."):(s=!f,"adapter.js deprecation warnings "+(f?"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(f,p){s&&console.warn(f+" is deprecated, please use "+p+" instead.")}function b(f){var p={browser:null,version:null};if(f===void 0||!f.navigator)return p.browser="Not a browser.",p;var{navigator:g}=f;if(g.mozGetUserMedia)p.browser="firefox",p.version=a(g.userAgent,/Firefox\/(\d+)\./,1);else if(g.webkitGetUserMedia||f.isSecureContext===!1&&f.webkitRTCPeerConnection&&!f.RTCIceGatherer)p.browser="chrome",p.version=a(g.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(g.mediaDevices&&g.userAgent.match(/Edge\/(\d+).(\d+)$/))p.browser="edge",p.version=a(g.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!f.RTCPeerConnection||!g.userAgent.match(/AppleWebKit\/(\d+)\./))return p.browser="Not a supported browser.",p;p.browser="safari",p.version=a(g.userAgent,/AppleWebKit\/(\d+)\./,1),p.supportsUnifiedPlan=f.RTCRtpTransceiver&&"currentDirection"in f.RTCRtpTransceiver.prototype}return p}function w(f){return Object.prototype.toString.call(f)==="[object Object]"}function v(f){return w(f)?Object.keys(f).reduce(function(p,g){var E=w(f[g]),C=E?v(f[g]):f[g],T=E&&!Object.keys(C).length;return C===void 0||T?p:Object.assign(p,i({},g,C))},{}):f}function x(f,p,g){p&&!g.has(p.id)&&(g.set(p.id,p),Object.keys(p).forEach(function(E){E.endsWith("Id")?x(f,f.get(p[E]),g):E.endsWith("Ids")&&p[E].forEach(function(C){x(f,f.get(C),g)})}))}function m(f,p,g){var E=g?"outbound-rtp":"inbound-rtp",C=new Map;if(p===null)return C;var T=[];return f.forEach(function(S){S.type==="track"&&S.trackIdentifier===p.id&&T.push(S)}),T.forEach(function(S){f.forEach(function(I){I.type===E&&I.trackId===S.id&&x(f,I,C)})}),C}},{}],s6SN:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetUserMedia=c;var i=r(o("../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 l=n();if(l&&l.has(d))return l.get(d);var u={},h=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var b in d)if(Object.prototype.hasOwnProperty.call(d,b)){var w=h?Object.getOwnPropertyDescriptor(d,b):null;w&&(w.get||w.set)?Object.defineProperty(u,b,w):u[b]=d[b]}return u.default=d,l&&l.set(d,u),u}function s(d){return(s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(l){return typeof l}:function(l){return l&&typeof Symbol=="function"&&l.constructor===Symbol&&l!==Symbol.prototype?"symbol":typeof l})(d)}var a=i.log;function c(d,l){var u=d&&d.navigator;if(u.mediaDevices){var h=function(x){if(s(x)!=="object"||x.mandatory||x.optional)return x;var m={};return Object.keys(x).forEach(function(f){if(f!=="require"&&f!=="advanced"&&f!=="mediaSource"){var p=s(x[f])==="object"?x[f]:{ideal:x[f]};p.exact!==void 0&&typeof p.exact=="number"&&(p.min=p.max=p.exact);var g=function(C,T){return C?C+T.charAt(0).toUpperCase()+T.slice(1):T==="deviceId"?"sourceId":T};if(p.ideal!==void 0){m.optional=m.optional||[];var E={};typeof p.ideal=="number"?(E[g("min",f)]=p.ideal,m.optional.push(E),(E={})[g("max",f)]=p.ideal,m.optional.push(E)):(E[g("",f)]=p.ideal,m.optional.push(E))}p.exact!==void 0&&typeof p.exact!="number"?(m.mandatory=m.mandatory||{},m.mandatory[g("",f)]=p.exact):["min","max"].forEach(function(C){p[C]!==void 0&&(m.mandatory=m.mandatory||{},m.mandatory[g(C,f)]=p[C])})}}),x.advanced&&(m.optional=(m.optional||[]).concat(x.advanced)),m},b=function(x,m){if(l.version>=61)return m(x);if((x=JSON.parse(JSON.stringify(x)))&&s(x.audio)==="object"){var f=function(C,T,S){T in C&&!(S in C)&&(C[S]=C[T],delete C[T])};f((x=JSON.parse(JSON.stringify(x))).audio,"autoGainControl","googAutoGainControl"),f(x.audio,"noiseSuppression","googNoiseSuppression"),x.audio=h(x.audio)}if(x&&s(x.video)==="object"){var p=x.video.facingMode;p=p&&(s(p)==="object"?p:{ideal:p});var g,E=l.version<66;if(p&&(p.exact==="user"||p.exact==="environment"||p.ideal==="user"||p.ideal==="environment")&&(!u.mediaDevices.getSupportedConstraints||!u.mediaDevices.getSupportedConstraints().facingMode||E)&&(delete x.video.facingMode,p.exact==="environment"||p.ideal==="environment"?g=["back","rear"]:p.exact!=="user"&&p.ideal!=="user"||(g=["front"]),g))return u.mediaDevices.enumerateDevices().then(function(C){var T=(C=C.filter(function(S){return S.kind==="videoinput"})).find(function(S){return g.some(function(I){return S.label.toLowerCase().includes(I)})});return!T&&C.length&&g.includes("back")&&(T=C[C.length-1]),T&&(x.video.deviceId=p.exact?{exact:T.deviceId}:{ideal:T.deviceId}),x.video=h(x.video),a("chrome: "+JSON.stringify(x)),m(x)});x.video=h(x.video)}return a("chrome: "+JSON.stringify(x)),m(x)},w=function(x){return l.version>=64?x:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[x.name]||x.name,message:x.message,constraint:x.constraint||x.constraintName,toString:function(){return this.name+(this.message&&": ")+this.message}}};if(u.getUserMedia=function(x,m,f){b(x,function(p){u.webkitGetUserMedia(p,m,function(g){f&&f(w(g))})})}.bind(u),u.mediaDevices.getUserMedia){var v=u.mediaDevices.getUserMedia.bind(u.mediaDevices);u.mediaDevices.getUserMedia=function(x){return b(x,function(m){return v(m).then(function(f){if(m.audio&&!f.getAudioTracks().length||m.video&&!f.getVideoTracks().length)throw f.getTracks().forEach(function(p){p.stop()}),new DOMException("","NotFoundError");return f},function(f){return Promise.reject(w(f))})})}}}}},{"../utils.js":"iSxC"}],VHa8:[function(o,e,t){"use strict";function i(n,r){n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||n.navigator.mediaDevices&&(typeof r=="function"?n.navigator.mediaDevices.getDisplayMedia=function(s){return r(s).then(function(a){var c=s.video&&s.video.width,d=s.video&&s.video.height,l=s.video&&s.video.frameRate;return s.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:a,maxFrameRate:l||3}},c&&(s.video.mandatory.maxWidth=c),d&&(s.video.mandatory.maxHeight=d),n.navigator.mediaDevices.getUserMedia(s)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetDisplayMedia=i},{}],uI5X:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimMediaStream=l,t.shimOnTrack=u,t.shimGetSendersWithDtmf=h,t.shimGetStats=b,t.shimSenderReceiverGetStats=w,t.shimAddTrackRemoveTrackWithNative=v,t.shimAddTrackRemoveTrack=x,t.shimPeerConnection=m,t.fixNegotiationNeeded=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=a(o("../utils.js")),n=o("./getusermedia"),r=o("./getdisplaymedia");function s(){if(typeof WeakMap!="function")return null;var p=new WeakMap;return s=function(){return p},p}function a(p){if(p&&p.__esModule)return p;if(p===null||typeof p!="object"&&typeof p!="function")return{default:p};var g=s();if(g&&g.has(p))return g.get(p);var E={},C=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var T in p)if(Object.prototype.hasOwnProperty.call(p,T)){var S=C?Object.getOwnPropertyDescriptor(p,T):null;S&&(S.get||S.set)?Object.defineProperty(E,T,S):E[T]=p[T]}return E.default=p,g&&g.set(p,E),E}function c(p,g,E){return g in p?Object.defineProperty(p,g,{value:E,enumerable:!0,configurable:!0,writable:!0}):p[g]=E,p}function d(p){return(d=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})(p)}function l(p){p.MediaStream=p.MediaStream||p.webkitMediaStream}function u(p){if(d(p)!=="object"||!p.RTCPeerConnection||"ontrack"in p.RTCPeerConnection.prototype)i.wrapPeerConnectionEvent(p,"track",function(E){return E.transceiver||Object.defineProperty(E,"transceiver",{value:{receiver:E.receiver}}),E});else{Object.defineProperty(p.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(E){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=E)},enumerable:!0,configurable:!0});var g=p.RTCPeerConnection.prototype.setRemoteDescription;p.RTCPeerConnection.prototype.setRemoteDescription=function(){var E=this;return this._ontrackpoly||(this._ontrackpoly=function(C){C.stream.addEventListener("addtrack",function(T){var S;S=p.RTCPeerConnection.prototype.getReceivers?E.getReceivers().find(function(A){return A.track&&A.track.id===T.track.id}):{track:T.track};var I=new Event("track");I.track=T.track,I.receiver=S,I.transceiver={receiver:S},I.streams=[C.stream],E.dispatchEvent(I)}),C.stream.getTracks().forEach(function(T){var S;S=p.RTCPeerConnection.prototype.getReceivers?E.getReceivers().find(function(A){return A.track&&A.track.id===T.id}):{track:T};var I=new Event("track");I.track=T,I.receiver=S,I.transceiver={receiver:S},I.streams=[C.stream],E.dispatchEvent(I)})},this.addEventListener("addstream",this._ontrackpoly)),g.apply(this,arguments)}}}function h(p){if(d(p)==="object"&&p.RTCPeerConnection&&!("getSenders"in p.RTCPeerConnection.prototype)&&"createDTMFSender"in p.RTCPeerConnection.prototype){var g=function(A,k){return{track:k,get dtmf(){return this._dtmf===void 0&&(k.kind==="audio"?this._dtmf=A.createDTMFSender(k):this._dtmf=null),this._dtmf},_pc:A}};if(!p.RTCPeerConnection.prototype.getSenders){p.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};var E=p.RTCPeerConnection.prototype.addTrack;p.RTCPeerConnection.prototype.addTrack=function(A,k){var j=E.apply(this,arguments);return j||(j=g(this,A),this._senders.push(j)),j};var C=p.RTCPeerConnection.prototype.removeTrack;p.RTCPeerConnection.prototype.removeTrack=function(A){C.apply(this,arguments);var k=this._senders.indexOf(A);k!==-1&&this._senders.splice(k,1)}}var T=p.RTCPeerConnection.prototype.addStream;p.RTCPeerConnection.prototype.addStream=function(A){var k=this;this._senders=this._senders||[],T.apply(this,[A]),A.getTracks().forEach(function(j){k._senders.push(g(k,j))})};var S=p.RTCPeerConnection.prototype.removeStream;p.RTCPeerConnection.prototype.removeStream=function(A){var k=this;this._senders=this._senders||[],S.apply(this,[A]),A.getTracks().forEach(function(j){var F=k._senders.find(function(W){return W.track===j});F&&k._senders.splice(k._senders.indexOf(F),1)})}}else if(d(p)==="object"&&p.RTCPeerConnection&&"getSenders"in p.RTCPeerConnection.prototype&&"createDTMFSender"in p.RTCPeerConnection.prototype&&p.RTCRtpSender&&!("dtmf"in p.RTCRtpSender.prototype)){var I=p.RTCPeerConnection.prototype.getSenders;p.RTCPeerConnection.prototype.getSenders=function(){var A=this,k=I.apply(this,[]);return k.forEach(function(j){return j._pc=A}),k},Object.defineProperty(p.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 b(p){if(p.RTCPeerConnection){var g=p.RTCPeerConnection.prototype.getStats;p.RTCPeerConnection.prototype.getStats=function(){var E=this,[C,T,S]=arguments;if(arguments.length>0&&typeof C=="function")return g.apply(this,arguments);if(g.length===0&&(arguments.length===0||typeof C!="function"))return g.apply(this,[]);var I=function(k){var j={};return k.result().forEach(function(F){var W={id:F.id,timestamp:F.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[F.type]||F.type};F.names().forEach(function(z){W[z]=F.stat(z)}),j[W.id]=W}),j},A=function(k){return new Map(Object.keys(k).map(function(j){return[j,k[j]]}))};return arguments.length>=2?g.apply(this,[function(k){T(A(I(k)))},C]):new Promise(function(k,j){g.apply(E,[function(F){k(A(I(F)))},j])}).then(T,S)}}}function w(p){if(d(p)==="object"&&p.RTCPeerConnection&&p.RTCRtpSender&&p.RTCRtpReceiver){if(!("getStats"in p.RTCRtpSender.prototype)){var g=p.RTCPeerConnection.prototype.getSenders;g&&(p.RTCPeerConnection.prototype.getSenders=function(){var S=this,I=g.apply(this,[]);return I.forEach(function(A){return A._pc=S}),I});var E=p.RTCPeerConnection.prototype.addTrack;E&&(p.RTCPeerConnection.prototype.addTrack=function(){var S=E.apply(this,arguments);return S._pc=this,S}),p.RTCRtpSender.prototype.getStats=function(){var S=this;return this._pc.getStats().then(function(I){return i.filterStats(I,S.track,!0)})}}if(!("getStats"in p.RTCRtpReceiver.prototype)){var C=p.RTCPeerConnection.prototype.getReceivers;C&&(p.RTCPeerConnection.prototype.getReceivers=function(){var S=this,I=C.apply(this,[]);return I.forEach(function(A){return A._pc=S}),I}),i.wrapPeerConnectionEvent(p,"track",function(S){return S.receiver._pc=S.srcElement,S}),p.RTCRtpReceiver.prototype.getStats=function(){var S=this;return this._pc.getStats().then(function(I){return i.filterStats(I,S.track,!1)})}}if("getStats"in p.RTCRtpSender.prototype&&"getStats"in p.RTCRtpReceiver.prototype){var T=p.RTCPeerConnection.prototype.getStats;p.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof p.MediaStreamTrack){var S,I,A,k=arguments[0];return this.getSenders().forEach(function(j){j.track===k&&(S?A=!0:S=j)}),this.getReceivers().forEach(function(j){return j.track===k&&(I?A=!0:I=j),j.track===k}),A||S&&I?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):S?S.getStats():I?I.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return T.apply(this,arguments)}}}}function v(p){p.RTCPeerConnection.prototype.getLocalStreams=function(){var S=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(function(I){return S._shimmedLocalStreams[I][0]})};var g=p.RTCPeerConnection.prototype.addTrack;p.RTCPeerConnection.prototype.addTrack=function(S,I){if(!I)return g.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var A=g.apply(this,arguments);return this._shimmedLocalStreams[I.id]?this._shimmedLocalStreams[I.id].indexOf(A)===-1&&this._shimmedLocalStreams[I.id].push(A):this._shimmedLocalStreams[I.id]=[I,A],A};var E=p.RTCPeerConnection.prototype.addStream;p.RTCPeerConnection.prototype.addStream=function(S){var I=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},S.getTracks().forEach(function(j){if(I.getSenders().find(function(F){return F.track===j}))throw new DOMException("Track already exists.","InvalidAccessError")});var A=this.getSenders();E.apply(this,arguments);var k=this.getSenders().filter(function(j){return A.indexOf(j)===-1});this._shimmedLocalStreams[S.id]=[S].concat(k)};var C=p.RTCPeerConnection.prototype.removeStream;p.RTCPeerConnection.prototype.removeStream=function(S){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[S.id],C.apply(this,arguments)};var T=p.RTCPeerConnection.prototype.removeTrack;p.RTCPeerConnection.prototype.removeTrack=function(S){var I=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},S&&Object.keys(this._shimmedLocalStreams).forEach(function(A){var k=I._shimmedLocalStreams[A].indexOf(S);k!==-1&&I._shimmedLocalStreams[A].splice(k,1),I._shimmedLocalStreams[A].length===1&&delete I._shimmedLocalStreams[A]}),T.apply(this,arguments)}}function x(p,g){if(p.RTCPeerConnection){if(p.RTCPeerConnection.prototype.addTrack&&g.version>=65)return v(p);var E=p.RTCPeerConnection.prototype.getLocalStreams;p.RTCPeerConnection.prototype.getLocalStreams=function(){var k=this,j=E.apply(this);return this._reverseStreams=this._reverseStreams||{},j.map(function(F){return k._reverseStreams[F.id]})};var C=p.RTCPeerConnection.prototype.addStream;p.RTCPeerConnection.prototype.addStream=function(k){var j=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},k.getTracks().forEach(function(W){if(j.getSenders().find(function(z){return z.track===W}))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[k.id]){var F=new p.MediaStream(k.getTracks());this._streams[k.id]=F,this._reverseStreams[F.id]=k,k=F}C.apply(this,[k])};var T=p.RTCPeerConnection.prototype.removeStream;p.RTCPeerConnection.prototype.removeStream=function(k){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},T.apply(this,[this._streams[k.id]||k]),delete this._reverseStreams[this._streams[k.id]?this._streams[k.id].id:k.id],delete this._streams[k.id]},p.RTCPeerConnection.prototype.addTrack=function(k,j){var F=this;if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var W=[].slice.call(arguments,1);if(W.length!==1||!W[0].getTracks().find(function(he){return he===k}))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(he){return he.track===k}))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var z=this._streams[j.id];if(z)z.addTrack(k),Promise.resolve().then(function(){F.dispatchEvent(new Event("negotiationneeded"))});else{var re=new p.MediaStream([k]);this._streams[j.id]=re,this._reverseStreams[re.id]=j,this.addStream(re)}return this.getSenders().find(function(he){return he.track===k})},["createOffer","createAnswer"].forEach(function(k){var j=p.RTCPeerConnection.prototype[k],F=c({},k,function(){var W=this,z=arguments;return arguments.length&&typeof arguments[0]=="function"?j.apply(this,[function(re){var he=A(W,re);z[0].apply(null,[he])},function(re){z[1]&&z[1].apply(null,re)},arguments[2]]):j.apply(this,arguments).then(function(re){return A(W,re)})});p.RTCPeerConnection.prototype[k]=F[k]});var S=p.RTCPeerConnection.prototype.setLocalDescription;p.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=(k=this,j=arguments[0],F=j.sdp,Object.keys(k._reverseStreams||[]).forEach(function(W){var z=k._reverseStreams[W],re=k._streams[z.id];F=F.replace(new RegExp(z.id,"g"),re.id)}),new RTCSessionDescription({type:j.type,sdp:F})),S.apply(this,arguments)):S.apply(this,arguments);var k,j,F};var I=Object.getOwnPropertyDescriptor(p.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(p.RTCPeerConnection.prototype,"localDescription",{get:function(){var k=I.get.apply(this);return k.type===""?k:A(this,k)}}),p.RTCPeerConnection.prototype.removeTrack=function(k){var j,F=this;if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!k._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(k._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{},Object.keys(this._streams).forEach(function(W){F._streams[W].getTracks().find(function(z){return k.track===z})&&(j=F._streams[W])}),j&&(j.getTracks().length===1?this.removeStream(this._reverseStreams[j.id]):j.removeTrack(k.track),this.dispatchEvent(new Event("negotiationneeded")))}}function A(k,j){var F=j.sdp;return Object.keys(k._reverseStreams||[]).forEach(function(W){var z=k._reverseStreams[W],re=k._streams[z.id];F=F.replace(new RegExp(re.id,"g"),z.id)}),new RTCSessionDescription({type:j.type,sdp:F})}}function m(p,g){!p.RTCPeerConnection&&p.webkitRTCPeerConnection&&(p.RTCPeerConnection=p.webkitRTCPeerConnection),p.RTCPeerConnection&&g.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(E){var C=p.RTCPeerConnection.prototype[E],T=c({},E,function(){return arguments[0]=new(E==="addIceCandidate"?p.RTCIceCandidate:p.RTCSessionDescription)(arguments[0]),C.apply(this,arguments)});p.RTCPeerConnection.prototype[E]=T[E]})}function f(p,g){i.wrapPeerConnectionEvent(p,"negotiationneeded",function(E){var C=E.target;if(!(g.version<72||C.getConfiguration&&C.getConfiguration().sdpSemantics==="plan-b")||C.signalingState==="stable")return E})}},{"../utils.js":"iSxC","./getusermedia":"s6SN","./getdisplaymedia":"VHa8"}],NZ1C:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterIceServers=s;var i=r(o("../utils"));function n(){if(typeof WeakMap!="function")return null;var a=new WeakMap;return n=function(){return a},a}function r(a){if(a&&a.__esModule)return a;if(a===null||typeof a!="object"&&typeof a!="function")return{default:a};var c=n();if(c&&c.has(a))return c.get(a);var d={},l=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var u in a)if(Object.prototype.hasOwnProperty.call(a,u)){var h=l?Object.getOwnPropertyDescriptor(a,u):null;h&&(h.get||h.set)?Object.defineProperty(d,u,h):d[u]=a[u]}return d.default=a,c&&c.set(a,d),d}function s(a,c){var d=!1;return(a=JSON.parse(JSON.stringify(a))).filter(function(l){if(l&&(l.urls||l.url)){var u=l.urls||l.url;l.url&&!l.urls&&i.deprecated("RTCIceServer.url","RTCIceServer.urls");var h=typeof u=="string";return h&&(u=[u]),u=u.filter(function(b){if(b.indexOf("stun:")===0)return!1;var w=b.startsWith("turn")&&!b.startsWith("turn:[")&&b.includes("transport=udp");return w&&!d?(d=!0,!0):w&&!d}),delete l.url,l.urls=h?u[0]:u,!!u.length}})}},{"../utils":"iSxC"}],YHvh:[function(o,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,s){return(s>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(s){return s.indexOf(r)===0})},i.parseCandidate=function(n){for(var r,s={foundation:(r=n.indexOf("a=candidate:")===0?n.substring(12).split(" "):n.substring(10).split(" "))[0],component:parseInt(r[1],10),protocol:r[2].toLowerCase(),priority:parseInt(r[3],10),ip:r[4],address:r[4],port:parseInt(r[5],10),type:r[7]},a=8;a<r.length;a+=2)switch(r[a]){case"raddr":s.relatedAddress=r[a+1];break;case"rport":s.relatedPort=parseInt(r[a+1],10);break;case"tcptype":s.tcpType=r[a+1];break;case"ufrag":s.ufrag=r[a+1],s.usernameFragment=r[a+1];break;default:s[r[a]]=r[a+1]}return s},i.writeCandidate=function(n){var r=[];r.push(n.foundation),r.push(n.component),r.push(n.protocol.toUpperCase()),r.push(n.priority),r.push(n.address||n.ip),r.push(n.port);var s=n.type;return r.push("typ"),r.push(s),s!=="host"&&n.relatedAddress&&n.relatedPort&&(r.push("raddr"),r.push(n.relatedAddress),r.push("rport"),r.push(n.relatedPort)),n.tcpType&&n.protocol.toLowerCase()==="tcp"&&(r.push("tcptype"),r.push(n.tcpType)),(n.usernameFragment||n.ufrag)&&(r.push("ufrag"),r.push(n.usernameFragment||n.ufrag)),"candidate:"+r.join(" ")},i.parseIceOptions=function(n){return n.substr(14).split(" ")},i.parseRtpMap=function(n){var r=n.substr(9).split(" "),s={payloadType:parseInt(r.shift(),10)};return r=r[0].split("/"),s.name=r[0],s.clockRate=parseInt(r[1],10),s.channels=r.length===3?parseInt(r[2],10):1,s.numChannels=s.channels,s},i.writeRtpMap=function(n){var r=n.payloadType;n.preferredPayloadType!==void 0&&(r=n.preferredPayloadType);var s=n.channels||n.numChannels||1;return"a=rtpmap:"+r+" "+n.name+"/"+n.clockRate+(s!==1?"/"+s:"")+`\r
@@ -45,9 +45,9 @@ t=0 0\r
45
45
  `;x+="a="+f,x+="a=ssrc:"+u.sendEncodingParameters[0].ssrc+" "+f,u.sendEncodingParameters[0].rtx&&(x+="a=ssrc:"+u.sendEncodingParameters[0].rtx.ssrc+" "+f,x+="a=ssrc-group:FID "+u.sendEncodingParameters[0].ssrc+" "+u.sendEncodingParameters[0].rtx.ssrc+`\r
46
46
  `)}return x+="a=ssrc:"+u.sendEncodingParameters[0].ssrc+" cname:"+i.localCName+`\r
47
47
  `,u.rtpSender&&u.sendEncodingParameters[0].rtx&&(x+="a=ssrc:"+u.sendEncodingParameters[0].rtx.ssrc+" cname:"+i.localCName+`\r
48
- `),x}function s(u,h){var b=!1;return(u=JSON.parse(JSON.stringify(u))).filter(function(w){if(w&&(w.urls||w.url)){var v=w.urls||w.url;w.url&&!w.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var x=typeof v=="string";return x&&(v=[v]),v=v.filter(function(m){return m.indexOf("turn:")===0&&m.indexOf("transport=udp")!==-1&&m.indexOf("turn:[")===-1&&!b?(b=!0,!0):m.indexOf("stun:")===0&&h>=14393&&m.indexOf("?transport=udp")===-1}),delete w.url,w.urls=x?v[0]:v,!!v.length}})}function a(u,h){var b={codecs:[],headerExtensions:[],fecMechanisms:[]},w=function(x,m){x=parseInt(x,10);for(var f=0;f<m.length;f++)if(m[f].payloadType===x||m[f].preferredPayloadType===x)return m[f]},v=function(x,m,f,p){var g=w(x.parameters.apt,f),E=w(m.parameters.apt,p);return g&&E&&g.name.toLowerCase()===E.name.toLowerCase()};return u.codecs.forEach(function(x){for(var m=0;m<h.codecs.length;m++){var f=h.codecs[m];if(x.name.toLowerCase()===f.name.toLowerCase()&&x.clockRate===f.clockRate){if(x.name.toLowerCase()==="rtx"&&x.parameters&&f.parameters.apt&&!v(x,f,u.codecs,h.codecs))continue;(f=JSON.parse(JSON.stringify(f))).numChannels=Math.min(x.numChannels,f.numChannels),b.codecs.push(f),f.rtcpFeedback=f.rtcpFeedback.filter(function(p){for(var g=0;g<x.rtcpFeedback.length;g++)if(x.rtcpFeedback[g].type===p.type&&x.rtcpFeedback[g].parameter===p.parameter)return!0;return!1});break}}}),u.headerExtensions.forEach(function(x){for(var m=0;m<h.headerExtensions.length;m++){var f=h.headerExtensions[m];if(x.uri===f.uri){b.headerExtensions.push(f);break}}}),b}function c(u,h,b){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(b)!==-1}function d(u,h){var b=u.getRemoteCandidates().find(function(w){return h.foundation===w.foundation&&h.ip===w.ip&&h.port===w.port&&h.priority===w.priority&&h.protocol===w.protocol&&h.type===w.type});return b||u.addRemoteCandidate(h),!b}function l(u,h){var b=new Error(h);return b.name=u,b.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[u],b}e.exports=function(u,h){function b(m,f){f.addTrack(m),f.dispatchEvent(new u.MediaStreamTrackEvent("addtrack",{track:m}))}function w(m,f,p,g){var E=new Event("track");E.track=f,E.receiver=p,E.transceiver={receiver:p},E.streams=g,u.setTimeout(function(){m._dispatchEvent("track",E)})}var v=function(m){var f=this,p=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach(function(E){f[E]=p[E].bind(p)}),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",m=JSON.parse(JSON.stringify(m||{})),this.usingBundle=m.bundlePolicy==="max-bundle",m.rtcpMuxPolicy==="negotiate")throw l("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(m.rtcpMuxPolicy||(m.rtcpMuxPolicy="require"),m.iceTransportPolicy){case"all":case"relay":break;default:m.iceTransportPolicy="all"}switch(m.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:m.bundlePolicy="balanced"}if(m.iceServers=s(m.iceServers||[],h),this._iceGatherers=[],m.iceCandidatePoolSize)for(var g=m.iceCandidatePoolSize;g>0;g--)this._iceGatherers.push(new u.RTCIceGatherer({iceServers:m.iceServers,gatherPolicy:m.iceTransportPolicy}));else m.iceCandidatePoolSize=0;this._config=m,this.transceivers=[],this._sdpSessionId=i.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(v.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(v.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),v.prototype.onicecandidate=null,v.prototype.onaddstream=null,v.prototype.ontrack=null,v.prototype.onremovestream=null,v.prototype.onsignalingstatechange=null,v.prototype.oniceconnectionstatechange=null,v.prototype.onconnectionstatechange=null,v.prototype.onicegatheringstatechange=null,v.prototype.onnegotiationneeded=null,v.prototype.ondatachannel=null,v.prototype._dispatchEvent=function(m,f){this._isClosed||(this.dispatchEvent(f),typeof this["on"+m]=="function"&&this["on"+m](f))},v.prototype._emitGatheringStateChange=function(){var m=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",m)},v.prototype.getConfiguration=function(){return this._config},v.prototype.getLocalStreams=function(){return this.localStreams},v.prototype.getRemoteStreams=function(){return this.remoteStreams},v.prototype._createTransceiver=function(m,f){var p=this.transceivers.length>0,g={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:m,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&p)g.iceTransport=this.transceivers[0].iceTransport,g.dtlsTransport=this.transceivers[0].dtlsTransport;else{var E=this._createIceAndDtlsTransports();g.iceTransport=E.iceTransport,g.dtlsTransport=E.dtlsTransport}return f||this.transceivers.push(g),g},v.prototype.addTrack=function(m,f){if(this._isClosed)throw l("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var p;if(this.transceivers.find(function(E){return E.track===m}))throw l("InvalidAccessError","Track already exists.");for(var g=0;g<this.transceivers.length;g++)this.transceivers[g].track||this.transceivers[g].kind!==m.kind||(p=this.transceivers[g]);return p||(p=this._createTransceiver(m.kind)),this._maybeFireNegotiationNeeded(),this.localStreams.indexOf(f)===-1&&this.localStreams.push(f),p.track=m,p.stream=f,p.rtpSender=new u.RTCRtpSender(m,p.dtlsTransport),p.rtpSender},v.prototype.addStream=function(m){var f=this;if(h>=15025)m.getTracks().forEach(function(g){f.addTrack(g,m)});else{var p=m.clone();m.getTracks().forEach(function(g,E){var C=p.getTracks()[E];g.addEventListener("enabled",function(T){C.enabled=T.enabled})}),p.getTracks().forEach(function(g){f.addTrack(g,p)})}},v.prototype.removeTrack=function(m){if(this._isClosed)throw l("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(m instanceof u.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var f=this.transceivers.find(function(g){return g.rtpSender===m});if(!f)throw l("InvalidAccessError","Sender was not created by this connection.");var p=f.stream;f.rtpSender.stop(),f.rtpSender=null,f.track=null,f.stream=null,this.transceivers.map(function(g){return g.stream}).indexOf(p)===-1&&this.localStreams.indexOf(p)>-1&&this.localStreams.splice(this.localStreams.indexOf(p),1),this._maybeFireNegotiationNeeded()},v.prototype.removeStream=function(m){var f=this;m.getTracks().forEach(function(p){var g=f.getSenders().find(function(E){return E.track===p});g&&f.removeTrack(g)})},v.prototype.getSenders=function(){return this.transceivers.filter(function(m){return!!m.rtpSender}).map(function(m){return m.rtpSender})},v.prototype.getReceivers=function(){return this.transceivers.filter(function(m){return!!m.rtpReceiver}).map(function(m){return m.rtpReceiver})},v.prototype._createIceGatherer=function(m,f){var p=this;if(f&&m>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var g=new u.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(g,"state",{value:"new",writable:!0}),this.transceivers[m].bufferedCandidateEvents=[],this.transceivers[m].bufferCandidates=function(E){var C=!E.candidate||Object.keys(E.candidate).length===0;g.state=C?"completed":"gathering",p.transceivers[m].bufferedCandidateEvents!==null&&p.transceivers[m].bufferedCandidateEvents.push(E)},g.addEventListener("localcandidate",this.transceivers[m].bufferCandidates),g},v.prototype._gather=function(m,f){var p=this,g=this.transceivers[f].iceGatherer;if(!g.onlocalcandidate){var E=this.transceivers[f].bufferedCandidateEvents;this.transceivers[f].bufferedCandidateEvents=null,g.removeEventListener("localcandidate",this.transceivers[f].bufferCandidates),g.onlocalcandidate=function(C){if(!(p.usingBundle&&f>0)){var T=new Event("icecandidate");T.candidate={sdpMid:m,sdpMLineIndex:f};var S=C.candidate,I=!S||Object.keys(S).length===0;if(I)g.state!=="new"&&g.state!=="gathering"||(g.state="completed");else{g.state==="new"&&(g.state="gathering"),S.component=1,S.ufrag=g.getLocalParameters().usernameFragment;var D=i.writeCandidate(S);T.candidate=Object.assign(T.candidate,i.parseCandidate(D)),T.candidate.candidate=D,T.candidate.toJSON=function(){return{candidate:T.candidate.candidate,sdpMid:T.candidate.sdpMid,sdpMLineIndex:T.candidate.sdpMLineIndex,usernameFragment:T.candidate.usernameFragment}}}var O=i.getMediaSections(p._localDescription.sdp);O[T.candidate.sdpMLineIndex]+=I?`a=end-of-candidates\r
48
+ `),x}function s(u,h){var b=!1;return(u=JSON.parse(JSON.stringify(u))).filter(function(w){if(w&&(w.urls||w.url)){var v=w.urls||w.url;w.url&&!w.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var x=typeof v=="string";return x&&(v=[v]),v=v.filter(function(m){return m.indexOf("turn:")===0&&m.indexOf("transport=udp")!==-1&&m.indexOf("turn:[")===-1&&!b?(b=!0,!0):m.indexOf("stun:")===0&&h>=14393&&m.indexOf("?transport=udp")===-1}),delete w.url,w.urls=x?v[0]:v,!!v.length}})}function a(u,h){var b={codecs:[],headerExtensions:[],fecMechanisms:[]},w=function(x,m){x=parseInt(x,10);for(var f=0;f<m.length;f++)if(m[f].payloadType===x||m[f].preferredPayloadType===x)return m[f]},v=function(x,m,f,p){var g=w(x.parameters.apt,f),E=w(m.parameters.apt,p);return g&&E&&g.name.toLowerCase()===E.name.toLowerCase()};return u.codecs.forEach(function(x){for(var m=0;m<h.codecs.length;m++){var f=h.codecs[m];if(x.name.toLowerCase()===f.name.toLowerCase()&&x.clockRate===f.clockRate){if(x.name.toLowerCase()==="rtx"&&x.parameters&&f.parameters.apt&&!v(x,f,u.codecs,h.codecs))continue;(f=JSON.parse(JSON.stringify(f))).numChannels=Math.min(x.numChannels,f.numChannels),b.codecs.push(f),f.rtcpFeedback=f.rtcpFeedback.filter(function(p){for(var g=0;g<x.rtcpFeedback.length;g++)if(x.rtcpFeedback[g].type===p.type&&x.rtcpFeedback[g].parameter===p.parameter)return!0;return!1});break}}}),u.headerExtensions.forEach(function(x){for(var m=0;m<h.headerExtensions.length;m++){var f=h.headerExtensions[m];if(x.uri===f.uri){b.headerExtensions.push(f);break}}}),b}function c(u,h,b){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(b)!==-1}function d(u,h){var b=u.getRemoteCandidates().find(function(w){return h.foundation===w.foundation&&h.ip===w.ip&&h.port===w.port&&h.priority===w.priority&&h.protocol===w.protocol&&h.type===w.type});return b||u.addRemoteCandidate(h),!b}function l(u,h){var b=new Error(h);return b.name=u,b.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[u],b}e.exports=function(u,h){function b(m,f){f.addTrack(m),f.dispatchEvent(new u.MediaStreamTrackEvent("addtrack",{track:m}))}function w(m,f,p,g){var E=new Event("track");E.track=f,E.receiver=p,E.transceiver={receiver:p},E.streams=g,u.setTimeout(function(){m._dispatchEvent("track",E)})}var v=function(m){var f=this,p=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach(function(E){f[E]=p[E].bind(p)}),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",m=JSON.parse(JSON.stringify(m||{})),this.usingBundle=m.bundlePolicy==="max-bundle",m.rtcpMuxPolicy==="negotiate")throw l("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(m.rtcpMuxPolicy||(m.rtcpMuxPolicy="require"),m.iceTransportPolicy){case"all":case"relay":break;default:m.iceTransportPolicy="all"}switch(m.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:m.bundlePolicy="balanced"}if(m.iceServers=s(m.iceServers||[],h),this._iceGatherers=[],m.iceCandidatePoolSize)for(var g=m.iceCandidatePoolSize;g>0;g--)this._iceGatherers.push(new u.RTCIceGatherer({iceServers:m.iceServers,gatherPolicy:m.iceTransportPolicy}));else m.iceCandidatePoolSize=0;this._config=m,this.transceivers=[],this._sdpSessionId=i.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(v.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(v.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),v.prototype.onicecandidate=null,v.prototype.onaddstream=null,v.prototype.ontrack=null,v.prototype.onremovestream=null,v.prototype.onsignalingstatechange=null,v.prototype.oniceconnectionstatechange=null,v.prototype.onconnectionstatechange=null,v.prototype.onicegatheringstatechange=null,v.prototype.onnegotiationneeded=null,v.prototype.ondatachannel=null,v.prototype._dispatchEvent=function(m,f){this._isClosed||(this.dispatchEvent(f),typeof this["on"+m]=="function"&&this["on"+m](f))},v.prototype._emitGatheringStateChange=function(){var m=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",m)},v.prototype.getConfiguration=function(){return this._config},v.prototype.getLocalStreams=function(){return this.localStreams},v.prototype.getRemoteStreams=function(){return this.remoteStreams},v.prototype._createTransceiver=function(m,f){var p=this.transceivers.length>0,g={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:m,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&p)g.iceTransport=this.transceivers[0].iceTransport,g.dtlsTransport=this.transceivers[0].dtlsTransport;else{var E=this._createIceAndDtlsTransports();g.iceTransport=E.iceTransport,g.dtlsTransport=E.dtlsTransport}return f||this.transceivers.push(g),g},v.prototype.addTrack=function(m,f){if(this._isClosed)throw l("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var p;if(this.transceivers.find(function(E){return E.track===m}))throw l("InvalidAccessError","Track already exists.");for(var g=0;g<this.transceivers.length;g++)this.transceivers[g].track||this.transceivers[g].kind!==m.kind||(p=this.transceivers[g]);return p||(p=this._createTransceiver(m.kind)),this._maybeFireNegotiationNeeded(),this.localStreams.indexOf(f)===-1&&this.localStreams.push(f),p.track=m,p.stream=f,p.rtpSender=new u.RTCRtpSender(m,p.dtlsTransport),p.rtpSender},v.prototype.addStream=function(m){var f=this;if(h>=15025)m.getTracks().forEach(function(g){f.addTrack(g,m)});else{var p=m.clone();m.getTracks().forEach(function(g,E){var C=p.getTracks()[E];g.addEventListener("enabled",function(T){C.enabled=T.enabled})}),p.getTracks().forEach(function(g){f.addTrack(g,p)})}},v.prototype.removeTrack=function(m){if(this._isClosed)throw l("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(m instanceof u.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var f=this.transceivers.find(function(g){return g.rtpSender===m});if(!f)throw l("InvalidAccessError","Sender was not created by this connection.");var p=f.stream;f.rtpSender.stop(),f.rtpSender=null,f.track=null,f.stream=null,this.transceivers.map(function(g){return g.stream}).indexOf(p)===-1&&this.localStreams.indexOf(p)>-1&&this.localStreams.splice(this.localStreams.indexOf(p),1),this._maybeFireNegotiationNeeded()},v.prototype.removeStream=function(m){var f=this;m.getTracks().forEach(function(p){var g=f.getSenders().find(function(E){return E.track===p});g&&f.removeTrack(g)})},v.prototype.getSenders=function(){return this.transceivers.filter(function(m){return!!m.rtpSender}).map(function(m){return m.rtpSender})},v.prototype.getReceivers=function(){return this.transceivers.filter(function(m){return!!m.rtpReceiver}).map(function(m){return m.rtpReceiver})},v.prototype._createIceGatherer=function(m,f){var p=this;if(f&&m>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var g=new u.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(g,"state",{value:"new",writable:!0}),this.transceivers[m].bufferedCandidateEvents=[],this.transceivers[m].bufferCandidates=function(E){var C=!E.candidate||Object.keys(E.candidate).length===0;g.state=C?"completed":"gathering",p.transceivers[m].bufferedCandidateEvents!==null&&p.transceivers[m].bufferedCandidateEvents.push(E)},g.addEventListener("localcandidate",this.transceivers[m].bufferCandidates),g},v.prototype._gather=function(m,f){var p=this,g=this.transceivers[f].iceGatherer;if(!g.onlocalcandidate){var E=this.transceivers[f].bufferedCandidateEvents;this.transceivers[f].bufferedCandidateEvents=null,g.removeEventListener("localcandidate",this.transceivers[f].bufferCandidates),g.onlocalcandidate=function(C){if(!(p.usingBundle&&f>0)){var T=new Event("icecandidate");T.candidate={sdpMid:m,sdpMLineIndex:f};var S=C.candidate,I=!S||Object.keys(S).length===0;if(I)g.state!=="new"&&g.state!=="gathering"||(g.state="completed");else{g.state==="new"&&(g.state="gathering"),S.component=1,S.ufrag=g.getLocalParameters().usernameFragment;var A=i.writeCandidate(S);T.candidate=Object.assign(T.candidate,i.parseCandidate(A)),T.candidate.candidate=A,T.candidate.toJSON=function(){return{candidate:T.candidate.candidate,sdpMid:T.candidate.sdpMid,sdpMLineIndex:T.candidate.sdpMLineIndex,usernameFragment:T.candidate.usernameFragment}}}var k=i.getMediaSections(p._localDescription.sdp);k[T.candidate.sdpMLineIndex]+=I?`a=end-of-candidates\r
49
49
  `:"a="+T.candidate.candidate+`\r
50
- `,p._localDescription.sdp=i.getDescription(p._localDescription.sdp)+O.join("");var j=p.transceivers.every(function(F){return F.iceGatherer&&F.iceGatherer.state==="completed"});p.iceGatheringState!=="gathering"&&(p.iceGatheringState="gathering",p._emitGatheringStateChange()),I||p._dispatchEvent("icecandidate",T),j&&(p._dispatchEvent("icecandidate",new Event("icecandidate")),p.iceGatheringState="complete",p._emitGatheringStateChange())}},u.setTimeout(function(){E.forEach(function(C){g.onlocalcandidate(C)})},0)}},v.prototype._createIceAndDtlsTransports=function(){var m=this,f=new u.RTCIceTransport(null);f.onicestatechange=function(){m._updateIceConnectionState(),m._updateConnectionState()};var p=new u.RTCDtlsTransport(f);return p.ondtlsstatechange=function(){m._updateConnectionState()},p.onerror=function(){Object.defineProperty(p,"state",{value:"failed",writable:!0}),m._updateConnectionState()},{iceTransport:f,dtlsTransport:p}},v.prototype._disposeIceAndDtlsTransports=function(m){var f=this.transceivers[m].iceGatherer;f&&(delete f.onlocalcandidate,delete this.transceivers[m].iceGatherer);var p=this.transceivers[m].iceTransport;p&&(delete p.onicestatechange,delete this.transceivers[m].iceTransport);var g=this.transceivers[m].dtlsTransport;g&&(delete g.ondtlsstatechange,delete g.onerror,delete this.transceivers[m].dtlsTransport)},v.prototype._transceive=function(m,f,p){var g=a(m.localCapabilities,m.remoteCapabilities);f&&m.rtpSender&&(g.encodings=m.sendEncodingParameters,g.rtcp={cname:i.localCName,compound:m.rtcpParameters.compound},m.recvEncodingParameters.length&&(g.rtcp.ssrc=m.recvEncodingParameters[0].ssrc),m.rtpSender.send(g)),p&&m.rtpReceiver&&g.codecs.length>0&&(m.kind==="video"&&m.recvEncodingParameters&&h<15019&&m.recvEncodingParameters.forEach(function(E){delete E.rtx}),m.recvEncodingParameters.length?g.encodings=m.recvEncodingParameters:g.encodings=[{}],g.rtcp={compound:m.rtcpParameters.compound},m.rtcpParameters.cname&&(g.rtcp.cname=m.rtcpParameters.cname),m.sendEncodingParameters.length&&(g.rtcp.ssrc=m.sendEncodingParameters[0].ssrc),m.rtpReceiver.receive(g))},v.prototype.setLocalDescription=function(m){var f,p,g=this;if(["offer","answer"].indexOf(m.type)===-1)return Promise.reject(l("TypeError",'Unsupported type "'+m.type+'"'));if(!c("setLocalDescription",m.type,g.signalingState)||g._isClosed)return Promise.reject(l("InvalidStateError","Can not set local "+m.type+" in state "+g.signalingState));if(m.type==="offer")f=i.splitSections(m.sdp),p=f.shift(),f.forEach(function(C,T){var S=i.parseRtpParameters(C);g.transceivers[T].localCapabilities=S}),g.transceivers.forEach(function(C,T){g._gather(C.mid,T)});else if(m.type==="answer"){f=i.splitSections(g._remoteDescription.sdp),p=f.shift();var E=i.matchPrefix(p,"a=ice-lite").length>0;f.forEach(function(C,T){var S=g.transceivers[T],I=S.iceGatherer,D=S.iceTransport,O=S.dtlsTransport,j=S.localCapabilities,F=S.remoteCapabilities;if(!(i.isRejected(C)&&i.matchPrefix(C,"a=bundle-only").length===0)&&!S.rejected){var W=i.getIceParameters(C,p),z=i.getDtlsParameters(C,p);E&&(z.role="server"),g.usingBundle&&T!==0||(g._gather(S.mid,T),D.state==="new"&&D.start(I,W,E?"controlling":"controlled"),O.state==="new"&&O.start(z));var ne=a(j,F);g._transceive(S,ne.codecs.length>0,!1)}})}return g._localDescription={type:m.type,sdp:m.sdp},m.type==="offer"?g._updateSignalingState("have-local-offer"):g._updateSignalingState("stable"),Promise.resolve()},v.prototype.setRemoteDescription=function(m){var f=this;if(["offer","answer"].indexOf(m.type)===-1)return Promise.reject(l("TypeError",'Unsupported type "'+m.type+'"'));if(!c("setRemoteDescription",m.type,f.signalingState)||f._isClosed)return Promise.reject(l("InvalidStateError","Can not set remote "+m.type+" in state "+f.signalingState));var p={};f.remoteStreams.forEach(function(D){p[D.id]=D});var g=[],E=i.splitSections(m.sdp),C=E.shift(),T=i.matchPrefix(C,"a=ice-lite").length>0,S=i.matchPrefix(C,"a=group:BUNDLE ").length>0;f.usingBundle=S;var I=i.matchPrefix(C,"a=ice-options:")[0];return f.canTrickleIceCandidates=!!I&&I.substr(14).split(" ").indexOf("trickle")>=0,E.forEach(function(D,O){var j=i.splitLines(D),F=i.getKind(D),W=i.isRejected(D)&&i.matchPrefix(D,"a=bundle-only").length===0,z=j[0].substr(2).split(" ")[2],ne=i.getDirection(D,C),ue=i.parseMsid(D),Ch=i.getMid(D)||i.generateIdentifier();if(W||F==="application"&&(z==="DTLS/SCTP"||z==="UDP/DTLS/SCTP"))f.transceivers[O]={mid:Ch,kind:F,protocol:z,rejected:!0};else{var Q,Th,_s,yc,$i,_c,xc,xs,en;!W&&f.transceivers[O]&&f.transceivers[O].rejected&&(f.transceivers[O]=f._createTransceiver(F,!0));var Rh,Sh,Ph=i.parseRtpParameters(D);W||(Rh=i.getIceParameters(D,C),(Sh=i.getDtlsParameters(D,C)).role="client"),xc=i.parseRtpEncodingParameters(D);var Oh=i.parseRtcpParameters(D),kh=i.matchPrefix(D,"a=end-of-candidates",C).length>0,ao=i.matchPrefix(D,"a=candidate:").map(function(ot){return i.parseCandidate(ot)}).filter(function(ot){return ot.component===1});if((m.type==="offer"||m.type==="answer")&&!W&&S&&O>0&&f.transceivers[O]&&(f._disposeIceAndDtlsTransports(O),f.transceivers[O].iceGatherer=f.transceivers[0].iceGatherer,f.transceivers[O].iceTransport=f.transceivers[0].iceTransport,f.transceivers[O].dtlsTransport=f.transceivers[0].dtlsTransport,f.transceivers[O].rtpSender&&f.transceivers[O].rtpSender.setTransport(f.transceivers[0].dtlsTransport),f.transceivers[O].rtpReceiver&&f.transceivers[O].rtpReceiver.setTransport(f.transceivers[0].dtlsTransport)),m.type!=="offer"||W)m.type==="answer"&&!W&&(Th=(Q=f.transceivers[O]).iceGatherer,_s=Q.iceTransport,yc=Q.dtlsTransport,$i=Q.rtpReceiver,_c=Q.sendEncodingParameters,xs=Q.localCapabilities,f.transceivers[O].recvEncodingParameters=xc,f.transceivers[O].remoteCapabilities=Ph,f.transceivers[O].rtcpParameters=Oh,ao.length&&_s.state==="new"&&(!T&&!kh||S&&O!==0?ao.forEach(function(ot){d(Q.iceTransport,ot)}):_s.setRemoteCandidates(ao)),S&&O!==0||(_s.state==="new"&&_s.start(Th,Rh,"controlling"),yc.state==="new"&&yc.start(Sh)),!a(Q.localCapabilities,Q.remoteCapabilities).codecs.filter(function(ot){return ot.name.toLowerCase()==="rtx"}).length&&Q.sendEncodingParameters[0].rtx&&delete Q.sendEncodingParameters[0].rtx,f._transceive(Q,ne==="sendrecv"||ne==="recvonly",ne==="sendrecv"||ne==="sendonly"),!$i||ne!=="sendrecv"&&ne!=="sendonly"?delete Q.rtpReceiver:(en=$i.track,ue?(p[ue.stream]||(p[ue.stream]=new u.MediaStream),b(en,p[ue.stream]),g.push([en,$i,p[ue.stream]])):(p.default||(p.default=new u.MediaStream),b(en,p.default),g.push([en,$i,p.default]))));else{(Q=f.transceivers[O]||f._createTransceiver(F)).mid=Ch,Q.iceGatherer||(Q.iceGatherer=f._createIceGatherer(O,S)),ao.length&&Q.iceTransport.state==="new"&&(!kh||S&&O!==0?ao.forEach(function(ot){d(Q.iceTransport,ot)}):Q.iceTransport.setRemoteCandidates(ao)),xs=u.RTCRtpReceiver.getCapabilities(F),h<15019&&(xs.codecs=xs.codecs.filter(function(ot){return ot.name!=="rtx"})),_c=Q.sendEncodingParameters||[{ssrc:1001*(2*O+2)}];var lo,wc=!1;ne==="sendrecv"||ne==="sendonly"?(wc=!Q.rtpReceiver,$i=Q.rtpReceiver||new u.RTCRtpReceiver(Q.dtlsTransport,F),wc&&(en=$i.track,ue&&ue.stream==="-"||(ue?(p[ue.stream]||(p[ue.stream]=new u.MediaStream,Object.defineProperty(p[ue.stream],"id",{get:function(){return ue.stream}})),Object.defineProperty(en,"id",{get:function(){return ue.track}}),lo=p[ue.stream]):(p.default||(p.default=new u.MediaStream),lo=p.default)),lo&&(b(en,lo),Q.associatedRemoteMediaStreams.push(lo)),g.push([en,$i,lo]))):Q.rtpReceiver&&Q.rtpReceiver.track&&(Q.associatedRemoteMediaStreams.forEach(function(ot){var Ec,Mh,Ih=ot.getTracks().find(function(rg){return rg.id===Q.rtpReceiver.track.id});Ih&&(Ec=Ih,(Mh=ot).removeTrack(Ec),Mh.dispatchEvent(new u.MediaStreamTrackEvent("removetrack",{track:Ec})))}),Q.associatedRemoteMediaStreams=[]),Q.localCapabilities=xs,Q.remoteCapabilities=Ph,Q.rtpReceiver=$i,Q.rtcpParameters=Oh,Q.sendEncodingParameters=_c,Q.recvEncodingParameters=xc,f._transceive(f.transceivers[O],!1,wc)}}}),f._dtlsRole===void 0&&(f._dtlsRole=m.type==="offer"?"active":"passive"),f._remoteDescription={type:m.type,sdp:m.sdp},m.type==="offer"?f._updateSignalingState("have-remote-offer"):f._updateSignalingState("stable"),Object.keys(p).forEach(function(D){var O=p[D];if(O.getTracks().length){if(f.remoteStreams.indexOf(O)===-1){f.remoteStreams.push(O);var j=new Event("addstream");j.stream=O,u.setTimeout(function(){f._dispatchEvent("addstream",j)})}g.forEach(function(F){var W=F[0],z=F[1];O.id===F[2].id&&w(f,W,z,[O])})}}),g.forEach(function(D){D[2]||w(f,D[0],D[1],[])}),u.setTimeout(function(){f&&f.transceivers&&f.transceivers.forEach(function(D){D.iceTransport&&D.iceTransport.state==="new"&&D.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),D.iceTransport.addRemoteCandidate({}))})},4e3),Promise.resolve()},v.prototype.close=function(){this.transceivers.forEach(function(m){m.iceTransport&&m.iceTransport.stop(),m.dtlsTransport&&m.dtlsTransport.stop(),m.rtpSender&&m.rtpSender.stop(),m.rtpReceiver&&m.rtpReceiver.stop()}),this._isClosed=!0,this._updateSignalingState("closed")},v.prototype._updateSignalingState=function(m){this.signalingState=m;var f=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",f)},v.prototype._maybeFireNegotiationNeeded=function(){var m=this;this.signalingState==="stable"&&this.needNegotiation!==!0&&(this.needNegotiation=!0,u.setTimeout(function(){if(m.needNegotiation){m.needNegotiation=!1;var f=new Event("negotiationneeded");m._dispatchEvent("negotiationneeded",f)}},0))},v.prototype._updateIceConnectionState=function(){var m,f={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(g){g.iceTransport&&!g.rejected&&f[g.iceTransport.state]++}),m="new",f.failed>0?m="failed":f.checking>0?m="checking":f.disconnected>0?m="disconnected":f.new>0?m="new":f.connected>0?m="connected":f.completed>0&&(m="completed"),m!==this.iceConnectionState){this.iceConnectionState=m;var p=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",p)}},v.prototype._updateConnectionState=function(){var m,f={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(g){g.iceTransport&&g.dtlsTransport&&!g.rejected&&(f[g.iceTransport.state]++,f[g.dtlsTransport.state]++)}),f.connected+=f.completed,m="new",f.failed>0?m="failed":f.connecting>0?m="connecting":f.disconnected>0?m="disconnected":f.new>0?m="new":f.connected>0&&(m="connected"),m!==this.connectionState){this.connectionState=m;var p=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",p)}},v.prototype.createOffer=function(){var m=this;if(m._isClosed)return Promise.reject(l("InvalidStateError","Can not call createOffer after close"));var f=m.transceivers.filter(function(T){return T.kind==="audio"}).length,p=m.transceivers.filter(function(T){return T.kind==="video"}).length,g=arguments[0];if(g){if(g.mandatory||g.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");g.offerToReceiveAudio!==void 0&&(f=g.offerToReceiveAudio===!0?1:g.offerToReceiveAudio===!1?0:g.offerToReceiveAudio),g.offerToReceiveVideo!==void 0&&(p=g.offerToReceiveVideo===!0?1:g.offerToReceiveVideo===!1?0:g.offerToReceiveVideo)}for(m.transceivers.forEach(function(T){T.kind==="audio"?--f<0&&(T.wantReceive=!1):T.kind==="video"&&--p<0&&(T.wantReceive=!1)});f>0||p>0;)f>0&&(m._createTransceiver("audio"),f--),p>0&&(m._createTransceiver("video"),p--);var E=i.writeSessionBoilerplate(m._sdpSessionId,m._sdpSessionVersion++);m.transceivers.forEach(function(T,S){var I=T.track,D=T.kind,O=T.mid||i.generateIdentifier();T.mid=O,T.iceGatherer||(T.iceGatherer=m._createIceGatherer(S,m.usingBundle));var j=u.RTCRtpSender.getCapabilities(D);h<15019&&(j.codecs=j.codecs.filter(function(W){return W.name!=="rtx"})),j.codecs.forEach(function(W){W.name==="H264"&&W.parameters["level-asymmetry-allowed"]===void 0&&(W.parameters["level-asymmetry-allowed"]="1"),T.remoteCapabilities&&T.remoteCapabilities.codecs&&T.remoteCapabilities.codecs.forEach(function(z){W.name.toLowerCase()===z.name.toLowerCase()&&W.clockRate===z.clockRate&&(W.preferredPayloadType=z.payloadType)})}),j.headerExtensions.forEach(function(W){(T.remoteCapabilities&&T.remoteCapabilities.headerExtensions||[]).forEach(function(z){W.uri===z.uri&&(W.id=z.id)})});var F=T.sendEncodingParameters||[{ssrc:1001*(2*S+1)}];I&&h>=15019&&D==="video"&&!F[0].rtx&&(F[0].rtx={ssrc:F[0].ssrc+1}),T.wantReceive&&(T.rtpReceiver=new u.RTCRtpReceiver(T.dtlsTransport,D)),T.localCapabilities=j,T.sendEncodingParameters=F}),m._config.bundlePolicy!=="max-compat"&&(E+="a=group:BUNDLE "+m.transceivers.map(function(T){return T.mid}).join(" ")+`\r
50
+ `,p._localDescription.sdp=i.getDescription(p._localDescription.sdp)+k.join("");var j=p.transceivers.every(function(F){return F.iceGatherer&&F.iceGatherer.state==="completed"});p.iceGatheringState!=="gathering"&&(p.iceGatheringState="gathering",p._emitGatheringStateChange()),I||p._dispatchEvent("icecandidate",T),j&&(p._dispatchEvent("icecandidate",new Event("icecandidate")),p.iceGatheringState="complete",p._emitGatheringStateChange())}},u.setTimeout(function(){E.forEach(function(C){g.onlocalcandidate(C)})},0)}},v.prototype._createIceAndDtlsTransports=function(){var m=this,f=new u.RTCIceTransport(null);f.onicestatechange=function(){m._updateIceConnectionState(),m._updateConnectionState()};var p=new u.RTCDtlsTransport(f);return p.ondtlsstatechange=function(){m._updateConnectionState()},p.onerror=function(){Object.defineProperty(p,"state",{value:"failed",writable:!0}),m._updateConnectionState()},{iceTransport:f,dtlsTransport:p}},v.prototype._disposeIceAndDtlsTransports=function(m){var f=this.transceivers[m].iceGatherer;f&&(delete f.onlocalcandidate,delete this.transceivers[m].iceGatherer);var p=this.transceivers[m].iceTransport;p&&(delete p.onicestatechange,delete this.transceivers[m].iceTransport);var g=this.transceivers[m].dtlsTransport;g&&(delete g.ondtlsstatechange,delete g.onerror,delete this.transceivers[m].dtlsTransport)},v.prototype._transceive=function(m,f,p){var g=a(m.localCapabilities,m.remoteCapabilities);f&&m.rtpSender&&(g.encodings=m.sendEncodingParameters,g.rtcp={cname:i.localCName,compound:m.rtcpParameters.compound},m.recvEncodingParameters.length&&(g.rtcp.ssrc=m.recvEncodingParameters[0].ssrc),m.rtpSender.send(g)),p&&m.rtpReceiver&&g.codecs.length>0&&(m.kind==="video"&&m.recvEncodingParameters&&h<15019&&m.recvEncodingParameters.forEach(function(E){delete E.rtx}),m.recvEncodingParameters.length?g.encodings=m.recvEncodingParameters:g.encodings=[{}],g.rtcp={compound:m.rtcpParameters.compound},m.rtcpParameters.cname&&(g.rtcp.cname=m.rtcpParameters.cname),m.sendEncodingParameters.length&&(g.rtcp.ssrc=m.sendEncodingParameters[0].ssrc),m.rtpReceiver.receive(g))},v.prototype.setLocalDescription=function(m){var f,p,g=this;if(["offer","answer"].indexOf(m.type)===-1)return Promise.reject(l("TypeError",'Unsupported type "'+m.type+'"'));if(!c("setLocalDescription",m.type,g.signalingState)||g._isClosed)return Promise.reject(l("InvalidStateError","Can not set local "+m.type+" in state "+g.signalingState));if(m.type==="offer")f=i.splitSections(m.sdp),p=f.shift(),f.forEach(function(C,T){var S=i.parseRtpParameters(C);g.transceivers[T].localCapabilities=S}),g.transceivers.forEach(function(C,T){g._gather(C.mid,T)});else if(m.type==="answer"){f=i.splitSections(g._remoteDescription.sdp),p=f.shift();var E=i.matchPrefix(p,"a=ice-lite").length>0;f.forEach(function(C,T){var S=g.transceivers[T],I=S.iceGatherer,A=S.iceTransport,k=S.dtlsTransport,j=S.localCapabilities,F=S.remoteCapabilities;if(!(i.isRejected(C)&&i.matchPrefix(C,"a=bundle-only").length===0)&&!S.rejected){var W=i.getIceParameters(C,p),z=i.getDtlsParameters(C,p);E&&(z.role="server"),g.usingBundle&&T!==0||(g._gather(S.mid,T),A.state==="new"&&A.start(I,W,E?"controlling":"controlled"),k.state==="new"&&k.start(z));var re=a(j,F);g._transceive(S,re.codecs.length>0,!1)}})}return g._localDescription={type:m.type,sdp:m.sdp},m.type==="offer"?g._updateSignalingState("have-local-offer"):g._updateSignalingState("stable"),Promise.resolve()},v.prototype.setRemoteDescription=function(m){var f=this;if(["offer","answer"].indexOf(m.type)===-1)return Promise.reject(l("TypeError",'Unsupported type "'+m.type+'"'));if(!c("setRemoteDescription",m.type,f.signalingState)||f._isClosed)return Promise.reject(l("InvalidStateError","Can not set remote "+m.type+" in state "+f.signalingState));var p={};f.remoteStreams.forEach(function(A){p[A.id]=A});var g=[],E=i.splitSections(m.sdp),C=E.shift(),T=i.matchPrefix(C,"a=ice-lite").length>0,S=i.matchPrefix(C,"a=group:BUNDLE ").length>0;f.usingBundle=S;var I=i.matchPrefix(C,"a=ice-options:")[0];return f.canTrickleIceCandidates=!!I&&I.substr(14).split(" ").indexOf("trickle")>=0,E.forEach(function(A,k){var j=i.splitLines(A),F=i.getKind(A),W=i.isRejected(A)&&i.matchPrefix(A,"a=bundle-only").length===0,z=j[0].substr(2).split(" ")[2],re=i.getDirection(A,C),he=i.parseMsid(A),Mh=i.getMid(A)||i.generateIdentifier();if(W||F==="application"&&(z==="DTLS/SCTP"||z==="UDP/DTLS/SCTP"))f.transceivers[k]={mid:Mh,kind:F,protocol:z,rejected:!0};else{var Q,Ih,Es,Cc,rn,Tc,Rc,Cs,on;!W&&f.transceivers[k]&&f.transceivers[k].rejected&&(f.transceivers[k]=f._createTransceiver(F,!0));var Dh,Ah,Lh=i.parseRtpParameters(A);W||(Dh=i.getIceParameters(A,C),(Ah=i.getDtlsParameters(A,C)).role="client"),Rc=i.parseRtpEncodingParameters(A);var jh=i.parseRtcpParameters(A),Hh=i.matchPrefix(A,"a=end-of-candidates",C).length>0,co=i.matchPrefix(A,"a=candidate:").map(function(st){return i.parseCandidate(st)}).filter(function(st){return st.component===1});if((m.type==="offer"||m.type==="answer")&&!W&&S&&k>0&&f.transceivers[k]&&(f._disposeIceAndDtlsTransports(k),f.transceivers[k].iceGatherer=f.transceivers[0].iceGatherer,f.transceivers[k].iceTransport=f.transceivers[0].iceTransport,f.transceivers[k].dtlsTransport=f.transceivers[0].dtlsTransport,f.transceivers[k].rtpSender&&f.transceivers[k].rtpSender.setTransport(f.transceivers[0].dtlsTransport),f.transceivers[k].rtpReceiver&&f.transceivers[k].rtpReceiver.setTransport(f.transceivers[0].dtlsTransport)),m.type!=="offer"||W)m.type==="answer"&&!W&&(Ih=(Q=f.transceivers[k]).iceGatherer,Es=Q.iceTransport,Cc=Q.dtlsTransport,rn=Q.rtpReceiver,Tc=Q.sendEncodingParameters,Cs=Q.localCapabilities,f.transceivers[k].recvEncodingParameters=Rc,f.transceivers[k].remoteCapabilities=Lh,f.transceivers[k].rtcpParameters=jh,co.length&&Es.state==="new"&&(!T&&!Hh||S&&k!==0?co.forEach(function(st){d(Q.iceTransport,st)}):Es.setRemoteCandidates(co)),S&&k!==0||(Es.state==="new"&&Es.start(Ih,Dh,"controlling"),Cc.state==="new"&&Cc.start(Ah)),!a(Q.localCapabilities,Q.remoteCapabilities).codecs.filter(function(st){return st.name.toLowerCase()==="rtx"}).length&&Q.sendEncodingParameters[0].rtx&&delete Q.sendEncodingParameters[0].rtx,f._transceive(Q,re==="sendrecv"||re==="recvonly",re==="sendrecv"||re==="sendonly"),!rn||re!=="sendrecv"&&re!=="sendonly"?delete Q.rtpReceiver:(on=rn.track,he?(p[he.stream]||(p[he.stream]=new u.MediaStream),b(on,p[he.stream]),g.push([on,rn,p[he.stream]])):(p.default||(p.default=new u.MediaStream),b(on,p.default),g.push([on,rn,p.default]))));else{(Q=f.transceivers[k]||f._createTransceiver(F)).mid=Mh,Q.iceGatherer||(Q.iceGatherer=f._createIceGatherer(k,S)),co.length&&Q.iceTransport.state==="new"&&(!Hh||S&&k!==0?co.forEach(function(st){d(Q.iceTransport,st)}):Q.iceTransport.setRemoteCandidates(co)),Cs=u.RTCRtpReceiver.getCapabilities(F),h<15019&&(Cs.codecs=Cs.codecs.filter(function(st){return st.name!=="rtx"})),Tc=Q.sendEncodingParameters||[{ssrc:1001*(2*k+2)}];var uo,Sc=!1;re==="sendrecv"||re==="sendonly"?(Sc=!Q.rtpReceiver,rn=Q.rtpReceiver||new u.RTCRtpReceiver(Q.dtlsTransport,F),Sc&&(on=rn.track,he&&he.stream==="-"||(he?(p[he.stream]||(p[he.stream]=new u.MediaStream,Object.defineProperty(p[he.stream],"id",{get:function(){return he.stream}})),Object.defineProperty(on,"id",{get:function(){return he.track}}),uo=p[he.stream]):(p.default||(p.default=new u.MediaStream),uo=p.default)),uo&&(b(on,uo),Q.associatedRemoteMediaStreams.push(uo)),g.push([on,rn,uo]))):Q.rtpReceiver&&Q.rtpReceiver.track&&(Q.associatedRemoteMediaStreams.forEach(function(st){var Pc,Fh,Bh=st.getTracks().find(function(hg){return hg.id===Q.rtpReceiver.track.id});Bh&&(Pc=Bh,(Fh=st).removeTrack(Pc),Fh.dispatchEvent(new u.MediaStreamTrackEvent("removetrack",{track:Pc})))}),Q.associatedRemoteMediaStreams=[]),Q.localCapabilities=Cs,Q.remoteCapabilities=Lh,Q.rtpReceiver=rn,Q.rtcpParameters=jh,Q.sendEncodingParameters=Tc,Q.recvEncodingParameters=Rc,f._transceive(f.transceivers[k],!1,Sc)}}}),f._dtlsRole===void 0&&(f._dtlsRole=m.type==="offer"?"active":"passive"),f._remoteDescription={type:m.type,sdp:m.sdp},m.type==="offer"?f._updateSignalingState("have-remote-offer"):f._updateSignalingState("stable"),Object.keys(p).forEach(function(A){var k=p[A];if(k.getTracks().length){if(f.remoteStreams.indexOf(k)===-1){f.remoteStreams.push(k);var j=new Event("addstream");j.stream=k,u.setTimeout(function(){f._dispatchEvent("addstream",j)})}g.forEach(function(F){var W=F[0],z=F[1];k.id===F[2].id&&w(f,W,z,[k])})}}),g.forEach(function(A){A[2]||w(f,A[0],A[1],[])}),u.setTimeout(function(){f&&f.transceivers&&f.transceivers.forEach(function(A){A.iceTransport&&A.iceTransport.state==="new"&&A.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),A.iceTransport.addRemoteCandidate({}))})},4e3),Promise.resolve()},v.prototype.close=function(){this.transceivers.forEach(function(m){m.iceTransport&&m.iceTransport.stop(),m.dtlsTransport&&m.dtlsTransport.stop(),m.rtpSender&&m.rtpSender.stop(),m.rtpReceiver&&m.rtpReceiver.stop()}),this._isClosed=!0,this._updateSignalingState("closed")},v.prototype._updateSignalingState=function(m){this.signalingState=m;var f=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",f)},v.prototype._maybeFireNegotiationNeeded=function(){var m=this;this.signalingState==="stable"&&this.needNegotiation!==!0&&(this.needNegotiation=!0,u.setTimeout(function(){if(m.needNegotiation){m.needNegotiation=!1;var f=new Event("negotiationneeded");m._dispatchEvent("negotiationneeded",f)}},0))},v.prototype._updateIceConnectionState=function(){var m,f={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(g){g.iceTransport&&!g.rejected&&f[g.iceTransport.state]++}),m="new",f.failed>0?m="failed":f.checking>0?m="checking":f.disconnected>0?m="disconnected":f.new>0?m="new":f.connected>0?m="connected":f.completed>0&&(m="completed"),m!==this.iceConnectionState){this.iceConnectionState=m;var p=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",p)}},v.prototype._updateConnectionState=function(){var m,f={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(g){g.iceTransport&&g.dtlsTransport&&!g.rejected&&(f[g.iceTransport.state]++,f[g.dtlsTransport.state]++)}),f.connected+=f.completed,m="new",f.failed>0?m="failed":f.connecting>0?m="connecting":f.disconnected>0?m="disconnected":f.new>0?m="new":f.connected>0&&(m="connected"),m!==this.connectionState){this.connectionState=m;var p=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",p)}},v.prototype.createOffer=function(){var m=this;if(m._isClosed)return Promise.reject(l("InvalidStateError","Can not call createOffer after close"));var f=m.transceivers.filter(function(T){return T.kind==="audio"}).length,p=m.transceivers.filter(function(T){return T.kind==="video"}).length,g=arguments[0];if(g){if(g.mandatory||g.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");g.offerToReceiveAudio!==void 0&&(f=g.offerToReceiveAudio===!0?1:g.offerToReceiveAudio===!1?0:g.offerToReceiveAudio),g.offerToReceiveVideo!==void 0&&(p=g.offerToReceiveVideo===!0?1:g.offerToReceiveVideo===!1?0:g.offerToReceiveVideo)}for(m.transceivers.forEach(function(T){T.kind==="audio"?--f<0&&(T.wantReceive=!1):T.kind==="video"&&--p<0&&(T.wantReceive=!1)});f>0||p>0;)f>0&&(m._createTransceiver("audio"),f--),p>0&&(m._createTransceiver("video"),p--);var E=i.writeSessionBoilerplate(m._sdpSessionId,m._sdpSessionVersion++);m.transceivers.forEach(function(T,S){var I=T.track,A=T.kind,k=T.mid||i.generateIdentifier();T.mid=k,T.iceGatherer||(T.iceGatherer=m._createIceGatherer(S,m.usingBundle));var j=u.RTCRtpSender.getCapabilities(A);h<15019&&(j.codecs=j.codecs.filter(function(W){return W.name!=="rtx"})),j.codecs.forEach(function(W){W.name==="H264"&&W.parameters["level-asymmetry-allowed"]===void 0&&(W.parameters["level-asymmetry-allowed"]="1"),T.remoteCapabilities&&T.remoteCapabilities.codecs&&T.remoteCapabilities.codecs.forEach(function(z){W.name.toLowerCase()===z.name.toLowerCase()&&W.clockRate===z.clockRate&&(W.preferredPayloadType=z.payloadType)})}),j.headerExtensions.forEach(function(W){(T.remoteCapabilities&&T.remoteCapabilities.headerExtensions||[]).forEach(function(z){W.uri===z.uri&&(W.id=z.id)})});var F=T.sendEncodingParameters||[{ssrc:1001*(2*S+1)}];I&&h>=15019&&A==="video"&&!F[0].rtx&&(F[0].rtx={ssrc:F[0].ssrc+1}),T.wantReceive&&(T.rtpReceiver=new u.RTCRtpReceiver(T.dtlsTransport,A)),T.localCapabilities=j,T.sendEncodingParameters=F}),m._config.bundlePolicy!=="max-compat"&&(E+="a=group:BUNDLE "+m.transceivers.map(function(T){return T.mid}).join(" ")+`\r
51
51
  `),E+=`a=ice-options:trickle\r
52
52
  `,m.transceivers.forEach(function(T,S){E+=r(T,T.localCapabilities,"offer",T.stream,m._dtlsRole),E+=`a=rtcp-rsize\r
53
53
  `,!T.iceGatherer||m.iceGatheringState==="new"||S!==0&&m.usingBundle||(T.iceGatherer.getLocalCandidates().forEach(function(I){I.component=1,E+="a="+i.writeCandidate(I)+`\r
@@ -64,9 +64,9 @@ a=rtpmap:120 VP8/90000\r
64
64
  a=inactive\r
65
65
  a=mid:`+E.mid+`\r
66
66
  `);var T;E.stream&&(E.kind==="audio"?T=E.stream.getAudioTracks()[0]:E.kind==="video"&&(T=E.stream.getVideoTracks()[0]),T&&h>=15019&&E.kind==="video"&&!E.sendEncodingParameters[0].rtx&&(E.sendEncodingParameters[0].rtx={ssrc:E.sendEncodingParameters[0].ssrc+1}));var S=a(E.localCapabilities,E.remoteCapabilities);!S.codecs.filter(function(I){return I.name.toLowerCase()==="rtx"}).length&&E.sendEncodingParameters[0].rtx&&delete E.sendEncodingParameters[0].rtx,f+=r(E,S,"answer",E.stream,m._dtlsRole),E.rtcpParameters&&E.rtcpParameters.reducedSize&&(f+=`a=rtcp-rsize\r
67
- `)}});var g=new u.RTCSessionDescription({type:"answer",sdp:f});return Promise.resolve(g)},v.prototype.addIceCandidate=function(m){var f,p=this;return m&&m.sdpMLineIndex===void 0&&!m.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise(function(g,E){if(!p._remoteDescription)return E(l("InvalidStateError","Can not add ICE candidate without a remote description"));if(m&&m.candidate!==""){var C=m.sdpMLineIndex;if(m.sdpMid){for(var T=0;T<p.transceivers.length;T++)if(p.transceivers[T].mid===m.sdpMid){C=T;break}}var S=p.transceivers[C];if(!S)return E(l("OperationError","Can not add ICE candidate"));if(S.rejected)return g();var I=Object.keys(m.candidate).length>0?i.parseCandidate(m.candidate):{};if(I.protocol==="tcp"&&(I.port===0||I.port===9)||I.component&&I.component!==1)return g();if((C===0||C>0&&S.iceTransport!==p.transceivers[0].iceTransport)&&!d(S.iceTransport,I))return E(l("OperationError","Can not add ICE candidate"));var D=m.candidate.trim();D.indexOf("a=")===0&&(D=D.substr(2)),(f=i.getMediaSections(p._remoteDescription.sdp))[C]+="a="+(I.type?D:"end-of-candidates")+`\r
68
- `,p._remoteDescription.sdp=i.getDescription(p._remoteDescription.sdp)+f.join("")}else for(var O=0;O<p.transceivers.length&&(p.transceivers[O].rejected||(p.transceivers[O].iceTransport.addRemoteCandidate({}),(f=i.getMediaSections(p._remoteDescription.sdp))[O]+=`a=end-of-candidates\r
69
- `,p._remoteDescription.sdp=i.getDescription(p._remoteDescription.sdp)+f.join(""),!p.usingBundle));O++);g()})},v.prototype.getStats=function(m){if(m&&m instanceof u.MediaStreamTrack){var f=null;if(this.transceivers.forEach(function(g){g.rtpSender&&g.rtpSender.track===m?f=g.rtpSender:g.rtpReceiver&&g.rtpReceiver.track===m&&(f=g.rtpReceiver)}),!f)throw l("InvalidAccessError","Invalid selector.");return f.getStats()}var p=[];return this.transceivers.forEach(function(g){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach(function(E){g[E]&&p.push(g[E].getStats())})}),Promise.all(p).then(function(g){var E=new Map;return g.forEach(function(C){C.forEach(function(T){E.set(T.id,T)})}),E})},["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach(function(m){var f=u[m];if(f&&f.prototype&&f.prototype.getStats){var p=f.prototype.getStats;f.prototype.getStats=function(){return p.apply(this).then(function(g){var E=new Map;return Object.keys(g).forEach(function(C){g[C].type=n(g[C]),E.set(C,g[C])}),E})}}});var x=["createOffer","createAnswer"];return x.forEach(function(m){var f=v.prototype[m];v.prototype[m]=function(){var p=arguments;return typeof p[0]=="function"||typeof p[1]=="function"?f.apply(this,[arguments[2]]).then(function(g){typeof p[0]=="function"&&p[0].apply(null,[g])},function(g){typeof p[1]=="function"&&p[1].apply(null,[g])}):f.apply(this,arguments)}}),(x=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach(function(m){var f=v.prototype[m];v.prototype[m]=function(){var p=arguments;return typeof p[1]=="function"||typeof p[2]=="function"?f.apply(this,arguments).then(function(){typeof p[1]=="function"&&p[1].apply(null)},function(g){typeof p[2]=="function"&&p[2].apply(null,[g])}):f.apply(this,arguments)}}),["getStats"].forEach(function(m){var f=v.prototype[m];v.prototype[m]=function(){var p=arguments;return typeof p[1]=="function"?f.apply(this,arguments).then(function(){typeof p[1]=="function"&&p[1].apply(null)}):f.apply(this,arguments)}}),v}},{sdp:"YHvh"}],YdKx:[function(o,e,t){"use strict";function i(n){var r=n&&n.navigator,s=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(a){return s(a).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(o,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(o,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 s.shimGetUserMedia}}),Object.defineProperty(t,"shimGetDisplayMedia",{enumerable:!0,get:function(){return a.shimGetDisplayMedia}});var i=l(o("../utils")),n=o("./filtericeservers"),r=c(o("rtcpeerconnection-shim")),s=o("./getusermedia"),a=o("./getdisplaymedia");function c(b){return b&&b.__esModule?b:{default:b}}function d(){if(typeof WeakMap!="function")return null;var b=new WeakMap;return d=function(){return b},b}function l(b){if(b&&b.__esModule)return b;if(b===null||typeof b!="object"&&typeof b!="function")return{default:b};var w=d();if(w&&w.has(b))return w.get(b);var v={},x=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var m in b)if(Object.prototype.hasOwnProperty.call(b,m)){var f=x?Object.getOwnPropertyDescriptor(b,m):null;f&&(f.get||f.set)?Object.defineProperty(v,m,f):v[m]=b[m]}return v.default=b,w&&w.set(b,v),v}function u(b,w){if(b.RTCIceGatherer&&(b.RTCIceCandidate||(b.RTCIceCandidate=function(m){return m}),b.RTCSessionDescription||(b.RTCSessionDescription=function(m){return m}),w.version<15025)){var v=Object.getOwnPropertyDescriptor(b.MediaStreamTrack.prototype,"enabled");Object.defineProperty(b.MediaStreamTrack.prototype,"enabled",{set:function(m){v.set.call(this,m);var f=new Event("enabled");f.enabled=m,this.dispatchEvent(f)}})}!b.RTCRtpSender||"dtmf"in b.RTCRtpSender.prototype||Object.defineProperty(b.RTCRtpSender.prototype,"dtmf",{get:function(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=new b.RTCDtmfSender(this):this.track.kind==="video"&&(this._dtmf=null)),this._dtmf}}),b.RTCDtmfSender&&!b.RTCDTMFSender&&(b.RTCDTMFSender=b.RTCDtmfSender);var x=(0,r.default)(b,w.version);b.RTCPeerConnection=function(m){return m&&m.iceServers&&(m.iceServers=(0,n.filterIceServers)(m.iceServers,w.version),i.log("ICE servers after filtering:",m.iceServers)),new x(m)},b.RTCPeerConnection.prototype=x.prototype}function h(b){!b.RTCRtpSender||"replaceTrack"in b.RTCRtpSender.prototype||(b.RTCRtpSender.prototype.replaceTrack=b.RTCRtpSender.prototype.setTrack)}},{"../utils":"iSxC","./filtericeservers":"NZ1C","rtcpeerconnection-shim":"NJ2u","./getusermedia":"YdKx","./getdisplaymedia":"P3bV"}],GzSv:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetUserMedia=a;var i=r(o("../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 l={},u=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var h in c)if(Object.prototype.hasOwnProperty.call(c,h)){var b=u?Object.getOwnPropertyDescriptor(c,h):null;b&&(b.get||b.set)?Object.defineProperty(l,h,b):l[h]=c[h]}return l.default=c,d&&d.set(c,l),l}function s(c){return(s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(d){return typeof d}:function(d){return d&&typeof Symbol=="function"&&d.constructor===Symbol&&d!==Symbol.prototype?"symbol":typeof d})(c)}function a(c,d){var l=c&&c.navigator,u=c&&c.MediaStreamTrack;if(l.getUserMedia=function(x,m,f){i.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),l.mediaDevices.getUserMedia(x).then(m,f)},!(d.version>55&&"autoGainControl"in l.mediaDevices.getSupportedConstraints())){var h=function(x,m,f){m in x&&!(f in x)&&(x[f]=x[m],delete x[m])},b=l.mediaDevices.getUserMedia.bind(l.mediaDevices);if(l.mediaDevices.getUserMedia=function(x){return s(x)==="object"&&s(x.audio)==="object"&&(x=JSON.parse(JSON.stringify(x)),h(x.audio,"autoGainControl","mozAutoGainControl"),h(x.audio,"noiseSuppression","mozNoiseSuppression")),b(x)},u&&u.prototype.getSettings){var w=u.prototype.getSettings;u.prototype.getSettings=function(){var x=w.apply(this,arguments);return h(x,"mozAutoGainControl","autoGainControl"),h(x,"mozNoiseSuppression","noiseSuppression"),x}}if(u&&u.prototype.applyConstraints){var v=u.prototype.applyConstraints;u.prototype.applyConstraints=function(x){return this.kind==="audio"&&s(x)==="object"&&(x=JSON.parse(JSON.stringify(x)),h(x,"autoGainControl","mozAutoGainControl"),h(x,"noiseSuppression","mozNoiseSuppression")),v.apply(this,[x])}}}}},{"../utils":"iSxC"}],UuGU:[function(o,e,t){"use strict";function i(n,r){n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||n.navigator.mediaDevices&&(n.navigator.mediaDevices.getDisplayMedia=function(s){if(!s||!s.video){var a=new DOMException("getDisplayMedia without video constraints is undefined");return a.name="NotFoundError",a.code=8,Promise.reject(a)}return s.video===!0?s.video={mediaSource:r}:s.video.mediaSource=r,n.navigator.mediaDevices.getUserMedia(s)})}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetDisplayMedia=i},{}],Fzdr:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimOnTrack=l,t.shimPeerConnection=u,t.shimSenderGetStats=h,t.shimReceiverGetStats=b,t.shimRemoveStream=w,t.shimRTCDataChannel=v,t.shimAddTransceiver=x,t.shimGetParameters=m,t.shimCreateOffer=f,t.shimCreateAnswer=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=a(o("../utils")),n=o("./getusermedia"),r=o("./getdisplaymedia");function s(){if(typeof WeakMap!="function")return null;var g=new WeakMap;return s=function(){return g},g}function a(g){if(g&&g.__esModule)return g;if(g===null||typeof g!="object"&&typeof g!="function")return{default:g};var E=s();if(E&&E.has(g))return E.get(g);var C={},T=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var S in g)if(Object.prototype.hasOwnProperty.call(g,S)){var I=T?Object.getOwnPropertyDescriptor(g,S):null;I&&(I.get||I.set)?Object.defineProperty(C,S,I):C[S]=g[S]}return C.default=g,E&&E.set(g,C),C}function c(g,E,C){return E in g?Object.defineProperty(g,E,{value:C,enumerable:!0,configurable:!0,writable:!0}):g[E]=C,g}function d(g){return(d=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(E){return typeof E}:function(E){return E&&typeof Symbol=="function"&&E.constructor===Symbol&&E!==Symbol.prototype?"symbol":typeof E})(g)}function l(g){d(g)==="object"&&g.RTCTrackEvent&&"receiver"in g.RTCTrackEvent.prototype&&!("transceiver"in g.RTCTrackEvent.prototype)&&Object.defineProperty(g.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})}function u(g,E){if(d(g)==="object"&&(g.RTCPeerConnection||g.mozRTCPeerConnection)){!g.RTCPeerConnection&&g.mozRTCPeerConnection&&(g.RTCPeerConnection=g.mozRTCPeerConnection),E.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(S){var I=g.RTCPeerConnection.prototype[S],D=c({},S,function(){return arguments[0]=new(S==="addIceCandidate"?g.RTCIceCandidate:g.RTCSessionDescription)(arguments[0]),I.apply(this,arguments)});g.RTCPeerConnection.prototype[S]=D[S]});var C={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},T=g.RTCPeerConnection.prototype.getStats;g.RTCPeerConnection.prototype.getStats=function(){var[S,I,D]=arguments;return T.apply(this,[S||null]).then(function(O){if(E.version<53&&!I)try{O.forEach(function(j){j.type=C[j.type]||j.type})}catch(j){if(j.name!=="TypeError")throw j;O.forEach(function(F,W){O.set(W,Object.assign({},F,{type:C[F.type]||F.type}))})}return O}).then(I,D)}}}function h(g){if(d(g)==="object"&&g.RTCPeerConnection&&g.RTCRtpSender&&!(g.RTCRtpSender&&"getStats"in g.RTCRtpSender.prototype)){var E=g.RTCPeerConnection.prototype.getSenders;E&&(g.RTCPeerConnection.prototype.getSenders=function(){var T=this,S=E.apply(this,[]);return S.forEach(function(I){return I._pc=T}),S});var C=g.RTCPeerConnection.prototype.addTrack;C&&(g.RTCPeerConnection.prototype.addTrack=function(){var T=C.apply(this,arguments);return T._pc=this,T}),g.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}}function b(g){if(d(g)==="object"&&g.RTCPeerConnection&&g.RTCRtpSender&&!(g.RTCRtpSender&&"getStats"in g.RTCRtpReceiver.prototype)){var E=g.RTCPeerConnection.prototype.getReceivers;E&&(g.RTCPeerConnection.prototype.getReceivers=function(){var C=this,T=E.apply(this,[]);return T.forEach(function(S){return S._pc=C}),T}),i.wrapPeerConnectionEvent(g,"track",function(C){return C.receiver._pc=C.srcElement,C}),g.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}}function w(g){!g.RTCPeerConnection||"removeStream"in g.RTCPeerConnection.prototype||(g.RTCPeerConnection.prototype.removeStream=function(E){var C=this;i.deprecated("removeStream","removeTrack"),this.getSenders().forEach(function(T){T.track&&E.getTracks().includes(T.track)&&C.removeTrack(T)})})}function v(g){g.DataChannel&&!g.RTCDataChannel&&(g.RTCDataChannel=g.DataChannel)}function x(g){if(d(g)==="object"&&g.RTCPeerConnection){var E=g.RTCPeerConnection.prototype.addTransceiver;E&&(g.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];var C=arguments[1],T=C&&"sendEncodings"in C;T&&C.sendEncodings.forEach(function(O){if("rid"in O&&!/^[a-z0-9]{0,16}$/i.test(O.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in O&&!(parseFloat(O.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in O&&!(parseFloat(O.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});var S=E.apply(this,arguments);if(T){var{sender:I}=S,D=I.getParameters();"encodings"in D&&(D.encodings.length!==1||Object.keys(D.encodings[0]).length!==0)||(D.encodings=C.sendEncodings,I.sendEncodings=C.sendEncodings,this.setParametersPromises.push(I.setParameters(D).then(function(){delete I.sendEncodings}).catch(function(){delete I.sendEncodings})))}return S})}}function m(g){if(d(g)==="object"&&g.RTCRtpSender){var E=g.RTCRtpSender.prototype.getParameters;E&&(g.RTCRtpSender.prototype.getParameters=function(){var C=E.apply(this,arguments);return"encodings"in C||(C.encodings=[].concat(this.sendEncodings||[{}])),C})}}function f(g){if(d(g)==="object"&&g.RTCPeerConnection){var E=g.RTCPeerConnection.prototype.createOffer;g.RTCPeerConnection.prototype.createOffer=function(){var C=arguments,T=this;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return E.apply(T,C)}).finally(function(){T.setParametersPromises=[]}):E.apply(this,arguments)}}}function p(g){if(d(g)==="object"&&g.RTCPeerConnection){var E=g.RTCPeerConnection.prototype.createAnswer;g.RTCPeerConnection.prototype.createAnswer=function(){var C=arguments,T=this;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return E.apply(T,C)}).finally(function(){T.setParametersPromises=[]}):E.apply(this,arguments)}}}},{"../utils":"iSxC","./getusermedia":"GzSv","./getdisplaymedia":"UuGU"}],t1lL:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimLocalStreamsAPI=a,t.shimRemoteStreamsAPI=c,t.shimCallbacksAPI=d,t.shimGetUserMedia=l,t.shimConstraints=u,t.shimRTCIceServerUrls=h,t.shimTrackEventTransceiver=b,t.shimCreateOfferLegacy=w,t.shimAudioContext=v;var i=r(o("../utils"));function n(){if(typeof WeakMap!="function")return null;var x=new WeakMap;return n=function(){return x},x}function r(x){if(x&&x.__esModule)return x;if(x===null||typeof x!="object"&&typeof x!="function")return{default:x};var m=n();if(m&&m.has(x))return m.get(x);var f={},p=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var g in x)if(Object.prototype.hasOwnProperty.call(x,g)){var E=p?Object.getOwnPropertyDescriptor(x,g):null;E&&(E.get||E.set)?Object.defineProperty(f,g,E):f[g]=x[g]}return f.default=x,m&&m.set(x,f),f}function s(x){return(s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(m){return typeof m}:function(m){return m&&typeof Symbol=="function"&&m.constructor===Symbol&&m!==Symbol.prototype?"symbol":typeof m})(x)}function a(x){if(s(x)==="object"&&x.RTCPeerConnection){if("getLocalStreams"in x.RTCPeerConnection.prototype||(x.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in x.RTCPeerConnection.prototype)){var m=x.RTCPeerConnection.prototype.addTrack;x.RTCPeerConnection.prototype.addStream=function(f){var p=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(f)||this._localStreams.push(f),f.getAudioTracks().forEach(function(g){return m.call(p,g,f)}),f.getVideoTracks().forEach(function(g){return m.call(p,g,f)})},x.RTCPeerConnection.prototype.addTrack=function(f){for(var p=this,g=arguments.length,E=new Array(g>1?g-1:0),C=1;C<g;C++)E[C-1]=arguments[C];return E&&E.forEach(function(T){p._localStreams?p._localStreams.includes(T)||p._localStreams.push(T):p._localStreams=[T]}),m.apply(this,arguments)}}"removeStream"in x.RTCPeerConnection.prototype||(x.RTCPeerConnection.prototype.removeStream=function(f){var p=this;this._localStreams||(this._localStreams=[]);var g=this._localStreams.indexOf(f);if(g!==-1){this._localStreams.splice(g,1);var E=f.getTracks();this.getSenders().forEach(function(C){E.includes(C.track)&&p.removeTrack(C)})}})}}function c(x){if(s(x)==="object"&&x.RTCPeerConnection&&("getRemoteStreams"in x.RTCPeerConnection.prototype||(x.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in x.RTCPeerConnection.prototype))){Object.defineProperty(x.RTCPeerConnection.prototype,"onaddstream",{get:function(){return this._onaddstream},set:function(f){var p=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=f),this.addEventListener("track",this._onaddstreampoly=function(g){g.streams.forEach(function(E){if(p._remoteStreams||(p._remoteStreams=[]),!p._remoteStreams.includes(E)){p._remoteStreams.push(E);var C=new Event("addstream");C.stream=E,p.dispatchEvent(C)}})})}});var m=x.RTCPeerConnection.prototype.setRemoteDescription;x.RTCPeerConnection.prototype.setRemoteDescription=function(){var f=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(p){p.streams.forEach(function(g){if(f._remoteStreams||(f._remoteStreams=[]),!(f._remoteStreams.indexOf(g)>=0)){f._remoteStreams.push(g);var E=new Event("addstream");E.stream=g,f.dispatchEvent(E)}})}),m.apply(f,arguments)}}}function d(x){if(s(x)==="object"&&x.RTCPeerConnection){var m=x.RTCPeerConnection.prototype,f=m.createOffer,p=m.createAnswer,g=m.setLocalDescription,E=m.setRemoteDescription,C=m.addIceCandidate;m.createOffer=function(S,I){var D=arguments.length>=2?arguments[2]:arguments[0],O=f.apply(this,[D]);return I?(O.then(S,I),Promise.resolve()):O},m.createAnswer=function(S,I){var D=arguments.length>=2?arguments[2]:arguments[0],O=p.apply(this,[D]);return I?(O.then(S,I),Promise.resolve()):O};var T=function(S,I,D){var O=g.apply(this,[S]);return D?(O.then(I,D),Promise.resolve()):O};m.setLocalDescription=T,T=function(S,I,D){var O=E.apply(this,[S]);return D?(O.then(I,D),Promise.resolve()):O},m.setRemoteDescription=T,T=function(S,I,D){var O=C.apply(this,[S]);return D?(O.then(I,D),Promise.resolve()):O},m.addIceCandidate=T}}function l(x){var m=x&&x.navigator;if(m.mediaDevices&&m.mediaDevices.getUserMedia){var f=m.mediaDevices,p=f.getUserMedia.bind(f);m.mediaDevices.getUserMedia=function(g){return p(u(g))}}!m.getUserMedia&&m.mediaDevices&&m.mediaDevices.getUserMedia&&(m.getUserMedia=function(g,E,C){m.mediaDevices.getUserMedia(g).then(E,C)}.bind(m))}function u(x){return x&&x.video!==void 0?Object.assign({},x,{video:i.compactObject(x.video)}):x}function h(x){if(x.RTCPeerConnection){var m=x.RTCPeerConnection;x.RTCPeerConnection=function(f,p){if(f&&f.iceServers){for(var g=[],E=0;E<f.iceServers.length;E++){var C=f.iceServers[E];!C.hasOwnProperty("urls")&&C.hasOwnProperty("url")?(i.deprecated("RTCIceServer.url","RTCIceServer.urls"),(C=JSON.parse(JSON.stringify(C))).urls=C.url,delete C.url,g.push(C)):g.push(f.iceServers[E])}f.iceServers=g}return new m(f,p)},x.RTCPeerConnection.prototype=m.prototype,"generateCertificate"in m&&Object.defineProperty(x.RTCPeerConnection,"generateCertificate",{get:function(){return m.generateCertificate}})}}function b(x){s(x)==="object"&&x.RTCTrackEvent&&"receiver"in x.RTCTrackEvent.prototype&&!("transceiver"in x.RTCTrackEvent.prototype)&&Object.defineProperty(x.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})}function w(x){var m=x.RTCPeerConnection.prototype.createOffer;x.RTCPeerConnection.prototype.createOffer=function(f){if(f){f.offerToReceiveAudio!==void 0&&(f.offerToReceiveAudio=!!f.offerToReceiveAudio);var p=this.getTransceivers().find(function(E){return E.receiver.track.kind==="audio"});f.offerToReceiveAudio===!1&&p?p.direction==="sendrecv"?p.setDirection?p.setDirection("sendonly"):p.direction="sendonly":p.direction==="recvonly"&&(p.setDirection?p.setDirection("inactive"):p.direction="inactive"):f.offerToReceiveAudio!==!0||p||this.addTransceiver("audio"),f.offerToReceiveVideo!==void 0&&(f.offerToReceiveVideo=!!f.offerToReceiveVideo);var g=this.getTransceivers().find(function(E){return E.receiver.track.kind==="video"});f.offerToReceiveVideo===!1&&g?g.direction==="sendrecv"?g.setDirection?g.setDirection("sendonly"):g.direction="sendonly":g.direction==="recvonly"&&(g.setDirection?g.setDirection("inactive"):g.direction="inactive"):f.offerToReceiveVideo!==!0||g||this.addTransceiver("video")}return m.apply(this,arguments)}}function v(x){s(x)!=="object"||x.AudioContext||(x.AudioContext=x.webkitAudioContext)}},{"../utils":"iSxC"}],GOQK:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimRTCIceCandidate=d,t.shimMaxMessageSize=l,t.shimSendThrowTypeError=u,t.shimConnectionState=h,t.removeExtmapAllowMixed=b,t.shimAddIceCandidateNullOrEmpty=w;var i=a(o("sdp")),n=s(o("./utils"));function r(){if(typeof WeakMap!="function")return null;var v=new WeakMap;return r=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 x=r();if(x&&x.has(v))return x.get(v);var m={},f=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var p in v)if(Object.prototype.hasOwnProperty.call(v,p)){var g=f?Object.getOwnPropertyDescriptor(v,p):null;g&&(g.get||g.set)?Object.defineProperty(m,p,g):m[p]=v[p]}return m.default=v,x&&x.set(v,m),m}function a(v){return v&&v.__esModule?v:{default:v}}function c(v){return(c=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(x){return typeof x}:function(x){return x&&typeof Symbol=="function"&&x.constructor===Symbol&&x!==Symbol.prototype?"symbol":typeof x})(v)}function d(v){if(v.RTCIceCandidate&&!(v.RTCIceCandidate&&"foundation"in v.RTCIceCandidate.prototype)){var x=v.RTCIceCandidate;v.RTCIceCandidate=function(m){if(c(m)==="object"&&m.candidate&&m.candidate.indexOf("a=")===0&&((m=JSON.parse(JSON.stringify(m))).candidate=m.candidate.substr(2)),m.candidate&&m.candidate.length){var f=new x(m),p=i.default.parseCandidate(m.candidate),g=Object.assign(f,p);return g.toJSON=function(){return{candidate:g.candidate,sdpMid:g.sdpMid,sdpMLineIndex:g.sdpMLineIndex,usernameFragment:g.usernameFragment}},g}return new x(m)},v.RTCIceCandidate.prototype=x.prototype,n.wrapPeerConnectionEvent(v,"icecandidate",function(m){return m.candidate&&Object.defineProperty(m,"candidate",{value:new v.RTCIceCandidate(m.candidate),writable:"false"}),m})}}function l(v,x){if(v.RTCPeerConnection){"sctp"in v.RTCPeerConnection.prototype||Object.defineProperty(v.RTCPeerConnection.prototype,"sctp",{get:function(){return this._sctp===void 0?null:this._sctp}});var m=v.RTCPeerConnection.prototype.setRemoteDescription;v.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,x.browser==="chrome"&&x.version>=76){var{sdpSemantics:f}=this.getConfiguration();f==="plan-b"&&Object.defineProperty(this,"sctp",{get:function(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0})}if(function(D){if(!D||!D.sdp)return!1;var O=i.default.splitSections(D.sdp);return O.shift(),O.some(function(j){var F=i.default.parseMLine(j);return F&&F.kind==="application"&&F.protocol.indexOf("SCTP")!==-1})}(arguments[0])){var p,g=function(D){var O=D.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(O===null||O.length<2)return-1;var j=parseInt(O[1],10);return j!=j?-1:j}(arguments[0]),E=(S=g,I=65536,x.browser==="firefox"&&(I=x.version<57?S===-1?16384:2147483637:x.version<60?x.version===57?65535:65536:2147483637),I),C=function(D,O){var j=65536;x.browser==="firefox"&&x.version===57&&(j=65535);var F=i.default.matchPrefix(D.sdp,"a=max-message-size:");return F.length>0?j=parseInt(F[0].substr(19),10):x.browser==="firefox"&&O!==-1&&(j=2147483637),j}(arguments[0],g);p=E===0&&C===0?Number.POSITIVE_INFINITY:E===0||C===0?Math.max(E,C):Math.min(E,C);var T={};Object.defineProperty(T,"maxMessageSize",{get:function(){return p}}),this._sctp=T}var S,I;return m.apply(this,arguments)}}}function u(v){if(v.RTCPeerConnection&&"createDataChannel"in v.RTCPeerConnection.prototype){var x=v.RTCPeerConnection.prototype.createDataChannel;v.RTCPeerConnection.prototype.createDataChannel=function(){var f=x.apply(this,arguments);return m(f,this),f},n.wrapPeerConnectionEvent(v,"datachannel",function(f){return m(f.channel,f.target),f})}function m(f,p){var g=f.send;f.send=function(){var E=arguments[0],C=E.length||E.size||E.byteLength;if(f.readyState==="open"&&p.sctp&&C>p.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+p.sctp.maxMessageSize+" bytes)");return g.apply(f,arguments)}}}function h(v){if(v.RTCPeerConnection&&!("connectionState"in v.RTCPeerConnection.prototype)){var x=v.RTCPeerConnection.prototype;Object.defineProperty(x,"connectionState",{get:function(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(x,"onconnectionstatechange",{get:function(){return this._onconnectionstatechange||null},set:function(m){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),m&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=m)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(function(m){var f=x[m];x[m]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(p){var g=p.target;if(g._lastConnectionState!==g.connectionState){g._lastConnectionState=g.connectionState;var E=new Event("connectionstatechange",p);g.dispatchEvent(E)}return p},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),f.apply(this,arguments)}})}}function b(v,x){if(v.RTCPeerConnection&&!(x.browser==="chrome"&&x.version>=71||x.browser==="safari"&&x.version>=605)){var m=v.RTCPeerConnection.prototype.setRemoteDescription;v.RTCPeerConnection.prototype.setRemoteDescription=function(f){if(f&&f.sdp&&f.sdp.indexOf(`
67
+ `)}});var g=new u.RTCSessionDescription({type:"answer",sdp:f});return Promise.resolve(g)},v.prototype.addIceCandidate=function(m){var f,p=this;return m&&m.sdpMLineIndex===void 0&&!m.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise(function(g,E){if(!p._remoteDescription)return E(l("InvalidStateError","Can not add ICE candidate without a remote description"));if(m&&m.candidate!==""){var C=m.sdpMLineIndex;if(m.sdpMid){for(var T=0;T<p.transceivers.length;T++)if(p.transceivers[T].mid===m.sdpMid){C=T;break}}var S=p.transceivers[C];if(!S)return E(l("OperationError","Can not add ICE candidate"));if(S.rejected)return g();var I=Object.keys(m.candidate).length>0?i.parseCandidate(m.candidate):{};if(I.protocol==="tcp"&&(I.port===0||I.port===9)||I.component&&I.component!==1)return g();if((C===0||C>0&&S.iceTransport!==p.transceivers[0].iceTransport)&&!d(S.iceTransport,I))return E(l("OperationError","Can not add ICE candidate"));var A=m.candidate.trim();A.indexOf("a=")===0&&(A=A.substr(2)),(f=i.getMediaSections(p._remoteDescription.sdp))[C]+="a="+(I.type?A:"end-of-candidates")+`\r
68
+ `,p._remoteDescription.sdp=i.getDescription(p._remoteDescription.sdp)+f.join("")}else for(var k=0;k<p.transceivers.length&&(p.transceivers[k].rejected||(p.transceivers[k].iceTransport.addRemoteCandidate({}),(f=i.getMediaSections(p._remoteDescription.sdp))[k]+=`a=end-of-candidates\r
69
+ `,p._remoteDescription.sdp=i.getDescription(p._remoteDescription.sdp)+f.join(""),!p.usingBundle));k++);g()})},v.prototype.getStats=function(m){if(m&&m instanceof u.MediaStreamTrack){var f=null;if(this.transceivers.forEach(function(g){g.rtpSender&&g.rtpSender.track===m?f=g.rtpSender:g.rtpReceiver&&g.rtpReceiver.track===m&&(f=g.rtpReceiver)}),!f)throw l("InvalidAccessError","Invalid selector.");return f.getStats()}var p=[];return this.transceivers.forEach(function(g){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach(function(E){g[E]&&p.push(g[E].getStats())})}),Promise.all(p).then(function(g){var E=new Map;return g.forEach(function(C){C.forEach(function(T){E.set(T.id,T)})}),E})},["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach(function(m){var f=u[m];if(f&&f.prototype&&f.prototype.getStats){var p=f.prototype.getStats;f.prototype.getStats=function(){return p.apply(this).then(function(g){var E=new Map;return Object.keys(g).forEach(function(C){g[C].type=n(g[C]),E.set(C,g[C])}),E})}}});var x=["createOffer","createAnswer"];return x.forEach(function(m){var f=v.prototype[m];v.prototype[m]=function(){var p=arguments;return typeof p[0]=="function"||typeof p[1]=="function"?f.apply(this,[arguments[2]]).then(function(g){typeof p[0]=="function"&&p[0].apply(null,[g])},function(g){typeof p[1]=="function"&&p[1].apply(null,[g])}):f.apply(this,arguments)}}),(x=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach(function(m){var f=v.prototype[m];v.prototype[m]=function(){var p=arguments;return typeof p[1]=="function"||typeof p[2]=="function"?f.apply(this,arguments).then(function(){typeof p[1]=="function"&&p[1].apply(null)},function(g){typeof p[2]=="function"&&p[2].apply(null,[g])}):f.apply(this,arguments)}}),["getStats"].forEach(function(m){var f=v.prototype[m];v.prototype[m]=function(){var p=arguments;return typeof p[1]=="function"?f.apply(this,arguments).then(function(){typeof p[1]=="function"&&p[1].apply(null)}):f.apply(this,arguments)}}),v}},{sdp:"YHvh"}],YdKx:[function(o,e,t){"use strict";function i(n){var r=n&&n.navigator,s=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(a){return s(a).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(o,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(o,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 s.shimGetUserMedia}}),Object.defineProperty(t,"shimGetDisplayMedia",{enumerable:!0,get:function(){return a.shimGetDisplayMedia}});var i=l(o("../utils")),n=o("./filtericeservers"),r=c(o("rtcpeerconnection-shim")),s=o("./getusermedia"),a=o("./getdisplaymedia");function c(b){return b&&b.__esModule?b:{default:b}}function d(){if(typeof WeakMap!="function")return null;var b=new WeakMap;return d=function(){return b},b}function l(b){if(b&&b.__esModule)return b;if(b===null||typeof b!="object"&&typeof b!="function")return{default:b};var w=d();if(w&&w.has(b))return w.get(b);var v={},x=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var m in b)if(Object.prototype.hasOwnProperty.call(b,m)){var f=x?Object.getOwnPropertyDescriptor(b,m):null;f&&(f.get||f.set)?Object.defineProperty(v,m,f):v[m]=b[m]}return v.default=b,w&&w.set(b,v),v}function u(b,w){if(b.RTCIceGatherer&&(b.RTCIceCandidate||(b.RTCIceCandidate=function(m){return m}),b.RTCSessionDescription||(b.RTCSessionDescription=function(m){return m}),w.version<15025)){var v=Object.getOwnPropertyDescriptor(b.MediaStreamTrack.prototype,"enabled");Object.defineProperty(b.MediaStreamTrack.prototype,"enabled",{set:function(m){v.set.call(this,m);var f=new Event("enabled");f.enabled=m,this.dispatchEvent(f)}})}!b.RTCRtpSender||"dtmf"in b.RTCRtpSender.prototype||Object.defineProperty(b.RTCRtpSender.prototype,"dtmf",{get:function(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=new b.RTCDtmfSender(this):this.track.kind==="video"&&(this._dtmf=null)),this._dtmf}}),b.RTCDtmfSender&&!b.RTCDTMFSender&&(b.RTCDTMFSender=b.RTCDtmfSender);var x=(0,r.default)(b,w.version);b.RTCPeerConnection=function(m){return m&&m.iceServers&&(m.iceServers=(0,n.filterIceServers)(m.iceServers,w.version),i.log("ICE servers after filtering:",m.iceServers)),new x(m)},b.RTCPeerConnection.prototype=x.prototype}function h(b){!b.RTCRtpSender||"replaceTrack"in b.RTCRtpSender.prototype||(b.RTCRtpSender.prototype.replaceTrack=b.RTCRtpSender.prototype.setTrack)}},{"../utils":"iSxC","./filtericeservers":"NZ1C","rtcpeerconnection-shim":"NJ2u","./getusermedia":"YdKx","./getdisplaymedia":"P3bV"}],GzSv:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetUserMedia=a;var i=r(o("../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 l={},u=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var h in c)if(Object.prototype.hasOwnProperty.call(c,h)){var b=u?Object.getOwnPropertyDescriptor(c,h):null;b&&(b.get||b.set)?Object.defineProperty(l,h,b):l[h]=c[h]}return l.default=c,d&&d.set(c,l),l}function s(c){return(s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(d){return typeof d}:function(d){return d&&typeof Symbol=="function"&&d.constructor===Symbol&&d!==Symbol.prototype?"symbol":typeof d})(c)}function a(c,d){var l=c&&c.navigator,u=c&&c.MediaStreamTrack;if(l.getUserMedia=function(x,m,f){i.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),l.mediaDevices.getUserMedia(x).then(m,f)},!(d.version>55&&"autoGainControl"in l.mediaDevices.getSupportedConstraints())){var h=function(x,m,f){m in x&&!(f in x)&&(x[f]=x[m],delete x[m])},b=l.mediaDevices.getUserMedia.bind(l.mediaDevices);if(l.mediaDevices.getUserMedia=function(x){return s(x)==="object"&&s(x.audio)==="object"&&(x=JSON.parse(JSON.stringify(x)),h(x.audio,"autoGainControl","mozAutoGainControl"),h(x.audio,"noiseSuppression","mozNoiseSuppression")),b(x)},u&&u.prototype.getSettings){var w=u.prototype.getSettings;u.prototype.getSettings=function(){var x=w.apply(this,arguments);return h(x,"mozAutoGainControl","autoGainControl"),h(x,"mozNoiseSuppression","noiseSuppression"),x}}if(u&&u.prototype.applyConstraints){var v=u.prototype.applyConstraints;u.prototype.applyConstraints=function(x){return this.kind==="audio"&&s(x)==="object"&&(x=JSON.parse(JSON.stringify(x)),h(x,"autoGainControl","mozAutoGainControl"),h(x,"noiseSuppression","mozNoiseSuppression")),v.apply(this,[x])}}}}},{"../utils":"iSxC"}],UuGU:[function(o,e,t){"use strict";function i(n,r){n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||n.navigator.mediaDevices&&(n.navigator.mediaDevices.getDisplayMedia=function(s){if(!s||!s.video){var a=new DOMException("getDisplayMedia without video constraints is undefined");return a.name="NotFoundError",a.code=8,Promise.reject(a)}return s.video===!0?s.video={mediaSource:r}:s.video.mediaSource=r,n.navigator.mediaDevices.getUserMedia(s)})}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetDisplayMedia=i},{}],Fzdr:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimOnTrack=l,t.shimPeerConnection=u,t.shimSenderGetStats=h,t.shimReceiverGetStats=b,t.shimRemoveStream=w,t.shimRTCDataChannel=v,t.shimAddTransceiver=x,t.shimGetParameters=m,t.shimCreateOffer=f,t.shimCreateAnswer=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=a(o("../utils")),n=o("./getusermedia"),r=o("./getdisplaymedia");function s(){if(typeof WeakMap!="function")return null;var g=new WeakMap;return s=function(){return g},g}function a(g){if(g&&g.__esModule)return g;if(g===null||typeof g!="object"&&typeof g!="function")return{default:g};var E=s();if(E&&E.has(g))return E.get(g);var C={},T=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var S in g)if(Object.prototype.hasOwnProperty.call(g,S)){var I=T?Object.getOwnPropertyDescriptor(g,S):null;I&&(I.get||I.set)?Object.defineProperty(C,S,I):C[S]=g[S]}return C.default=g,E&&E.set(g,C),C}function c(g,E,C){return E in g?Object.defineProperty(g,E,{value:C,enumerable:!0,configurable:!0,writable:!0}):g[E]=C,g}function d(g){return(d=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(E){return typeof E}:function(E){return E&&typeof Symbol=="function"&&E.constructor===Symbol&&E!==Symbol.prototype?"symbol":typeof E})(g)}function l(g){d(g)==="object"&&g.RTCTrackEvent&&"receiver"in g.RTCTrackEvent.prototype&&!("transceiver"in g.RTCTrackEvent.prototype)&&Object.defineProperty(g.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})}function u(g,E){if(d(g)==="object"&&(g.RTCPeerConnection||g.mozRTCPeerConnection)){!g.RTCPeerConnection&&g.mozRTCPeerConnection&&(g.RTCPeerConnection=g.mozRTCPeerConnection),E.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(S){var I=g.RTCPeerConnection.prototype[S],A=c({},S,function(){return arguments[0]=new(S==="addIceCandidate"?g.RTCIceCandidate:g.RTCSessionDescription)(arguments[0]),I.apply(this,arguments)});g.RTCPeerConnection.prototype[S]=A[S]});var C={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},T=g.RTCPeerConnection.prototype.getStats;g.RTCPeerConnection.prototype.getStats=function(){var[S,I,A]=arguments;return T.apply(this,[S||null]).then(function(k){if(E.version<53&&!I)try{k.forEach(function(j){j.type=C[j.type]||j.type})}catch(j){if(j.name!=="TypeError")throw j;k.forEach(function(F,W){k.set(W,Object.assign({},F,{type:C[F.type]||F.type}))})}return k}).then(I,A)}}}function h(g){if(d(g)==="object"&&g.RTCPeerConnection&&g.RTCRtpSender&&!(g.RTCRtpSender&&"getStats"in g.RTCRtpSender.prototype)){var E=g.RTCPeerConnection.prototype.getSenders;E&&(g.RTCPeerConnection.prototype.getSenders=function(){var T=this,S=E.apply(this,[]);return S.forEach(function(I){return I._pc=T}),S});var C=g.RTCPeerConnection.prototype.addTrack;C&&(g.RTCPeerConnection.prototype.addTrack=function(){var T=C.apply(this,arguments);return T._pc=this,T}),g.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}}function b(g){if(d(g)==="object"&&g.RTCPeerConnection&&g.RTCRtpSender&&!(g.RTCRtpSender&&"getStats"in g.RTCRtpReceiver.prototype)){var E=g.RTCPeerConnection.prototype.getReceivers;E&&(g.RTCPeerConnection.prototype.getReceivers=function(){var C=this,T=E.apply(this,[]);return T.forEach(function(S){return S._pc=C}),T}),i.wrapPeerConnectionEvent(g,"track",function(C){return C.receiver._pc=C.srcElement,C}),g.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}}function w(g){!g.RTCPeerConnection||"removeStream"in g.RTCPeerConnection.prototype||(g.RTCPeerConnection.prototype.removeStream=function(E){var C=this;i.deprecated("removeStream","removeTrack"),this.getSenders().forEach(function(T){T.track&&E.getTracks().includes(T.track)&&C.removeTrack(T)})})}function v(g){g.DataChannel&&!g.RTCDataChannel&&(g.RTCDataChannel=g.DataChannel)}function x(g){if(d(g)==="object"&&g.RTCPeerConnection){var E=g.RTCPeerConnection.prototype.addTransceiver;E&&(g.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];var C=arguments[1],T=C&&"sendEncodings"in C;T&&C.sendEncodings.forEach(function(k){if("rid"in k&&!/^[a-z0-9]{0,16}$/i.test(k.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in k&&!(parseFloat(k.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in k&&!(parseFloat(k.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});var S=E.apply(this,arguments);if(T){var{sender:I}=S,A=I.getParameters();"encodings"in A&&(A.encodings.length!==1||Object.keys(A.encodings[0]).length!==0)||(A.encodings=C.sendEncodings,I.sendEncodings=C.sendEncodings,this.setParametersPromises.push(I.setParameters(A).then(function(){delete I.sendEncodings}).catch(function(){delete I.sendEncodings})))}return S})}}function m(g){if(d(g)==="object"&&g.RTCRtpSender){var E=g.RTCRtpSender.prototype.getParameters;E&&(g.RTCRtpSender.prototype.getParameters=function(){var C=E.apply(this,arguments);return"encodings"in C||(C.encodings=[].concat(this.sendEncodings||[{}])),C})}}function f(g){if(d(g)==="object"&&g.RTCPeerConnection){var E=g.RTCPeerConnection.prototype.createOffer;g.RTCPeerConnection.prototype.createOffer=function(){var C=arguments,T=this;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return E.apply(T,C)}).finally(function(){T.setParametersPromises=[]}):E.apply(this,arguments)}}}function p(g){if(d(g)==="object"&&g.RTCPeerConnection){var E=g.RTCPeerConnection.prototype.createAnswer;g.RTCPeerConnection.prototype.createAnswer=function(){var C=arguments,T=this;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return E.apply(T,C)}).finally(function(){T.setParametersPromises=[]}):E.apply(this,arguments)}}}},{"../utils":"iSxC","./getusermedia":"GzSv","./getdisplaymedia":"UuGU"}],t1lL:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimLocalStreamsAPI=a,t.shimRemoteStreamsAPI=c,t.shimCallbacksAPI=d,t.shimGetUserMedia=l,t.shimConstraints=u,t.shimRTCIceServerUrls=h,t.shimTrackEventTransceiver=b,t.shimCreateOfferLegacy=w,t.shimAudioContext=v;var i=r(o("../utils"));function n(){if(typeof WeakMap!="function")return null;var x=new WeakMap;return n=function(){return x},x}function r(x){if(x&&x.__esModule)return x;if(x===null||typeof x!="object"&&typeof x!="function")return{default:x};var m=n();if(m&&m.has(x))return m.get(x);var f={},p=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var g in x)if(Object.prototype.hasOwnProperty.call(x,g)){var E=p?Object.getOwnPropertyDescriptor(x,g):null;E&&(E.get||E.set)?Object.defineProperty(f,g,E):f[g]=x[g]}return f.default=x,m&&m.set(x,f),f}function s(x){return(s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(m){return typeof m}:function(m){return m&&typeof Symbol=="function"&&m.constructor===Symbol&&m!==Symbol.prototype?"symbol":typeof m})(x)}function a(x){if(s(x)==="object"&&x.RTCPeerConnection){if("getLocalStreams"in x.RTCPeerConnection.prototype||(x.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in x.RTCPeerConnection.prototype)){var m=x.RTCPeerConnection.prototype.addTrack;x.RTCPeerConnection.prototype.addStream=function(f){var p=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(f)||this._localStreams.push(f),f.getAudioTracks().forEach(function(g){return m.call(p,g,f)}),f.getVideoTracks().forEach(function(g){return m.call(p,g,f)})},x.RTCPeerConnection.prototype.addTrack=function(f){for(var p=this,g=arguments.length,E=new Array(g>1?g-1:0),C=1;C<g;C++)E[C-1]=arguments[C];return E&&E.forEach(function(T){p._localStreams?p._localStreams.includes(T)||p._localStreams.push(T):p._localStreams=[T]}),m.apply(this,arguments)}}"removeStream"in x.RTCPeerConnection.prototype||(x.RTCPeerConnection.prototype.removeStream=function(f){var p=this;this._localStreams||(this._localStreams=[]);var g=this._localStreams.indexOf(f);if(g!==-1){this._localStreams.splice(g,1);var E=f.getTracks();this.getSenders().forEach(function(C){E.includes(C.track)&&p.removeTrack(C)})}})}}function c(x){if(s(x)==="object"&&x.RTCPeerConnection&&("getRemoteStreams"in x.RTCPeerConnection.prototype||(x.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in x.RTCPeerConnection.prototype))){Object.defineProperty(x.RTCPeerConnection.prototype,"onaddstream",{get:function(){return this._onaddstream},set:function(f){var p=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=f),this.addEventListener("track",this._onaddstreampoly=function(g){g.streams.forEach(function(E){if(p._remoteStreams||(p._remoteStreams=[]),!p._remoteStreams.includes(E)){p._remoteStreams.push(E);var C=new Event("addstream");C.stream=E,p.dispatchEvent(C)}})})}});var m=x.RTCPeerConnection.prototype.setRemoteDescription;x.RTCPeerConnection.prototype.setRemoteDescription=function(){var f=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(p){p.streams.forEach(function(g){if(f._remoteStreams||(f._remoteStreams=[]),!(f._remoteStreams.indexOf(g)>=0)){f._remoteStreams.push(g);var E=new Event("addstream");E.stream=g,f.dispatchEvent(E)}})}),m.apply(f,arguments)}}}function d(x){if(s(x)==="object"&&x.RTCPeerConnection){var m=x.RTCPeerConnection.prototype,f=m.createOffer,p=m.createAnswer,g=m.setLocalDescription,E=m.setRemoteDescription,C=m.addIceCandidate;m.createOffer=function(S,I){var A=arguments.length>=2?arguments[2]:arguments[0],k=f.apply(this,[A]);return I?(k.then(S,I),Promise.resolve()):k},m.createAnswer=function(S,I){var A=arguments.length>=2?arguments[2]:arguments[0],k=p.apply(this,[A]);return I?(k.then(S,I),Promise.resolve()):k};var T=function(S,I,A){var k=g.apply(this,[S]);return A?(k.then(I,A),Promise.resolve()):k};m.setLocalDescription=T,T=function(S,I,A){var k=E.apply(this,[S]);return A?(k.then(I,A),Promise.resolve()):k},m.setRemoteDescription=T,T=function(S,I,A){var k=C.apply(this,[S]);return A?(k.then(I,A),Promise.resolve()):k},m.addIceCandidate=T}}function l(x){var m=x&&x.navigator;if(m.mediaDevices&&m.mediaDevices.getUserMedia){var f=m.mediaDevices,p=f.getUserMedia.bind(f);m.mediaDevices.getUserMedia=function(g){return p(u(g))}}!m.getUserMedia&&m.mediaDevices&&m.mediaDevices.getUserMedia&&(m.getUserMedia=function(g,E,C){m.mediaDevices.getUserMedia(g).then(E,C)}.bind(m))}function u(x){return x&&x.video!==void 0?Object.assign({},x,{video:i.compactObject(x.video)}):x}function h(x){if(x.RTCPeerConnection){var m=x.RTCPeerConnection;x.RTCPeerConnection=function(f,p){if(f&&f.iceServers){for(var g=[],E=0;E<f.iceServers.length;E++){var C=f.iceServers[E];!C.hasOwnProperty("urls")&&C.hasOwnProperty("url")?(i.deprecated("RTCIceServer.url","RTCIceServer.urls"),(C=JSON.parse(JSON.stringify(C))).urls=C.url,delete C.url,g.push(C)):g.push(f.iceServers[E])}f.iceServers=g}return new m(f,p)},x.RTCPeerConnection.prototype=m.prototype,"generateCertificate"in m&&Object.defineProperty(x.RTCPeerConnection,"generateCertificate",{get:function(){return m.generateCertificate}})}}function b(x){s(x)==="object"&&x.RTCTrackEvent&&"receiver"in x.RTCTrackEvent.prototype&&!("transceiver"in x.RTCTrackEvent.prototype)&&Object.defineProperty(x.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})}function w(x){var m=x.RTCPeerConnection.prototype.createOffer;x.RTCPeerConnection.prototype.createOffer=function(f){if(f){f.offerToReceiveAudio!==void 0&&(f.offerToReceiveAudio=!!f.offerToReceiveAudio);var p=this.getTransceivers().find(function(E){return E.receiver.track.kind==="audio"});f.offerToReceiveAudio===!1&&p?p.direction==="sendrecv"?p.setDirection?p.setDirection("sendonly"):p.direction="sendonly":p.direction==="recvonly"&&(p.setDirection?p.setDirection("inactive"):p.direction="inactive"):f.offerToReceiveAudio!==!0||p||this.addTransceiver("audio"),f.offerToReceiveVideo!==void 0&&(f.offerToReceiveVideo=!!f.offerToReceiveVideo);var g=this.getTransceivers().find(function(E){return E.receiver.track.kind==="video"});f.offerToReceiveVideo===!1&&g?g.direction==="sendrecv"?g.setDirection?g.setDirection("sendonly"):g.direction="sendonly":g.direction==="recvonly"&&(g.setDirection?g.setDirection("inactive"):g.direction="inactive"):f.offerToReceiveVideo!==!0||g||this.addTransceiver("video")}return m.apply(this,arguments)}}function v(x){s(x)!=="object"||x.AudioContext||(x.AudioContext=x.webkitAudioContext)}},{"../utils":"iSxC"}],GOQK:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimRTCIceCandidate=d,t.shimMaxMessageSize=l,t.shimSendThrowTypeError=u,t.shimConnectionState=h,t.removeExtmapAllowMixed=b,t.shimAddIceCandidateNullOrEmpty=w;var i=a(o("sdp")),n=s(o("./utils"));function r(){if(typeof WeakMap!="function")return null;var v=new WeakMap;return r=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 x=r();if(x&&x.has(v))return x.get(v);var m={},f=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var p in v)if(Object.prototype.hasOwnProperty.call(v,p)){var g=f?Object.getOwnPropertyDescriptor(v,p):null;g&&(g.get||g.set)?Object.defineProperty(m,p,g):m[p]=v[p]}return m.default=v,x&&x.set(v,m),m}function a(v){return v&&v.__esModule?v:{default:v}}function c(v){return(c=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(x){return typeof x}:function(x){return x&&typeof Symbol=="function"&&x.constructor===Symbol&&x!==Symbol.prototype?"symbol":typeof x})(v)}function d(v){if(v.RTCIceCandidate&&!(v.RTCIceCandidate&&"foundation"in v.RTCIceCandidate.prototype)){var x=v.RTCIceCandidate;v.RTCIceCandidate=function(m){if(c(m)==="object"&&m.candidate&&m.candidate.indexOf("a=")===0&&((m=JSON.parse(JSON.stringify(m))).candidate=m.candidate.substr(2)),m.candidate&&m.candidate.length){var f=new x(m),p=i.default.parseCandidate(m.candidate),g=Object.assign(f,p);return g.toJSON=function(){return{candidate:g.candidate,sdpMid:g.sdpMid,sdpMLineIndex:g.sdpMLineIndex,usernameFragment:g.usernameFragment}},g}return new x(m)},v.RTCIceCandidate.prototype=x.prototype,n.wrapPeerConnectionEvent(v,"icecandidate",function(m){return m.candidate&&Object.defineProperty(m,"candidate",{value:new v.RTCIceCandidate(m.candidate),writable:"false"}),m})}}function l(v,x){if(v.RTCPeerConnection){"sctp"in v.RTCPeerConnection.prototype||Object.defineProperty(v.RTCPeerConnection.prototype,"sctp",{get:function(){return this._sctp===void 0?null:this._sctp}});var m=v.RTCPeerConnection.prototype.setRemoteDescription;v.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,x.browser==="chrome"&&x.version>=76){var{sdpSemantics:f}=this.getConfiguration();f==="plan-b"&&Object.defineProperty(this,"sctp",{get:function(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0})}if(function(A){if(!A||!A.sdp)return!1;var k=i.default.splitSections(A.sdp);return k.shift(),k.some(function(j){var F=i.default.parseMLine(j);return F&&F.kind==="application"&&F.protocol.indexOf("SCTP")!==-1})}(arguments[0])){var p,g=function(A){var k=A.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(k===null||k.length<2)return-1;var j=parseInt(k[1],10);return j!=j?-1:j}(arguments[0]),E=(S=g,I=65536,x.browser==="firefox"&&(I=x.version<57?S===-1?16384:2147483637:x.version<60?x.version===57?65535:65536:2147483637),I),C=function(A,k){var j=65536;x.browser==="firefox"&&x.version===57&&(j=65535);var F=i.default.matchPrefix(A.sdp,"a=max-message-size:");return F.length>0?j=parseInt(F[0].substr(19),10):x.browser==="firefox"&&k!==-1&&(j=2147483637),j}(arguments[0],g);p=E===0&&C===0?Number.POSITIVE_INFINITY:E===0||C===0?Math.max(E,C):Math.min(E,C);var T={};Object.defineProperty(T,"maxMessageSize",{get:function(){return p}}),this._sctp=T}var S,I;return m.apply(this,arguments)}}}function u(v){if(v.RTCPeerConnection&&"createDataChannel"in v.RTCPeerConnection.prototype){var x=v.RTCPeerConnection.prototype.createDataChannel;v.RTCPeerConnection.prototype.createDataChannel=function(){var f=x.apply(this,arguments);return m(f,this),f},n.wrapPeerConnectionEvent(v,"datachannel",function(f){return m(f.channel,f.target),f})}function m(f,p){var g=f.send;f.send=function(){var E=arguments[0],C=E.length||E.size||E.byteLength;if(f.readyState==="open"&&p.sctp&&C>p.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+p.sctp.maxMessageSize+" bytes)");return g.apply(f,arguments)}}}function h(v){if(v.RTCPeerConnection&&!("connectionState"in v.RTCPeerConnection.prototype)){var x=v.RTCPeerConnection.prototype;Object.defineProperty(x,"connectionState",{get:function(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(x,"onconnectionstatechange",{get:function(){return this._onconnectionstatechange||null},set:function(m){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),m&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=m)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(function(m){var f=x[m];x[m]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(p){var g=p.target;if(g._lastConnectionState!==g.connectionState){g._lastConnectionState=g.connectionState;var E=new Event("connectionstatechange",p);g.dispatchEvent(E)}return p},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),f.apply(this,arguments)}})}}function b(v,x){if(v.RTCPeerConnection&&!(x.browser==="chrome"&&x.version>=71||x.browser==="safari"&&x.version>=605)){var m=v.RTCPeerConnection.prototype.setRemoteDescription;v.RTCPeerConnection.prototype.setRemoteDescription=function(f){if(f&&f.sdp&&f.sdp.indexOf(`
70
70
  a=extmap-allow-mixed`)!==-1){var p=f.sdp.split(`
71
71
  `).filter(function(g){return g.trim()!=="a=extmap-allow-mixed"}).join(`
72
72
  `);v.RTCSessionDescription&&f instanceof v.RTCSessionDescription?arguments[0]=new v.RTCSessionDescription({type:f.type,sdp:p}):f.sdp=p}return m.apply(this,arguments)}}}function w(v,x){if(v.RTCPeerConnection&&v.RTCPeerConnection.prototype){var m=v.RTCPeerConnection.prototype.addIceCandidate;m&&m.length!==0&&(v.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(x.browser==="chrome"&&x.version<78||x.browser==="firefox"&&x.version<68||x.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():m.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}}},{sdp:"YHvh","./utils":"iSxC"}],KtlG:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.adapterFactory=u;var i=l(o("./utils")),n=l(o("./chrome/chrome_shim")),r=l(o("./edge/edge_shim")),s=l(o("./firefox/firefox_shim")),a=l(o("./safari/safari_shim")),c=l(o("./common_shim"));function d(){if(typeof WeakMap!="function")return null;var h=new WeakMap;return d=function(){return h},h}function l(h){if(h&&h.__esModule)return h;if(h===null||typeof h!="object"&&typeof h!="function")return{default:h};var b=d();if(b&&b.has(h))return b.get(h);var w={},v=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var x in h)if(Object.prototype.hasOwnProperty.call(h,x)){var m=v?Object.getOwnPropertyDescriptor(h,x):null;m&&(m.get||m.set)?Object.defineProperty(w,x,m):w[x]=h[x]}return w.default=h,b&&b.set(h,w),w}function u(){var{window:h}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0},w=i.log,v=i.detectBrowser(h),x={browserDetails:v,commonShim:c,extractVersion:i.extractVersion,disableLog:i.disableLog,disableWarnings:i.disableWarnings};switch(v.browser){case"chrome":if(!n||!n.shimPeerConnection||!b.shimChrome)return w("Chrome shim is not included in this adapter release."),x;if(v.version===null)return w("Chrome shim can not determine version, not shimming."),x;w("adapter.js shimming chrome."),x.browserShim=n,c.shimAddIceCandidateNullOrEmpty(h,v),n.shimGetUserMedia(h,v),n.shimMediaStream(h,v),n.shimPeerConnection(h,v),n.shimOnTrack(h,v),n.shimAddTrackRemoveTrack(h,v),n.shimGetSendersWithDtmf(h,v),n.shimGetStats(h,v),n.shimSenderReceiverGetStats(h,v),n.fixNegotiationNeeded(h,v),c.shimRTCIceCandidate(h,v),c.shimConnectionState(h,v),c.shimMaxMessageSize(h,v),c.shimSendThrowTypeError(h,v),c.removeExtmapAllowMixed(h,v);break;case"firefox":if(!s||!s.shimPeerConnection||!b.shimFirefox)return w("Firefox shim is not included in this adapter release."),x;w("adapter.js shimming firefox."),x.browserShim=s,c.shimAddIceCandidateNullOrEmpty(h,v),s.shimGetUserMedia(h,v),s.shimPeerConnection(h,v),s.shimOnTrack(h,v),s.shimRemoveStream(h,v),s.shimSenderGetStats(h,v),s.shimReceiverGetStats(h,v),s.shimRTCDataChannel(h,v),s.shimAddTransceiver(h,v),s.shimGetParameters(h,v),s.shimCreateOffer(h,v),s.shimCreateAnswer(h,v),c.shimRTCIceCandidate(h,v),c.shimConnectionState(h,v),c.shimMaxMessageSize(h,v),c.shimSendThrowTypeError(h,v);break;case"edge":if(!r||!r.shimPeerConnection||!b.shimEdge)return w("MS edge shim is not included in this adapter release."),x;w("adapter.js shimming edge."),x.browserShim=r,r.shimGetUserMedia(h,v),r.shimGetDisplayMedia(h,v),r.shimPeerConnection(h,v),r.shimReplaceTrack(h,v),c.shimMaxMessageSize(h,v),c.shimSendThrowTypeError(h,v);break;case"safari":if(!a||!b.shimSafari)return w("Safari shim is not included in this adapter release."),x;w("adapter.js shimming safari."),x.browserShim=a,c.shimAddIceCandidateNullOrEmpty(h,v),a.shimRTCIceServerUrls(h,v),a.shimCreateOfferLegacy(h,v),a.shimCallbacksAPI(h,v),a.shimLocalStreamsAPI(h,v),a.shimRemoteStreamsAPI(h,v),a.shimTrackEventTransceiver(h,v),a.shimGetUserMedia(h,v),a.shimAudioContext(h,v),c.shimRTCIceCandidate(h,v),c.shimMaxMessageSize(h,v),c.shimSendThrowTypeError(h,v),c.removeExtmapAllowMixed(h,v);break;default:w("Unsupported browser!")}return x}},{"./utils":"iSxC","./chrome/chrome_shim":"uI5X","./edge/edge_shim":"XRic","./firefox/firefox_shim":"Fzdr","./safari/safari_shim":"t1lL","./common_shim":"GOQK"}],tI1X:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var i=o("./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(o,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(o("webrtc-adapter"));t.webRTCAdapter=n.default},{"webrtc-adapter":"tI1X"}],I31f:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Supports=void 0;var i=o("./adapter");t.Supports=new(function(){function n(){this.isIOS=["iPad","iPhone","iPod"].includes(navigator.platform),this.supportedBrowsers=["firefox","chrome","safari"],this.minFirefoxVersion=59,this.minChromeVersion=72,this.minSafariVersion=605}return n.prototype.isWebRTCSupported=function(){return typeof RTCPeerConnection<"u"},n.prototype.isBrowserSupported=function(){var r=this.getBrowser(),s=this.getVersion();return!!this.supportedBrowsers.includes(r)&&(r==="chrome"?s>=this.minChromeVersion:r==="firefox"?s>=this.minFirefoxVersion:r==="safari"&&!this.isIOS&&s>=this.minSafariVersion)},n.prototype.getBrowser=function(){return i.webRTCAdapter.browserDetails.browser},n.prototype.getVersion=function(){return i.webRTCAdapter.browserDetails.version||0},n.prototype.isUnifiedPlanSupported=function(){var r,s=this.getBrowser(),a=i.webRTCAdapter.browserDetails.version||0;if(s==="chrome"&&a<72)return!1;if(s==="firefox"&&a>=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:
@@ -75,9 +75,9 @@ a=extmap-allow-mixed`)!==-1){var p=f.sdp.split(`
75
75
  isIOS:`+this.isIOS+`
76
76
  isWebRTCSupported:`+this.isWebRTCSupported()+`
77
77
  isBrowserSupported:`+this.isBrowserSupported()+`
78
- isUnifiedPlanSupported:`+this.isUnifiedPlanSupported()},n}())},{"./adapter":"sXtV"}],BHXf:[function(o,e,t){"use strict";var i=this&&this.__createBinding||(Object.create?function(d,l,u,h){h===void 0&&(h=u),Object.defineProperty(d,h,{enumerable:!0,get:function(){return l[u]}})}:function(d,l,u,h){h===void 0&&(h=u),d[h]=l[u]}),n=this&&this.__setModuleDefault||(Object.create?function(d,l){Object.defineProperty(d,"default",{enumerable:!0,value:l})}:function(d,l){d.default=l}),r=this&&this.__importStar||function(d){if(d&&d.__esModule)return d;var l={};if(d!=null)for(var u in d)u!=="default"&&Object.prototype.hasOwnProperty.call(d,u)&&i(l,d,u);return n(l,d),l};Object.defineProperty(t,"__esModule",{value:!0}),t.util=void 0;var s=r(o("peerjs-js-binarypack")),a=o("./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=a.Supports.getBrowser(),this.browserVersion=a.Supports.getVersion(),this.supports=function(){var l,u={browser:a.Supports.isBrowserSupported(),webRTC:a.Supports.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!u.webRTC)return u;try{l=new RTCPeerConnection(c),u.audioVideo=!0;var h=void 0;try{h=l.createDataChannel("_PEERJSTEST",{ordered:!0}),u.data=!0,u.reliable=!!h.ordered;try{h.binaryType="blob",u.binaryBlob=!a.Supports.isIOS}catch{}}catch{}finally{h&&h.close()}}catch{}finally{l&&l.close()}return u}(),this.pack=s.pack,this.unpack=s.unpack,this._dataCount=1}return d.prototype.noop=function(){},d.prototype.validateId=function(l){return!l||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(l)},d.prototype.chunk=function(l){for(var u=[],h=l.size,b=Math.ceil(h/t.util.chunkedMTU),w=0,v=0;v<h;){var x=Math.min(h,v+t.util.chunkedMTU),m=l.slice(v,x),f={__peerData:this._dataCount,n:w,data:m,total:b};u.push(f),v=x,w++}return this._dataCount++,u},d.prototype.blobToArrayBuffer=function(l,u){var h=new FileReader;return h.onload=function(b){b.target&&u(b.target.result)},h.readAsArrayBuffer(l),h},d.prototype.binaryStringToArrayBuffer=function(l){for(var u=new Uint8Array(l.length),h=0;h<l.length;h++)u[h]=255&l.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(o,e,t){"use strict";var i=Object.prototype.hasOwnProperty,n="~";function r(){}function s(l,u,h){this.fn=l,this.context=u,this.once=h||!1}function a(l,u,h,b,w){if(typeof h!="function")throw new TypeError("The listener must be a function");var v=new s(h,b||l,w),x=n?n+u:u;return l._events[x]?l._events[x].fn?l._events[x]=[l._events[x],v]:l._events[x].push(v):(l._events[x]=v,l._eventsCount++),l}function c(l,u){--l._eventsCount==0?l._events=new r:delete l._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 l,u,h=[];if(this._eventsCount===0)return h;for(u in l=this._events)i.call(l,u)&&h.push(n?u.slice(1):u);return Object.getOwnPropertySymbols?h.concat(Object.getOwnPropertySymbols(l)):h},d.prototype.listeners=function(l){var u=n?n+l:l,h=this._events[u];if(!h)return[];if(h.fn)return[h.fn];for(var b=0,w=h.length,v=new Array(w);b<w;b++)v[b]=h[b].fn;return v},d.prototype.listenerCount=function(l){var u=n?n+l:l,h=this._events[u];return h?h.fn?1:h.length:0},d.prototype.emit=function(l,u,h,b,w,v){var x=n?n+l:l;if(!this._events[x])return!1;var m,f,p=this._events[x],g=arguments.length;if(p.fn){switch(p.once&&this.removeListener(l,p.fn,void 0,!0),g){case 1:return p.fn.call(p.context),!0;case 2:return p.fn.call(p.context,u),!0;case 3:return p.fn.call(p.context,u,h),!0;case 4:return p.fn.call(p.context,u,h,b),!0;case 5:return p.fn.call(p.context,u,h,b,w),!0;case 6:return p.fn.call(p.context,u,h,b,w,v),!0}for(f=1,m=new Array(g-1);f<g;f++)m[f-1]=arguments[f];p.fn.apply(p.context,m)}else{var E,C=p.length;for(f=0;f<C;f++)switch(p[f].once&&this.removeListener(l,p[f].fn,void 0,!0),g){case 1:p[f].fn.call(p[f].context);break;case 2:p[f].fn.call(p[f].context,u);break;case 3:p[f].fn.call(p[f].context,u,h);break;case 4:p[f].fn.call(p[f].context,u,h,b);break;default:if(!m)for(E=1,m=new Array(g-1);E<g;E++)m[E-1]=arguments[E];p[f].fn.apply(p[f].context,m)}}return!0},d.prototype.on=function(l,u,h){return a(this,l,u,h,!1)},d.prototype.once=function(l,u,h){return a(this,l,u,h,!0)},d.prototype.removeListener=function(l,u,h,b){var w=n?n+l:l;if(!this._events[w])return this;if(!u)return c(this,w),this;var v=this._events[w];if(v.fn)v.fn!==u||b&&!v.once||h&&v.context!==h||c(this,w);else{for(var x=0,m=[],f=v.length;x<f;x++)(v[x].fn!==u||b&&!v[x].once||h&&v[x].context!==h)&&m.push(v[x]);m.length?this._events[w]=m.length===1?m[0]:m:c(this,w)}return this},d.prototype.removeAllListeners=function(l){var u;return l?(u=n?n+l:l,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(o,e,t){"use strict";var i=this&&this.__read||function(c,d){var l=typeof Symbol=="function"&&c[Symbol.iterator];if(!l)return c;var u,h,b=l.call(c),w=[];try{for(;(d===void 0||d-- >0)&&!(u=b.next()).done;)w.push(u.value)}catch(v){h={error:v}}finally{try{u&&!u.done&&(l=b.return)&&l.call(b)}finally{if(h)throw h.error}}return w},n=this&&this.__spreadArray||function(c,d){for(var l=0,u=d.length,h=c.length;l<u;l++,h++)c[h]=d[l];return c};Object.defineProperty(t,"__esModule",{value:!0}),t.LogLevel=void 0;var r,s="PeerJS: ";(function(c){c[c.Disabled=0]="Disabled",c[c.Errors=1]="Errors",c[c.Warnings=2]="Warnings",c[c.All=3]="All"})(r=t.LogLevel||(t.LogLevel={}));var a=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=[],l=0;l<arguments.length;l++)d[l]=arguments[l];this._logLevel>=r.All&&this._print.apply(this,n([r.All],i(d)))},c.prototype.warn=function(){for(var d=[],l=0;l<arguments.length;l++)d[l]=arguments[l];this._logLevel>=r.Warnings&&this._print.apply(this,n([r.Warnings],i(d)))},c.prototype.error=function(){for(var d=[],l=0;l<arguments.length;l++)d[l]=arguments[l];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 l=[],u=1;u<arguments.length;u++)l[u-1]=arguments[u];var h=n([s],i(l));for(var b in h)h[b]instanceof Error&&(h[b]="("+h[b].name+") "+h[b].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 a},{}],ZRYf:[function(o,e,t){"use strict";var i,n,r,s,a,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(l){l.Open="open",l.Stream="stream",l.Data="data",l.Close="close",l.Error="error",l.IceStateChanged="iceStateChanged"}(i=t.ConnectionEventType||(t.ConnectionEventType={})),function(l){l.Data="data",l.Media="media"}(n=t.ConnectionType||(t.ConnectionType={})),function(l){l.Open="open",l.Close="close",l.Connection="connection",l.Call="call",l.Disconnected="disconnected",l.Error="error"}(r=t.PeerEventType||(t.PeerEventType={})),function(l){l.BrowserIncompatible="browser-incompatible",l.Disconnected="disconnected",l.InvalidID="invalid-id",l.InvalidKey="invalid-key",l.Network="network",l.PeerUnavailable="peer-unavailable",l.SslUnavailable="ssl-unavailable",l.ServerError="server-error",l.SocketError="socket-error",l.SocketClosed="socket-closed",l.UnavailableID="unavailable-id",l.WebRTC="webrtc"}(s=t.PeerErrorType||(t.PeerErrorType={})),function(l){l.Binary="binary",l.BinaryUTF8="binary-utf8",l.JSON="json"}(a=t.SerializationType||(t.SerializationType={})),function(l){l.Message="message",l.Disconnected="disconnected",l.Error="error",l.Close="close"}(c=t.SocketEventType||(t.SocketEventType={})),function(l){l.Heartbeat="HEARTBEAT",l.Candidate="CANDIDATE",l.Offer="OFFER",l.Answer="ANSWER",l.Open="OPEN",l.Error="ERROR",l.IdTaken="ID-TAKEN",l.InvalidKey="INVALID-KEY",l.Leave="LEAVE",l.Expire="EXPIRE"}(d=t.ServerMessageType||(t.ServerMessageType={}))},{}],wJlv:[function(o,e,t){"use strict";var i=this&&this.__extends||function(){var h=function(b,w){return(h=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(v,x){v.__proto__=x}||function(v,x){for(var m in x)Object.prototype.hasOwnProperty.call(x,m)&&(v[m]=x[m])})(b,w)};return function(b,w){if(typeof w!="function"&&w!==null)throw new TypeError("Class extends value "+String(w)+" is not a constructor or null");function v(){this.constructor=b}h(b,w),b.prototype=w===null?Object.create(w):(v.prototype=w.prototype,new v)}}(),n=this&&this.__read||function(h,b){var w=typeof Symbol=="function"&&h[Symbol.iterator];if(!w)return h;var v,x,m=w.call(h),f=[];try{for(;(b===void 0||b-- >0)&&!(v=m.next()).done;)f.push(v.value)}catch(p){x={error:p}}finally{try{v&&!v.done&&(w=m.return)&&w.call(m)}finally{if(x)throw x.error}}return f},r=this&&this.__spreadArray||function(h,b){for(var w=0,v=b.length,x=h.length;w<v;w++,x++)h[x]=b[w];return h},s=this&&this.__values||function(h){var b=typeof Symbol=="function"&&Symbol.iterator,w=b&&h[b],v=0;if(w)return w.call(h);if(h&&typeof h.length=="number")return{next:function(){return h&&v>=h.length&&(h=void 0),{value:h&&h[v++],done:!h}}};throw new TypeError(b?"Object is not iterable.":"Symbol.iterator is not defined.")},a=this&&this.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(t,"__esModule",{value:!0}),t.Socket=void 0;var c=o("eventemitter3"),d=a(o("./logger")),l=o("./enums"),u=function(h){function b(w,v,x,m,f,p){p===void 0&&(p=5e3);var g=h.call(this)||this;g.pingInterval=p,g._disconnected=!0,g._messagesQueue=[];var E=w?"wss://":"ws://";return g._baseUrl=E+v+":"+x+m+"peerjs?key="+f,g}return i(b,h),b.prototype.start=function(w,v){var x=this;this._id=w;var m=this._baseUrl+"&id="+w+"&token="+v;!this._socket&&this._disconnected&&(this._socket=new WebSocket(m),this._disconnected=!1,this._socket.onmessage=function(f){var p;try{p=JSON.parse(f.data),d.default.log("Server message received:",p)}catch{return void d.default.log("Invalid server message",f.data)}x.emit(l.SocketEventType.Message,p)},this._socket.onclose=function(f){x._disconnected||(d.default.log("Socket closed.",f),x._cleanup(),x._disconnected=!0,x.emit(l.SocketEventType.Disconnected))},this._socket.onopen=function(){x._disconnected||(x._sendQueuedMessages(),d.default.log("Socket open"),x._scheduleHeartbeat())})},b.prototype._scheduleHeartbeat=function(){var w=this;this._wsPingTimer=setTimeout(function(){w._sendHeartbeat()},this.pingInterval)},b.prototype._sendHeartbeat=function(){if(this._wsOpen()){var w=JSON.stringify({type:l.ServerMessageType.Heartbeat});this._socket.send(w),this._scheduleHeartbeat()}else d.default.log("Cannot send heartbeat, because socket closed")},b.prototype._wsOpen=function(){return!!this._socket&&this._socket.readyState===1},b.prototype._sendQueuedMessages=function(){var w,v,x=r([],n(this._messagesQueue));this._messagesQueue=[];try{for(var m=s(x),f=m.next();!f.done;f=m.next()){var p=f.value;this.send(p)}}catch(g){w={error:g}}finally{try{f&&!f.done&&(v=m.return)&&v.call(m)}finally{if(w)throw w.error}}},b.prototype.send=function(w){if(!this._disconnected)if(this._id)if(w.type){if(this._wsOpen()){var v=JSON.stringify(w);this._socket.send(v)}}else this.emit(l.SocketEventType.Error,"Invalid message");else this._messagesQueue.push(w)},b.prototype.close=function(){this._disconnected||(this._cleanup(),this._disconnected=!0)},b.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)},b}(c.EventEmitter);t.Socket=u},{eventemitter3:"JJlS","./logger":"WOs9","./enums":"ZRYf"}],HCdX:[function(o,e,t){"use strict";var i=this&&this.__assign||function(){return(i=Object.assign||function(u){for(var h,b=1,w=arguments.length;b<w;b++)for(var v in h=arguments[b])Object.prototype.hasOwnProperty.call(h,v)&&(u[v]=h[v]);return u}).apply(this,arguments)},n=this&&this.__awaiter||function(u,h,b,w){return new(b||(b=Promise))(function(v,x){function m(g){try{p(w.next(g))}catch(E){x(E)}}function f(g){try{p(w.throw(g))}catch(E){x(E)}}function p(g){var E;g.done?v(g.value):(E=g.value,E instanceof b?E:new b(function(C){C(E)})).then(m,f)}p((w=w.apply(u,h||[])).next())})},r=this&&this.__generator||function(u,h){var b,w,v,x,m={label:0,sent:function(){if(1&v[0])throw v[1];return v[1]},trys:[],ops:[]};return x={next:f(0),throw:f(1),return:f(2)},typeof Symbol=="function"&&(x[Symbol.iterator]=function(){return this}),x;function f(p){return function(g){return function(E){if(b)throw new TypeError("Generator is already executing.");for(;m;)try{if(b=1,w&&(v=2&E[0]?w.return:E[0]?w.throw||((v=w.return)&&v.call(w),0):w.next)&&!(v=v.call(w,E[1])).done)return v;switch(w=0,v&&(E=[2&E[0],v.value]),E[0]){case 0:case 1:v=E;break;case 4:return m.label++,{value:E[1],done:!1};case 5:m.label++,w=E[1],E=[0];continue;case 7:E=m.ops.pop(),m.trys.pop();continue;default:if(!(v=(v=m.trys).length>0&&v[v.length-1])&&(E[0]===6||E[0]===2)){m=0;continue}if(E[0]===3&&(!v||E[1]>v[0]&&E[1]<v[3])){m.label=E[1];break}if(E[0]===6&&m.label<v[1]){m.label=v[1],v=E;break}if(v&&m.label<v[2]){m.label=v[2],m.ops.push(E);break}v[2]&&m.ops.pop(),m.trys.pop();continue}E=h.call(u,m)}catch(C){E=[6,C],w=0}finally{b=v=0}if(5&E[0])throw E[1];return{value:E[0]?E[1]:void 0,done:!0}}([p,g])}}},s=this&&this.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(t,"__esModule",{value:!0}),t.Negotiator=void 0;var a=o("./util"),c=s(o("./logger")),d=o("./enums"),l=function(){function u(h){this.connection=h}return u.prototype.startConnection=function(h){var b=this._startPeerConnection();if(this.connection.peerConnection=b,this.connection.type===d.ConnectionType.Media&&h._stream&&this._addTracksToConnection(h._stream,b),h.originator){if(this.connection.type===d.ConnectionType.Data){var w=this.connection,v={ordered:!!h.reliable},x=b.createDataChannel(w.label,v);w.initialize(x)}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 b=this,w=this.connection.peer,v=this.connection.connectionId,x=this.connection.type,m=this.connection.provider;c.default.log("Listening for ICE candidates."),h.onicecandidate=function(f){f.candidate&&f.candidate.candidate&&(c.default.log("Received ICE candidates for "+w+":",f.candidate),m.socket.send({type:d.ServerMessageType.Candidate,payload:{candidate:f.candidate,type:x,connectionId:v},dst:w}))},h.oniceconnectionstatechange=function(){switch(h.iceConnectionState){case"failed":c.default.log("iceConnectionState is failed, closing connections to "+w),b.connection.emit(d.ConnectionEventType.Error,new Error("Negotiation of connection to "+w+" failed.")),b.connection.close();break;case"closed":c.default.log("iceConnectionState is closed, closing connections to "+w),b.connection.emit(d.ConnectionEventType.Error,new Error("Connection to "+w+" closed.")),b.connection.close();break;case"disconnected":c.default.log("iceConnectionState changed to disconnected on the connection with "+w);break;case"completed":h.onicecandidate=a.util.noop}b.connection.emit(d.ConnectionEventType.IceStateChanged,h.iceConnectionState)},c.default.log("Listening for data channel"),h.ondatachannel=function(f){c.default.log("Received data channel");var p=f.channel;m.getConnection(w,v).initialize(p)},c.default.log("Listening for remote stream"),h.ontrack=function(f){c.default.log("Received remote stream");var p=f.streams[0],g=m.getConnection(w,v);if(g.type===d.ConnectionType.Media){var E=g;b._addStreamToMediaConnection(p,E)}}},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 b=h.signalingState!=="closed",w=!1;if(this.connection.type===d.ConnectionType.Data){var v=this.connection.dataChannel;v&&(w=!!v.readyState&&v.readyState!=="closed")}(b||w)&&h.close()}},u.prototype._makeOffer=function(){return n(this,void 0,Promise,function(){var h,b,w,v,x,m,f;return r(this,function(p){switch(p.label){case 0:h=this.connection.peerConnection,b=this.connection.provider,p.label=1;case 1:return p.trys.push([1,7,,8]),[4,h.createOffer(this.connection.options.constraints)];case 2:w=p.sent(),c.default.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(w.sdp=this.connection.options.sdpTransform(w.sdp)||w.sdp),p.label=3;case 3:return p.trys.push([3,5,,6]),[4,h.setLocalDescription(w)];case 4:return p.sent(),c.default.log("Set localDescription:",w,"for:"+this.connection.peer),v={sdp:w,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata,browser:a.util.browser},this.connection.type===d.ConnectionType.Data&&(x=this.connection,v=i(i({},v),{label:x.label,reliable:x.reliable,serialization:x.serialization})),b.socket.send({type:d.ServerMessageType.Offer,payload:v,dst:this.connection.peer}),[3,6];case 5:return(m=p.sent())!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(b.emitError(d.PeerErrorType.WebRTC,m),c.default.log("Failed to setLocalDescription, ",m)),[3,6];case 6:return[3,8];case 7:return f=p.sent(),b.emitError(d.PeerErrorType.WebRTC,f),c.default.log("Failed to createOffer, ",f),[3,8];case 8:return[2]}})})},u.prototype._makeAnswer=function(){return n(this,void 0,Promise,function(){var h,b,w,v,x;return r(this,function(m){switch(m.label){case 0:h=this.connection.peerConnection,b=this.connection.provider,m.label=1;case 1:return m.trys.push([1,7,,8]),[4,h.createAnswer()];case 2:w=m.sent(),c.default.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(w.sdp=this.connection.options.sdpTransform(w.sdp)||w.sdp),m.label=3;case 3:return m.trys.push([3,5,,6]),[4,h.setLocalDescription(w)];case 4:return m.sent(),c.default.log("Set localDescription:",w,"for:"+this.connection.peer),b.socket.send({type:d.ServerMessageType.Answer,payload:{sdp:w,type:this.connection.type,connectionId:this.connection.connectionId,browser:a.util.browser},dst:this.connection.peer}),[3,6];case 5:return v=m.sent(),b.emitError(d.PeerErrorType.WebRTC,v),c.default.log("Failed to setLocalDescription, ",v),[3,6];case 6:return[3,8];case 7:return x=m.sent(),b.emitError(d.PeerErrorType.WebRTC,x),c.default.log("Failed to create answer, ",x),[3,8];case 8:return[2]}})})},u.prototype.handleSDP=function(h,b){return n(this,void 0,Promise,function(){var w,v,x,m;return r(this,function(f){switch(f.label){case 0:b=new RTCSessionDescription(b),w=this.connection.peerConnection,v=this.connection.provider,c.default.log("Setting remote description",b),x=this,f.label=1;case 1:return f.trys.push([1,5,,6]),[4,w.setRemoteDescription(b)];case 2:return f.sent(),c.default.log("Set remoteDescription:"+h+" for:"+this.connection.peer),h!=="OFFER"?[3,4]:[4,x._makeAnswer()];case 3:f.sent(),f.label=4;case 4:return[3,6];case 5:return m=f.sent(),v.emitError(d.PeerErrorType.WebRTC,m),c.default.log("Failed to setRemoteDescription, ",m),[3,6];case 6:return[2]}})})},u.prototype.handleCandidate=function(h){return n(this,void 0,Promise,function(){var b,w,v,x,m,f;return r(this,function(p){switch(p.label){case 0:c.default.log("handleCandidate:",h),b=h.candidate,w=h.sdpMLineIndex,v=h.sdpMid,x=this.connection.peerConnection,m=this.connection.provider,p.label=1;case 1:return p.trys.push([1,3,,4]),[4,x.addIceCandidate(new RTCIceCandidate({sdpMid:v,sdpMLineIndex:w,candidate:b}))];case 2:return p.sent(),c.default.log("Added ICE candidate for:"+this.connection.peer),[3,4];case 3:return f=p.sent(),m.emitError(d.PeerErrorType.WebRTC,f),c.default.log("Failed to handleCandidate, ",f),[3,4];case 4:return[2]}})})},u.prototype._addTracksToConnection=function(h,b){if(c.default.log("add tracks from stream "+h.id+" to peer connection"),!b.addTrack)return c.default.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");h.getTracks().forEach(function(w){b.addTrack(w,h)})},u.prototype._addStreamToMediaConnection=function(h,b){c.default.log("add stream "+h.id+" to media connection "+b.connectionId),b.addStream(h)},u}();t.Negotiator=l},{"./util":"BHXf","./logger":"WOs9","./enums":"ZRYf"}],tQFK:[function(o,e,t){"use strict";var i=this&&this.__extends||function(){var s=function(a,c){return(s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,l){d.__proto__=l}||function(d,l){for(var u in l)Object.prototype.hasOwnProperty.call(l,u)&&(d[u]=l[u])})(a,c)};return function(a,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=a}s(a,c),a.prototype=c===null?Object.create(c):(d.prototype=c.prototype,new d)}}();Object.defineProperty(t,"__esModule",{value:!0}),t.BaseConnection=void 0;var n=o("eventemitter3"),r=function(s){function a(c,d,l){var u=s.call(this)||this;return u.peer=c,u.provider=d,u.options=l,u._open=!1,u.metadata=l.metadata,u}return i(a,s),Object.defineProperty(a.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),a}(n.EventEmitter);t.BaseConnection=r},{eventemitter3:"JJlS"}],dbHP:[function(o,e,t){"use strict";var i=this&&this.__extends||function(){var b=function(w,v){return(b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(x,m){x.__proto__=m}||function(x,m){for(var f in m)Object.prototype.hasOwnProperty.call(m,f)&&(x[f]=m[f])})(w,v)};return function(w,v){if(typeof v!="function"&&v!==null)throw new TypeError("Class extends value "+String(v)+" is not a constructor or null");function x(){this.constructor=w}b(w,v),w.prototype=v===null?Object.create(v):(x.prototype=v.prototype,new x)}}(),n=this&&this.__assign||function(){return(n=Object.assign||function(b){for(var w,v=1,x=arguments.length;v<x;v++)for(var m in w=arguments[v])Object.prototype.hasOwnProperty.call(w,m)&&(b[m]=w[m]);return b}).apply(this,arguments)},r=this&&this.__values||function(b){var w=typeof Symbol=="function"&&Symbol.iterator,v=w&&b[w],x=0;if(v)return v.call(b);if(b&&typeof b.length=="number")return{next:function(){return b&&x>=b.length&&(b=void 0),{value:b&&b[x++],done:!b}}};throw new TypeError(w?"Object is not iterable.":"Symbol.iterator is not defined.")},s=this&&this.__importDefault||function(b){return b&&b.__esModule?b:{default:b}};Object.defineProperty(t,"__esModule",{value:!0}),t.MediaConnection=void 0;var a=o("./util"),c=s(o("./logger")),d=o("./negotiator"),l=o("./enums"),u=o("./baseconnection"),h=function(b){function w(v,x,m){var f=b.call(this,v,x,m)||this;return f._localStream=f.options._stream,f.connectionId=f.options.connectionId||w.ID_PREFIX+a.util.randomToken(),f._negotiator=new d.Negotiator(f),f._localStream&&f._negotiator.startConnection({_stream:f._localStream,originator:!0}),f}return i(w,b),Object.defineProperty(w.prototype,"type",{get:function(){return l.ConnectionType.Media},enumerable:!1,configurable:!0}),Object.defineProperty(w.prototype,"localStream",{get:function(){return this._localStream},enumerable:!1,configurable:!0}),Object.defineProperty(w.prototype,"remoteStream",{get:function(){return this._remoteStream},enumerable:!1,configurable:!0}),w.prototype.addStream=function(v){c.default.log("Receiving stream",v),this._remoteStream=v,b.prototype.emit.call(this,l.ConnectionEventType.Stream,v)},w.prototype.handleMessage=function(v){var x=v.type,m=v.payload;switch(v.type){case l.ServerMessageType.Answer:this._negotiator.handleSDP(x,m.sdp),this._open=!0;break;case l.ServerMessageType.Candidate:this._negotiator.handleCandidate(m.candidate);break;default:c.default.warn("Unrecognized message type:"+x+" from peer:"+this.peer)}},w.prototype.answer=function(v,x){var m,f;if(x===void 0&&(x={}),this._localStream)c.default.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");else{this._localStream=v,x&&x.sdpTransform&&(this.options.sdpTransform=x.sdpTransform),this._negotiator.startConnection(n(n({},this.options._payload),{_stream:v}));var p=this.provider._getMessages(this.connectionId);try{for(var g=r(p),E=g.next();!E.done;E=g.next()){var C=E.value;this.handleMessage(C)}}catch(T){m={error:T}}finally{try{E&&!E.done&&(f=g.return)&&f.call(g)}finally{if(m)throw m.error}}this._open=!0}},w.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,b.prototype.emit.call(this,l.ConnectionEventType.Close))},w.ID_PREFIX="mc_",w}(u.BaseConnection);t.MediaConnection=h},{"./util":"BHXf","./logger":"WOs9","./negotiator":"HCdX","./enums":"ZRYf","./baseconnection":"tQFK"}],GGp6:[function(o,e,t){"use strict";var i=this&&this.__extends||function(){var c=function(d,l){return(c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(u,h){u.__proto__=h}||function(u,h){for(var b in h)Object.prototype.hasOwnProperty.call(h,b)&&(u[b]=h[b])})(d,l)};return function(d,l){if(typeof l!="function"&&l!==null)throw new TypeError("Class extends value "+String(l)+" is not a constructor or null");function u(){this.constructor=d}c(d,l),d.prototype=l===null?Object.create(l):(u.prototype=l.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=o("eventemitter3"),s=n(o("./logger")),a=function(c){function d(){var l=c.call(this)||this;return l.fileReader=new FileReader,l._queue=[],l._processing=!1,l.fileReader.onload=function(u){l._processing=!1,u.target&&l.emit("done",u.target.result),l.doNextTask()},l.fileReader.onerror=function(u){s.default.error("EncodingQueue error:",u),l._processing=!1,l.destroy(),l.emit("error",u)},l}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(l){this.queue.push(l),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=a},{eventemitter3:"JJlS","./logger":"WOs9"}],GBTQ:[function(o,e,t){"use strict";var i=this&&this.__extends||function(){var b=function(w,v){return(b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(x,m){x.__proto__=m}||function(x,m){for(var f in m)Object.prototype.hasOwnProperty.call(m,f)&&(x[f]=m[f])})(w,v)};return function(w,v){if(typeof v!="function"&&v!==null)throw new TypeError("Class extends value "+String(v)+" is not a constructor or null");function x(){this.constructor=w}b(w,v),w.prototype=v===null?Object.create(v):(x.prototype=v.prototype,new x)}}(),n=this&&this.__values||function(b){var w=typeof Symbol=="function"&&Symbol.iterator,v=w&&b[w],x=0;if(v)return v.call(b);if(b&&typeof b.length=="number")return{next:function(){return b&&x>=b.length&&(b=void 0),{value:b&&b[x++],done:!b}}};throw new TypeError(w?"Object is not iterable.":"Symbol.iterator is not defined.")},r=this&&this.__importDefault||function(b){return b&&b.__esModule?b:{default:b}};Object.defineProperty(t,"__esModule",{value:!0}),t.DataConnection=void 0;var s=o("./util"),a=r(o("./logger")),c=o("./negotiator"),d=o("./enums"),l=o("./baseconnection"),u=o("./encodingQueue"),h=function(b){function w(v,x,m){var f=b.call(this,v,x,m)||this;return f.stringify=JSON.stringify,f.parse=JSON.parse,f._buffer=[],f._bufferSize=0,f._buffering=!1,f._chunkedData={},f._encodingQueue=new u.EncodingQueue,f.connectionId=f.options.connectionId||w.ID_PREFIX+s.util.randomToken(),f.label=f.options.label||f.connectionId,f.serialization=f.options.serialization||d.SerializationType.Binary,f.reliable=!!f.options.reliable,f._encodingQueue.on("done",function(p){f._bufferedSend(p)}),f._encodingQueue.on("error",function(){a.default.error("DC#"+f.connectionId+": Error occured in encoding from blob to arraybuffer, close DC"),f.close()}),f._negotiator=new c.Negotiator(f),f._negotiator.startConnection(f.options._payload||{originator:!0}),f}return i(w,b),Object.defineProperty(w.prototype,"type",{get:function(){return d.ConnectionType.Data},enumerable:!1,configurable:!0}),Object.defineProperty(w.prototype,"dataChannel",{get:function(){return this._dc},enumerable:!1,configurable:!0}),Object.defineProperty(w.prototype,"bufferSize",{get:function(){return this._bufferSize},enumerable:!1,configurable:!0}),w.prototype.initialize=function(v){this._dc=v,this._configureDataChannel()},w.prototype._configureDataChannel=function(){var v=this;s.util.supports.binaryBlob&&!s.util.supports.reliable||(this.dataChannel.binaryType="arraybuffer"),this.dataChannel.onopen=function(){a.default.log("DC#"+v.connectionId+" dc connection success"),v._open=!0,v.emit(d.ConnectionEventType.Open)},this.dataChannel.onmessage=function(x){a.default.log("DC#"+v.connectionId+" dc onmessage:",x.data),v._handleDataMessage(x)},this.dataChannel.onclose=function(){a.default.log("DC#"+v.connectionId+" dc closed for:",v.peer),v.close()}},w.prototype._handleDataMessage=function(v){var x=this,m=v.data,f=m.constructor,p=m;if(this.serialization===d.SerializationType.Binary||this.serialization===d.SerializationType.BinaryUTF8){if(f===Blob)return void s.util.blobToArrayBuffer(m,function(E){var C=s.util.unpack(E);x.emit(d.ConnectionEventType.Data,C)});if(f===ArrayBuffer)p=s.util.unpack(m);else if(f===String){var g=s.util.binaryStringToArrayBuffer(m);p=s.util.unpack(g)}}else this.serialization===d.SerializationType.JSON&&(p=this.parse(m));p.__peerData?this._handleChunk(p):b.prototype.emit.call(this,d.ConnectionEventType.Data,p)},w.prototype._handleChunk=function(v){var x=v.__peerData,m=this._chunkedData[x]||{data:[],count:0,total:v.total};if(m.data[v.n]=v.data,m.count++,this._chunkedData[x]=m,m.total===m.count){delete this._chunkedData[x];var f=new Blob(m.data);this._handleDataMessage({data:f})}},w.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,b.prototype.emit.call(this,d.ConnectionEventType.Close))},w.prototype.send=function(v,x){if(this.open)if(this.serialization===d.SerializationType.JSON)this._bufferedSend(this.stringify(v));else if(this.serialization===d.SerializationType.Binary||this.serialization===d.SerializationType.BinaryUTF8){var m=s.util.pack(v);if(!x&&m.size>s.util.chunkedMTU)return void this._sendChunks(m);s.util.supports.binaryBlob?this._bufferedSend(m):this._encodingQueue.enque(m)}else this._bufferedSend(v);else b.prototype.emit.call(this,d.ConnectionEventType.Error,new Error("Connection is not open. You should listen for the `open` event before sending messages."))},w.prototype._bufferedSend=function(v){!this._buffering&&this._trySend(v)||(this._buffer.push(v),this._bufferSize=this._buffer.length)},w.prototype._trySend=function(v){var x=this;if(!this.open)return!1;if(this.dataChannel.bufferedAmount>w.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(function(){x._buffering=!1,x._tryBuffer()},50),!1;try{this.dataChannel.send(v)}catch(m){return a.default.error("DC#:"+this.connectionId+" Error when sending:",m),this._buffering=!0,this.close(),!1}return!0},w.prototype._tryBuffer=function(){if(this.open&&this._buffer.length!==0){var v=this._buffer[0];this._trySend(v)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}},w.prototype._sendChunks=function(v){var x,m,f=s.util.chunk(v);a.default.log("DC#"+this.connectionId+" Try to send "+f.length+" chunks...");try{for(var p=n(f),g=p.next();!g.done;g=p.next()){var E=g.value;this.send(E,!0)}}catch(C){x={error:C}}finally{try{g&&!g.done&&(m=p.return)&&m.call(p)}finally{if(x)throw x.error}}},w.prototype.handleMessage=function(v){var x=v.payload;switch(v.type){case d.ServerMessageType.Answer:this._negotiator.handleSDP(v.type,x.sdp);break;case d.ServerMessageType.Candidate:this._negotiator.handleCandidate(x.candidate);break;default:a.default.warn("Unrecognized message type:",v.type,"from peer:",this.peer)}},w.ID_PREFIX="dc_",w.MAX_BUFFERED_AMOUNT=8388608,w}(l.BaseConnection);t.DataConnection=h},{"./util":"BHXf","./logger":"WOs9","./negotiator":"HCdX","./enums":"ZRYf","./baseconnection":"tQFK","./encodingQueue":"GGp6"}],in7L:[function(o,e,t){"use strict";var i=this&&this.__awaiter||function(d,l,u,h){return new(u||(u=Promise))(function(b,w){function v(f){try{m(h.next(f))}catch(p){w(p)}}function x(f){try{m(h.throw(f))}catch(p){w(p)}}function m(f){var p;f.done?b(f.value):(p=f.value,p instanceof u?p:new u(function(g){g(p)})).then(v,x)}m((h=h.apply(d,l||[])).next())})},n=this&&this.__generator||function(d,l){var u,h,b,w,v={label:0,sent:function(){if(1&b[0])throw b[1];return b[1]},trys:[],ops:[]};return w={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(w[Symbol.iterator]=function(){return this}),w;function x(m){return function(f){return function(p){if(u)throw new TypeError("Generator is already executing.");for(;v;)try{if(u=1,h&&(b=2&p[0]?h.return:p[0]?h.throw||((b=h.return)&&b.call(h),0):h.next)&&!(b=b.call(h,p[1])).done)return b;switch(h=0,b&&(p=[2&p[0],b.value]),p[0]){case 0:case 1:b=p;break;case 4:return v.label++,{value:p[1],done:!1};case 5:v.label++,h=p[1],p=[0];continue;case 7:p=v.ops.pop(),v.trys.pop();continue;default:if(!(b=(b=v.trys).length>0&&b[b.length-1])&&(p[0]===6||p[0]===2)){v=0;continue}if(p[0]===3&&(!b||p[1]>b[0]&&p[1]<b[3])){v.label=p[1];break}if(p[0]===6&&v.label<b[1]){v.label=b[1],b=p;break}if(b&&v.label<b[2]){v.label=b[2],v.ops.push(p);break}b[2]&&v.ops.pop(),v.trys.pop();continue}p=l.call(d,v)}catch(g){p=[6,g],h=0}finally{u=b=0}if(5&p[0])throw p[1];return{value:p[0]?p[1]:void 0,done:!0}}([m,f])}}},r=this&&this.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(t,"__esModule",{value:!0}),t.API=void 0;var s=o("./util"),a=r(o("./logger")),c=function(){function d(l){this._options=l}return d.prototype._buildUrl=function(l){var u=(this._options.secure?"https://":"http://")+this._options.host+":"+this._options.port+this._options.path+this._options.key+"/"+l;return u+="?ts="+new Date().getTime()+Math.random()},d.prototype.retrieveId=function(){return i(this,void 0,Promise,function(){var l,u,h,b;return n(this,function(w){switch(w.label){case 0:l=this._buildUrl("id"),w.label=1;case 1:return w.trys.push([1,3,,4]),[4,fetch(l)];case 2:if((u=w.sent()).status!==200)throw new Error("Error. Status:"+u.status);return[2,u.text()];case 3:throw h=w.sent(),a.default.error("Error retrieving ID",h),b="",this._options.path==="/"&&this._options.host!==s.util.CLOUD_HOST&&(b=" 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."+b);case 4:return[2]}})})},d.prototype.listAllPeers=function(){return i(this,void 0,Promise,function(){var l,u,h,b;return n(this,function(w){switch(w.label){case 0:l=this._buildUrl("peers"),w.label=1;case 1:return w.trys.push([1,3,,4]),[4,fetch(l)];case 2:if((u=w.sent()).status!==200)throw u.status===401?(h="",h=this._options.host===s.util.CLOUD_HOST?"It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":"You need to enable `allow_discovery` on your self-hosted PeerServer to use this feature.",new Error("It doesn't look like you have permission to list peers IDs. "+h)):new Error("Error. Status:"+u.status);return[2,u.json()];case 3:throw b=w.sent(),a.default.error("Error retrieving list peers",b),new Error("Could not get list peers from the server."+b);case 4:return[2]}})})},d}();t.API=c},{"./util":"BHXf","./logger":"WOs9"}],Hxpd:[function(o,e,t){"use strict";var i=this&&this.__extends||function(){var f=function(p,g){return(f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(E,C){E.__proto__=C}||function(E,C){for(var T in C)Object.prototype.hasOwnProperty.call(C,T)&&(E[T]=C[T])})(p,g)};return function(p,g){if(typeof g!="function"&&g!==null)throw new TypeError("Class extends value "+String(g)+" is not a constructor or null");function E(){this.constructor=p}f(p,g),p.prototype=g===null?Object.create(g):(E.prototype=g.prototype,new E)}}(),n=this&&this.__assign||function(){return(n=Object.assign||function(f){for(var p,g=1,E=arguments.length;g<E;g++)for(var C in p=arguments[g])Object.prototype.hasOwnProperty.call(p,C)&&(f[C]=p[C]);return f}).apply(this,arguments)},r=this&&this.__values||function(f){var p=typeof Symbol=="function"&&Symbol.iterator,g=p&&f[p],E=0;if(g)return g.call(f);if(f&&typeof f.length=="number")return{next:function(){return f&&E>=f.length&&(f=void 0),{value:f&&f[E++],done:!f}}};throw new TypeError(p?"Object is not iterable.":"Symbol.iterator is not defined.")},s=this&&this.__read||function(f,p){var g=typeof Symbol=="function"&&f[Symbol.iterator];if(!g)return f;var E,C,T=g.call(f),S=[];try{for(;(p===void 0||p-- >0)&&!(E=T.next()).done;)S.push(E.value)}catch(I){C={error:I}}finally{try{E&&!E.done&&(g=T.return)&&g.call(T)}finally{if(C)throw C.error}}return S},a=this&&this.__importDefault||function(f){return f&&f.__esModule?f:{default:f}};Object.defineProperty(t,"__esModule",{value:!0}),t.Peer=void 0;var c=o("eventemitter3"),d=o("./util"),l=a(o("./logger")),u=o("./socket"),h=o("./mediaconnection"),b=o("./dataconnection"),w=o("./enums"),v=o("./api"),x=function(){return function(){}}(),m=function(f){function p(g,E){var C,T=f.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,g&&g.constructor==Object?E=g:g&&(C=g.toString()),E=n({debug:0,host:d.util.CLOUD_HOST,port:d.util.CLOUD_PORT,path:"/",key:p.DEFAULT_KEY,token:d.util.randomToken(),config:d.util.defaultConfig},E),T._options=E,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&&l.default.setLogFunction(T._options.logFunction),l.default.logLevel=T._options.debug||0,T._api=new v.API(E),T._socket=T._createServerConnection(),d.util.supports.audioVideo||d.util.supports.data?C&&!d.util.validateId(C)?(T._delayedAbort(w.PeerErrorType.InvalidID,'ID "'+C+'" is invalid'),T):(C?T._initialize(C):T._api.retrieveId().then(function(S){return T._initialize(S)}).catch(function(S){return T._abort(w.PeerErrorType.ServerError,S)}),T):(T._delayedAbort(w.PeerErrorType.BrowserIncompatible,"The current browser does not support WebRTC"),T)}return i(p,f),Object.defineProperty(p.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"socket",{get:function(){return this._socket},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"connections",{get:function(){var g,E,C=Object.create(null);try{for(var T=r(this._connections),S=T.next();!S.done;S=T.next()){var I=s(S.value,2),D=I[0],O=I[1];C[D]=O}}catch(j){g={error:j}}finally{try{S&&!S.done&&(E=T.return)&&E.call(T)}finally{if(g)throw g.error}}return C},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"disconnected",{get:function(){return this._disconnected},enumerable:!1,configurable:!0}),p.prototype._createServerConnection=function(){var g=this,E=new u.Socket(this._options.secure,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval);return E.on(w.SocketEventType.Message,function(C){g._handleMessage(C)}),E.on(w.SocketEventType.Error,function(C){g._abort(w.PeerErrorType.SocketError,C)}),E.on(w.SocketEventType.Disconnected,function(){g.disconnected||(g.emitError(w.PeerErrorType.Network,"Lost connection to server."),g.disconnect())}),E.on(w.SocketEventType.Close,function(){g.disconnected||g._abort(w.PeerErrorType.SocketClosed,"Underlying socket is already closed.")}),E},p.prototype._initialize=function(g){this._id=g,this.socket.start(g,this._options.token)},p.prototype._handleMessage=function(g){var E,C,T=g.type,S=g.payload,I=g.src;switch(T){case w.ServerMessageType.Open:this._lastServerId=this.id,this._open=!0,this.emit(w.PeerEventType.Open,this.id);break;case w.ServerMessageType.Error:this._abort(w.PeerErrorType.ServerError,S.msg);break;case w.ServerMessageType.IdTaken:this._abort(w.PeerErrorType.UnavailableID,'ID "'+this.id+'" is taken');break;case w.ServerMessageType.InvalidKey:this._abort(w.PeerErrorType.InvalidKey,'API KEY "'+this._options.key+'" is invalid');break;case w.ServerMessageType.Leave:l.default.log("Received leave message from "+I),this._cleanupPeer(I),this._connections.delete(I);break;case w.ServerMessageType.Expire:this.emitError(w.PeerErrorType.PeerUnavailable,"Could not connect to peer "+I);break;case w.ServerMessageType.Offer:var D=S.connectionId;if((z=this.getConnection(I,D))&&(z.close(),l.default.warn("Offer received for existing Connection ID:"+D)),S.type===w.ConnectionType.Media)z=new h.MediaConnection(I,this,{connectionId:D,_payload:S,metadata:S.metadata}),this._addConnection(I,z),this.emit(w.PeerEventType.Call,z);else{if(S.type!==w.ConnectionType.Data)return void l.default.warn("Received malformed connection type:"+S.type);z=new b.DataConnection(I,this,{connectionId:D,_payload:S,metadata:S.metadata,label:S.label,serialization:S.serialization,reliable:S.reliable}),this._addConnection(I,z),this.emit(w.PeerEventType.Connection,z)}var O=this._getMessages(D);try{for(var j=r(O),F=j.next();!F.done;F=j.next()){var W=F.value;z.handleMessage(W)}}catch(ne){E={error:ne}}finally{try{F&&!F.done&&(C=j.return)&&C.call(j)}finally{if(E)throw E.error}}break;default:if(!S)return void l.default.warn("You received a malformed message from "+I+" of type "+T);var z;D=S.connectionId,(z=this.getConnection(I,D))&&z.peerConnection?z.handleMessage(g):D?this._storeMessage(D,g):l.default.warn("You received an unrecognized message:",g)}},p.prototype._storeMessage=function(g,E){this._lostMessages.has(g)||this._lostMessages.set(g,[]),this._lostMessages.get(g).push(E)},p.prototype._getMessages=function(g){var E=this._lostMessages.get(g);return E?(this._lostMessages.delete(g),E):[]},p.prototype.connect=function(g,E){if(E===void 0&&(E={}),this.disconnected)return l.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(w.PeerErrorType.Disconnected,"Cannot connect to new Peer after disconnecting from server.");var C=new b.DataConnection(g,this,E);return this._addConnection(g,C),C},p.prototype.call=function(g,E,C){if(C===void 0&&(C={}),this.disconnected)return l.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(w.PeerErrorType.Disconnected,"Cannot connect to new Peer after disconnecting from server.");if(E){C._stream=E;var T=new h.MediaConnection(g,this,C);return this._addConnection(g,T),T}l.default.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.")},p.prototype._addConnection=function(g,E){l.default.log("add connection "+E.type+":"+E.connectionId+" to peerId:"+g),this._connections.has(g)||this._connections.set(g,[]),this._connections.get(g).push(E)},p.prototype._removeConnection=function(g){var E=this._connections.get(g.peer);if(E){var C=E.indexOf(g);C!==-1&&E.splice(C,1)}this._lostMessages.delete(g.connectionId)},p.prototype.getConnection=function(g,E){var C,T,S=this._connections.get(g);if(!S)return null;try{for(var I=r(S),D=I.next();!D.done;D=I.next()){var O=D.value;if(O.connectionId===E)return O}}catch(j){C={error:j}}finally{try{D&&!D.done&&(T=I.return)&&T.call(I)}finally{if(C)throw C.error}}return null},p.prototype._delayedAbort=function(g,E){var C=this;setTimeout(function(){C._abort(g,E)},0)},p.prototype._abort=function(g,E){l.default.error("Aborting!"),this.emitError(g,E),this._lastServerId?this.disconnect():this.destroy()},p.prototype.emitError=function(g,E){var C;l.default.error("Error:",E),(C=typeof E=="string"?new Error(E):E).type=g,this.emit(w.PeerEventType.Error,C)},p.prototype.destroy=function(){this.destroyed||(l.default.log("Destroy peer with ID:"+this.id),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit(w.PeerEventType.Close))},p.prototype._cleanup=function(){var g,E;try{for(var C=r(this._connections.keys()),T=C.next();!T.done;T=C.next()){var S=T.value;this._cleanupPeer(S),this._connections.delete(S)}}catch(I){g={error:I}}finally{try{T&&!T.done&&(E=C.return)&&E.call(C)}finally{if(g)throw g.error}}this.socket.removeAllListeners()},p.prototype._cleanupPeer=function(g){var E,C,T=this._connections.get(g);if(T)try{for(var S=r(T),I=S.next();!I.done;I=S.next())I.value.close()}catch(D){E={error:D}}finally{try{I&&!I.done&&(C=S.return)&&C.call(S)}finally{if(E)throw E.error}}},p.prototype.disconnect=function(){if(!this.disconnected){var g=this.id;l.default.log("Disconnect peer with ID:"+g),this._disconnected=!0,this._open=!1,this.socket.close(),this._lastServerId=g,this._id=null,this.emit(w.PeerEventType.Disconnected,g)}},p.prototype.reconnect=function(){if(this.disconnected&&!this.destroyed)l.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!");l.default.error("In a hurry? We're still trying to make the initial connection!")}},p.prototype.listAllPeers=function(g){var E=this;g===void 0&&(g=function(C){}),this._api.listAllPeers().then(function(C){return g(C)}).catch(function(C){return E._abort(w.PeerErrorType.ServerError,C)})},p.DEFAULT_KEY="peerjs",p}(c.EventEmitter);t.Peer=m},{eventemitter3:"JJlS","./util":"BHXf","./logger":"WOs9","./socket":"wJlv","./mediaconnection":"dbHP","./dataconnection":"GBTQ","./enums":"ZRYf","./api":"in7L"}],iTK6:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.peerjs=void 0;var i=o("./util"),n=o("./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 Xp=Es((ZC,Np)=>{(function(){var o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e={rotl:function(t,i){return t<<i|t>>>32-i},rotr:function(t,i){return t<<32-i|t>>>i},endian:function(t){if(t.constructor==Number)return e.rotl(t,8)&16711935|e.rotl(t,24)&4278255360;for(var i=0;i<t.length;i++)t[i]=e.endian(t[i]);return t},randomBytes:function(t){for(var i=[];t>0;t--)i.push(Math.floor(Math.random()*256));return i},bytesToWords:function(t){for(var i=[],n=0,r=0;n<t.length;n++,r+=8)i[r>>>5]|=t[n]<<24-r%32;return i},wordsToBytes:function(t){for(var i=[],n=0;n<t.length*32;n+=8)i.push(t[n>>>5]>>>24-n%32&255);return i},bytesToHex:function(t){for(var i=[],n=0;n<t.length;n++)i.push((t[n]>>>4).toString(16)),i.push((t[n]&15).toString(16));return i.join("")},hexToBytes:function(t){for(var i=[],n=0;n<t.length;n+=2)i.push(parseInt(t.substr(n,2),16));return i},bytesToBase64:function(t){for(var i=[],n=0;n<t.length;n+=3)for(var r=t[n]<<16|t[n+1]<<8|t[n+2],s=0;s<4;s++)n*8+s*6<=t.length*8?i.push(o.charAt(r>>>6*(3-s)&63)):i.push("=");return i.join("")},base64ToBytes:function(t){t=t.replace(/[^A-Z0-9+\/]/ig,"");for(var i=[],n=0,r=0;n<t.length;r=++n%4)r!=0&&i.push((o.indexOf(t.charAt(n-1))&Math.pow(2,-2*r+8)-1)<<r*2|o.indexOf(t.charAt(n))>>>6-r*2);return i}};Np.exports=e})()});var pd=Es(($C,Qp)=>{var hd={utf8:{stringToBytes:function(o){return hd.bin.stringToBytes(unescape(encodeURIComponent(o)))},bytesToString:function(o){return decodeURIComponent(escape(hd.bin.bytesToString(o)))}},bin:{stringToBytes:function(o){for(var e=[],t=0;t<o.length;t++)e.push(o.charCodeAt(t)&255);return e},bytesToString:function(o){for(var e=[],t=0;t<o.length;t++)e.push(String.fromCharCode(o[t]));return e.join("")}}};Qp.exports=hd});var Kp=Es((eT,Yp)=>{Yp.exports=function(o){return o!=null&&(qp(o)||Ab(o)||!!o._isBuffer)};function qp(o){return!!o.constructor&&typeof o.constructor.isBuffer=="function"&&o.constructor.isBuffer(o)}function Ab(o){return typeof o.readFloatLE=="function"&&typeof o.slice=="function"&&qp(o.slice(0,0))}});var Zp=Es((tT,Jp)=>{(function(){var o=Xp(),e=pd().utf8,t=Kp(),i=pd().bin,n=function(r,s){r.constructor==String?s&&s.encoding==="binary"?r=i.stringToBytes(r):r=e.stringToBytes(r):t(r)?r=Array.prototype.slice.call(r,0):!Array.isArray(r)&&r.constructor!==Uint8Array&&(r=r.toString());for(var a=o.bytesToWords(r),c=r.length*8,d=1732584193,l=-271733879,u=-1732584194,h=271733878,b=0;b<a.length;b++)a[b]=(a[b]<<8|a[b]>>>24)&16711935|(a[b]<<24|a[b]>>>8)&4278255360;a[c>>>5]|=128<<c%32,a[(c+64>>>9<<4)+14]=c;for(var w=n._ff,v=n._gg,x=n._hh,m=n._ii,b=0;b<a.length;b+=16){var f=d,p=l,g=u,E=h;d=w(d,l,u,h,a[b+0],7,-680876936),h=w(h,d,l,u,a[b+1],12,-389564586),u=w(u,h,d,l,a[b+2],17,606105819),l=w(l,u,h,d,a[b+3],22,-1044525330),d=w(d,l,u,h,a[b+4],7,-176418897),h=w(h,d,l,u,a[b+5],12,1200080426),u=w(u,h,d,l,a[b+6],17,-1473231341),l=w(l,u,h,d,a[b+7],22,-45705983),d=w(d,l,u,h,a[b+8],7,1770035416),h=w(h,d,l,u,a[b+9],12,-1958414417),u=w(u,h,d,l,a[b+10],17,-42063),l=w(l,u,h,d,a[b+11],22,-1990404162),d=w(d,l,u,h,a[b+12],7,1804603682),h=w(h,d,l,u,a[b+13],12,-40341101),u=w(u,h,d,l,a[b+14],17,-1502002290),l=w(l,u,h,d,a[b+15],22,1236535329),d=v(d,l,u,h,a[b+1],5,-165796510),h=v(h,d,l,u,a[b+6],9,-1069501632),u=v(u,h,d,l,a[b+11],14,643717713),l=v(l,u,h,d,a[b+0],20,-373897302),d=v(d,l,u,h,a[b+5],5,-701558691),h=v(h,d,l,u,a[b+10],9,38016083),u=v(u,h,d,l,a[b+15],14,-660478335),l=v(l,u,h,d,a[b+4],20,-405537848),d=v(d,l,u,h,a[b+9],5,568446438),h=v(h,d,l,u,a[b+14],9,-1019803690),u=v(u,h,d,l,a[b+3],14,-187363961),l=v(l,u,h,d,a[b+8],20,1163531501),d=v(d,l,u,h,a[b+13],5,-1444681467),h=v(h,d,l,u,a[b+2],9,-51403784),u=v(u,h,d,l,a[b+7],14,1735328473),l=v(l,u,h,d,a[b+12],20,-1926607734),d=x(d,l,u,h,a[b+5],4,-378558),h=x(h,d,l,u,a[b+8],11,-2022574463),u=x(u,h,d,l,a[b+11],16,1839030562),l=x(l,u,h,d,a[b+14],23,-35309556),d=x(d,l,u,h,a[b+1],4,-1530992060),h=x(h,d,l,u,a[b+4],11,1272893353),u=x(u,h,d,l,a[b+7],16,-155497632),l=x(l,u,h,d,a[b+10],23,-1094730640),d=x(d,l,u,h,a[b+13],4,681279174),h=x(h,d,l,u,a[b+0],11,-358537222),u=x(u,h,d,l,a[b+3],16,-722521979),l=x(l,u,h,d,a[b+6],23,76029189),d=x(d,l,u,h,a[b+9],4,-640364487),h=x(h,d,l,u,a[b+12],11,-421815835),u=x(u,h,d,l,a[b+15],16,530742520),l=x(l,u,h,d,a[b+2],23,-995338651),d=m(d,l,u,h,a[b+0],6,-198630844),h=m(h,d,l,u,a[b+7],10,1126891415),u=m(u,h,d,l,a[b+14],15,-1416354905),l=m(l,u,h,d,a[b+5],21,-57434055),d=m(d,l,u,h,a[b+12],6,1700485571),h=m(h,d,l,u,a[b+3],10,-1894986606),u=m(u,h,d,l,a[b+10],15,-1051523),l=m(l,u,h,d,a[b+1],21,-2054922799),d=m(d,l,u,h,a[b+8],6,1873313359),h=m(h,d,l,u,a[b+15],10,-30611744),u=m(u,h,d,l,a[b+6],15,-1560198380),l=m(l,u,h,d,a[b+13],21,1309151649),d=m(d,l,u,h,a[b+4],6,-145523070),h=m(h,d,l,u,a[b+11],10,-1120210379),u=m(u,h,d,l,a[b+2],15,718787259),l=m(l,u,h,d,a[b+9],21,-343485551),d=d+f>>>0,l=l+p>>>0,u=u+g>>>0,h=h+E>>>0}return o.endian([d,l,u,h])};n._ff=function(r,s,a,c,d,l,u){var h=r+(s&a|~s&c)+(d>>>0)+u;return(h<<l|h>>>32-l)+s},n._gg=function(r,s,a,c,d,l,u){var h=r+(s&c|a&~c)+(d>>>0)+u;return(h<<l|h>>>32-l)+s},n._hh=function(r,s,a,c,d,l,u){var h=r+(s^a^c)+(d>>>0)+u;return(h<<l|h>>>32-l)+s},n._ii=function(r,s,a,c,d,l,u){var h=r+(a^(s|~c))+(d>>>0)+u;return(h<<l|h>>>32-l)+s},n._blocksize=16,n._digestsize=16,Jp.exports=function(r,s){if(r==null)throw new Error("Illegal argument "+r);var a=o.wordsToBytes(n(r,s));return s&&s.asBytes?a:s&&s.asString?i.bytesToString(a):o.bytesToHex(a)}})()});var Pc=()=>o=>o;var Ti=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]}},Oc=!1,Rc=[];setTimeout(()=>{Oc&&console.log(Rc)},100);function kc(){return new URLSearchParams(window.location.search)}function M(o){Oc&&!Rc.includes(o)&&Rc.push(o);let e=kc();if(e.has(o)){let t=e.get(o);return t||!0}return!1}Oc=M("help")===!0;function co(o,e,t){o.has(e)?o.set(e,t.toString()):o.append(e,t.toString())}function Hh(o,e){window.history.replaceState(null,o,"?"+e.toString())}function Fh(o,e){return Math.floor(Math.random()*(e-o+1))+o}var Lh=["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"],jh=["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 Bh(){let o=Lh[Math.floor(Math.random()*Lh.length)],e=jh[Math.floor(Math.random()*jh.length)];return o+"_"+e}function Uh(o){return o=o.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),o.trim()}function Fn(o,e,t=!0,i=!1){if(e==null)return null;if(e.userData&&e.userData.guid===o)return e;if(e.guid==o)return e;if(i&&e.userData?.components){for(let n of e.userData.components)if(n.guid===o)return n}if(t){if(e.scenes)for(let n in e.scenes){let r=e.scenes[n],s=Fn(o,r,t,i);if(s)return s}if(e.children)for(let n in e.children){let r=e.children[n],s=Fn(o,r,t,i);if(s)return s}}}function Cs(o,e){if(o!=null&&typeof o=="object"){let t;Array.isArray(o)?t=[]:(t=Object.create(o),Object.assign(t,o));for(let i of Object.keys(o)){let n=o[i];e&&!e(o,i,n)?t[i]=n:n?.clone!==void 0&&typeof n.clone=="function"?t[i]=n.clone():t[i]=Cs(n,e)}return t}return o}function Gh(o){return new Promise((e,t)=>{setTimeout(e,o)})}var Tc=M("debugsourcepath");function Ri(o,e){if(o===void 0)return Tc&&console.warn("getPath: source is undefined, returning uri",e),e;if(e.startsWith("http"))return Tc&&console.warn("getPath: uri is absolute, returning uri",e),e;let t=o.lastIndexOf("/");if(t>=0){let i=o.substring(0,t+1),n=e.lastIndexOf("/");return n>=0?i+=e.substring(n+1):i+=e,Tc&&console.log("getPath:",o,` - changed uri from
78
+ isUnifiedPlanSupported:`+this.isUnifiedPlanSupported()},n}())},{"./adapter":"sXtV"}],BHXf:[function(o,e,t){"use strict";var i=this&&this.__createBinding||(Object.create?function(d,l,u,h){h===void 0&&(h=u),Object.defineProperty(d,h,{enumerable:!0,get:function(){return l[u]}})}:function(d,l,u,h){h===void 0&&(h=u),d[h]=l[u]}),n=this&&this.__setModuleDefault||(Object.create?function(d,l){Object.defineProperty(d,"default",{enumerable:!0,value:l})}:function(d,l){d.default=l}),r=this&&this.__importStar||function(d){if(d&&d.__esModule)return d;var l={};if(d!=null)for(var u in d)u!=="default"&&Object.prototype.hasOwnProperty.call(d,u)&&i(l,d,u);return n(l,d),l};Object.defineProperty(t,"__esModule",{value:!0}),t.util=void 0;var s=r(o("peerjs-js-binarypack")),a=o("./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=a.Supports.getBrowser(),this.browserVersion=a.Supports.getVersion(),this.supports=function(){var l,u={browser:a.Supports.isBrowserSupported(),webRTC:a.Supports.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!u.webRTC)return u;try{l=new RTCPeerConnection(c),u.audioVideo=!0;var h=void 0;try{h=l.createDataChannel("_PEERJSTEST",{ordered:!0}),u.data=!0,u.reliable=!!h.ordered;try{h.binaryType="blob",u.binaryBlob=!a.Supports.isIOS}catch{}}catch{}finally{h&&h.close()}}catch{}finally{l&&l.close()}return u}(),this.pack=s.pack,this.unpack=s.unpack,this._dataCount=1}return d.prototype.noop=function(){},d.prototype.validateId=function(l){return!l||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(l)},d.prototype.chunk=function(l){for(var u=[],h=l.size,b=Math.ceil(h/t.util.chunkedMTU),w=0,v=0;v<h;){var x=Math.min(h,v+t.util.chunkedMTU),m=l.slice(v,x),f={__peerData:this._dataCount,n:w,data:m,total:b};u.push(f),v=x,w++}return this._dataCount++,u},d.prototype.blobToArrayBuffer=function(l,u){var h=new FileReader;return h.onload=function(b){b.target&&u(b.target.result)},h.readAsArrayBuffer(l),h},d.prototype.binaryStringToArrayBuffer=function(l){for(var u=new Uint8Array(l.length),h=0;h<l.length;h++)u[h]=255&l.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(o,e,t){"use strict";var i=Object.prototype.hasOwnProperty,n="~";function r(){}function s(l,u,h){this.fn=l,this.context=u,this.once=h||!1}function a(l,u,h,b,w){if(typeof h!="function")throw new TypeError("The listener must be a function");var v=new s(h,b||l,w),x=n?n+u:u;return l._events[x]?l._events[x].fn?l._events[x]=[l._events[x],v]:l._events[x].push(v):(l._events[x]=v,l._eventsCount++),l}function c(l,u){--l._eventsCount==0?l._events=new r:delete l._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 l,u,h=[];if(this._eventsCount===0)return h;for(u in l=this._events)i.call(l,u)&&h.push(n?u.slice(1):u);return Object.getOwnPropertySymbols?h.concat(Object.getOwnPropertySymbols(l)):h},d.prototype.listeners=function(l){var u=n?n+l:l,h=this._events[u];if(!h)return[];if(h.fn)return[h.fn];for(var b=0,w=h.length,v=new Array(w);b<w;b++)v[b]=h[b].fn;return v},d.prototype.listenerCount=function(l){var u=n?n+l:l,h=this._events[u];return h?h.fn?1:h.length:0},d.prototype.emit=function(l,u,h,b,w,v){var x=n?n+l:l;if(!this._events[x])return!1;var m,f,p=this._events[x],g=arguments.length;if(p.fn){switch(p.once&&this.removeListener(l,p.fn,void 0,!0),g){case 1:return p.fn.call(p.context),!0;case 2:return p.fn.call(p.context,u),!0;case 3:return p.fn.call(p.context,u,h),!0;case 4:return p.fn.call(p.context,u,h,b),!0;case 5:return p.fn.call(p.context,u,h,b,w),!0;case 6:return p.fn.call(p.context,u,h,b,w,v),!0}for(f=1,m=new Array(g-1);f<g;f++)m[f-1]=arguments[f];p.fn.apply(p.context,m)}else{var E,C=p.length;for(f=0;f<C;f++)switch(p[f].once&&this.removeListener(l,p[f].fn,void 0,!0),g){case 1:p[f].fn.call(p[f].context);break;case 2:p[f].fn.call(p[f].context,u);break;case 3:p[f].fn.call(p[f].context,u,h);break;case 4:p[f].fn.call(p[f].context,u,h,b);break;default:if(!m)for(E=1,m=new Array(g-1);E<g;E++)m[E-1]=arguments[E];p[f].fn.apply(p[f].context,m)}}return!0},d.prototype.on=function(l,u,h){return a(this,l,u,h,!1)},d.prototype.once=function(l,u,h){return a(this,l,u,h,!0)},d.prototype.removeListener=function(l,u,h,b){var w=n?n+l:l;if(!this._events[w])return this;if(!u)return c(this,w),this;var v=this._events[w];if(v.fn)v.fn!==u||b&&!v.once||h&&v.context!==h||c(this,w);else{for(var x=0,m=[],f=v.length;x<f;x++)(v[x].fn!==u||b&&!v[x].once||h&&v[x].context!==h)&&m.push(v[x]);m.length?this._events[w]=m.length===1?m[0]:m:c(this,w)}return this},d.prototype.removeAllListeners=function(l){var u;return l?(u=n?n+l:l,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(o,e,t){"use strict";var i=this&&this.__read||function(c,d){var l=typeof Symbol=="function"&&c[Symbol.iterator];if(!l)return c;var u,h,b=l.call(c),w=[];try{for(;(d===void 0||d-- >0)&&!(u=b.next()).done;)w.push(u.value)}catch(v){h={error:v}}finally{try{u&&!u.done&&(l=b.return)&&l.call(b)}finally{if(h)throw h.error}}return w},n=this&&this.__spreadArray||function(c,d){for(var l=0,u=d.length,h=c.length;l<u;l++,h++)c[h]=d[l];return c};Object.defineProperty(t,"__esModule",{value:!0}),t.LogLevel=void 0;var r,s="PeerJS: ";(function(c){c[c.Disabled=0]="Disabled",c[c.Errors=1]="Errors",c[c.Warnings=2]="Warnings",c[c.All=3]="All"})(r=t.LogLevel||(t.LogLevel={}));var a=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=[],l=0;l<arguments.length;l++)d[l]=arguments[l];this._logLevel>=r.All&&this._print.apply(this,n([r.All],i(d)))},c.prototype.warn=function(){for(var d=[],l=0;l<arguments.length;l++)d[l]=arguments[l];this._logLevel>=r.Warnings&&this._print.apply(this,n([r.Warnings],i(d)))},c.prototype.error=function(){for(var d=[],l=0;l<arguments.length;l++)d[l]=arguments[l];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 l=[],u=1;u<arguments.length;u++)l[u-1]=arguments[u];var h=n([s],i(l));for(var b in h)h[b]instanceof Error&&(h[b]="("+h[b].name+") "+h[b].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 a},{}],ZRYf:[function(o,e,t){"use strict";var i,n,r,s,a,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(l){l.Open="open",l.Stream="stream",l.Data="data",l.Close="close",l.Error="error",l.IceStateChanged="iceStateChanged"}(i=t.ConnectionEventType||(t.ConnectionEventType={})),function(l){l.Data="data",l.Media="media"}(n=t.ConnectionType||(t.ConnectionType={})),function(l){l.Open="open",l.Close="close",l.Connection="connection",l.Call="call",l.Disconnected="disconnected",l.Error="error"}(r=t.PeerEventType||(t.PeerEventType={})),function(l){l.BrowserIncompatible="browser-incompatible",l.Disconnected="disconnected",l.InvalidID="invalid-id",l.InvalidKey="invalid-key",l.Network="network",l.PeerUnavailable="peer-unavailable",l.SslUnavailable="ssl-unavailable",l.ServerError="server-error",l.SocketError="socket-error",l.SocketClosed="socket-closed",l.UnavailableID="unavailable-id",l.WebRTC="webrtc"}(s=t.PeerErrorType||(t.PeerErrorType={})),function(l){l.Binary="binary",l.BinaryUTF8="binary-utf8",l.JSON="json"}(a=t.SerializationType||(t.SerializationType={})),function(l){l.Message="message",l.Disconnected="disconnected",l.Error="error",l.Close="close"}(c=t.SocketEventType||(t.SocketEventType={})),function(l){l.Heartbeat="HEARTBEAT",l.Candidate="CANDIDATE",l.Offer="OFFER",l.Answer="ANSWER",l.Open="OPEN",l.Error="ERROR",l.IdTaken="ID-TAKEN",l.InvalidKey="INVALID-KEY",l.Leave="LEAVE",l.Expire="EXPIRE"}(d=t.ServerMessageType||(t.ServerMessageType={}))},{}],wJlv:[function(o,e,t){"use strict";var i=this&&this.__extends||function(){var h=function(b,w){return(h=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(v,x){v.__proto__=x}||function(v,x){for(var m in x)Object.prototype.hasOwnProperty.call(x,m)&&(v[m]=x[m])})(b,w)};return function(b,w){if(typeof w!="function"&&w!==null)throw new TypeError("Class extends value "+String(w)+" is not a constructor or null");function v(){this.constructor=b}h(b,w),b.prototype=w===null?Object.create(w):(v.prototype=w.prototype,new v)}}(),n=this&&this.__read||function(h,b){var w=typeof Symbol=="function"&&h[Symbol.iterator];if(!w)return h;var v,x,m=w.call(h),f=[];try{for(;(b===void 0||b-- >0)&&!(v=m.next()).done;)f.push(v.value)}catch(p){x={error:p}}finally{try{v&&!v.done&&(w=m.return)&&w.call(m)}finally{if(x)throw x.error}}return f},r=this&&this.__spreadArray||function(h,b){for(var w=0,v=b.length,x=h.length;w<v;w++,x++)h[x]=b[w];return h},s=this&&this.__values||function(h){var b=typeof Symbol=="function"&&Symbol.iterator,w=b&&h[b],v=0;if(w)return w.call(h);if(h&&typeof h.length=="number")return{next:function(){return h&&v>=h.length&&(h=void 0),{value:h&&h[v++],done:!h}}};throw new TypeError(b?"Object is not iterable.":"Symbol.iterator is not defined.")},a=this&&this.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(t,"__esModule",{value:!0}),t.Socket=void 0;var c=o("eventemitter3"),d=a(o("./logger")),l=o("./enums"),u=function(h){function b(w,v,x,m,f,p){p===void 0&&(p=5e3);var g=h.call(this)||this;g.pingInterval=p,g._disconnected=!0,g._messagesQueue=[];var E=w?"wss://":"ws://";return g._baseUrl=E+v+":"+x+m+"peerjs?key="+f,g}return i(b,h),b.prototype.start=function(w,v){var x=this;this._id=w;var m=this._baseUrl+"&id="+w+"&token="+v;!this._socket&&this._disconnected&&(this._socket=new WebSocket(m),this._disconnected=!1,this._socket.onmessage=function(f){var p;try{p=JSON.parse(f.data),d.default.log("Server message received:",p)}catch{return void d.default.log("Invalid server message",f.data)}x.emit(l.SocketEventType.Message,p)},this._socket.onclose=function(f){x._disconnected||(d.default.log("Socket closed.",f),x._cleanup(),x._disconnected=!0,x.emit(l.SocketEventType.Disconnected))},this._socket.onopen=function(){x._disconnected||(x._sendQueuedMessages(),d.default.log("Socket open"),x._scheduleHeartbeat())})},b.prototype._scheduleHeartbeat=function(){var w=this;this._wsPingTimer=setTimeout(function(){w._sendHeartbeat()},this.pingInterval)},b.prototype._sendHeartbeat=function(){if(this._wsOpen()){var w=JSON.stringify({type:l.ServerMessageType.Heartbeat});this._socket.send(w),this._scheduleHeartbeat()}else d.default.log("Cannot send heartbeat, because socket closed")},b.prototype._wsOpen=function(){return!!this._socket&&this._socket.readyState===1},b.prototype._sendQueuedMessages=function(){var w,v,x=r([],n(this._messagesQueue));this._messagesQueue=[];try{for(var m=s(x),f=m.next();!f.done;f=m.next()){var p=f.value;this.send(p)}}catch(g){w={error:g}}finally{try{f&&!f.done&&(v=m.return)&&v.call(m)}finally{if(w)throw w.error}}},b.prototype.send=function(w){if(!this._disconnected)if(this._id)if(w.type){if(this._wsOpen()){var v=JSON.stringify(w);this._socket.send(v)}}else this.emit(l.SocketEventType.Error,"Invalid message");else this._messagesQueue.push(w)},b.prototype.close=function(){this._disconnected||(this._cleanup(),this._disconnected=!0)},b.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)},b}(c.EventEmitter);t.Socket=u},{eventemitter3:"JJlS","./logger":"WOs9","./enums":"ZRYf"}],HCdX:[function(o,e,t){"use strict";var i=this&&this.__assign||function(){return(i=Object.assign||function(u){for(var h,b=1,w=arguments.length;b<w;b++)for(var v in h=arguments[b])Object.prototype.hasOwnProperty.call(h,v)&&(u[v]=h[v]);return u}).apply(this,arguments)},n=this&&this.__awaiter||function(u,h,b,w){return new(b||(b=Promise))(function(v,x){function m(g){try{p(w.next(g))}catch(E){x(E)}}function f(g){try{p(w.throw(g))}catch(E){x(E)}}function p(g){var E;g.done?v(g.value):(E=g.value,E instanceof b?E:new b(function(C){C(E)})).then(m,f)}p((w=w.apply(u,h||[])).next())})},r=this&&this.__generator||function(u,h){var b,w,v,x,m={label:0,sent:function(){if(1&v[0])throw v[1];return v[1]},trys:[],ops:[]};return x={next:f(0),throw:f(1),return:f(2)},typeof Symbol=="function"&&(x[Symbol.iterator]=function(){return this}),x;function f(p){return function(g){return function(E){if(b)throw new TypeError("Generator is already executing.");for(;m;)try{if(b=1,w&&(v=2&E[0]?w.return:E[0]?w.throw||((v=w.return)&&v.call(w),0):w.next)&&!(v=v.call(w,E[1])).done)return v;switch(w=0,v&&(E=[2&E[0],v.value]),E[0]){case 0:case 1:v=E;break;case 4:return m.label++,{value:E[1],done:!1};case 5:m.label++,w=E[1],E=[0];continue;case 7:E=m.ops.pop(),m.trys.pop();continue;default:if(!(v=(v=m.trys).length>0&&v[v.length-1])&&(E[0]===6||E[0]===2)){m=0;continue}if(E[0]===3&&(!v||E[1]>v[0]&&E[1]<v[3])){m.label=E[1];break}if(E[0]===6&&m.label<v[1]){m.label=v[1],v=E;break}if(v&&m.label<v[2]){m.label=v[2],m.ops.push(E);break}v[2]&&m.ops.pop(),m.trys.pop();continue}E=h.call(u,m)}catch(C){E=[6,C],w=0}finally{b=v=0}if(5&E[0])throw E[1];return{value:E[0]?E[1]:void 0,done:!0}}([p,g])}}},s=this&&this.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(t,"__esModule",{value:!0}),t.Negotiator=void 0;var a=o("./util"),c=s(o("./logger")),d=o("./enums"),l=function(){function u(h){this.connection=h}return u.prototype.startConnection=function(h){var b=this._startPeerConnection();if(this.connection.peerConnection=b,this.connection.type===d.ConnectionType.Media&&h._stream&&this._addTracksToConnection(h._stream,b),h.originator){if(this.connection.type===d.ConnectionType.Data){var w=this.connection,v={ordered:!!h.reliable},x=b.createDataChannel(w.label,v);w.initialize(x)}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 b=this,w=this.connection.peer,v=this.connection.connectionId,x=this.connection.type,m=this.connection.provider;c.default.log("Listening for ICE candidates."),h.onicecandidate=function(f){f.candidate&&f.candidate.candidate&&(c.default.log("Received ICE candidates for "+w+":",f.candidate),m.socket.send({type:d.ServerMessageType.Candidate,payload:{candidate:f.candidate,type:x,connectionId:v},dst:w}))},h.oniceconnectionstatechange=function(){switch(h.iceConnectionState){case"failed":c.default.log("iceConnectionState is failed, closing connections to "+w),b.connection.emit(d.ConnectionEventType.Error,new Error("Negotiation of connection to "+w+" failed.")),b.connection.close();break;case"closed":c.default.log("iceConnectionState is closed, closing connections to "+w),b.connection.emit(d.ConnectionEventType.Error,new Error("Connection to "+w+" closed.")),b.connection.close();break;case"disconnected":c.default.log("iceConnectionState changed to disconnected on the connection with "+w);break;case"completed":h.onicecandidate=a.util.noop}b.connection.emit(d.ConnectionEventType.IceStateChanged,h.iceConnectionState)},c.default.log("Listening for data channel"),h.ondatachannel=function(f){c.default.log("Received data channel");var p=f.channel;m.getConnection(w,v).initialize(p)},c.default.log("Listening for remote stream"),h.ontrack=function(f){c.default.log("Received remote stream");var p=f.streams[0],g=m.getConnection(w,v);if(g.type===d.ConnectionType.Media){var E=g;b._addStreamToMediaConnection(p,E)}}},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 b=h.signalingState!=="closed",w=!1;if(this.connection.type===d.ConnectionType.Data){var v=this.connection.dataChannel;v&&(w=!!v.readyState&&v.readyState!=="closed")}(b||w)&&h.close()}},u.prototype._makeOffer=function(){return n(this,void 0,Promise,function(){var h,b,w,v,x,m,f;return r(this,function(p){switch(p.label){case 0:h=this.connection.peerConnection,b=this.connection.provider,p.label=1;case 1:return p.trys.push([1,7,,8]),[4,h.createOffer(this.connection.options.constraints)];case 2:w=p.sent(),c.default.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(w.sdp=this.connection.options.sdpTransform(w.sdp)||w.sdp),p.label=3;case 3:return p.trys.push([3,5,,6]),[4,h.setLocalDescription(w)];case 4:return p.sent(),c.default.log("Set localDescription:",w,"for:"+this.connection.peer),v={sdp:w,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata,browser:a.util.browser},this.connection.type===d.ConnectionType.Data&&(x=this.connection,v=i(i({},v),{label:x.label,reliable:x.reliable,serialization:x.serialization})),b.socket.send({type:d.ServerMessageType.Offer,payload:v,dst:this.connection.peer}),[3,6];case 5:return(m=p.sent())!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(b.emitError(d.PeerErrorType.WebRTC,m),c.default.log("Failed to setLocalDescription, ",m)),[3,6];case 6:return[3,8];case 7:return f=p.sent(),b.emitError(d.PeerErrorType.WebRTC,f),c.default.log("Failed to createOffer, ",f),[3,8];case 8:return[2]}})})},u.prototype._makeAnswer=function(){return n(this,void 0,Promise,function(){var h,b,w,v,x;return r(this,function(m){switch(m.label){case 0:h=this.connection.peerConnection,b=this.connection.provider,m.label=1;case 1:return m.trys.push([1,7,,8]),[4,h.createAnswer()];case 2:w=m.sent(),c.default.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(w.sdp=this.connection.options.sdpTransform(w.sdp)||w.sdp),m.label=3;case 3:return m.trys.push([3,5,,6]),[4,h.setLocalDescription(w)];case 4:return m.sent(),c.default.log("Set localDescription:",w,"for:"+this.connection.peer),b.socket.send({type:d.ServerMessageType.Answer,payload:{sdp:w,type:this.connection.type,connectionId:this.connection.connectionId,browser:a.util.browser},dst:this.connection.peer}),[3,6];case 5:return v=m.sent(),b.emitError(d.PeerErrorType.WebRTC,v),c.default.log("Failed to setLocalDescription, ",v),[3,6];case 6:return[3,8];case 7:return x=m.sent(),b.emitError(d.PeerErrorType.WebRTC,x),c.default.log("Failed to create answer, ",x),[3,8];case 8:return[2]}})})},u.prototype.handleSDP=function(h,b){return n(this,void 0,Promise,function(){var w,v,x,m;return r(this,function(f){switch(f.label){case 0:b=new RTCSessionDescription(b),w=this.connection.peerConnection,v=this.connection.provider,c.default.log("Setting remote description",b),x=this,f.label=1;case 1:return f.trys.push([1,5,,6]),[4,w.setRemoteDescription(b)];case 2:return f.sent(),c.default.log("Set remoteDescription:"+h+" for:"+this.connection.peer),h!=="OFFER"?[3,4]:[4,x._makeAnswer()];case 3:f.sent(),f.label=4;case 4:return[3,6];case 5:return m=f.sent(),v.emitError(d.PeerErrorType.WebRTC,m),c.default.log("Failed to setRemoteDescription, ",m),[3,6];case 6:return[2]}})})},u.prototype.handleCandidate=function(h){return n(this,void 0,Promise,function(){var b,w,v,x,m,f;return r(this,function(p){switch(p.label){case 0:c.default.log("handleCandidate:",h),b=h.candidate,w=h.sdpMLineIndex,v=h.sdpMid,x=this.connection.peerConnection,m=this.connection.provider,p.label=1;case 1:return p.trys.push([1,3,,4]),[4,x.addIceCandidate(new RTCIceCandidate({sdpMid:v,sdpMLineIndex:w,candidate:b}))];case 2:return p.sent(),c.default.log("Added ICE candidate for:"+this.connection.peer),[3,4];case 3:return f=p.sent(),m.emitError(d.PeerErrorType.WebRTC,f),c.default.log("Failed to handleCandidate, ",f),[3,4];case 4:return[2]}})})},u.prototype._addTracksToConnection=function(h,b){if(c.default.log("add tracks from stream "+h.id+" to peer connection"),!b.addTrack)return c.default.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");h.getTracks().forEach(function(w){b.addTrack(w,h)})},u.prototype._addStreamToMediaConnection=function(h,b){c.default.log("add stream "+h.id+" to media connection "+b.connectionId),b.addStream(h)},u}();t.Negotiator=l},{"./util":"BHXf","./logger":"WOs9","./enums":"ZRYf"}],tQFK:[function(o,e,t){"use strict";var i=this&&this.__extends||function(){var s=function(a,c){return(s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,l){d.__proto__=l}||function(d,l){for(var u in l)Object.prototype.hasOwnProperty.call(l,u)&&(d[u]=l[u])})(a,c)};return function(a,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=a}s(a,c),a.prototype=c===null?Object.create(c):(d.prototype=c.prototype,new d)}}();Object.defineProperty(t,"__esModule",{value:!0}),t.BaseConnection=void 0;var n=o("eventemitter3"),r=function(s){function a(c,d,l){var u=s.call(this)||this;return u.peer=c,u.provider=d,u.options=l,u._open=!1,u.metadata=l.metadata,u}return i(a,s),Object.defineProperty(a.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),a}(n.EventEmitter);t.BaseConnection=r},{eventemitter3:"JJlS"}],dbHP:[function(o,e,t){"use strict";var i=this&&this.__extends||function(){var b=function(w,v){return(b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(x,m){x.__proto__=m}||function(x,m){for(var f in m)Object.prototype.hasOwnProperty.call(m,f)&&(x[f]=m[f])})(w,v)};return function(w,v){if(typeof v!="function"&&v!==null)throw new TypeError("Class extends value "+String(v)+" is not a constructor or null");function x(){this.constructor=w}b(w,v),w.prototype=v===null?Object.create(v):(x.prototype=v.prototype,new x)}}(),n=this&&this.__assign||function(){return(n=Object.assign||function(b){for(var w,v=1,x=arguments.length;v<x;v++)for(var m in w=arguments[v])Object.prototype.hasOwnProperty.call(w,m)&&(b[m]=w[m]);return b}).apply(this,arguments)},r=this&&this.__values||function(b){var w=typeof Symbol=="function"&&Symbol.iterator,v=w&&b[w],x=0;if(v)return v.call(b);if(b&&typeof b.length=="number")return{next:function(){return b&&x>=b.length&&(b=void 0),{value:b&&b[x++],done:!b}}};throw new TypeError(w?"Object is not iterable.":"Symbol.iterator is not defined.")},s=this&&this.__importDefault||function(b){return b&&b.__esModule?b:{default:b}};Object.defineProperty(t,"__esModule",{value:!0}),t.MediaConnection=void 0;var a=o("./util"),c=s(o("./logger")),d=o("./negotiator"),l=o("./enums"),u=o("./baseconnection"),h=function(b){function w(v,x,m){var f=b.call(this,v,x,m)||this;return f._localStream=f.options._stream,f.connectionId=f.options.connectionId||w.ID_PREFIX+a.util.randomToken(),f._negotiator=new d.Negotiator(f),f._localStream&&f._negotiator.startConnection({_stream:f._localStream,originator:!0}),f}return i(w,b),Object.defineProperty(w.prototype,"type",{get:function(){return l.ConnectionType.Media},enumerable:!1,configurable:!0}),Object.defineProperty(w.prototype,"localStream",{get:function(){return this._localStream},enumerable:!1,configurable:!0}),Object.defineProperty(w.prototype,"remoteStream",{get:function(){return this._remoteStream},enumerable:!1,configurable:!0}),w.prototype.addStream=function(v){c.default.log("Receiving stream",v),this._remoteStream=v,b.prototype.emit.call(this,l.ConnectionEventType.Stream,v)},w.prototype.handleMessage=function(v){var x=v.type,m=v.payload;switch(v.type){case l.ServerMessageType.Answer:this._negotiator.handleSDP(x,m.sdp),this._open=!0;break;case l.ServerMessageType.Candidate:this._negotiator.handleCandidate(m.candidate);break;default:c.default.warn("Unrecognized message type:"+x+" from peer:"+this.peer)}},w.prototype.answer=function(v,x){var m,f;if(x===void 0&&(x={}),this._localStream)c.default.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");else{this._localStream=v,x&&x.sdpTransform&&(this.options.sdpTransform=x.sdpTransform),this._negotiator.startConnection(n(n({},this.options._payload),{_stream:v}));var p=this.provider._getMessages(this.connectionId);try{for(var g=r(p),E=g.next();!E.done;E=g.next()){var C=E.value;this.handleMessage(C)}}catch(T){m={error:T}}finally{try{E&&!E.done&&(f=g.return)&&f.call(g)}finally{if(m)throw m.error}}this._open=!0}},w.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,b.prototype.emit.call(this,l.ConnectionEventType.Close))},w.ID_PREFIX="mc_",w}(u.BaseConnection);t.MediaConnection=h},{"./util":"BHXf","./logger":"WOs9","./negotiator":"HCdX","./enums":"ZRYf","./baseconnection":"tQFK"}],GGp6:[function(o,e,t){"use strict";var i=this&&this.__extends||function(){var c=function(d,l){return(c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(u,h){u.__proto__=h}||function(u,h){for(var b in h)Object.prototype.hasOwnProperty.call(h,b)&&(u[b]=h[b])})(d,l)};return function(d,l){if(typeof l!="function"&&l!==null)throw new TypeError("Class extends value "+String(l)+" is not a constructor or null");function u(){this.constructor=d}c(d,l),d.prototype=l===null?Object.create(l):(u.prototype=l.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=o("eventemitter3"),s=n(o("./logger")),a=function(c){function d(){var l=c.call(this)||this;return l.fileReader=new FileReader,l._queue=[],l._processing=!1,l.fileReader.onload=function(u){l._processing=!1,u.target&&l.emit("done",u.target.result),l.doNextTask()},l.fileReader.onerror=function(u){s.default.error("EncodingQueue error:",u),l._processing=!1,l.destroy(),l.emit("error",u)},l}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(l){this.queue.push(l),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=a},{eventemitter3:"JJlS","./logger":"WOs9"}],GBTQ:[function(o,e,t){"use strict";var i=this&&this.__extends||function(){var b=function(w,v){return(b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(x,m){x.__proto__=m}||function(x,m){for(var f in m)Object.prototype.hasOwnProperty.call(m,f)&&(x[f]=m[f])})(w,v)};return function(w,v){if(typeof v!="function"&&v!==null)throw new TypeError("Class extends value "+String(v)+" is not a constructor or null");function x(){this.constructor=w}b(w,v),w.prototype=v===null?Object.create(v):(x.prototype=v.prototype,new x)}}(),n=this&&this.__values||function(b){var w=typeof Symbol=="function"&&Symbol.iterator,v=w&&b[w],x=0;if(v)return v.call(b);if(b&&typeof b.length=="number")return{next:function(){return b&&x>=b.length&&(b=void 0),{value:b&&b[x++],done:!b}}};throw new TypeError(w?"Object is not iterable.":"Symbol.iterator is not defined.")},r=this&&this.__importDefault||function(b){return b&&b.__esModule?b:{default:b}};Object.defineProperty(t,"__esModule",{value:!0}),t.DataConnection=void 0;var s=o("./util"),a=r(o("./logger")),c=o("./negotiator"),d=o("./enums"),l=o("./baseconnection"),u=o("./encodingQueue"),h=function(b){function w(v,x,m){var f=b.call(this,v,x,m)||this;return f.stringify=JSON.stringify,f.parse=JSON.parse,f._buffer=[],f._bufferSize=0,f._buffering=!1,f._chunkedData={},f._encodingQueue=new u.EncodingQueue,f.connectionId=f.options.connectionId||w.ID_PREFIX+s.util.randomToken(),f.label=f.options.label||f.connectionId,f.serialization=f.options.serialization||d.SerializationType.Binary,f.reliable=!!f.options.reliable,f._encodingQueue.on("done",function(p){f._bufferedSend(p)}),f._encodingQueue.on("error",function(){a.default.error("DC#"+f.connectionId+": Error occured in encoding from blob to arraybuffer, close DC"),f.close()}),f._negotiator=new c.Negotiator(f),f._negotiator.startConnection(f.options._payload||{originator:!0}),f}return i(w,b),Object.defineProperty(w.prototype,"type",{get:function(){return d.ConnectionType.Data},enumerable:!1,configurable:!0}),Object.defineProperty(w.prototype,"dataChannel",{get:function(){return this._dc},enumerable:!1,configurable:!0}),Object.defineProperty(w.prototype,"bufferSize",{get:function(){return this._bufferSize},enumerable:!1,configurable:!0}),w.prototype.initialize=function(v){this._dc=v,this._configureDataChannel()},w.prototype._configureDataChannel=function(){var v=this;s.util.supports.binaryBlob&&!s.util.supports.reliable||(this.dataChannel.binaryType="arraybuffer"),this.dataChannel.onopen=function(){a.default.log("DC#"+v.connectionId+" dc connection success"),v._open=!0,v.emit(d.ConnectionEventType.Open)},this.dataChannel.onmessage=function(x){a.default.log("DC#"+v.connectionId+" dc onmessage:",x.data),v._handleDataMessage(x)},this.dataChannel.onclose=function(){a.default.log("DC#"+v.connectionId+" dc closed for:",v.peer),v.close()}},w.prototype._handleDataMessage=function(v){var x=this,m=v.data,f=m.constructor,p=m;if(this.serialization===d.SerializationType.Binary||this.serialization===d.SerializationType.BinaryUTF8){if(f===Blob)return void s.util.blobToArrayBuffer(m,function(E){var C=s.util.unpack(E);x.emit(d.ConnectionEventType.Data,C)});if(f===ArrayBuffer)p=s.util.unpack(m);else if(f===String){var g=s.util.binaryStringToArrayBuffer(m);p=s.util.unpack(g)}}else this.serialization===d.SerializationType.JSON&&(p=this.parse(m));p.__peerData?this._handleChunk(p):b.prototype.emit.call(this,d.ConnectionEventType.Data,p)},w.prototype._handleChunk=function(v){var x=v.__peerData,m=this._chunkedData[x]||{data:[],count:0,total:v.total};if(m.data[v.n]=v.data,m.count++,this._chunkedData[x]=m,m.total===m.count){delete this._chunkedData[x];var f=new Blob(m.data);this._handleDataMessage({data:f})}},w.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,b.prototype.emit.call(this,d.ConnectionEventType.Close))},w.prototype.send=function(v,x){if(this.open)if(this.serialization===d.SerializationType.JSON)this._bufferedSend(this.stringify(v));else if(this.serialization===d.SerializationType.Binary||this.serialization===d.SerializationType.BinaryUTF8){var m=s.util.pack(v);if(!x&&m.size>s.util.chunkedMTU)return void this._sendChunks(m);s.util.supports.binaryBlob?this._bufferedSend(m):this._encodingQueue.enque(m)}else this._bufferedSend(v);else b.prototype.emit.call(this,d.ConnectionEventType.Error,new Error("Connection is not open. You should listen for the `open` event before sending messages."))},w.prototype._bufferedSend=function(v){!this._buffering&&this._trySend(v)||(this._buffer.push(v),this._bufferSize=this._buffer.length)},w.prototype._trySend=function(v){var x=this;if(!this.open)return!1;if(this.dataChannel.bufferedAmount>w.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(function(){x._buffering=!1,x._tryBuffer()},50),!1;try{this.dataChannel.send(v)}catch(m){return a.default.error("DC#:"+this.connectionId+" Error when sending:",m),this._buffering=!0,this.close(),!1}return!0},w.prototype._tryBuffer=function(){if(this.open&&this._buffer.length!==0){var v=this._buffer[0];this._trySend(v)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}},w.prototype._sendChunks=function(v){var x,m,f=s.util.chunk(v);a.default.log("DC#"+this.connectionId+" Try to send "+f.length+" chunks...");try{for(var p=n(f),g=p.next();!g.done;g=p.next()){var E=g.value;this.send(E,!0)}}catch(C){x={error:C}}finally{try{g&&!g.done&&(m=p.return)&&m.call(p)}finally{if(x)throw x.error}}},w.prototype.handleMessage=function(v){var x=v.payload;switch(v.type){case d.ServerMessageType.Answer:this._negotiator.handleSDP(v.type,x.sdp);break;case d.ServerMessageType.Candidate:this._negotiator.handleCandidate(x.candidate);break;default:a.default.warn("Unrecognized message type:",v.type,"from peer:",this.peer)}},w.ID_PREFIX="dc_",w.MAX_BUFFERED_AMOUNT=8388608,w}(l.BaseConnection);t.DataConnection=h},{"./util":"BHXf","./logger":"WOs9","./negotiator":"HCdX","./enums":"ZRYf","./baseconnection":"tQFK","./encodingQueue":"GGp6"}],in7L:[function(o,e,t){"use strict";var i=this&&this.__awaiter||function(d,l,u,h){return new(u||(u=Promise))(function(b,w){function v(f){try{m(h.next(f))}catch(p){w(p)}}function x(f){try{m(h.throw(f))}catch(p){w(p)}}function m(f){var p;f.done?b(f.value):(p=f.value,p instanceof u?p:new u(function(g){g(p)})).then(v,x)}m((h=h.apply(d,l||[])).next())})},n=this&&this.__generator||function(d,l){var u,h,b,w,v={label:0,sent:function(){if(1&b[0])throw b[1];return b[1]},trys:[],ops:[]};return w={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(w[Symbol.iterator]=function(){return this}),w;function x(m){return function(f){return function(p){if(u)throw new TypeError("Generator is already executing.");for(;v;)try{if(u=1,h&&(b=2&p[0]?h.return:p[0]?h.throw||((b=h.return)&&b.call(h),0):h.next)&&!(b=b.call(h,p[1])).done)return b;switch(h=0,b&&(p=[2&p[0],b.value]),p[0]){case 0:case 1:b=p;break;case 4:return v.label++,{value:p[1],done:!1};case 5:v.label++,h=p[1],p=[0];continue;case 7:p=v.ops.pop(),v.trys.pop();continue;default:if(!(b=(b=v.trys).length>0&&b[b.length-1])&&(p[0]===6||p[0]===2)){v=0;continue}if(p[0]===3&&(!b||p[1]>b[0]&&p[1]<b[3])){v.label=p[1];break}if(p[0]===6&&v.label<b[1]){v.label=b[1],b=p;break}if(b&&v.label<b[2]){v.label=b[2],v.ops.push(p);break}b[2]&&v.ops.pop(),v.trys.pop();continue}p=l.call(d,v)}catch(g){p=[6,g],h=0}finally{u=b=0}if(5&p[0])throw p[1];return{value:p[0]?p[1]:void 0,done:!0}}([m,f])}}},r=this&&this.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(t,"__esModule",{value:!0}),t.API=void 0;var s=o("./util"),a=r(o("./logger")),c=function(){function d(l){this._options=l}return d.prototype._buildUrl=function(l){var u=(this._options.secure?"https://":"http://")+this._options.host+":"+this._options.port+this._options.path+this._options.key+"/"+l;return u+="?ts="+new Date().getTime()+Math.random()},d.prototype.retrieveId=function(){return i(this,void 0,Promise,function(){var l,u,h,b;return n(this,function(w){switch(w.label){case 0:l=this._buildUrl("id"),w.label=1;case 1:return w.trys.push([1,3,,4]),[4,fetch(l)];case 2:if((u=w.sent()).status!==200)throw new Error("Error. Status:"+u.status);return[2,u.text()];case 3:throw h=w.sent(),a.default.error("Error retrieving ID",h),b="",this._options.path==="/"&&this._options.host!==s.util.CLOUD_HOST&&(b=" 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."+b);case 4:return[2]}})})},d.prototype.listAllPeers=function(){return i(this,void 0,Promise,function(){var l,u,h,b;return n(this,function(w){switch(w.label){case 0:l=this._buildUrl("peers"),w.label=1;case 1:return w.trys.push([1,3,,4]),[4,fetch(l)];case 2:if((u=w.sent()).status!==200)throw u.status===401?(h="",h=this._options.host===s.util.CLOUD_HOST?"It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":"You need to enable `allow_discovery` on your self-hosted PeerServer to use this feature.",new Error("It doesn't look like you have permission to list peers IDs. "+h)):new Error("Error. Status:"+u.status);return[2,u.json()];case 3:throw b=w.sent(),a.default.error("Error retrieving list peers",b),new Error("Could not get list peers from the server."+b);case 4:return[2]}})})},d}();t.API=c},{"./util":"BHXf","./logger":"WOs9"}],Hxpd:[function(o,e,t){"use strict";var i=this&&this.__extends||function(){var f=function(p,g){return(f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(E,C){E.__proto__=C}||function(E,C){for(var T in C)Object.prototype.hasOwnProperty.call(C,T)&&(E[T]=C[T])})(p,g)};return function(p,g){if(typeof g!="function"&&g!==null)throw new TypeError("Class extends value "+String(g)+" is not a constructor or null");function E(){this.constructor=p}f(p,g),p.prototype=g===null?Object.create(g):(E.prototype=g.prototype,new E)}}(),n=this&&this.__assign||function(){return(n=Object.assign||function(f){for(var p,g=1,E=arguments.length;g<E;g++)for(var C in p=arguments[g])Object.prototype.hasOwnProperty.call(p,C)&&(f[C]=p[C]);return f}).apply(this,arguments)},r=this&&this.__values||function(f){var p=typeof Symbol=="function"&&Symbol.iterator,g=p&&f[p],E=0;if(g)return g.call(f);if(f&&typeof f.length=="number")return{next:function(){return f&&E>=f.length&&(f=void 0),{value:f&&f[E++],done:!f}}};throw new TypeError(p?"Object is not iterable.":"Symbol.iterator is not defined.")},s=this&&this.__read||function(f,p){var g=typeof Symbol=="function"&&f[Symbol.iterator];if(!g)return f;var E,C,T=g.call(f),S=[];try{for(;(p===void 0||p-- >0)&&!(E=T.next()).done;)S.push(E.value)}catch(I){C={error:I}}finally{try{E&&!E.done&&(g=T.return)&&g.call(T)}finally{if(C)throw C.error}}return S},a=this&&this.__importDefault||function(f){return f&&f.__esModule?f:{default:f}};Object.defineProperty(t,"__esModule",{value:!0}),t.Peer=void 0;var c=o("eventemitter3"),d=o("./util"),l=a(o("./logger")),u=o("./socket"),h=o("./mediaconnection"),b=o("./dataconnection"),w=o("./enums"),v=o("./api"),x=function(){return function(){}}(),m=function(f){function p(g,E){var C,T=f.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,g&&g.constructor==Object?E=g:g&&(C=g.toString()),E=n({debug:0,host:d.util.CLOUD_HOST,port:d.util.CLOUD_PORT,path:"/",key:p.DEFAULT_KEY,token:d.util.randomToken(),config:d.util.defaultConfig},E),T._options=E,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&&l.default.setLogFunction(T._options.logFunction),l.default.logLevel=T._options.debug||0,T._api=new v.API(E),T._socket=T._createServerConnection(),d.util.supports.audioVideo||d.util.supports.data?C&&!d.util.validateId(C)?(T._delayedAbort(w.PeerErrorType.InvalidID,'ID "'+C+'" is invalid'),T):(C?T._initialize(C):T._api.retrieveId().then(function(S){return T._initialize(S)}).catch(function(S){return T._abort(w.PeerErrorType.ServerError,S)}),T):(T._delayedAbort(w.PeerErrorType.BrowserIncompatible,"The current browser does not support WebRTC"),T)}return i(p,f),Object.defineProperty(p.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"socket",{get:function(){return this._socket},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"connections",{get:function(){var g,E,C=Object.create(null);try{for(var T=r(this._connections),S=T.next();!S.done;S=T.next()){var I=s(S.value,2),A=I[0],k=I[1];C[A]=k}}catch(j){g={error:j}}finally{try{S&&!S.done&&(E=T.return)&&E.call(T)}finally{if(g)throw g.error}}return C},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"disconnected",{get:function(){return this._disconnected},enumerable:!1,configurable:!0}),p.prototype._createServerConnection=function(){var g=this,E=new u.Socket(this._options.secure,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval);return E.on(w.SocketEventType.Message,function(C){g._handleMessage(C)}),E.on(w.SocketEventType.Error,function(C){g._abort(w.PeerErrorType.SocketError,C)}),E.on(w.SocketEventType.Disconnected,function(){g.disconnected||(g.emitError(w.PeerErrorType.Network,"Lost connection to server."),g.disconnect())}),E.on(w.SocketEventType.Close,function(){g.disconnected||g._abort(w.PeerErrorType.SocketClosed,"Underlying socket is already closed.")}),E},p.prototype._initialize=function(g){this._id=g,this.socket.start(g,this._options.token)},p.prototype._handleMessage=function(g){var E,C,T=g.type,S=g.payload,I=g.src;switch(T){case w.ServerMessageType.Open:this._lastServerId=this.id,this._open=!0,this.emit(w.PeerEventType.Open,this.id);break;case w.ServerMessageType.Error:this._abort(w.PeerErrorType.ServerError,S.msg);break;case w.ServerMessageType.IdTaken:this._abort(w.PeerErrorType.UnavailableID,'ID "'+this.id+'" is taken');break;case w.ServerMessageType.InvalidKey:this._abort(w.PeerErrorType.InvalidKey,'API KEY "'+this._options.key+'" is invalid');break;case w.ServerMessageType.Leave:l.default.log("Received leave message from "+I),this._cleanupPeer(I),this._connections.delete(I);break;case w.ServerMessageType.Expire:this.emitError(w.PeerErrorType.PeerUnavailable,"Could not connect to peer "+I);break;case w.ServerMessageType.Offer:var A=S.connectionId;if((z=this.getConnection(I,A))&&(z.close(),l.default.warn("Offer received for existing Connection ID:"+A)),S.type===w.ConnectionType.Media)z=new h.MediaConnection(I,this,{connectionId:A,_payload:S,metadata:S.metadata}),this._addConnection(I,z),this.emit(w.PeerEventType.Call,z);else{if(S.type!==w.ConnectionType.Data)return void l.default.warn("Received malformed connection type:"+S.type);z=new b.DataConnection(I,this,{connectionId:A,_payload:S,metadata:S.metadata,label:S.label,serialization:S.serialization,reliable:S.reliable}),this._addConnection(I,z),this.emit(w.PeerEventType.Connection,z)}var k=this._getMessages(A);try{for(var j=r(k),F=j.next();!F.done;F=j.next()){var W=F.value;z.handleMessage(W)}}catch(re){E={error:re}}finally{try{F&&!F.done&&(C=j.return)&&C.call(j)}finally{if(E)throw E.error}}break;default:if(!S)return void l.default.warn("You received a malformed message from "+I+" of type "+T);var z;A=S.connectionId,(z=this.getConnection(I,A))&&z.peerConnection?z.handleMessage(g):A?this._storeMessage(A,g):l.default.warn("You received an unrecognized message:",g)}},p.prototype._storeMessage=function(g,E){this._lostMessages.has(g)||this._lostMessages.set(g,[]),this._lostMessages.get(g).push(E)},p.prototype._getMessages=function(g){var E=this._lostMessages.get(g);return E?(this._lostMessages.delete(g),E):[]},p.prototype.connect=function(g,E){if(E===void 0&&(E={}),this.disconnected)return l.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(w.PeerErrorType.Disconnected,"Cannot connect to new Peer after disconnecting from server.");var C=new b.DataConnection(g,this,E);return this._addConnection(g,C),C},p.prototype.call=function(g,E,C){if(C===void 0&&(C={}),this.disconnected)return l.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(w.PeerErrorType.Disconnected,"Cannot connect to new Peer after disconnecting from server.");if(E){C._stream=E;var T=new h.MediaConnection(g,this,C);return this._addConnection(g,T),T}l.default.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.")},p.prototype._addConnection=function(g,E){l.default.log("add connection "+E.type+":"+E.connectionId+" to peerId:"+g),this._connections.has(g)||this._connections.set(g,[]),this._connections.get(g).push(E)},p.prototype._removeConnection=function(g){var E=this._connections.get(g.peer);if(E){var C=E.indexOf(g);C!==-1&&E.splice(C,1)}this._lostMessages.delete(g.connectionId)},p.prototype.getConnection=function(g,E){var C,T,S=this._connections.get(g);if(!S)return null;try{for(var I=r(S),A=I.next();!A.done;A=I.next()){var k=A.value;if(k.connectionId===E)return k}}catch(j){C={error:j}}finally{try{A&&!A.done&&(T=I.return)&&T.call(I)}finally{if(C)throw C.error}}return null},p.prototype._delayedAbort=function(g,E){var C=this;setTimeout(function(){C._abort(g,E)},0)},p.prototype._abort=function(g,E){l.default.error("Aborting!"),this.emitError(g,E),this._lastServerId?this.disconnect():this.destroy()},p.prototype.emitError=function(g,E){var C;l.default.error("Error:",E),(C=typeof E=="string"?new Error(E):E).type=g,this.emit(w.PeerEventType.Error,C)},p.prototype.destroy=function(){this.destroyed||(l.default.log("Destroy peer with ID:"+this.id),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit(w.PeerEventType.Close))},p.prototype._cleanup=function(){var g,E;try{for(var C=r(this._connections.keys()),T=C.next();!T.done;T=C.next()){var S=T.value;this._cleanupPeer(S),this._connections.delete(S)}}catch(I){g={error:I}}finally{try{T&&!T.done&&(E=C.return)&&E.call(C)}finally{if(g)throw g.error}}this.socket.removeAllListeners()},p.prototype._cleanupPeer=function(g){var E,C,T=this._connections.get(g);if(T)try{for(var S=r(T),I=S.next();!I.done;I=S.next())I.value.close()}catch(A){E={error:A}}finally{try{I&&!I.done&&(C=S.return)&&C.call(S)}finally{if(E)throw E.error}}},p.prototype.disconnect=function(){if(!this.disconnected){var g=this.id;l.default.log("Disconnect peer with ID:"+g),this._disconnected=!0,this._open=!1,this.socket.close(),this._lastServerId=g,this._id=null,this.emit(w.PeerEventType.Disconnected,g)}},p.prototype.reconnect=function(){if(this.disconnected&&!this.destroyed)l.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!");l.default.error("In a hurry? We're still trying to make the initial connection!")}},p.prototype.listAllPeers=function(g){var E=this;g===void 0&&(g=function(C){}),this._api.listAllPeers().then(function(C){return g(C)}).catch(function(C){return E._abort(w.PeerErrorType.ServerError,C)})},p.DEFAULT_KEY="peerjs",p}(c.EventEmitter);t.Peer=m},{eventemitter3:"JJlS","./util":"BHXf","./logger":"WOs9","./socket":"wJlv","./mediaconnection":"dbHP","./dataconnection":"GBTQ","./enums":"ZRYf","./api":"in7L"}],iTK6:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.peerjs=void 0;var i=o("./util"),n=o("./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 $p=Rs((l0,Zp)=>{(function(){var o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e={rotl:function(t,i){return t<<i|t>>>32-i},rotr:function(t,i){return t<<32-i|t>>>i},endian:function(t){if(t.constructor==Number)return e.rotl(t,8)&16711935|e.rotl(t,24)&4278255360;for(var i=0;i<t.length;i++)t[i]=e.endian(t[i]);return t},randomBytes:function(t){for(var i=[];t>0;t--)i.push(Math.floor(Math.random()*256));return i},bytesToWords:function(t){for(var i=[],n=0,r=0;n<t.length;n++,r+=8)i[r>>>5]|=t[n]<<24-r%32;return i},wordsToBytes:function(t){for(var i=[],n=0;n<t.length*32;n+=8)i.push(t[n>>>5]>>>24-n%32&255);return i},bytesToHex:function(t){for(var i=[],n=0;n<t.length;n++)i.push((t[n]>>>4).toString(16)),i.push((t[n]&15).toString(16));return i.join("")},hexToBytes:function(t){for(var i=[],n=0;n<t.length;n+=2)i.push(parseInt(t.substr(n,2),16));return i},bytesToBase64:function(t){for(var i=[],n=0;n<t.length;n+=3)for(var r=t[n]<<16|t[n+1]<<8|t[n+2],s=0;s<4;s++)n*8+s*6<=t.length*8?i.push(o.charAt(r>>>6*(3-s)&63)):i.push("=");return i.join("")},base64ToBytes:function(t){t=t.replace(/[^A-Z0-9+\/]/ig,"");for(var i=[],n=0,r=0;n<t.length;r=++n%4)r!=0&&i.push((o.indexOf(t.charAt(n-1))&Math.pow(2,-2*r+8)-1)<<r*2|o.indexOf(t.charAt(n))>>>6-r*2);return i}};Zp.exports=e})()});var vd=Rs((c0,ef)=>{var bd={utf8:{stringToBytes:function(o){return bd.bin.stringToBytes(unescape(encodeURIComponent(o)))},bytesToString:function(o){return decodeURIComponent(escape(bd.bin.bytesToString(o)))}},bin:{stringToBytes:function(o){for(var e=[],t=0;t<o.length;t++)e.push(o.charCodeAt(t)&255);return e},bytesToString:function(o){for(var e=[],t=0;t<o.length;t++)e.push(String.fromCharCode(o[t]));return e.join("")}}};ef.exports=bd});var rf=Rs((d0,nf)=>{nf.exports=function(o){return o!=null&&(tf(o)||Gb(o)||!!o._isBuffer)};function tf(o){return!!o.constructor&&typeof o.constructor.isBuffer=="function"&&o.constructor.isBuffer(o)}function Gb(o){return typeof o.readFloatLE=="function"&&typeof o.slice=="function"&&tf(o.slice(0,0))}});var sf=Rs((u0,of)=>{(function(){var o=$p(),e=vd().utf8,t=rf(),i=vd().bin,n=function(r,s){r.constructor==String?s&&s.encoding==="binary"?r=i.stringToBytes(r):r=e.stringToBytes(r):t(r)?r=Array.prototype.slice.call(r,0):!Array.isArray(r)&&r.constructor!==Uint8Array&&(r=r.toString());for(var a=o.bytesToWords(r),c=r.length*8,d=1732584193,l=-271733879,u=-1732584194,h=271733878,b=0;b<a.length;b++)a[b]=(a[b]<<8|a[b]>>>24)&16711935|(a[b]<<24|a[b]>>>8)&4278255360;a[c>>>5]|=128<<c%32,a[(c+64>>>9<<4)+14]=c;for(var w=n._ff,v=n._gg,x=n._hh,m=n._ii,b=0;b<a.length;b+=16){var f=d,p=l,g=u,E=h;d=w(d,l,u,h,a[b+0],7,-680876936),h=w(h,d,l,u,a[b+1],12,-389564586),u=w(u,h,d,l,a[b+2],17,606105819),l=w(l,u,h,d,a[b+3],22,-1044525330),d=w(d,l,u,h,a[b+4],7,-176418897),h=w(h,d,l,u,a[b+5],12,1200080426),u=w(u,h,d,l,a[b+6],17,-1473231341),l=w(l,u,h,d,a[b+7],22,-45705983),d=w(d,l,u,h,a[b+8],7,1770035416),h=w(h,d,l,u,a[b+9],12,-1958414417),u=w(u,h,d,l,a[b+10],17,-42063),l=w(l,u,h,d,a[b+11],22,-1990404162),d=w(d,l,u,h,a[b+12],7,1804603682),h=w(h,d,l,u,a[b+13],12,-40341101),u=w(u,h,d,l,a[b+14],17,-1502002290),l=w(l,u,h,d,a[b+15],22,1236535329),d=v(d,l,u,h,a[b+1],5,-165796510),h=v(h,d,l,u,a[b+6],9,-1069501632),u=v(u,h,d,l,a[b+11],14,643717713),l=v(l,u,h,d,a[b+0],20,-373897302),d=v(d,l,u,h,a[b+5],5,-701558691),h=v(h,d,l,u,a[b+10],9,38016083),u=v(u,h,d,l,a[b+15],14,-660478335),l=v(l,u,h,d,a[b+4],20,-405537848),d=v(d,l,u,h,a[b+9],5,568446438),h=v(h,d,l,u,a[b+14],9,-1019803690),u=v(u,h,d,l,a[b+3],14,-187363961),l=v(l,u,h,d,a[b+8],20,1163531501),d=v(d,l,u,h,a[b+13],5,-1444681467),h=v(h,d,l,u,a[b+2],9,-51403784),u=v(u,h,d,l,a[b+7],14,1735328473),l=v(l,u,h,d,a[b+12],20,-1926607734),d=x(d,l,u,h,a[b+5],4,-378558),h=x(h,d,l,u,a[b+8],11,-2022574463),u=x(u,h,d,l,a[b+11],16,1839030562),l=x(l,u,h,d,a[b+14],23,-35309556),d=x(d,l,u,h,a[b+1],4,-1530992060),h=x(h,d,l,u,a[b+4],11,1272893353),u=x(u,h,d,l,a[b+7],16,-155497632),l=x(l,u,h,d,a[b+10],23,-1094730640),d=x(d,l,u,h,a[b+13],4,681279174),h=x(h,d,l,u,a[b+0],11,-358537222),u=x(u,h,d,l,a[b+3],16,-722521979),l=x(l,u,h,d,a[b+6],23,76029189),d=x(d,l,u,h,a[b+9],4,-640364487),h=x(h,d,l,u,a[b+12],11,-421815835),u=x(u,h,d,l,a[b+15],16,530742520),l=x(l,u,h,d,a[b+2],23,-995338651),d=m(d,l,u,h,a[b+0],6,-198630844),h=m(h,d,l,u,a[b+7],10,1126891415),u=m(u,h,d,l,a[b+14],15,-1416354905),l=m(l,u,h,d,a[b+5],21,-57434055),d=m(d,l,u,h,a[b+12],6,1700485571),h=m(h,d,l,u,a[b+3],10,-1894986606),u=m(u,h,d,l,a[b+10],15,-1051523),l=m(l,u,h,d,a[b+1],21,-2054922799),d=m(d,l,u,h,a[b+8],6,1873313359),h=m(h,d,l,u,a[b+15],10,-30611744),u=m(u,h,d,l,a[b+6],15,-1560198380),l=m(l,u,h,d,a[b+13],21,1309151649),d=m(d,l,u,h,a[b+4],6,-145523070),h=m(h,d,l,u,a[b+11],10,-1120210379),u=m(u,h,d,l,a[b+2],15,718787259),l=m(l,u,h,d,a[b+9],21,-343485551),d=d+f>>>0,l=l+p>>>0,u=u+g>>>0,h=h+E>>>0}return o.endian([d,l,u,h])};n._ff=function(r,s,a,c,d,l,u){var h=r+(s&a|~s&c)+(d>>>0)+u;return(h<<l|h>>>32-l)+s},n._gg=function(r,s,a,c,d,l,u){var h=r+(s&c|a&~c)+(d>>>0)+u;return(h<<l|h>>>32-l)+s},n._hh=function(r,s,a,c,d,l,u){var h=r+(s^a^c)+(d>>>0)+u;return(h<<l|h>>>32-l)+s},n._ii=function(r,s,a,c,d,l,u){var h=r+(a^(s|~c))+(d>>>0)+u;return(h<<l|h>>>32-l)+s},n._blocksize=16,n._digestsize=16,of.exports=function(r,s){if(r==null)throw new Error("Illegal argument "+r);var a=o.wordsToBytes(n(r,s));return s&&s.asBytes?a:s&&s.asString?i.bytesToString(a):o.bytesToHex(a)}})()});var Dc=()=>o=>o;var Pi=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]}},Ac=!1,Mc=[];setTimeout(()=>{Ac&&console.log(Mc)},100);function Lc(){return new URLSearchParams(window.location.search)}function O(o){Ac&&!Mc.includes(o)&&Mc.push(o);let e=Lc();if(e.has(o)){let t=e.get(o);return t||!0}return!1}Ac=O("help")===!0;function ho(o,e,t){o.has(e)?o.set(e,t.toString()):o.append(e,t.toString())}function Wh(o,e){window.history.replaceState(null,o,"?"+e.toString())}function Nh(o,e){return Math.floor(Math.random()*(e-o+1))+o}var Vh=["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"],zh=["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 Xh(){let o=Vh[Math.floor(Math.random()*Vh.length)],e=zh[Math.floor(Math.random()*zh.length)];return o+"_"+e}function Qh(o){return o=o.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),o.trim()}function Un(o,e,t=!0,i=!1){if(e==null)return null;if(e.userData&&e.userData.guid===o)return e;if(e.guid==o)return e;if(i&&e.userData?.components){for(let n of e.userData.components)if(n.guid===o)return n}if(t){if(e.scenes)for(let n in e.scenes){let r=e.scenes[n],s=Un(o,r,t,i);if(s)return s}if(e.children)for(let n in e.children){let r=e.children[n],s=Un(o,r,t,i);if(s)return s}}}function Ss(o,e){if(o!=null&&typeof o=="object"){let t;Array.isArray(o)?t=[]:(t=Object.create(o),Object.assign(t,o));for(let i of Object.keys(o)){let n=o[i];e&&!e(o,i,n)?t[i]=n:n?.clone!==void 0&&typeof n.clone=="function"?t[i]=n.clone():t[i]=Ss(n,e)}return t}return o}function qh(o){return new Promise((e,t)=>{setTimeout(e,o)})}var kc=O("debugsourcepath");function Oi(o,e){if(o===void 0)return kc&&console.warn("getPath: source is undefined, returning uri",e),e;if(e.startsWith("http"))return kc&&console.warn("getPath: uri is absolute, returning uri",e),e;let t=o.lastIndexOf("/");if(t>=0){let i=o.substring(0,t+1),n=e.lastIndexOf("/");return n>=0?i+=e.substring(n+1):i+=e,kc&&console.log("getPath:",o,` - changed uri from
79
79
  `,e,`
80
- \u2192 `,i),i}return e}var Sc=class{subscribeWrite(e){this.writeCallbacks.push(e)}writeCallbacks=[];constructor(e,t){this._object=e,this._prop=t,this._wrapperProp=Symbol("$"+t),this.apply()}_applied=!1;_object;_prop;_wrapperProp;apply(){if(this._applied||!this._object)return;let e=this._object,t=this._prop;if(e[t]===void 0)return;this._applied=!0,e[this._wrapperProp]!==void 0&&console.warn("Watcher is being applied to an object that already has a wrapper property. This is not (yet) supported");let i=e[t];e[this._wrapperProp]=i,Object.defineProperty(e,t,{get:()=>e[this._wrapperProp],set:s=>{e[this._wrapperProp]=s;for(let a of this.writeCallbacks)a(s,this._prop)}})}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}},tn=class{_watches=[];constructor(e,t){if(Array.isArray(t))for(let i of t)this._watches.push(new tn(e,i));else this._watches.push(new Sc(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}};function va(){return typeof window.orientation<"u"||navigator.userAgent.indexOf("IEMobile")!==-1}function ya(){return/WebXRViewer\//i.test(navigator.userAgent)}function ei(o=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(o)===!0}function Vh(){return window.location.hostname.includes("glitch.me")}import{DepthTexture as tv,WebGLRenderer as iv}from"three";import*as Re from"three";import*as ti from"three";var nn=null,Bn=null,Si=null,Mc=!1,Dc=!1,zh=null,Nh="\u{1F4DC}",Ic=M("console"),ug=M("noerrors");Ic&&Lc();if(!ug&&(Ic||ei())){console.log("Add the ?console query parameter to the url to show the debug console (on mobile it will automatically open for local development when your get errors)");let o=va();if(o&&(Xh(),Qh(!0),o)){let e=document.querySelector("needle-engine");e?.addEventListener("enter-ar",()=>{if(Ic||nn||jc()>0){if(M("noerrors"))return;let t=e.getAROverlayContainer?.call(e),i=qh();i&&t&&t.appendChild(i)}}),e?.addEventListener("exit-ar",()=>{gg()})}}var Ac=Symbol("consoleParent");function Lc(){if(nn!==null){Dc=!0,nn.showSwitch();return}Qh()}function hg(){nn!==null&&(Dc=!1,nn.hide(),nn.hideSwitch())}function Xh(){zh||(zh=setInterval(pg,500))}var Wh=0;function pg(){let o=jc(),e=o!==Wh;Wh=o,e&&fg()}function fg(){Lc(),Si&&(Si.setAttribute("error","true"),Si.innerText="\u{1F92C}")}function mg(){Si&&(Si.removeAttribute("error"),Si.innerText=Nh)}function gg(){Bn&&Bn[Ac]&&Bn[Ac].appendChild(Bn)}function Qh(o=!1){if(nn||Mc)return;Mc=!0;let e=document.createElement("script");e.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",e.onload=()=>{if(Mc=!1,Dc=!0,Xh(),nn=new window.VConsole,Bn=qh(),Bn&&(Bn[Ac]=Bn.parentElement),nn.setSwitchPosition(20,10),Si=bg(),Si){Si.innerText=Nh,Si.addEventListener("click",mg);let t=document.createElement("style"),i=40;t.innerHTML=`
80
+ \u2192 `,i),i}return e}var Ic=class{subscribeWrite(e){this.writeCallbacks.push(e)}writeCallbacks=[];constructor(e,t){this._object=e,this._prop=t,this._wrapperProp=Symbol("$"+t),this.apply()}_applied=!1;_object;_prop;_wrapperProp;apply(){if(this._applied||!this._object)return;let e=this._object,t=this._prop;if(e[t]===void 0)return;this._applied=!0,e[this._wrapperProp]!==void 0&&console.warn("Watcher is being applied to an object that already has a wrapper property. This is not (yet) supported");let i=e[t];e[this._wrapperProp]=i,Object.defineProperty(e,t,{get:()=>e[this._wrapperProp],set:s=>{e[this._wrapperProp]=s;for(let a of this.writeCallbacks)a(s,this._prop)}})}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}},sn=class{_watches=[];constructor(e,t){if(Array.isArray(t))for(let i of t)this._watches.push(new sn(e,i));else this._watches.push(new Ic(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}};function Ea(){return typeof window.orientation<"u"||navigator.userAgent.indexOf("IEMobile")!==-1}function Ca(){return/WebXRViewer\//i.test(navigator.userAgent)}function ti(o=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(o)===!0}function Yh(){return window.location.hostname.includes("glitch.me")}import{DepthTexture as cv,WebGLRenderer as dv}from"three";import*as Re from"three";import*as ii from"three";var an=null,Gn=null,ki=null,jc=!1,Bc=!1,Kh=null,Zh="\u{1F4DC}",Hc=O("console"),yg=O("noerrors");Hc&&Uc();if(!yg&&(Hc||ti())){console.log("Add the ?console query parameter to the url to show the debug console (on mobile it will automatically open for local development when your get errors)");let o=Ea();if(o&&($h(),ep(!0),o)){let e=document.querySelector("needle-engine");e?.addEventListener("enter-ar",()=>{if(Hc||an||Gc()>0){if(O("noerrors"))return;let t=e.getAROverlayContainer?.call(e),i=tp();i&&t&&t.appendChild(i)}}),e?.addEventListener("exit-ar",()=>{Cg()})}}var Fc=Symbol("consoleParent");function Uc(){if(an!==null){Bc=!0,an.showSwitch();return}ep()}function _g(){an!==null&&(Bc=!1,an.hide(),an.hideSwitch())}function $h(){Kh||(Kh=setInterval(xg,500))}var Jh=0;function xg(){let o=Gc(),e=o!==Jh;Jh=o,e&&wg()}function wg(){Uc(),ki&&(ki.setAttribute("error","true"),ki.innerText="\u{1F92C}")}function Eg(){ki&&(ki.removeAttribute("error"),ki.innerText=Zh)}function Cg(){Gn&&Gn[Fc]&&Gn[Fc].appendChild(Gn)}function ep(o=!1){if(an||jc)return;jc=!0;let e=document.createElement("script");e.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",e.onload=()=>{if(jc=!1,Bc=!0,$h(),an=new window.VConsole,Gn=tp(),Gn&&(Gn[Fc]=Gn.parentElement),an.setSwitchPosition(20,10),ki=Tg(),ki){ki.innerText=Zh,ki.addEventListener("click",Eg);let t=document.createElement("style"),i=40;t.innerHTML=`
81
81
  #__vconsole .vc-switch {
82
82
  border: 1px solid rgba(255,255,255,.2);
83
83
  border-radius: 50%;
@@ -116,26 +116,26 @@ a=extmap-allow-mixed`)!==-1){var p=f.sdp.split(`
116
116
  transform: scale(1, 1);
117
117
  }
118
118
  }
119
- `,document.head.appendChild(t),o===!0&&hg()}},document.body.appendChild(e)}function bg(){let o=document.querySelector("#__vconsole .vc-switch");return o||null}function qh(){let o=document.querySelector("#__vconsole");return o||null}function Ye(o,e=0){Rs(e,o)}function _a(o){Ye(o,1)}var Pi=M("gizmos"),Te=M("debugextension");var wa=M("debugresolvedependencies"),vg=["/extensions/","extensions/"],yg=[{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 uo(o,e){wa&&console.log(o,e);let t=[];Hc(yg,o,e,t);let i=await Promise.all(t);return typeof e=="string"&&i.length===1?i[0]:i}function Hc(o,e,t,i){if(typeof t=="object"&&t!==void 0&&t!==null)for(let n of Object.keys(t)){let r=t[n];if(typeof r=="string"){let s=Yh(e,r);if(s!==null)typeof s.then=="function"?i.push(s.then(a=>t[n]=a)):t[n]=s;else for(let a of o){let c=Fc(a.prefix,r);if(c>=0){wa&&console.log(a,c,a.dependencyName),i.push(e?.getDependency(a.dependencyName,c).then(d=>(t[n]=d,d)));break}}}else if(Array.isArray(r))for(let s=0;s<r.length;s++){let a=r[s],c=Yh(e,a);if(c!==null){typeof c.then=="function"?i.push(c.then(d=>r[s]=d)):r[s]=c;continue}for(let d of o){let l=Fc(d.prefix,a);if(l>=0){wa&&console.log(d,l,d.dependencyName),i.push(e?.getDependency(d.dependencyName,l).then(u=>r[s]=u));break}}typeof a=="object"&&Hc(o,e,a,i)}else typeof r=="object"&&Hc(o,e,r,i)}else typeof t=="string"&&_g(o,e,t,i)}function Yh(o,e){if(o&&o.plugins&&typeof e=="string"){for(let t of vg)if(e.startsWith(t)){let i=e.substring(t.length),n=i.indexOf("/");n>=0&&(i=i.substring(0,n));let r=o.plugins[i];if(Te&&console.log(i,r),typeof r?.resolve=="function"){let s=e.substring(t.length+i.length+1);return r.resolve(o,s)}break}}return null}function _g(o,e,t,i){for(let n of o){let r=Fc(n.prefix,t);if(r>=0)return wa&&console.log(n,r,n.dependencyName),i.push(e?.getDependency(n.dependencyName,r).then(s=>s)),!0}return!1}function Fc(o,e){if(typeof e=="string"&&e.startsWith(o)){let t=e.substring(o.length),i=Number.parseInt(t);if(i>=0)return i}return-1}var Bc=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]}},Kh=Symbol("BuiltInType"),P=new Bc;var Uc="NEEDLE_persistent_assets";function Jh(o){return o?.___persistentAsset===!0}var Ea=class{get name(){return Uc}parser;constructor(e){this.parser=e}async afterRoot(e){if(!this.parser?.json?.extensions)return;let t=this.parser.json.extensions[Uc];if(!t)return;Te&&console.log(t);let i=new Array;for(let n of t?.assets){let r=uo(this.parser,n);r&&i.push(r)}await Promise.all(i)}resolve(e,t){let i=Number.parseInt(t);if(i>=0){Te&&console.log(t);let n=e.json.extensions[Uc];if(n){let r=n?.assets[i];if(r&&typeof r=="object"){r.___persistentAsset=!0;let s=r.__type;if(s){let a=P.get(s)}}return r}}return null}};var _r=M("debugserializer"),Gc=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])}_r&&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){_r&&console.log("invalid type");return}let i=e.name??e.constructor?.name;if(!i){_r&&console.log("invalid name",i);return}let n=this.getSerializer(i);if(n!==void 0)return _r&&console.log("FOUND "+i,e.name,e.constructor.name,n,this.typeMap),n;let r=Object.getPrototypeOf(e);if(!(r.prototype||r.constructor)){_r&&console.warn("No prototype for "+i,e,e.name,e.prototype,e.constructor.name);return}let a=r.prototype??r.constructor;if(a!==e){let c=this.getSerializerForConstructor(a,++t);if(c){_r&&console.log("FOUND "+a.constructor.name,a.name,a,c);let d=a.name??a.constructor.name;d==="Function"?console.error("Registering Function is not allowed, something went wrong",e,a,c):this.register(d,c)}return c}}},Ta=new Gc,rn=class{constructor(e){if(Array.isArray(e))for(let t of e)Ta.register(t.name,this);else Ta.register(e.name,this)}},Ra=class{isDevMode=ei();cache={};registerDefinedKeys(e,t){!this.isDevMode||this.cache[e]===void 0&&(this.cache[e]=Object.keys(t))}getDefinedKey(e,t){return this.cache[e]===void 0?!1:this.cache[e].includes(t)}},ho=class{root;gltf;gltfId;object;target;nodeId;nodeToObject;objectToNode;context;path;implementationInformation;constructor(e){this.root=e}};function zc(o,e){let t=o.$serializedTypes;if(t===void 0)return null;let i={};for(let n in t){let r=o[n];if(r!=null&&typeof r=="object"){let s=Ta.getSerializerForConstructor(r);if(s){i[n]=s.onSerialize(r,e);continue}}i[n]=r}return i.name=o.constructor.name,typeof o.guid=="string"&&(i.guid=o.guid),i}var Ca=[];function Zh(o,e){if(!o)return e;typeof o.$serializedTypes=="object"&&(e||(e={}),Object.assign(e,o.$serializedTypes));let t=Object.getPrototypeOf(o);return Zh(t,e)}function Ss(o,e,t){if(!o)return!1;if(t.target=o,o.onBeforeDeserialize!==void 0){let r=o.onBeforeDeserialize(e,t);if(typeof r=="boolean")return r}let i=Zh(o);if(e){if(typeof e.guid=="string"&&(o.guid=e.guid),i)for(let r in i){let s=i[r],a=e[r];if(!(o[r]!==void 0&&a===void 0))if(t.path=r,s===null)o[r]=a;else{let c=function(d){let u=d.type;return u?Vc(a,u,t,void 0,o[r]):Vc(a,d,t,void 0,o[r])};var n=c;if(o.onBeforeDeserializeMember!==void 0&&o.onBeforeDeserializeMember(r,a,t)===!0)continue;if(Array.isArray(s))for(let d=0;d<s.length;d++){let l=s[d],u=c(l);if(u!==void 0||d===s.length-1){o[r]=u;break}}else o[r]=c(s);Ca.length=0,o.onAfterDeserializeMember!==void 0&&o.onAfterDeserializeMember(r,a,t)}}Eg(o,e)}return wg(o,e,t.implementationInformation),o.onAfterDeserialize!==void 0&&o.onAfterDeserialize(e,t),t.path=void 0,!0}var xg=M("noerrors");function wg(o,e,t){if(xg||!e||ei()===!1||!o||o.constructor&&o.constructor[Kh]===!0)return;let i=o.constructor?.name,n=Object.getOwnPropertyNames(e);for(let r of n){if(r==="sourceId")continue;let s=o[r],a=e[r];t?.getDefinedKey(i,r)!==!1&&a!=null&&(typeof a=="object"?(s===void 0||!s.isObject3D)&&(typeof a.node=="number"||typeof a.guid=="string")&&(s!==void 0&&Object.keys(s).length>1||(Ye(`<strong>Missing serialization for object reference!</strong>
119
+ `,document.head.appendChild(t),o===!0&&_g()}},document.body.appendChild(e)}function Tg(){let o=document.querySelector("#__vconsole .vc-switch");return o||null}function tp(){let o=document.querySelector("#__vconsole");return o||null}function Ke(o,e=0){Os(e,o)}function Ta(o){Ke(o,1)}var Mi=O("gizmos"),Te=O("debugextension");var Sa=O("debugresolvedependencies"),Rg=["/extensions/","extensions/"],Sg=[{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 po(o,e){Sa&&console.log(o,e);let t=[];Vc(Sg,o,e,t);let i=await Promise.all(t);return typeof e=="string"&&i.length===1?i[0]:i}function Vc(o,e,t,i){if(typeof t=="object"&&t!==void 0&&t!==null)for(let n of Object.keys(t)){let r=t[n];if(typeof r=="string"){let s=ip(e,r);if(s!==null)typeof s.then=="function"?i.push(s.then(a=>t[n]=a)):t[n]=s;else for(let a of o){let c=zc(a.prefix,r);if(c>=0){Sa&&console.log(a,c,a.dependencyName),i.push(e?.getDependency(a.dependencyName,c).then(d=>(t[n]=d,d)));break}}}else if(Array.isArray(r))for(let s=0;s<r.length;s++){let a=r[s],c=ip(e,a);if(c!==null){typeof c.then=="function"?i.push(c.then(d=>r[s]=d)):r[s]=c;continue}for(let d of o){let l=zc(d.prefix,a);if(l>=0){Sa&&console.log(d,l,d.dependencyName),i.push(e?.getDependency(d.dependencyName,l).then(u=>r[s]=u));break}}typeof a=="object"&&Vc(o,e,a,i)}else typeof r=="object"&&Vc(o,e,r,i)}else typeof t=="string"&&Pg(o,e,t,i)}function ip(o,e){if(o&&o.plugins&&typeof e=="string"){for(let t of Rg)if(e.startsWith(t)){let i=e.substring(t.length),n=i.indexOf("/");n>=0&&(i=i.substring(0,n));let r=o.plugins[i];if(Te&&console.log(i,r),typeof r?.resolve=="function"){let s=e.substring(t.length+i.length+1);return r.resolve(o,s)}break}}return null}function Pg(o,e,t,i){for(let n of o){let r=zc(n.prefix,t);if(r>=0)return Sa&&console.log(n,r,n.dependencyName),i.push(e?.getDependency(n.dependencyName,r).then(s=>s)),!0}return!1}function zc(o,e){if(typeof e=="string"&&e.startsWith(o)){let t=e.substring(o.length),i=Number.parseInt(t);if(i>=0)return i}return-1}var Wc=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]}},np=Symbol("BuiltInType"),P=new Wc;var Nc="NEEDLE_persistent_assets";function rp(o){return o?.___persistentAsset===!0}var Pa=class{get name(){return Nc}parser;constructor(e){this.parser=e}async afterRoot(e){if(!this.parser?.json?.extensions)return;let t=this.parser.json.extensions[Nc];if(!t)return;Te&&console.log(t);let i=new Array;for(let n of t?.assets){let r=po(this.parser,n);r&&i.push(r)}await Promise.all(i)}resolve(e,t){let i=Number.parseInt(t);if(i>=0){Te&&console.log(t);let n=e.json.extensions[Nc];if(n){let r=n?.assets[i];if(r&&typeof r=="object"){r.___persistentAsset=!0;let s=r.__type;if(s){let a=P.get(s)}}return r}}return null}};var wr=O("debugserializer"),Xc=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])}wr&&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){wr&&console.log("invalid type");return}let i=e.name??e.constructor?.name;if(!i){wr&&console.log("invalid name",i);return}let n=this.getSerializer(i);if(n!==void 0)return wr&&console.log("FOUND "+i,e.name,e.constructor.name,n,this.typeMap),n;let r=Object.getPrototypeOf(e);if(!(r.prototype||r.constructor)){wr&&console.warn("No prototype for "+i,e,e.name,e.prototype,e.constructor.name);return}let a=r.prototype??r.constructor;if(a!==e){let c=this.getSerializerForConstructor(a,++t);if(c){wr&&console.log("FOUND "+a.constructor.name,a.name,a,c);let d=a.name??a.constructor.name;d==="Function"?console.error("Registering Function is not allowed, something went wrong",e,a,c):this.register(d,c)}return c}}},ka=new Xc,ln=class{constructor(e){if(Array.isArray(e))for(let t of e)ka.register(t.name,this);else ka.register(e.name,this)}},Ma=class{isDevMode=ti();cache={};registerDefinedKeys(e,t){!this.isDevMode||this.cache[e]===void 0&&(this.cache[e]=Object.keys(t))}getDefinedKey(e,t){return this.cache[e]===void 0?!1:this.cache[e].includes(t)}},fo=class{root;gltf;gltfId;object;target;nodeId;nodeToObject;objectToNode;context;path;implementationInformation;constructor(e){this.root=e}};function qc(o,e){let t=o.$serializedTypes;if(t===void 0)return null;let i={};for(let n in t){let r=o[n];if(r!=null&&typeof r=="object"){let s=ka.getSerializerForConstructor(r);if(s){i[n]=s.onSerialize(r,e);continue}}i[n]=r}return i.name=o.constructor.name,typeof o.guid=="string"&&(i.guid=o.guid),i}var Oa=[];function op(o,e){if(!o)return e;typeof o.$serializedTypes=="object"&&(e||(e={}),Object.assign(e,o.$serializedTypes));let t=Object.getPrototypeOf(o);return op(t,e)}function ks(o,e,t){if(!o)return!1;if(t.target=o,o.onBeforeDeserialize!==void 0){let r=o.onBeforeDeserialize(e,t);if(typeof r=="boolean")return r}let i=op(o);if(e){if(typeof e.guid=="string"&&(o.guid=e.guid),i)for(let r in i){let s=i[r],a=e[r];if(!(o[r]!==void 0&&a===void 0))if(t.path=r,s===null)o[r]=a;else{let c=function(d){let u=d.type;return u?Qc(a,u,t,void 0,o[r]):Qc(a,d,t,void 0,o[r])};var n=c;if(o.onBeforeDeserializeMember!==void 0&&o.onBeforeDeserializeMember(r,a,t)===!0)continue;if(Array.isArray(s))for(let d=0;d<s.length;d++){let l=s[d],u=c(l);if(u!==void 0||d===s.length-1){o[r]=u;break}}else o[r]=c(s);Oa.length=0,o.onAfterDeserializeMember!==void 0&&o.onAfterDeserializeMember(r,a,t)}}Mg(o,e)}return kg(o,e,t.implementationInformation),o.onAfterDeserialize!==void 0&&o.onAfterDeserialize(e,t),t.path=void 0,!0}var Og=O("noerrors");function kg(o,e,t){if(Og||!e||ti()===!1||!o||o.constructor&&o.constructor[np]===!0)return;let i=o.constructor?.name,n=Object.getOwnPropertyNames(e);for(let r of n){if(r==="sourceId")continue;let s=o[r],a=e[r];t?.getDefinedKey(i,r)!==!1&&a!=null&&(typeof a=="object"?(s===void 0||!s.isObject3D)&&(typeof a.node=="number"||typeof a.guid=="string")&&(s!==void 0&&Object.keys(s).length>1||(Ke(`<strong>Missing serialization for object reference!</strong>
120
120
 
121
121
  Please change to:
122
122
  @serializable(Object3D)
123
123
  ${r}? : Object3D;
124
124
 
125
125
  in script ${i}.ts
126
- <a href="https://docs.needle.tools/serializable" target="_blank">documentation</a>`,1),console.warn(i,r,o[r],o))):typeof s=="string"&&(a.endsWith(".gltf")||a.endsWith(".glb"))&&(Ye(`<strong>Missing serialization for object reference!</strong>
126
+ <a href="https://docs.needle.tools/serializable" target="_blank">documentation</a>`,1),console.warn(i,r,o[r],o))):typeof s=="string"&&(a.endsWith(".gltf")||a.endsWith(".glb"))&&(Ke(`<strong>Missing serialization for object reference!</strong>
127
127
 
128
128
  Please change to:
129
129
  @serializable(AssetReference)
130
130
  ${r}? : AssetReference;
131
131
 
132
132
  in script ${i}.ts
133
- <a href="https://docs.needle.tools/serializable" target="_blank">documentation</a>`,1),console.warn(i,r,o[r],o)))}}function Eg(o,e){for(let i of Object.keys(e)){let n=e[i];if(typeof n=="object"&&n!==null&&n!==void 0){let r=o[i];if(!r){_r&&console.log(i,"is undefined on",o);continue}for(let s of Object.keys(n))r[s]===void 0&&t(n[s])&&!t(r)&&(r[s]=n[s])}}function t(i){switch(typeof i){case"number":case"string":case"boolean":return!0}return!1}}function Vc(o,e,t,i,n){let r=typeof e=="function"&&e.prototype===void 0,s=e;if(r)try{if(s=e?.call(e,n),r=!1,s==null)return}catch(l){console.error("Error in callback",l,o)}if(!r&&n instanceof s)return n;if(n&&typeof n=="object"&&Jh(n)){if(n.__concreteInstance)return n.__concreteInstance;let l=n;if(!l.$serializedTypes&&s.prototype.$serializedTypes&&(l.$serializedTypes=s.prototype.$serializedTypes),l.$serializedTypes&&Ss(l,o,t),n&&s!==void 0)try{let u=new s;Te&&console.log("Create concrete instance for persistent asset",n,"instance:",u),Mt(u,n),n.__concreteInstance=u,n=u}catch(u){console.error("Error creating instance or creating values on instance",u,n,s)}return n}if(i||(i={serializer:Ta.getSerializerForConstructor(s)}),Array.isArray(o)){let l=[];for(let u=0;u<o.length;u++){let h=o[u],b=Vc(h,e,t,i,h);l.push(b)}return l}let a=i.serializer;if(a)return a.onDeserialize(o,t);let c;if(o&&(o.isMaterial||o.isTexture||o.isObject3D))c=o;else{if(o===void 0)return;c=new s(...Cg(o))}let d=c;return d.$serializedTypes&&Ss(d,o,t),c}function Cg(o){if(Ca.length=0,typeof o=="object"&&o!==null&&o!==void 0)for(let e of Object.keys(o))Ca.push(o[e]);return Ca}var Sa=Symbol("assigned component properties");function Mt(o,e,t){if(e==null||o==null)return;let i=!1;o[Sa]=!0;let n=o.constructor?.name??"unknown";t?.registerDefinedKeys(n,o);for(let r of Object.keys(e)){let s=Tg(o,r);i&&s===void 0||(!s||s.writable===!0||s?.set!==void 0)&&(o[r]=e[r])}delete o[Sa]}function Tg(o,e){let t;do t=Object.getOwnPropertyDescriptor(o,e);while(!t&&(o=Object.getPrototypeOf(o)));return t}var on=M("debuginput"),Ps=class{key;keyType;source;constructor(e){this.key=e.key,this.keyType=e.type,this.source=e}};var Pa=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<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e<0||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]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}*foreachPointerId(e){for(let t=0;t<this._pointerTypes.length;t++)if(this._pointerIsActive[t]){if(e!==void 0){let i=this._pointerTypes[t];if(Array.isArray(e)){let n=!1;for(let r of e)if(i===r){n=!0;break}if(!n)continue}else if(e!==i)continue}yield t}}*foreachTouchId(){for(let e=0;e<this._pointerTypes.length;e++)this._pointerTypes[e]==="touch"&&this._pointerIsActive[e]&&(yield e)}_pointerIsActive(e){return e<0?!1:this._pointerPressed[e]||this._pointerDown[e]||this._pointerUp[e]}context;_pointerDown=[!1];_pointerUp=[!1];_pointerClick=[!1];_pointerDoubleClick=[!1];_pointerPressed=[!1];_pointerPositions=[new ti.Vector2];_pointerPositionsLastFrame=[new ti.Vector2];_pointerPositionsDelta=[new ti.Vector2];_pointerPositionsRC=[new ti.Vector2];_pointerPositionDown=[new ti.Vector2];_pointerDownTime=[];_pointerUpTime=[];_pointerIds=[];_pointerTypes=[""];_mouseWheelChanged=[!1];_mouseWheelDeltaY=[0];_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){on&&Ye("Create Pointer down"),this.onDown(e)}createPointerMove(e){on&&Ye("Create Pointer move"),this.onMove(e)}createPointerUp(e){on&&Ye("Create Pointer up"),this.onUp(e)}convertScreenspaceToRaycastSpace(e){e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1}constructor(e){super(),this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame.bind(this)),window.addEventListener("touchstart",this.onTouchStart.bind(this),!1),window.addEventListener("touchmove",this.onTouchMove.bind(this),{passive:!0}),window.addEventListener("touchend",this.onTouchUp.bind(this),!1),window.addEventListener("mousedown",this.onMouseDown.bind(this),!1),window.addEventListener("mousemove",this.onMouseMove.bind(this),!1),window.addEventListener("mouseup",this.onMouseUp.bind(this),!1),window.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;for(let e=0;e<this._mouseWheelDeltaY.length;e++)this._mouseWheelDeltaY[e]=0}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 Ps(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 Ps(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 Ps(e)))}onMouseWheel(e){this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;let t=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=t+e.deltaY}onTouchStart(e){if(!(e.changedTouches.length<=0))for(let t=0;t<e.changedTouches.length;t++){let i=e.changedTouches[t],r={button:this.getPointerIndex(i.identifier),clientX:i.clientX,clientY:i.clientY,pointerType:"touch",source:e};this.onDown(r)}}onTouchMove(e){if(!(e.changedTouches.length<=0))for(let t=0;t<e.changedTouches.length;t++){let i=e.changedTouches[t],r={button:this.getPointerIndex(i.identifier),clientX:i.clientX,clientY:i.clientY,pointerType:"touch",source:e};this.onMove(r)}}onTouchUp(e){if(!(e.changedTouches.length<=0))for(let t=0;t<e.changedTouches.length;t++){let i=e.changedTouches[t],r={button:this.getPointerIndex(i.identifier),clientX:i.clientX,clientY:i.clientY,pointerType:"touch",source:e};this.onUp(r)}}onMouseDown(e){if(e.defaultPrevented)return;let t=e.button;this.onDown({button:t,clientX:e.clientX,clientY:e.clientY,pointerType:"mouse",source:e})}onMouseMove(e){if(e.defaultPrevented)return;let i={button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:"mouse",source:e,movementX:e.movementX,movementY:e.movementY};this.onMove(i)}onMouseUp(e){if(e.defaultPrevented)return;let t=e.button;this.onUp({button:t,clientX:e.clientX,clientY:e.clientY,pointerType:"mouse",source:e})}isInRect(e){if(this.context.isInXR)return!0;let t=this.context.domElement.getBoundingClientRect(),i=e.clientX,n=e.clientY,r=i>=t.x&&i<=t.right&&n>=t.y&&n<=t.bottom;return on&&!r&&console.log("Not in rect",t,i,n),r}onDown(e){if(on&&console.log(e.pointerType,"DOWN",e.button),!!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;e.button>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new ti.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){let t=this.getPointerPressed(e.button);t===!1&&!this.isInRect(e)||e.pointerType==="touch"&&!t||(on&&console.log(e.pointerType,"MOVE",e.button),this.updatePointerPosition(e),this.setPointerStateT(e.button,this._pointerEvent,e.source),this.onDispatchEvent("pointermove",e))}onUp(e){if(this._pointerIds?.length>=e.button&&(this._pointerIds[e.button]=-1),!this._pointerPressed[e.button]){on&&console.log(e.pointerType,"UP",e.button,"was not down");return}if(on&&console.log(e.pointerType,"UP",e.button),this.setPointerState(e.button,this._pointerPressed,!1),this.setPointerStateT(e.button,this._pointerEvent,e.source),this.setPointerState(e.button,this._pointerUp,!0),this.updatePointerPosition(e),!this._pointerPositionDown[e.button]){on&&_a("Received pointer up event without matching down event for button: "+e.button),console.warn("Received pointer up event without matching down event for button: "+e.button);return}let i=e.clientX-this._pointerPositionDown[e.button].x,n=e.clientY-this._pointerPositionDown[e.button].y;if(e.button>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),Math.abs(i)<5&&Math.abs(n)<5){this.setPointerState(e.button,this._pointerClick,!0);let r=this._pointerUpTime[e.button],s=this.context.time.time-r;s<this._doubleClickTimeThreshold&&s>0&&this.setPointerState(e.button,this._pointerDoubleClick,!0)}this._pointerUpTime[e.button]=this.context.time.time,this.onDispatchEvent("pointerup",e)}updatePointerPosition(e){for(;e.button>=this._pointerPositions.length;)this._pointerPositions.push(new ti.Vector2);for(;e.button>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new ti.Vector2);for(;e.button>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new ti.Vector2);let t=this._pointerPositionsLastFrame[e.button];t.copy(this._pointerPositions[e.button]);let i=e.movementX!==void 0?e.movementX:e.clientX-t.x,n=e.movementY!==void 0?e.movementY:e.clientY-t.y;this._pointerPositionsDelta[e.button].set(i,n),this._pointerPositions[e.button].x=e.clientX,this._pointerPositions[e.button].y=e.clientY;let r=e.clientX,s=e.clientY;for(;e.button>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new ti.Vector2);let a=this._pointerPositionsRC[e.button];a.set(r,s),this.convertScreenspaceToRaycastSpace(a)}getPointerIndex(e){let t=this._pointerIds,i=-1;for(let n=0;n<t.length;n++){if(t[n]===e)return n;i===-1&&t[n]===-1&&(i=n)}return i!==-1?(t[i]=e,i):(t.push(e),t.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=G.Current;try{G.Current=this.context;let n=new Event(e);Mt(n,t),this.dispatchEvent(n)}finally{G.Current=i}}};import{Box3 as pb,BufferAttribute as Up,BufferGeometry as fb,Layers as od,LineBasicMaterial as mb,LineSegments as gb,Matrix4 as bb,Quaternion as vb,Raycaster as yb,Sphere as _b,Vector2 as xb,Vector3 as td}from"three";import*as he from"three";var Wc=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}inverseLerp(e,t,i){return(i-e)/(t-e)}remap(e,t,i,n,r){return n+(r-n)*(e-t)/(i-t)}moveTowards(e,t,i){return e+=i,(i<0&&e<t||i>0&&e>t)&&(e=t),e}toDegrees(e){return e*180/Math.PI}toRadians(e){return e*Math.PI/180}gammaToLinear(e){return Math.pow(e,2.2)}linearToGamma(e){return Math.pow(e,1/2.2)}},H=new Wc;import{WebGLRenderer as Rg,Vector3 as Sg,Quaternion as Pg,Uniform as $h,Texture as Og,ShaderMaterial as ep}from"three";function np(o,e,t){let i=o.length(),n=e.length(),r=H.lerp(i,n,t);return o.lerp(e,t).normalize().multiplyScalar(r)}var Tw=new Pg().setFromAxisAngle(new Sg(0,1,0),Math.PI);var Xc=new Ti(()=>new he.Vector3,100);function B(o,e=null,t=!0){let i=e??Xc.get();return o?o.parent?(t&&o.updateWorldMatrix(!0,!1),o.matrixWorldNeedsUpdate&&o.updateMatrixWorld(),i.setFromMatrixPosition(o.matrixWorld),i):i.copy(o.position):i.set(0,0,0)}function te(o,e){if(!o)return;let t=Xc.get();e!==t&&t.copy(e),(o?.parent??o).worldToLocal(t),o.position.set(t.x,t.y,t.z)}function sn(o,e,t,i){let n=Xc.get();n.set(e,t,i),te(o,n)}var xr=new he.Quaternion,Os=new he.Quaternion,Nc=new he.Quaternion;function pe(o,e=null){if(!o)return Os.set(0,0,0,1);let t=e??Os;return o.parent?(o.getWorldQuaternion(t),t):t.copy(o.quaternion)}function Ke(o,e){if(!o)return;e!==xr&&xr.copy(e);let t=xr;o?.parent?.getWorldQuaternion(Nc),Nc.invert();let n=Nc.multiply(t);o.quaternion.set(n.x,n.y,n.z,n.w)}function rp(o,e,t,i,n){xr.set(e,t,i,n),Ke(o,xr)}var Oa=new he.Vector3,Rw=new he.Vector3;function Me(o,e=null){return o?o.parent?(o.getWorldScale(e??Oa),e??Oa):Oa.copy(o.scale):Oa.set(0,0,0)}var Sw=new he.Vector3,Pw=new he.Quaternion;var tp=new he.Euler,ip=new he.Euler,kg=new he.Vector3;function Mg(o){return o.getWorldQuaternion(Os),ip.setFromQuaternion(Os),ip}function op(o,e){Ke(o,Os.setFromEuler(e))}function ka(o){let e=Mg(o),t=kg;return t.set(e.x,e.y,e.z),t.x=H.toDegrees(t.x),t.y=H.toDegrees(t.y),t.z=H.toDegrees(t.z),t}function Ma(o,e,t,i,n=!0){n&&(e=H.toRadians(e),t=H.toRadians(t),i=H.toRadians(i)),tp.set(e,t,i),xr.setFromEuler(tp),Ke(o,xr)}function ks(o,e=!0){!o||(e?function t(i){console.groupCollapsed((i.name?i.name:"(no name : "+i.type+")")+" %o",i),i.children.forEach(t),console.groupEnd()}(o):o.traverse(function(t){for(var i="|___",n=t;n.parent!==null;)i=" "+i,n=n.parent;console.log(i+t.name+" <"+t.type+">")}))}function sp(o){if(o){let e=o;return e.blendMode!==void 0&&e.clampWhenFinished!==void 0&&e.enabled!==void 0&&e.fadeIn!==void 0&&e.getClip!==void 0}return!1}var po=class{static createBlitMaterial(e){return new ep({uniforms:{map:new $h(null)},vertexShader:this.vertex,fragmentShader:e})}static copyTexture(e,t){let i=t??this.blipMaterial;i.uniforms.map.value=e,i.needsUpdate=!0,i.uniformsNeedUpdate=!0;let n=this.mesh;n.material=i,n.frustumCulled=!1,this.scene.children.length=0,this.scene.add(n),this.renderer.setSize(e.image.width,e.image.height),this.renderer.clear(),this.renderer.render(this.scene,this.perspectiveCam);let r=new Og(this.renderer.domElement);return r.name="Copy",r.needsUpdate=!0,r}static textureToCanvas(e,t){if(!e)return null;(t===!0||e.isCompressedTexture===!0)&&(e=Ig(e));let i=e.image;if(Ag(i)){let n=document.createElement("canvas");n.width=i.width,n.height=i.height;let r=n.getContext("2d");return r?(r.drawImage(i,0,0,i.width,i.height,0,0,n.width,n.height),n):(console.error("Failed getting canvas 2d context"),null)}return null}},ii=po;A(ii,"planeGeometry",new he.PlaneGeometry(2,2,1,1)),A(ii,"renderer",new Rg({antialias:!1})),A(ii,"perspectiveCam",new he.PerspectiveCamera),A(ii,"scene",new he.Scene),A(ii,"vertex",`
133
+ <a href="https://docs.needle.tools/serializable" target="_blank">documentation</a>`,1),console.warn(i,r,o[r],o)))}}function Mg(o,e){for(let i of Object.keys(e)){let n=e[i];if(typeof n=="object"&&n!==null&&n!==void 0){let r=o[i];if(!r){wr&&console.log(i,"is undefined on",o);continue}for(let s of Object.keys(n))r[s]===void 0&&t(n[s])&&!t(r)&&(r[s]=n[s])}}function t(i){switch(typeof i){case"number":case"string":case"boolean":return!0}return!1}}function Qc(o,e,t,i,n){let r=typeof e=="function"&&e.prototype===void 0,s=e;if(r)try{if(s=e?.call(e,n),r=!1,s==null)return}catch(l){console.error("Error in callback",l,o)}if(!r&&n instanceof s)return n;if(n&&typeof n=="object"&&rp(n)){if(n.__concreteInstance)return n.__concreteInstance;let l=n;if(!l.$serializedTypes&&s.prototype.$serializedTypes&&(l.$serializedTypes=s.prototype.$serializedTypes),l.$serializedTypes&&ks(l,o,t),n&&s!==void 0)try{let u=new s;Te&&console.log("Create concrete instance for persistent asset",n,"instance:",u),It(u,n),n.__concreteInstance=u,n=u}catch(u){console.error("Error creating instance or creating values on instance",u,n,s)}return n}if(i||(i={serializer:ka.getSerializerForConstructor(s)}),Array.isArray(o)){let l=[];for(let u=0;u<o.length;u++){let h=o[u],b=Qc(h,e,t,i,h);l.push(b)}return l}let a=i.serializer;if(a)return a.onDeserialize(o,t);let c;if(o&&(o.isMaterial||o.isTexture||o.isObject3D))c=o;else{if(o===void 0)return;c=new s(...Ig(o))}let d=c;return d.$serializedTypes&&ks(d,o,t),c}function Ig(o){if(Oa.length=0,typeof o=="object"&&o!==null&&o!==void 0)for(let e of Object.keys(o))Oa.push(o[e]);return Oa}var Ia=Symbol("assigned component properties");function It(o,e,t){if(e==null||o==null)return;let i=!1;o[Ia]=!0;let n=o.constructor?.name??"unknown";t?.registerDefinedKeys(n,o);for(let r of Object.keys(e)){let s=Dg(o,r);i&&s===void 0||(!s||s.writable===!0||s?.set!==void 0)&&(o[r]=e[r])}delete o[Ia]}function Dg(o,e){let t;do t=Object.getOwnPropertyDescriptor(o,e);while(!t&&(o=Object.getPrototypeOf(o)));return t}var cn=O("debuginput"),Ms=class{key;keyType;source;constructor(e){this.key=e.key,this.keyType=e.type,this.source=e}};var Da=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<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e<0||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]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}*foreachPointerId(e){for(let t=0;t<this._pointerTypes.length;t++)if(this._pointerIsActive[t]){if(e!==void 0){let i=this._pointerTypes[t];if(Array.isArray(e)){let n=!1;for(let r of e)if(i===r){n=!0;break}if(!n)continue}else if(e!==i)continue}yield t}}*foreachTouchId(){for(let e=0;e<this._pointerTypes.length;e++)this._pointerTypes[e]==="touch"&&this._pointerIsActive[e]&&(yield e)}_pointerIsActive(e){return e<0?!1:this._pointerPressed[e]||this._pointerDown[e]||this._pointerUp[e]}context;_pointerDown=[!1];_pointerUp=[!1];_pointerClick=[!1];_pointerDoubleClick=[!1];_pointerPressed=[!1];_pointerPositions=[new ii.Vector2];_pointerPositionsLastFrame=[new ii.Vector2];_pointerPositionsDelta=[new ii.Vector2];_pointerPositionsRC=[new ii.Vector2];_pointerPositionDown=[new ii.Vector2];_pointerDownTime=[];_pointerUpTime=[];_pointerIds=[];_pointerTypes=[""];_mouseWheelChanged=[!1];_mouseWheelDeltaY=[0];_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){cn&&Ke("Create Pointer down"),this.onDown(e)}createPointerMove(e){cn&&Ke("Create Pointer move"),this.onMove(e)}createPointerUp(e){cn&&Ke("Create Pointer up"),this.onUp(e)}convertScreenspaceToRaycastSpace(e){e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1}constructor(e){super(),this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame.bind(this)),window.addEventListener("touchstart",this.onTouchStart.bind(this),!1),window.addEventListener("touchmove",this.onTouchMove.bind(this),{passive:!0}),window.addEventListener("touchend",this.onTouchUp.bind(this),!1),window.addEventListener("mousedown",this.onMouseDown.bind(this),!1),window.addEventListener("mousemove",this.onMouseMove.bind(this),!1),window.addEventListener("mouseup",this.onMouseUp.bind(this),!1),window.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;for(let e=0;e<this._mouseWheelDeltaY.length;e++)this._mouseWheelDeltaY[e]=0}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 Ms(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 Ms(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 Ms(e)))}onMouseWheel(e){this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;let t=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=t+e.deltaY}onTouchStart(e){if(!(e.changedTouches.length<=0))for(let t=0;t<e.changedTouches.length;t++){let i=e.changedTouches[t],r={button:this.getPointerIndex(i.identifier),clientX:i.clientX,clientY:i.clientY,pointerType:"touch",source:e};this.onDown(r)}}onTouchMove(e){if(!(e.changedTouches.length<=0))for(let t=0;t<e.changedTouches.length;t++){let i=e.changedTouches[t],r={button:this.getPointerIndex(i.identifier),clientX:i.clientX,clientY:i.clientY,pointerType:"touch",source:e};this.onMove(r)}}onTouchUp(e){if(!(e.changedTouches.length<=0))for(let t=0;t<e.changedTouches.length;t++){let i=e.changedTouches[t],r={button:this.getPointerIndex(i.identifier),clientX:i.clientX,clientY:i.clientY,pointerType:"touch",source:e};this.onUp(r)}}onMouseDown(e){if(e.defaultPrevented)return;let t=e.button;this.onDown({button:t,clientX:e.clientX,clientY:e.clientY,pointerType:"mouse",source:e})}onMouseMove(e){if(e.defaultPrevented)return;let i={button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:"mouse",source:e,movementX:e.movementX,movementY:e.movementY};this.onMove(i)}onMouseUp(e){if(e.defaultPrevented)return;let t=e.button;this.onUp({button:t,clientX:e.clientX,clientY:e.clientY,pointerType:"mouse",source:e})}isInRect(e){if(this.context.isInXR)return!0;let t=this.context.domElement.getBoundingClientRect(),i=e.clientX,n=e.clientY,r=i>=t.x&&i<=t.right&&n>=t.y&&n<=t.bottom;return cn&&!r&&console.log("Not in rect",t,i,n),r}onDown(e){if(cn&&console.log(e.pointerType,"DOWN",e.button),!!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;e.button>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new ii.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){let t=this.getPointerPressed(e.button);t===!1&&!this.isInRect(e)||e.pointerType==="touch"&&!t||(cn&&console.log(e.pointerType,"MOVE",e.button),this.updatePointerPosition(e),this.setPointerStateT(e.button,this._pointerEvent,e.source),this.onDispatchEvent("pointermove",e))}onUp(e){if(this._pointerIds?.length>=e.button&&(this._pointerIds[e.button]=-1),!this._pointerPressed[e.button]){cn&&console.log(e.pointerType,"UP",e.button,"was not down");return}if(cn&&console.log(e.pointerType,"UP",e.button),this.setPointerState(e.button,this._pointerPressed,!1),this.setPointerStateT(e.button,this._pointerEvent,e.source),this.setPointerState(e.button,this._pointerUp,!0),this.updatePointerPosition(e),!this._pointerPositionDown[e.button]){cn&&Ta("Received pointer up event without matching down event for button: "+e.button),console.warn("Received pointer up event without matching down event for button: "+e.button);return}let i=e.clientX-this._pointerPositionDown[e.button].x,n=e.clientY-this._pointerPositionDown[e.button].y;if(e.button>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),Math.abs(i)<5&&Math.abs(n)<5){this.setPointerState(e.button,this._pointerClick,!0);let r=this._pointerUpTime[e.button],s=this.context.time.time-r;s<this._doubleClickTimeThreshold&&s>0&&this.setPointerState(e.button,this._pointerDoubleClick,!0)}this._pointerUpTime[e.button]=this.context.time.time,this.onDispatchEvent("pointerup",e)}updatePointerPosition(e){for(;e.button>=this._pointerPositions.length;)this._pointerPositions.push(new ii.Vector2);for(;e.button>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new ii.Vector2);for(;e.button>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new ii.Vector2);let t=this._pointerPositionsLastFrame[e.button];t.copy(this._pointerPositions[e.button]);let i=e.movementX!==void 0?e.movementX:e.clientX-t.x,n=e.movementY!==void 0?e.movementY:e.clientY-t.y;this._pointerPositionsDelta[e.button].set(i,n),this._pointerPositions[e.button].x=e.clientX,this._pointerPositions[e.button].y=e.clientY;let r=e.clientX,s=e.clientY;for(;e.button>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new ii.Vector2);let a=this._pointerPositionsRC[e.button];a.set(r,s),this.convertScreenspaceToRaycastSpace(a)}getPointerIndex(e){let t=this._pointerIds,i=-1;for(let n=0;n<t.length;n++){if(t[n]===e)return n;i===-1&&t[n]===-1&&(i=n)}return i!==-1?(t[i]=e,i):(t.push(e),t.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=G.Current;try{G.Current=this.context;let n=new Event(e);It(n,t),this.dispatchEvent(n)}finally{G.Current=i}}};import{Box3 as xb,BufferAttribute as Qp,BufferGeometry as wb,Layers as dd,LineBasicMaterial as Eb,LineSegments as Cb,Matrix4 as Tb,Quaternion as Rb,Raycaster as Sb,Sphere as Pb,Vector2 as Ob,Vector3 as sd}from"three";import*as pe from"three";var Yc=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}inverseLerp(e,t,i){return(i-e)/(t-e)}remap(e,t,i,n,r){return n+(r-n)*(e-t)/(i-t)}moveTowards(e,t,i){return e+=i,(i<0&&e<t||i>0&&e>t)&&(e=t),e}toDegrees(e){return e*180/Math.PI}toRadians(e){return e*Math.PI/180}gammaToLinear(e){return Math.pow(e,2.2)}linearToGamma(e){return Math.pow(e,1/2.2)}},H=new Yc;import{WebGLRenderer as Ag,Vector3 as Lg,Quaternion as jg,Uniform as sp,Texture as Hg,ShaderMaterial as ap}from"three";function dp(o,e,t){let i=o.length(),n=e.length(),r=H.lerp(i,n,t);return o.lerp(e,t).normalize().multiplyScalar(r)}var Lw=new jg().setFromAxisAngle(new Lg(0,1,0),Math.PI);var Jc=new Pi(()=>new pe.Vector3,100);function B(o,e=null,t=!0){let i=e??Jc.get();return o?o.parent?(t&&o.updateWorldMatrix(!0,!1),o.matrixWorldNeedsUpdate&&o.updateMatrixWorld(),i.setFromMatrixPosition(o.matrixWorld),i):i.copy(o.position):i.set(0,0,0)}function ie(o,e){if(!o)return;let t=Jc.get();e!==t&&t.copy(e),(o?.parent??o).worldToLocal(t),o.position.set(t.x,t.y,t.z)}function dn(o,e,t,i){let n=Jc.get();n.set(e,t,i),ie(o,n)}var Er=new pe.Quaternion,Is=new pe.Quaternion,Kc=new pe.Quaternion;function fe(o,e=null){if(!o)return Is.set(0,0,0,1);let t=e??Is;return o.parent?(o.getWorldQuaternion(t),t):t.copy(o.quaternion)}function Je(o,e){if(!o)return;e!==Er&&Er.copy(e);let t=Er;o?.parent?.getWorldQuaternion(Kc),Kc.invert();let n=Kc.multiply(t);o.quaternion.set(n.x,n.y,n.z,n.w)}function up(o,e,t,i,n){Er.set(e,t,i,n),Je(o,Er)}var Aa=new pe.Vector3,jw=new pe.Vector3;function Me(o,e=null){return o?o.parent?(o.getWorldScale(e??Aa),e??Aa):Aa.copy(o.scale):Aa.set(0,0,0)}var Hw=new pe.Vector3,Fw=new pe.Quaternion;var lp=new pe.Euler,cp=new pe.Euler,Fg=new pe.Vector3;function Bg(o){return o.getWorldQuaternion(Is),cp.setFromQuaternion(Is),cp}function hp(o,e){Je(o,Is.setFromEuler(e))}function La(o){let e=Bg(o),t=Fg;return t.set(e.x,e.y,e.z),t.x=H.toDegrees(t.x),t.y=H.toDegrees(t.y),t.z=H.toDegrees(t.z),t}function ja(o,e,t,i,n=!0){n&&(e=H.toRadians(e),t=H.toRadians(t),i=H.toRadians(i)),lp.set(e,t,i),Er.setFromEuler(lp),Je(o,Er)}function Ds(o,e=!0){!o||(e?function t(i){console.groupCollapsed((i.name?i.name:"(no name : "+i.type+")")+" %o",i),i.children.forEach(t),console.groupEnd()}(o):o.traverse(function(t){for(var i="|___",n=t;n.parent!==null;)i=" "+i,n=n.parent;console.log(i+t.name+" <"+t.type+">")}))}function pp(o){if(o){let e=o;return e.blendMode!==void 0&&e.clampWhenFinished!==void 0&&e.enabled!==void 0&&e.fadeIn!==void 0&&e.getClip!==void 0}return!1}var mo=class{static createBlitMaterial(e){return new ap({uniforms:{map:new sp(null)},vertexShader:this.vertex,fragmentShader:e})}static copyTexture(e,t){let i=t??this.blipMaterial;i.uniforms.map.value=e,i.needsUpdate=!0,i.uniformsNeedUpdate=!0;let n=this.mesh;n.material=i,n.frustumCulled=!1,this.scene.children.length=0,this.scene.add(n),this.renderer.setSize(e.image.width,e.image.height),this.renderer.clear(),this.renderer.render(this.scene,this.perspectiveCam);let r=new Hg(this.renderer.domElement);return r.name="Copy",r.needsUpdate=!0,r}static textureToCanvas(e,t){if(!e)return null;(t===!0||e.isCompressedTexture===!0)&&(e=Ug(e));let i=e.image;if(Gg(i)){let n=document.createElement("canvas");n.width=i.width,n.height=i.height;let r=n.getContext("2d");return r?(r.drawImage(i,0,0,i.width,i.height,0,0,n.width,n.height),n):(console.error("Failed getting canvas 2d context"),null)}return null}},ni=mo;D(ni,"planeGeometry",new pe.PlaneGeometry(2,2,1,1)),D(ni,"renderer",new Ag({antialias:!1})),D(ni,"perspectiveCam",new pe.PerspectiveCamera),D(ni,"scene",new pe.Scene),D(ni,"vertex",`
134
134
  varying vec2 vUv;
135
135
  void main(){
136
136
  vUv = uv;
137
137
  gl_Position = vec4(position.xy * 1.0,0.,.999999);
138
- }`),A(ii,"fragment",`
138
+ }`),D(ni,"fragment",`
139
139
  uniform sampler2D map;
140
140
  varying vec2 vUv;
141
141
  void main(){
@@ -143,13 +143,13 @@ in script ${i}.ts
143
143
  uv.y = 1.0 - uv.y;
144
144
  gl_FragColor = texture2D( map, uv);
145
145
  // gl_FragColor = vec4(uv.xy, 0, 1);
146
- }`),A(ii,"blipMaterial",new ep({uniforms:{map:new $h(null)},vertexShader:po.vertex,fragmentShader:po.fragment})),A(ii,"mesh",new he.Mesh(po.planeGeometry,po.blipMaterial));function Ig(o){return ii.copyTexture(o)}function Ag(o){return typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&o instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&o instanceof ImageBitmap}import{Vector3 as Dg}from"three";var Fw=Symbol("object"),ap=new Ti(()=>new Dg,20),Ia=class{_point;_normal;distance;impulse;friction;get point(){return ap.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return ap.get().set(this._normal.x,this._normal.y,this._normal.z)}constructor(e,t,i,n,r){this._point=e,this.distance=t,this._normal=i,this.impulse=n,this.friction=r}},Ms=class{contacts;constructor(e,t,i){this.me=e,this._collider=t,this._gameObject=t.gameObject,this.contacts=i}me;_collider;get collider(){return this._collider}_gameObject;get gameObject(){return this._gameObject}get rigidBody(){return this.collider?.attachedRigidbody}};function Er(o,e){try{e?o(e):o()}catch(t){return console.error(t),!1}return!0}var Oi="__isActiveInHierarchy",Cr="builtin_components";var Hg=M("debugnewscripts"),fe=[];function dn(o){if(!(o.new_scripts.length<=0)){if(Hg&&console.log("Register new components",o.new_scripts.length,o.alias?"element: "+o.alias:""),o.new_scripts_pre_setup_callbacks.length>0){for(let e of o.new_scripts_pre_setup_callbacks)!e||e();o.new_scripts_pre_setup_callbacks.length=0}fe.length=0,o.new_scripts.length>0&&fe.push(...o.new_scripts),o.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=o,Is(t.gameObject),qc(t,o)}catch(t){console.error(t),ln(fe[e],o),fe.splice(e,1),e--}for(let e=0;e<fe.length;e++)try{let t=fe[e];if(t.destroyed){ln(fe[e],o),fe.splice(e,1),e--;continue}t.__internalAwake!==void 0&&(t.gameObject||console.error("MISSING GAMEOBJECT",t,t.gameObject),Is(t.gameObject),t.activeAndEnabled&&Er(t.__internalAwake.bind(t)))}catch(t){console.error(t),ln(fe[e],o),fe.splice(e,1),e--}for(let e=0;e<fe.length;e++)try{let t=fe[e];if(t.destroyed||t.enabled===!1||(Is(t.gameObject),t.activeAndEnabled===!1))continue;t.__internalEnable!==void 0&&(t.enabled=!0,Er(t.__internalEnable.bind(t)))}catch(t){console.error(t),ln(fe[e],o),fe.splice(e,1),e--}for(let e=0;e<fe.length;e++)try{let t=fe[e];if(t.destroyed||!t.gameObject)continue;o.new_script_start.push(t)}catch(t){console.error(t),ln(fe[e],o),fe.splice(e,1),e--}fe.length=0;for(let e of o.new_scripts_post_setup_callbacks)e&&e();o.new_scripts_post_setup_callbacks.length=0}}function lp(o){!o||(o.__internalDisable(),ln(o,o.context))}function Aa(o,e){for(let t=0;t<o.new_script_start.length;t++)try{let i=o.new_script_start[t];if(e!==void 0&&i.gameObject!==e||i.destroyed||i.activeAndEnabled===!1)continue;Er(i.__internalAwake.bind(i)),Er(i.__internalEnable.bind(i)),Er(i.__internalStart.bind(i)),o.new_script_start.splice(t,1),t--}catch(i){console.error(i),ln(o.new_script_start[t],o),o.new_script_start.splice(t,1),t--}}function qc(o,e){e.scripts.indexOf(o)===-1&&(e.scripts.push(o),o.earlyUpdate&&e.scripts_earlyUpdate.push(o),o.update&&e.scripts_update.push(o),o.lateUpdate&&e.scripts_lateUpdate.push(o),o.onBeforeRender&&e.scripts_onBeforeRender.push(o),o.onAfterRender&&e.scripts_onAfterRender.push(o),o.onPausedChanged&&e.scripts_pausedChanged.push(o))}function ln(o,e){an(o,e.new_scripts),an(o,e.new_script_start),an(o,e.scripts),an(o,e.scripts_earlyUpdate),an(o,e.scripts_update),an(o,e.scripts_lateUpdate),an(o,e.scripts_onBeforeRender),an(o,e.scripts_onAfterRender),an(o,e.scripts_pausedChanged),e.stopAllCoroutinesFrom(o)}function an(o,e){let t=e.indexOf(o);t>=0&&e.splice(t,1)}var Fg={},Qc={};function fo(o){if(o||(o=G.Current.scene),!o){console.trace("Invalid call - no current context.");return}cp(o,cn(o),!0)}function cp(o,e,t){let i=!1,n=cn(o);if(Fg[o.uuid]=n,e&&(e=cn(o)),o[Oi]=e,!i){let r=Qc[o.uuid];r!==void 0&&r!==e&&t&&Bg(o,s=>{e?(Er(s.__internalAwake.bind(s)),s.enabled=!0):s.enabled=!1})}if(Qc[o.uuid]=e,o.children)for(let r of o.children)cp(r,e,t)}function Is(o){let e=!0,t=o,i=!1;for(;t&&t;){if(t.type==="Scene"&&(i=!0),!cn(t)){e=!1;break}t=t.parent}if(!o){console.error("GO is null");return}Qc[o.uuid]=e,o[Oi]=e&&i}function Bg(o,e){if(o.userData?.components)for(let t of o.userData.components)e(t)}import*as As from"three";var up=/^(?:[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 Ug(o){return typeof o=="string"&&up.test(o)}var hp=Ug;var He=[];for(let o=0;o<256;++o)He.push((o+256).toString(16).slice(1));function pp(o,e=0){return(He[o[e+0]]+He[o[e+1]]+He[o[e+2]]+He[o[e+3]]+"-"+He[o[e+4]]+He[o[e+5]]+"-"+He[o[e+6]]+He[o[e+7]]+"-"+He[o[e+8]]+He[o[e+9]]+"-"+He[o[e+10]]+He[o[e+11]]+He[o[e+12]]+He[o[e+13]]+He[o[e+14]]+He[o[e+15]]).toLowerCase()}function Gg(o){if(!hp(o))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(o.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(o.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(o.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(o.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(o.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 fp=Gg;function Vg(o){o=unescape(encodeURIComponent(o));let e=[];for(let t=0;t<o.length;++t)e.push(o.charCodeAt(t));return e}var zg="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Wg="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Yc(o,e,t){function i(n,r,s,a){var c;if(typeof n=="string"&&(n=Vg(n)),typeof r=="string"&&(r=fp(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,s){a=a||0;for(let l=0;l<16;++l)s[a+l]=d[l];return s}return pp(d)}try{i.name=o}catch{}return i.DNS=zg,i.URL=Wg,i}function Ng(o,e,t,i){switch(o){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 Kc(o,e){return o<<e|o>>>32-e}function Xg(o){let e=[1518500249,1859775393,2400959708,3395469782],t=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof o=="string"){let s=unescape(encodeURIComponent(o));o=[];for(let a=0;a<s.length;++a)o.push(s.charCodeAt(a))}else Array.isArray(o)||(o=Array.prototype.slice.call(o));o.push(128);let i=o.length/4+2,n=Math.ceil(i/16),r=new Array(n);for(let s=0;s<n;++s){let a=new Uint32Array(16);for(let c=0;c<16;++c)a[c]=o[s*64+c*4]<<24|o[s*64+c*4+1]<<16|o[s*64+c*4+2]<<8|o[s*64+c*4+3];r[s]=a}r[n-1][14]=(o.length-1)*8/Math.pow(2,32),r[n-1][14]=Math.floor(r[n-1][14]),r[n-1][15]=(o.length-1)*8&4294967295;for(let s=0;s<n;++s){let a=new Uint32Array(80);for(let b=0;b<16;++b)a[b]=r[s][b];for(let b=16;b<80;++b)a[b]=Kc(a[b-3]^a[b-8]^a[b-14]^a[b-16],1);let c=t[0],d=t[1],l=t[2],u=t[3],h=t[4];for(let b=0;b<80;++b){let w=Math.floor(b/20),v=Kc(c,5)+Ng(w,d,l,u)+h+e[w]+a[b]>>>0;h=u,u=l,l=Kc(d,30)>>>0,d=c,c=v}t[0]=t[0]+c>>>0,t[1]=t[1]+d>>>0,t[2]=t[2]+l>>>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 mp=Xg;var Qg=Yc("v5",80,mp),Da=Qg;var La=M("debugcomponents"),gp="eff8ba80-635d-11ec-90d6-0242ac120003",Ie=class{get seed(){return this._seed}set seed(e){this._seed=e}_originalSeed;_seed;constructor(e){this._originalSeed=e,this._seed=e}reset(){this._seed=this._originalSeed}generateUUID(e){if(typeof e=="string")return Da(e,gp);let t=this._seed;return this._seed-=1,Da(t.toString(),gp)}initialize(e){typeof e=="string"?this._seed=Ie.hash(e):this._seed=e}static createFromString(e){return new Ie(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 ja=class{guid;constructor(e){this.guid=e}};function mo(o,e,t=!0){if(!o)return;let i=o;if(ni(o,t),!e){console.warn("Can not send destroy: No networking connection provided",o.guid);return}if(!e.isConnected){console.warn("Can not send destroy: not connected",o.guid);return}let n=o.guid;if(!n&&i.uuid&&(n=i.uuid),!n){console.warn("Can not send destroy: failed to find guid",o);return}let r=new ja(n);e.send("instance-destroyed",r,2)}function bp(o,e){let t=new ja(o);e.send("instance-destroyed",t,2)}function vp(o){o.connection.beginListen("instance-destroyed",e=>{La&&console.log("[Remote] Destroyed",o.scene,e);let t=Tr(e.guid,o.scene);t&&ni(t)})}var Jc=class{guid;originalGuid;seed;visible;hostData;dontSave;parent;position;rotation;scale;constructor(e,t){this.originalGuid=e,this.guid=t}};function Ha(o,e,t,i){let n=o;if(!n.guid)return console.warn("Can not instantiate: No guid",n),null;if(e.context||(e.context=G.Current),!e.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;let r=e?{...e}:null,{instance:s,seed:a}=qg(n,e);if(s){let c=s;if(c.guid){La&&console.log("[Local] new instance","gameobject:",s?.guid);let d=new Jc(n.guid,c.guid);d.seed=a,r&&(r.position&&(d.position={x:r.position.x,y:r.position.y,z:r.position.z}),r.rotation&&(d.rotation={x:r.rotation.x,y:r.rotation.y,z:r.rotation.z,w:r.rotation.w}),r.scale&&(d.scale={x:r.scale.x,y:r.scale.y,z:r.scale.z})),d.position||(d.position={x:c.position.x,y:c.position.y,z:c.position.z}),d.rotation||(d.rotation={x:c.quaternion.x,y:c.quaternion.y,z:c.quaternion.z,w:c.quaternion.w}),d.scale||(d.scale={x:c.scale.x,y:c.scale.y,z:c.scale.z}),d.visible=n.visible,r?.parent&&(typeof r.parent=="string"?d.parent=r.parent:d.parent=r.parent.guid),d.hostData=t,i===!1&&(d.dontSave=!0),e?.context?.connection.send("new-instance-created",d)}else console.warn("Missing guid, can not send new instance event",c)}return s}function Fa(){return Math.random()*9999999}function yp(o){o.connection.beginListen("new-instance-created",async e=>{let t=await Yg(e.originalGuid,o.scene);if(!t){console.warn("could not find object that was instantiated: "+e.guid);return}let i=new Fe;e.position&&(i.position=new As.Vector3(e.position.x,e.position.y,e.position.z)),e.rotation&&(i.rotation=new As.Quaternion(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w)),e.scale&&(i.scale=new As.Vector3(e.scale.x,e.scale.y,e.scale.z)),i.parent=e.parent,e.seed&&(i.idProvider=new Ie(e.seed)),i.visible=e.visible,i.context=o,La&&o.alias&&console.log("[Remote] instantiate in: "+o.alias);let n=Rr(t,i);n&&(e.parent==="scene"&&o.scene.add(n),La&&console.log("[Remote] new instance","gameobject:",n?.guid,t))})}function qg(o,e){let t=Fa(),i=e??new Fe;i.idProvider=new Ie(t);let n=Rr(o,i);return{seed:t,instance:n}}var _p={};function xp(o,e){_p[o]=e}async function Yg(o,e){let t=_p[o];if(t!=null){let i=await t(o);if(i)return i}return wp(o,e)}function wp(o,e){if(e===null||!o)return null;if(e.guid===o)return e;if(e.children)for(let t of e.children){let i=wp(o,t);if(i)return i}return null}var Ep=new Map;function Cp(o,e){if(!o)return;if(!e){console.warn("No prototype found",o,o.prototype,o.constructor);return}let t=Ep.get(e);t&&t.apply(o)}function Tp(o){let e=Kg(o.prototype);Ep.set(o,e)}function Kg(o){return new $c(o)}var $c=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 st}from"three";var ed=M("debuggetcomponent");function Jg(o){return o==null||o.isObject3D?o:o.object&&o.object.isObject3D?o.object:o}function Ba(o,e){if(!o||!o.userData.components)return;let t=o.userData.components.indexOf(e);t<0||(e.gameObject=null,o.userData.components.splice(t,1))}function Ua(o,e){let t=Sr(o,e);if(t)return t;let i=new e;return Un(o,i)}function Un(o,e,t=!0){o||new Error("Can not add componet to null object"),o.userData||(o.userData={}),o.userData.components||(o.userData.components=[]),o.userData.components.push(e),e.gameObject=o,yo(o),Ga(e);try{e.__internalAwake&&t&&(Is(o),e.__internalAwake())}catch(i){console.error(i)}return e}function Sp(o,e){if(e.gameObject!==o){if(e.gameObject&&e.gameObject.userData.components){let t=e.gameObject.userData.components.indexOf(e);e.gameObject.userData.components.splice(t,1)}if(!o.userData.components)o.userData.components=[];else if(o.userData.components.includes(e))return;o.userData.components.push(e),e.gameObject=o}}function Pp(o){if(o.gameObject&&o.gameObject.userData.components){let e=o.gameObject.userData.components.indexOf(o);o.gameObject.userData.components.splice(e,1)}o.__internalDisable&&o.__internalDisable(),o.onDestroy&&o.onDestroy(),ln(o,o.context??G.Current),o.__internalDestroy(),o.gameObject=null}var Rp=!1;function Op(o,e,t){if(o!=null){if(!o.isObject3D){console.error("Object is not object3D");return}if(!o?.userData?.components)return null;if(typeof e=="string"&&(Rp||(Rp=!0,console.warn(`Accessing components by name is not supported.
146
+ }`),D(ni,"blipMaterial",new ap({uniforms:{map:new sp(null)},vertexShader:mo.vertex,fragmentShader:mo.fragment})),D(ni,"mesh",new pe.Mesh(mo.planeGeometry,mo.blipMaterial));function Ug(o){return ni.copyTexture(o)}function Gg(o){return typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&o instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&o instanceof ImageBitmap}import{Vector3 as Vg}from"three";var qw=Symbol("object"),fp=new Pi(()=>new Vg,20),Ha=class{_point;_normal;distance;impulse;friction;get point(){return fp.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return fp.get().set(this._normal.x,this._normal.y,this._normal.z)}constructor(e,t,i,n,r){this._point=e,this.distance=t,this._normal=i,this.impulse=n,this.friction=r}},As=class{contacts;constructor(e,t,i){this.me=e,this._collider=t,this._gameObject=t.gameObject,this.contacts=i}me;_collider;get collider(){return this._collider}_gameObject;get gameObject(){return this._gameObject}get rigidBody(){return this.collider?.attachedRigidbody}};function Tr(o,e){try{e?o(e):o()}catch(t){return console.error(t),!1}return!0}var Ii="__isActiveInHierarchy",Rr="builtin_components";var Ng=O("debugnewscripts"),me=[];function fn(o){if(!(o.new_scripts.length<=0)){if(Ng&&console.log("Register new components",o.new_scripts.length,o.alias?"element: "+o.alias:""),o.new_scripts_pre_setup_callbacks.length>0){for(let e of o.new_scripts_pre_setup_callbacks)!e||e();o.new_scripts_pre_setup_callbacks.length=0}me.length=0,o.new_scripts.length>0&&me.push(...o.new_scripts),o.new_scripts.length=0;for(let e=0;e<me.length;e++)try{let t=me[e];if(t.destroyed)continue;if(!t.gameObject){console.error("MISSING GAMEOBJECT - will ignore",t),me.splice(e,1),e--;continue}t.context=o,Ls(t.gameObject),$c(t,o)}catch(t){console.error(t),hn(me[e],o),me.splice(e,1),e--}for(let e=0;e<me.length;e++)try{let t=me[e];if(t.destroyed){hn(me[e],o),me.splice(e,1),e--;continue}t.__internalAwake!==void 0&&(t.gameObject||console.error("MISSING GAMEOBJECT",t,t.gameObject),Ls(t.gameObject),t.activeAndEnabled&&Tr(t.__internalAwake.bind(t)))}catch(t){console.error(t),hn(me[e],o),me.splice(e,1),e--}for(let e=0;e<me.length;e++)try{let t=me[e];if(t.destroyed||t.enabled===!1||(Ls(t.gameObject),t.activeAndEnabled===!1))continue;t.__internalEnable!==void 0&&(t.enabled=!0,Tr(t.__internalEnable.bind(t)))}catch(t){console.error(t),hn(me[e],o),me.splice(e,1),e--}for(let e=0;e<me.length;e++)try{let t=me[e];if(t.destroyed||!t.gameObject)continue;o.new_script_start.push(t)}catch(t){console.error(t),hn(me[e],o),me.splice(e,1),e--}me.length=0;for(let e of o.new_scripts_post_setup_callbacks)e&&e();o.new_scripts_post_setup_callbacks.length=0}}function mp(o){!o||(o.__internalDisable(),hn(o,o.context))}function Fa(o,e){for(let t=0;t<o.new_script_start.length;t++)try{let i=o.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)),o.new_script_start.splice(t,1),t--}catch(i){console.error(i),hn(o.new_script_start[t],o),o.new_script_start.splice(t,1),t--}}function $c(o,e){e.scripts.indexOf(o)===-1&&(e.scripts.push(o),o.earlyUpdate&&e.scripts_earlyUpdate.push(o),o.update&&e.scripts_update.push(o),o.lateUpdate&&e.scripts_lateUpdate.push(o),o.onBeforeRender&&e.scripts_onBeforeRender.push(o),o.onAfterRender&&e.scripts_onAfterRender.push(o),o.onPausedChanged&&e.scripts_pausedChanged.push(o))}function hn(o,e){un(o,e.new_scripts),un(o,e.new_script_start),un(o,e.scripts),un(o,e.scripts_earlyUpdate),un(o,e.scripts_update),un(o,e.scripts_lateUpdate),un(o,e.scripts_onBeforeRender),un(o,e.scripts_onAfterRender),un(o,e.scripts_pausedChanged),e.stopAllCoroutinesFrom(o)}function un(o,e){let t=e.indexOf(o);t>=0&&e.splice(t,1)}var Xg={},Zc={};function go(o){if(o||(o=G.Current.scene),!o){console.trace("Invalid call - no current context.");return}gp(o,pn(o),!0)}function gp(o,e,t){let i=!1,n=pn(o);if(Xg[o.uuid]=n,e&&(e=pn(o)),o[Ii]=e,!i){let r=Zc[o.uuid];r!==void 0&&r!==e&&t&&Qg(o,s=>{e?(Tr(s.__internalAwake.bind(s)),s.enabled=!0):s.enabled=!1})}if(Zc[o.uuid]=e,o.children)for(let r of o.children)gp(r,e,t)}function Ls(o){let e=!0,t=o,i=!1;for(;t&&t;){if(t.type==="Scene"&&(i=!0),!pn(t)){e=!1;break}t=t.parent}if(!o){console.error("GO is null");return}Zc[o.uuid]=e,o[Ii]=e&&i}function Qg(o,e){if(o.userData?.components)for(let t of o.userData.components)e(t)}import*as js from"three";var vp=/^(?:[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 qg(o){return typeof o=="string"&&vp.test(o)}var yp=qg;var He=[];for(let o=0;o<256;++o)He.push((o+256).toString(16).slice(1));function _p(o,e=0){return(He[o[e+0]]+He[o[e+1]]+He[o[e+2]]+He[o[e+3]]+"-"+He[o[e+4]]+He[o[e+5]]+"-"+He[o[e+6]]+He[o[e+7]]+"-"+He[o[e+8]]+He[o[e+9]]+"-"+He[o[e+10]]+He[o[e+11]]+He[o[e+12]]+He[o[e+13]]+He[o[e+14]]+He[o[e+15]]).toLowerCase()}function Yg(o){if(!yp(o))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(o.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(o.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(o.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(o.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(o.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 xp=Yg;function Kg(o){o=unescape(encodeURIComponent(o));let e=[];for(let t=0;t<o.length;++t)e.push(o.charCodeAt(t));return e}var Jg="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Zg="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function ed(o,e,t){function i(n,r,s,a){var c;if(typeof n=="string"&&(n=Kg(n)),typeof r=="string"&&(r=xp(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,s){a=a||0;for(let l=0;l<16;++l)s[a+l]=d[l];return s}return _p(d)}try{i.name=o}catch{}return i.DNS=Jg,i.URL=Zg,i}function $g(o,e,t,i){switch(o){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 td(o,e){return o<<e|o>>>32-e}function eb(o){let e=[1518500249,1859775393,2400959708,3395469782],t=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof o=="string"){let s=unescape(encodeURIComponent(o));o=[];for(let a=0;a<s.length;++a)o.push(s.charCodeAt(a))}else Array.isArray(o)||(o=Array.prototype.slice.call(o));o.push(128);let i=o.length/4+2,n=Math.ceil(i/16),r=new Array(n);for(let s=0;s<n;++s){let a=new Uint32Array(16);for(let c=0;c<16;++c)a[c]=o[s*64+c*4]<<24|o[s*64+c*4+1]<<16|o[s*64+c*4+2]<<8|o[s*64+c*4+3];r[s]=a}r[n-1][14]=(o.length-1)*8/Math.pow(2,32),r[n-1][14]=Math.floor(r[n-1][14]),r[n-1][15]=(o.length-1)*8&4294967295;for(let s=0;s<n;++s){let a=new Uint32Array(80);for(let b=0;b<16;++b)a[b]=r[s][b];for(let b=16;b<80;++b)a[b]=td(a[b-3]^a[b-8]^a[b-14]^a[b-16],1);let c=t[0],d=t[1],l=t[2],u=t[3],h=t[4];for(let b=0;b<80;++b){let w=Math.floor(b/20),v=td(c,5)+$g(w,d,l,u)+h+e[w]+a[b]>>>0;h=u,u=l,l=td(d,30)>>>0,d=c,c=v}t[0]=t[0]+c>>>0,t[1]=t[1]+d>>>0,t[2]=t[2]+l>>>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 wp=eb;var tb=ed("v5",80,wp),Ba=tb;var Ua=O("debugcomponents"),Ep="eff8ba80-635d-11ec-90d6-0242ac120003",Ie=class{get seed(){return this._seed}set seed(e){this._seed=e}_originalSeed;_seed;constructor(e){this._originalSeed=e,this._seed=e}reset(){this._seed=this._originalSeed}generateUUID(e){if(typeof e=="string")return Ba(e,Ep);let t=this._seed;return this._seed-=1,Ba(t.toString(),Ep)}initialize(e){typeof e=="string"?this._seed=Ie.hash(e):this._seed=e}static createFromString(e){return new Ie(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 Ga=class{guid;constructor(e){this.guid=e}};function bo(o,e,t=!0){if(!o)return;let i=o;if(ri(o,t),!e){console.warn("Can not send destroy: No networking connection provided",o.guid);return}if(!e.isConnected){console.warn("Can not send destroy: not connected",o.guid);return}let n=o.guid;if(!n&&i.uuid&&(n=i.uuid),!n){console.warn("Can not send destroy: failed to find guid",o);return}let r=new Ga(n);e.send("instance-destroyed",r,2)}function Cp(o,e){let t=new Ga(o);e.send("instance-destroyed",t,2)}function Tp(o){o.connection.beginListen("instance-destroyed",e=>{Ua&&console.log("[Remote] Destroyed",o.scene,e);let t=Sr(e.guid,o.scene);t&&ri(t)})}var id=class{guid;originalGuid;seed;visible;hostData;dontSave;parent;position;rotation;scale;constructor(e,t){this.originalGuid=e,this.guid=t}};function Va(o,e,t,i){let n=o;if(!n.guid)return console.warn("Can not instantiate: No guid",n),null;if(e.context||(e.context=G.Current),!e.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;let r=e?{...e}:null,{instance:s,seed:a}=ib(n,e);if(s){let c=s;if(c.guid){Ua&&console.log("[Local] new instance","gameobject:",s?.guid);let d=new id(n.guid,c.guid);d.seed=a,r&&(r.position&&(d.position={x:r.position.x,y:r.position.y,z:r.position.z}),r.rotation&&(d.rotation={x:r.rotation.x,y:r.rotation.y,z:r.rotation.z,w:r.rotation.w}),r.scale&&(d.scale={x:r.scale.x,y:r.scale.y,z:r.scale.z})),d.position||(d.position={x:c.position.x,y:c.position.y,z:c.position.z}),d.rotation||(d.rotation={x:c.quaternion.x,y:c.quaternion.y,z:c.quaternion.z,w:c.quaternion.w}),d.scale||(d.scale={x:c.scale.x,y:c.scale.y,z:c.scale.z}),d.visible=n.visible,r?.parent&&(typeof r.parent=="string"?d.parent=r.parent:d.parent=r.parent.guid),d.hostData=t,i===!1&&(d.dontSave=!0),e?.context?.connection.send("new-instance-created",d)}else console.warn("Missing guid, can not send new instance event",c)}return s}function za(){return Math.random()*9999999}function Rp(o){o.connection.beginListen("new-instance-created",async e=>{let t=await nb(e.originalGuid,o.scene);if(!t){console.warn("could not find object that was instantiated: "+e.guid);return}let i=new Fe;e.position&&(i.position=new js.Vector3(e.position.x,e.position.y,e.position.z)),e.rotation&&(i.rotation=new js.Quaternion(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w)),e.scale&&(i.scale=new js.Vector3(e.scale.x,e.scale.y,e.scale.z)),i.parent=e.parent,e.seed&&(i.idProvider=new Ie(e.seed)),i.visible=e.visible,i.context=o,Ua&&o.alias&&console.log("[Remote] instantiate in: "+o.alias);let n=Pr(t,i);n&&(e.parent==="scene"&&o.scene.add(n),Ua&&console.log("[Remote] new instance","gameobject:",n?.guid,t))})}function ib(o,e){let t=za(),i=e??new Fe;i.idProvider=new Ie(t);let n=Pr(o,i);return{seed:t,instance:n}}var Sp={};function Pp(o,e){Sp[o]=e}async function nb(o,e){let t=Sp[o];if(t!=null){let i=await t(o);if(i)return i}return Op(o,e)}function Op(o,e){if(e===null||!o)return null;if(e.guid===o)return e;if(e.children)for(let t of e.children){let i=Op(o,t);if(i)return i}return null}var kp=new Map;function Mp(o,e){if(!o)return;if(!e){console.warn("No prototype found",o,o.prototype,o.constructor);return}let t=kp.get(e);t&&t.apply(o)}function Ip(o){let e=rb(o.prototype);kp.set(o,e)}function rb(o){return new rd(o)}var rd=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 at}from"three";var od=O("debuggetcomponent");function ob(o){return o==null||o.isObject3D?o:o.object&&o.object.isObject3D?o.object:o}function Wa(o,e){if(!o||!o.userData.components)return;let t=o.userData.components.indexOf(e);t<0||(e.gameObject=null,o.userData.components.splice(t,1))}function Na(o,e){let t=Or(o,e);if(t)return t;let i=new e;return Vn(o,i)}function Vn(o,e,t=!0){o||new Error("Can not add componet to null object"),o.userData||(o.userData={}),o.userData.components||(o.userData.components=[]),o.userData.components.push(e),e.gameObject=o,xo(o),Xa(e);try{e.__internalAwake&&t&&(Ls(o),e.__internalAwake())}catch(i){console.error(i)}return e}function Ap(o,e){if(e.gameObject!==o){if(e.gameObject&&e.gameObject.userData.components){let t=e.gameObject.userData.components.indexOf(e);e.gameObject.userData.components.splice(t,1)}if(!o.userData.components)o.userData.components=[];else if(o.userData.components.includes(e))return;o.userData.components.push(e),e.gameObject=o}}function Lp(o){if(o.gameObject&&o.gameObject.userData.components){let e=o.gameObject.userData.components.indexOf(o);o.gameObject.userData.components.splice(e,1)}o.__internalDisable&&o.__internalDisable(),o.onDestroy&&o.onDestroy(),hn(o,o.context??G.Current),o.__internalDestroy(),o.gameObject=null}var Dp=!1;function jp(o,e,t){if(o!=null){if(!o.isObject3D){console.error("Object is not object3D");return}if(!o?.userData?.components)return null;if(typeof e=="string"&&(Dp||(Dp=!0,console.warn(`Accessing components by name is not supported.
147
147
  Please use the component type instead. This may keep working in local development but it will fail when bundling your application.
148
148
 
149
149
  You can import other modules your main module to get access to types
150
150
  or if you use npmdefs you can make types available globally using globalThis:
151
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis`))),ed&&console.log("FIND",e),e!=null){for(let i=0;i<o.userData.components.length;i++){let n=o.userData.components[i];if(e===null||n.constructor.name===e.name||n.constructor.name===e)if(ed&&console.log("MATCH BY NAME",n),t)t.push(n);else return n}for(let i=0;i<o.userData.components.length;i++){let n=o.userData.components[i],r=Object.getPrototypeOf(n.constructor);do{if(r===e)if(ed&&console.log("MATCH BY PROTOYPE",r),t)t.push(n);else return n;r=Object.getPrototypeOf(r)}while(r)}return t}}}function Sr(o,e){return Op(o,e)}function bo(o,e,t){return t||(t=[]),Op(o,e,t)}function Pr(o,e,t){let i=Sr(o,e);if(t===!1&&i.enabled===!1)return null;if(i)return i;for(let n=0;n<o?.children?.length;n++){let r=Pr(o.children[n],e);if(r)return r}return null}function vo(o,e,t){t||(t=[]),bo(o,e,t);for(let i=0;i<o?.children?.length;i++)vo(o.children[i],e,t);return t}function go(o,e){if(!o)return null;if(Array.isArray(o)){for(let i=0;i<o.length;i++){let n=Jg(o[i]),r=go(n,e);if(r)return r}return null}let t=Sr(o,e);return t||(o.parent?go(o.parent,e):null)}function Ds(o,e,t){return t||(t=[]),o?(bo(o,e,t),o.parent?Ds(o.parent,e,t):t):t}function kp(o,e,t){if(!o)return null;if(!e&&(e=G.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[Oi]===!1)continue;if(r.constructor==o)return r;let s=Pr(r,o);if(s)return s}return null}function Mp(o,e,t){if(!o)return e;if(!t&&(t=G.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==o)return r;vo(r,o,e)}return e}function yo(o){o&&o.isObject3D===!0&&Cp(o,st)}st.prototype.SetActive=function(o){this.visible=o};st.prototype.addNewComponent=function(o){return Un(this,new o)};st.prototype.removeComponent=function(o){return Ba(this,o)};st.prototype.getOrAddComponent=function(o){return Ua(this,o)};st.prototype.getComponent=function(o){return Sr(this,o)};st.prototype.getComponents=function(o,e){return bo(this,o,e)};st.prototype.getComponentInChildren=function(o){return Pr(this,o)};st.prototype.getComponentsInChildren=function(o,e){return vo(this,o,e)};st.prototype.getComponentInParent=function(o){return go(this,o)};st.prototype.getComponentsInParent=function(o,e){return Ds(this,o,e)};Object.getOwnPropertyDescriptor(st.prototype,"activeSelf")||Object.defineProperty(st.prototype,"activeSelf",{get:function(){return cn(this)},set:function(o){_o(this,o,!0)}});Tp(st);var Va=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[Va]=!0,e.matrixWorldNeedsUpdate=!0),t))for(let i of e.children)re.markDirty(i,!0)}};var Or=M("debuggetcomponent"),Zg=(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))(Zg||{}),Fe=class{idProvider;parent;keepWorldPosition;position;rotation;scale;visible;context},Ls=Symbol("isActive");function cn(o){let e=o.visible||za(o);return o[Ls]===void 0&&(o[Ls]=!0),o[Ls]&&e}function _o(o,e,t=!0){return typeof e=="number"&&(e=e>.5),o[Ls]=e,t&&(o.visible=e),o[Ls]}function Ap(o){return o[Oi]||za(o)}function Dp(o,e){o.__isUsingInstancing=e}function za(o){return re.isUsingInstancing(o)}function Tr(o,e){return Fn(o,e,!0,!0)}function ni(o,e=!0,t=!0){let i=o;if(i.isComponent){i.__internalDisable(),i.__internalDestroy();return}let n=o;if(Or&&console.log(n),e&&n.children)for(let s of n.children)ni(s,e,!1);let r=n.userData.components;if(r){let s=r.length;for(let a=0;a<r.length;a++){let c=r[a];c.__internalDisable(),c.__internalDestroy(),r.length<s&&(s=r.length,a--)}}t&&n.removeFromParent()}function ri(o,e,t=!0){if(!!o){if(o.isObject3D||new Error("Expected Object3D but got "+o),o.userData?.components)for(let i=0;i<o.userData.components.length;i++){let n=o.userData.components[i];if(n?.isComponent===!0){let r=e(n);if(r!==void 0)return r}}if(t&&o.children)for(let i=0;i<o.children.length;i++){let n=o.children[i];if(!n)continue;let r=ri(n,e,t);if(r!==void 0)return r}}}function Rr(o,e=null){if(o===null)return null;let t=null;e!==null&&(e.x!==void 0?(t=new Fe,t.position=e):t=e);let i=G.Current;t?.context&&(i=t.context),Or&&i.alias&&console.log("context",i.alias),t&&!t.idProvider&&(t.idProvider=new Ie(Date.now()));let n=[],r={},s={},a=Lp(i,o,t,n,r,s);a&&(eb(r),$g(s,r)),Or&&(ks(o,!0),ks(a,!0));let c={};for(let d in n){let l=n[d],u=l.guid;t&&t.idProvider&&(l.guid=t.idProvider.generateUUID(),c[u]=l.guid,Or&&console.log(l.name,l.guid)),Ga(l,i),l.__internalNewInstanceCreated&&l.__internalNewInstanceCreated()}for(let d in n){let l=n[d];l.resolveGuids&&l.resolveGuids(c),l.enabled!==!1&&(l.enabled=!0)}return dn(i),a}function Lp(o,e,t,i,n,r){if(!e)return null;let s=e.userData;e.userData={};let a=e.children;e.children=[];let c;if(c=e.clone(!1),yo(c),e.userData=s,e.children=a,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 l=c;l&&(l.guid=c.uuid)}e.animations&&e.animations.length>0&&(c.animations=[...e.animations]);let d=e.parent;if(d&&d.add(c),t?.position?te(c,t.position):c.position.copy(e.position),t?.rotation?Ke(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 l=null;if(typeof t.parent=="string"?l=Fn(t.parent,o.scene,!0):l=t.parent,l){let u=t.keepWorldPosition===!0?l.attach:l.add;u?u.call(l,c):console.error("Invalid parent object",l,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(let[l,u]of Object.entries(e.userData))l!=="components"&&(c.userData[l]=u);if(e.userData?.components){let l=e.userData.components,u=[];c.userData.components=u;for(let h=0;h<l.length;h++){let b=l[h],w=Object.create(b);Mt(w,b),u.push(w),w.gameObject=c,i.push(w)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0);for(let l in e.children){let u=e.children[l],h=Lp(o,u,t,i,n,r);h&&c.add(h)}return c}function $g(o,e){for(let t in o){let i=o[t],n=i.original,r=n.skeleton,s=i.clone;if(!r){console.warn("Skinned mesh has no skeleton?",i);continue}let a=r.bones,c=s.skeleton.clone();s.skeleton=c,s.bindMatrix.clone().copy(n.bindMatrix),s.bindMatrixInverse.copy(n.bindMatrixInverse);let d=[];c.bones=d;for(let l=0;l<a.length;l++){let u=a[l],b=e[u.uuid].clone;d.push(b)}}for(let t in o){let i=o[t].clone;i.skeleton.update(),i.bind(i.skeleton,i.bindMatrix),i.updateMatrixWorld(!0)}}function eb(o){for(let e in o){let i=o[e].clone;if(i.userData?.components)for(let n=0;n<i.userData.components.length;n++){let r=i.userData.components[n],s=Object.entries(r);for(let[a,c]of s)if(Array.isArray(c)){let d=[];r[a]=d;for(let l=0;l<c.length;l++){let u=c[l];if(typeof u!="object"){d.push(u);continue}let h=Ip(r,a,u,o);h!==void 0?d.push(h):d.push(u)}}else if(typeof c=="object"){let d=Ip(r,a,c,o);d!==void 0&&(r[a]=d)}}}}function Ip(o,e,t,i){if(t!=null){if(t.isComponent===!0){let n=t.gameObject;if(n){let r=n.uuid,s=i[r]?.clone;if(!s){Or&&console.log("reference did not change",e,o,t);return}let a=n.userData.components.indexOf(t);if(a>=0)return Or&&console.log(e,r),s.userData.components[a];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,s=i[r]?.clone;if(s)return Or&&console.log(e,"old",t,"new",s),s}}else if(t.isVector4||t.isVector3||t.isVector2||t.isQuaternion||t.isEuler)return t.clone()}}import un,{ActiveEvents as wb,Collider as Eb,ColliderDesc as js,EventQueue as Cb,JointData as Tb,RigidBody as Rb,RigidBodyType as id,World as Sb}from"@dimforge/rapier3d-compat";import{BufferAttribute as tb,Line as ib,BoxGeometry as Bp,EdgesGeometry as nb,Color as rb,LineSegments as ob,LineBasicMaterial as sb,Mesh as jp,SphereGeometry as ab,Vector3 as lb,Quaternion as cb}from"three";var bt=new lb,Hp=new cb,kr=8947848,Mr=class{static DrawRay(e,t,i=kr,n=0,r=!0){let s=Je.getLine(n),a=s.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),bt.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+bt.x,e.y+bt.y,e.z+bt.z),a.needsUpdate=!0,s.material.color.set(i),s.material.depthTest=r}static DrawDirection(e,t,i=kr,n=0,r=!0,s=1){let a=Je.getLine(n),c=a.geometry.getAttribute("position");c.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(bt.set(0,0,-s),Hp.set(t.x,t.y,t.z,t.w),bt.applyQuaternion(Hp)):(bt.set(t.x,t.y,t.z),bt.multiplyScalar(s)),c.setXYZ(1,e.x+bt.x,e.y+bt.y,e.z+bt.z),c.needsUpdate=!0,a.material.color.set(i),a.material.depthTest=r}static DrawLine(e,t,i=kr,n=0,r=!0){let s=Je.getLine(n),a=s.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),a.setXYZ(1,t.x,t.y,t.z),a.needsUpdate=!0,s.material.color.set(i),s.material.depthTest=r}static DrawWireSphere(e,t,i=kr,n=0,r=!0){let s=Je.getSphere(t,n,!0);sn(s,e.x,e.y,e.z),s.material.color.set(i),s.material.depthTest=r}static DrawSphere(e,t,i=kr,n=0,r=!0){let s=Je.getSphere(t,n,!1);sn(s,e.x,e.y,e.z),s.material.color.set(i),s.material.depthTest=r}static DrawBox(e,t,i=kr,n=0,r=!0){let s=Je.getBox(n);s.position.set(e.x,e.y,e.z),s.scale.set(t.x,t.y,t.z),s.material.color.set(i),s.material.depthTest=r,s.material.wireframe=!0}static DrawBox3(e,t=kr,i=0,n=!0){let r=Je.getBox(i);r.position.copy(e.getCenter(bt)),r.scale.copy(e.getSize(bt)),r.material.color.set(t),r.material.depthTest=n,r.material.wireframe=!0}},db=new Bp(1,1,1);function Wa(o=null){let e=new rb(o??14540253),t=new nb(db);return new ob(t,new sb({color:e}))}var Fp=Symbol("GizmoCache"),Je=class{static getBox(e){let t=this.boxesCache.pop();if(!t){let i=new Bp(1,1,1);t=new jp(i)}return this.registerTimedObject(G.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new ib;let i=t.geometry.getAttribute("position");i||(i=new tb(new Float32Array(2*3),3),t.geometry.setAttribute("position",i))}return this.registerTimedObject(G.Current,t,e,this.linesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new jp(new ab(.5,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(G.Current,n,t,this.spheresCache),n}static registerTimedObject(e,t,i,n){if(!this.contextPostRenderCallbacks.get(e)){let r=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,r),e.post_render_callbacks.push(r)}t[Fp]=n,this.timedObjectsBuffer.push(t),this.timesBuffer.push(G.Current.time.time+i),e.scene.add(t)}static onPostRender(e,t,i){let n=e.time.time;for(let r=0;r<t.length;r++)if(n>i[r]){let s=t[r];s[Fp].push(s),e.scene.remove(s),t.splice(r,1),i.splice(r,1)}}};A(Je,"linesCache",[]),A(Je,"spheresCache",[]),A(Je,"boxesCache",[]),A(Je,"timedObjectsBuffer",new Array),A(Je,"timesBuffer",new Array),A(Je,"contextPostRenderCallbacks",new Map);var xo=M("debugphysics"),nd=M("debugphysicscolliders"),rd=M("debugcollisions"),Pb=M("showcolliders"),wo=Symbol("needle component"),It=Symbol("physics body"),Ob=Symbol("rigidbody"),me=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 xb),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setMask(e){this.layerMask||(this.layerMask=new od);let t=this.layerMask;t?t.mask=e:this.layerMask=e}};A(me,"AllLayers",4294967295);var sd=class{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}},Ir=class{raycaster=new yb;defaultRaycastOptions=new me;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:0},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new od;sphereOverlap(e,t,i=!0){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;let n=new _b(e,t),r=this.sphereMask;r.enableAll(),r.disable(2);for(let s of this.context.scene.children)this.onSphereOverlap(s,n,r,this.sphereResults,i);return this.sphereResults.sort((s,a)=>s.distance-a.distance)}tempBoundingBox=new pb;onSphereOverlap(e,t,i,n,r){if(e.type==="Mesh"&&e.layers.test(i)){let s=e,a=s.geometry;if(a.boundingBox||a.computeBoundingBox(),a.boundingBox){s.matrixWorldNeedsUpdate&&s.updateMatrixWorld();let c=this.tempBoundingBox.copy(a.boundingBox).applyMatrix4(s.matrixWorld);if(t.intersectsBox(c)){let l=B(e).distanceTo(t.center),u=new sd(e,l,t.center.clone());if(n.push(u),!r)return}}}if(e.children)for(let s of e.children){let a=n.length;if(this.onSphereOverlap(s,t,i,n,r),a!=n.length&&!r)return}}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 a=e.cam??this.context.mainCamera;if(!a)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,a)}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 od?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),r.length=0,i.intersectObjects(n,e.recursive,r);let s=e.ignore;return s!==void 0&&s.length>0&&(r=r.filter(a=>!s.includes(a.object))),r}rapierRay=new un.Ray({x:0,y:0,z:0},{x:0,y:0,z:1});raycastVectorsBuffer=new Ti(()=>new td,10);raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){let r=this.getPhysicsRay(this.rapierRay,e,t);if(!r)return null;let s=this.world?.castRay(r,i,n);if(s){let a=r.pointAt(s.toi),c=this.raycastVectorsBuffer.get();return c.set(a.x,a.y,a.z),{point:c,collider:s.collider[wo]}}return null}getPhysicsRay(e,t,i=void 0){let n=this.context.mainCamera;if(t.z===void 0){if(!n)return console.error("Can not perform raycast from 2d point - no main camera found"),null;let a=this.raycastVectorsBuffer.get();(t.x>1||t.y>1||t.y<-1||t.x<-1)&&this.context.input.convertScreenspaceToRaycastSpace(t),a.set(t.x,t.y,-1),a.unproject(n),t=a}let r=t;e.origin.x=r.x,e.origin.y=r.y,e.origin.z=r.z;let s=this.raycastVectorsBuffer.get();if(i)s.set(i.x,i.y,i.z);else{if(!n)return console.error("Can not perform raycast - no camera found"),null;s.set(e.origin.x,e.origin.y,e.origin.z);let a=B(n);s.sub(a)}return s.normalize(),e.dir.x=s.x,e.dir.y=s.y,e.dir.z=s.z,e}_tempPosition=new td;_tempQuaternion=new vb;_tempScale=new td;_tempMatrix=new bb;_isUpdatingPhysicsWorld=!1;get isUpdating(){return this._isUpdatingPhysicsWorld}context;world;_hasCreatedWorld=!1;eventQueue;collisionHandler;objects=[];bodies=[];_meshCache=new Map;constructor(e){this.context=e}async createWorld(){if(this._hasCreatedWorld){console.error("Invalid call to create physics world: world is already created");return}this._hasCreatedWorld=!0,Ir._didLoadPhysicsEngine||(await un.init().then(()=>un),Ir._didLoadPhysicsEngine=!0);let e={x:0,y:-9.81,z:0};this.world=new Sb(e)}clearCaches(){this._meshCache.clear()}addBoxCollider(e,t,i){let n=e.gameObject,r=Me(n,this._tempPosition).multiply(i);r.multiplyScalar(.5);let s=js.cuboid(r.x,r.y,r.z);this.createCollider(e,s,t)}addSphereCollider(e,t,i){let n=e.gameObject,r=Me(n,this._tempPosition).multiplyScalar(i),s=js.ball(r.x);this.createCollider(e,s,t)}addCapsuleCollider(e,t,i,n){let r=e.gameObject,s=Me(r,this._tempPosition);xo&&console.log("capsule scale",s,i,n);let a=js.capsule(i*.5*s.y-n,n*s.x);this.createCollider(e,a,t)}addMeshCollider(e,t,i,n){let r=t.geometry;if(!r){xo&&console.warn("Missing mesh geometry",t.name);return}let s=r.getAttribute("position").array,a=r.index?.array;if(Math.abs(n.x-1)>1e-4||Math.abs(n.y-1)>1e-4||Math.abs(n.z-1)>1e-4){let d=r.uuid+"_"+n.x+"_"+n.y+"_"+n.z+"_"+i;if(this._meshCache.has(d))s=this._meshCache.get(d);else{console.warn("Your model is using scaled mesh colliders which is not optimal for performance",t.name,Object.assign({},n),t);let l=new Float32Array(s.length);for(let u=0;u<s.length;u+=3)l[u]=s[u]*n.x,l[u+1]=s[u+1]*n.y,l[u+2]=s[u+2]*n.z;s=l,this._meshCache.set(d,l)}}let c=i?js.convexMesh(s):js.trimesh(s,a);c&&this.createCollider(e,c)}createCollider(e,t,i){if(!this.world)throw new Error("Physics world not initialized");let n=this._tempMatrix,{rigidBody:r,useExplicitMassProperties:s}=this.getRigidbody(e,this._tempMatrix);n.decompose(this._tempPosition,this._tempQuaternion,this._tempScale),Me(e.gameObject,this._tempScale),i&&(i.multiply(this._tempScale),this._tempPosition.x-=i.x,this._tempPosition.y+=i.y,this._tempPosition.z+=i.z),t.setTranslation(this._tempPosition.x,this._tempPosition.y,this._tempPosition.z),t.setRotation(this._tempQuaternion),t.setSensor(e.isTrigger);let a=this.world.createCollider(t,r);return a[wo]=e,e[It]=a,a.setActiveEvents(wb.COLLISION_EVENTS),this.objects.push(e),this.bodies.push(a),a}getRigidbody(e,t){if(!this.world)throw new Error("Physics world not initialized");let i=null,n=!1;if(e.attachedRigidbody){let r=e.attachedRigidbody;if(i=r[It],n=!0,!i){let s=r.isKinematic&&!nd;xo&&console.log("Create rigidbody",s);let a=s?un.RigidBodyDesc.kinematicPositionBased():un.RigidBodyDesc.dynamic(),c=B(e.attachedRigidbody.gameObject);a.setTranslation(c.x,c.y,c.z),a.setRotation(pe(e.attachedRigidbody.gameObject)),i=this.world.createRigidBody(a),this.bodies.push(i),this.objects.push(r)}i[wo]=r,r[It]=i,this.internalUpdateProperties(r,i),this.getRigidbodyRelativeMatrix(e.gameObject,r.gameObject,t)}else{let r=un.RigidBodyDesc.kinematicPositionBased(),s=B(e.gameObject);r.setTranslation(s.x,s.y,s.z),r.setRotation(pe(e.gameObject)),i=this.world.createRigidBody(r),t.identity(),i[wo]=null}return e[Ob]=i,{rigidBody:i,useExplicitMassProperties:n}}removeBody(e){let t=e[It];if(e[It]=null,t&&this.world){let i=this.objects.findIndex(n=>n===e);if(i>=0){let n=this.bodies[i];if(this.bodies.splice(i,1),this.objects.splice(i,1),n instanceof Eb){let r=n;this.world?.removeCollider(r,!0);let s=r.parent();s&&s.numColliders()<=0&&this.world?.removeRigidBody(s)}else n instanceof Rb}}}updateBody(e,t,i){if(!(e.destroyed||!e.gameObject)&&!(!t&&!i))if(e.isCollider===!0)console.warn("TODO: implement updating collider position");else{let n=e,r=n[It];r&&this.syncPhysicsBody(n.gameObject,r,t,i)}}updateProperties(e){let t=e[It];t&&this.internalUpdateProperties(e,t)}internal_getRigidbody(e){return e[It]}internalUpdateProperties(e,t){t.enableCcd(e.collisionDetectionMode!==0),t.setLinearDamping(e.drag),t.setAngularDamping(e.angularDrag),t.setGravityScale(e.useGravity?1:0,!0),t.setEnabledRotations(!e.lockRotationX,!e.lockRotationY,!e.lockRotationZ,!0),t.setEnabledTranslations(!e.lockPositionX,!e.lockPositionY,!e.lockPositionZ,!0),e.isKinematic?t.setBodyType(un.RigidBodyType.KinematicPositionBased):t.setBodyType(un.RigidBodyType.Dynamic)}lines;step(e){!this.world||(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new Cb(!1)),this.world.step(this.eventQueue),this._isUpdatingPhysicsWorld=!1,this.updateDebugRendering(this.world))}updateDebugRendering(e){if(xo||nd||Pb){if(!this.lines){let i=new mb({color:2258688}),n=new fb;this.lines=new gb(n,i),this.context.scene.add(this.lines)}let t=e.debugRender();this.lines.geometry.setAttribute("position",new Up(t.vertices,3)),this.lines.geometry.setAttribute("color",new Up(t.colors,4))}}postStep(){!this.world||(this._isUpdatingPhysicsWorld=!0,this.syncObjects(),this._isUpdatingPhysicsWorld=!1,this.eventQueue&&!this.collisionHandler&&(this.collisionHandler=new ad(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()))}syncObjects(){if(!nd)for(let e=0;e<this.bodies.length;e++){let t=this.objects[e],i=this.bodies[e],n=t;if(n?.isCollider===!0&&!n.attachedRigidbody){let c=i.parent();c&&this.syncPhysicsBody(t.gameObject,c,!0,!0);continue}let r=i.translation(),s=i.rotation(),a=t.center;if(a&&a.isVector3){this._tempQuaternion.set(s.x,s.y,s.z,s.w);let c=this._tempPosition.copy(a).applyQuaternion(this._tempQuaternion),d=Me(t.gameObject);c.multiply(d),r.x-=c.x,r.y-=c.y,r.z-=c.z}sn(t.gameObject,r.x,r.y,r.z),rp(t.gameObject,s.x,s.y,s.z,s.w)}}syncPhysicsBody(e,t,i,n){let r=B(e,this._tempPosition),s=pe(e,this._tempQuaternion);switch(t.bodyType()){case id.Fixed:case id.KinematicPositionBased:case id.KinematicVelocityBased:i&&t.setNextKinematicTranslation(r),n&&t.setNextKinematicRotation(s);break;default:i&&t.setTranslation(r,!1),n&&t.setRotation(s,!1);break}t.wakeUp()}getRigidbodyRelativeMatrix(e,t,i,n){if(n===void 0&&(n=Ir._matricesBuffer,n.length=0),e===t){let r=Me(e,this._tempPosition);i.makeScale(r.x,r.y,r.z);for(let s=n.length-1;s>=0;s--)i.multiply(n[s]);return i}return n.push(e.matrix),e.parent&&this.getRigidbodyRelativeMatrix(e.parent,t,i,n),i}addFixedJoint(e,t){if(!this.world){console.error("Physics world not initialized");return}let i=e[It],n=t[It];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);let r=Tb.fixed(Ir.centerConnectionPos,Ir.centerConnectionRot,this._tempPosition,this._tempQuaternion),s=this.world.createImpulseJoint(r,i,n,!0);xo&&console.log("ADD FIXED JOINT",s)}addHingeJoint(e,t,i,n){if(!this.world){console.error("Physics world not initialized");return}let r=e[It],s=t[It];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);let a=un.JointData.revolute(i,this._tempPosition,n),c=this.world.createImpulseJoint(a,r,s,!0);xo&&console.log("ADD HINGE JOINT",c)}calculateJointRelativeMatrices(e,t,i){e.updateWorldMatrix(!0,!1),t.updateWorldMatrix(!0,!1);let n=e.matrixWorld,r=t.matrixWorld;n.elements[0]=1,n.elements[5]=1,n.elements[10]=1,r.elements[0]=1,r.elements[5]=1,r.elements[10]=1,i.copy(r).premultiply(n.invert()).invert()}},Gn=Ir;A(Gn,"_didLoadPhysicsEngine",!1),A(Gn,"_matricesBuffer",[]),A(Gn,"centerConnectionPos",{x:0,y:0,z:0}),A(Gn,"centerConnectionRot",{x:0,y:0,z:0,w:1});var ad=class{world;eventQueue;constructor(e,t){this.world=e,this.eventQueue=t}activeCollisions=[];activeCollisionsStay=[];activeTriggers=[];handleCollisionEvents(){!this.eventQueue||!this.world||this.eventQueue.drainCollisionEvents((e,t,i)=>{let n=this.world.getCollider(e),r=this.world.getCollider(t),s=n[wo],a=r[wo];rd&&console.log("EVT",s.name,a.name,i,n,r),s&&a&&(i?(this.onCollisionStarted(s,n,a,r),this.onCollisionStarted(a,r,s,n)):(this.onCollisionEnded(s,a),this.onCollisionEnded(a,s)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(e,t,i,n){let r=null;if(e.isTrigger||i.isTrigger)ri(e.gameObject,s=>{s.onTriggerEnter&&s.onTriggerEnter(i),this.activeTriggers.push({collider:e,component:s,otherCollider:i})});else{let s=e.gameObject;this.world.contactPair(t,n,(a,c)=>{ri(s,d=>{let l=d.onCollisionEnter||d.onCollisionStay||d.onCollisionExit;if(l||rd){if(!r){let u=[],h=a.normal();for(let b=0;b<a.numSolverContacts();b++){let w=a.solverContactPoint(b),v=a.contactImpulse(b);if(w){let x=a.contactDist(b),m=a.solverContactFriction(b),f=new Ia(w,x,h,v,m);u.push(f),rd&&Mr.DrawDirection(w,h,16711680,3,!0)}}r=new Ms(s,i,u)}if(l){let u={collider:e,component:d,collision:r};this.activeCollisions.push(u),d.onCollisionStay&&this.activeCollisionsStay.push(u),d.onCollisionEnter?.call(d,r)}}})})}}onHandleCollisionStay(){for(let e of this.activeCollisionsStay){let t=e.component;if(t.activeAndEnabled&&t.onCollisionStay){let i=e.collision;t.onCollisionStay(i)}}for(let e of this.activeTriggers){let t=e.component;if(t.activeAndEnabled&&t.onTriggerStay){let i=e.otherCollider;t.onTriggerStay(i)}}}onCollisionEnded(e,t){for(let i=0;i<this.activeCollisions.length;i++){let n=this.activeCollisions[i];if(n.collider===e&&n.collision.collider===t){let s=n.component;if(this.activeCollisions.splice(i,1),i--,s.activeAndEnabled&&s.onCollisionExit){let a=n.collision;s.onCollisionExit(a)}}}for(let i=0;i<this.activeCollisionsStay.length;i++){let n=this.activeCollisionsStay[i];if(n.collider===e&&n.collision.collider===t){let s=n.component;if(this.activeCollisionsStay.splice(i,1),i--,s.activeAndEnabled&&s.onCollisionExit){let a=n.collision;s.onCollisionExit(a)}}}for(let i=0;i<this.activeTriggers.length;i++){let n=this.activeTriggers[i];if(n.collider===e&&n.otherCollider===t){let s=n.component;if(this.activeTriggers.splice(i,1),i--,s.activeAndEnabled&&s.onTriggerExit){let a=n.otherCollider;s.onTriggerExit(a)}}}}};import{Clock as kb}from"three";var Na=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.deltaTime<=0&&(this.deltaTime=1e-12),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 Ib}from"websocket-ts";var ki=new Int32Array(2),Xa=new Float32Array(ki.buffer),Qa=new Float64Array(ki.buffer),Eo=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;var We=class{constructor(e,t){this.low=e|0,this.high=t|0}static create(e,t){return e==0&&t==0?We.ZERO:new We(e,t)}toFloat64(){return(this.low>>>0)+this.high*4294967296}equals(e){return this.low==e.low&&this.high==e.high}};We.ZERO=new We(0,0);var Hs;(function(o){o[o.UTF8_BYTES=1]="UTF8_BYTES",o[o.UTF16_STRING=2]="UTF16_STRING"})(Hs||(Hs={}));var Mi=class{constructor(e){this.bytes_=e,this.position_=0}static allocate(e){return new Mi(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 We(this.readInt32(e),this.readInt32(e+4))}readUint64(e){return new We(this.readUint32(e),this.readUint32(e+4))}readFloat32(e){return ki[0]=this.readInt32(e),Xa[0]}readFloat64(e){return ki[Eo?0:1]=this.readInt32(e),ki[Eo?1:0]=this.readInt32(e+4),Qa[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){Xa[0]=t,this.writeInt32(e,ki[0])}writeFloat64(e,t){Qa[0]=t,this.writeInt32(e,ki[Eo?0:1]),this.writeInt32(e+4,ki[Eo?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===Hs.UTF8_BYTES)return this.bytes_.subarray(e,e+i);for(;r<i;){let s,a=this.readUint8(e+r++);if(a<192)s=a;else{let c=this.readUint8(e+r++);if(a<224)s=(a&31)<<6|c&63;else{let d=this.readUint8(e+r++);if(a<240)s=(a&15)<<12|(c&63)<<6|d&63;else{let l=this.readUint8(e+r++);s=(a&7)<<18|(c&63)<<12|(d&63)<<6|l&63}}}s<65536?n+=String.fromCharCode(s):(s-=65536,n+=String.fromCharCode((s>>10)+55296,(s&(1<<10)-1)+56320))}return n}__union_with_string(e,t){return typeof e=="string"?this.__string(t):this.__union(e,t)}__indirect(e){return e+this.readInt32(e)}__vector(e){return e+this.readInt32(e)+4}__vector_len(e){return this.readInt32(e+this.readInt32(e))}__has_identifier(e){if(e.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let t=0;t<4;t++)if(e.charCodeAt(t)!=this.readInt8(this.position()+4+t))return!1;return!0}createLong(e,t){return We.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 vt=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=Mi.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=vt.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=Mi.allocate(i);return n.setPosition(i-t),n.bytes().set(e.bytes(),i-t),n}addOffset(e){this.prep(4,0),this.writeInt32(this.offset()-e+4)}startObject(e){this.notNested(),this.vtable==null&&(this.vtable=[]),this.vtable_in_use=e;for(let t=0;t<e;t++)this.vtable[t]=0;this.isNested=!0,this.object_start=this.offset()}endObject(){if(this.vtable==null||!this.isNested)throw new Error("FlatBuffers: endObject called without startObject");this.addInt32(0);let e=this.offset(),t=this.vtable_in_use-1;for(;t>=0&&this.vtable[t]==0;t--);let i=t+1;for(;t>=0;t--)this.addInt16(this.vtable[t]!=0?e-this.vtable[t]:0);let n=2;this.addInt16(e-this.object_start);let r=(i+n)*2;this.addInt16(r);let s=0,a=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(a+d)!=this.bb.readInt16(c+d))continue e;s=this.vtables[t];break}}return s?(this.space=this.bb.capacity()-e,this.bb.writeInt32(this.space,s-e)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-e,this.offset()-e)),this.isNested=!1,e}finish(e,t,i){let n=i?4:0;if(t){let r=t;if(this.prep(this.minalign,4+4+n),r.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let s=4-1;s>=0;s--)this.writeInt8(r.charCodeAt(s))}this.prep(this.minalign,4+n),this.addOffset(e),n&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(e,t){this.finish(e,t,!0)}requiredField(e,t){let i=this.bb.capacity()-e,n=i-this.bb.readInt32(i);if(!(this.bb.readInt16(n+t)!=0))throw new Error("FlatBuffers: field "+t+" must be set")}startVector(e,t,i){this.notNested(),this.vector_num_elems=t,this.prep(4,e*t),this.prep(i,e*t)}endVector(){return this.writeInt32(this.vector_num_elems),this.offset()}createSharedString(e){if(!e)return 0;if(this.string_maps||(this.string_maps=new Map),this.string_maps.has(e))return this.string_maps.get(e);let t=this.createString(e);return this.string_maps.set(e,t),t}createString(e){if(!e)return 0;let t;if(e instanceof Uint8Array)t=e;else{t=[];let i=0;for(;i<e.length;){let n,r=e.charCodeAt(i++);if(r<55296||r>=56320)n=r;else{let s=e.charCodeAt(i++);n=(r<<10)+s+(65536-(55296<<10)-56320)}n<128?t.push(n):(n<2048?t.push(n>>6&31|192):(n<65536?t.push(n>>12&15|224):t.push(n>>18&7|240,n>>12&63|128),t.push(n>>6&63|128)),t.push(n&63|128))}}this.addInt8(0),this.startVector(1,t.length,1),this.bb.setPosition(this.space-=t.length);for(let i=0,n=this.space,r=this.bb.bytes();i<t.length;i++)r[n++]=t[i];return this.endVector()}createLong(e,t){return We.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 Gp={};function To(o,e){Gp[o]=e}function Vp(o){let e=o.getBufferIdentifier(),t=Gp[e];return t(o)}function zp(o){return typeof o.guid=="function"?o.guid():null}var cd=ba(Ya(),1);var Ka=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 cd.default(e);t.on("error",i=>{console.error(i),this._host=void 0,this.trySetupClient(e)}),t.on("open",i=>{this._host=new ud(t)})}trySetupClient(e){this._client=new cd.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)})})}},dd=class{_peer;constructor(e){this._peer=e}};var ud=class extends dd{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 Ja="wss://needle-tiny-starter.glitch.me/socket",at=!!M("debugnet"),Za=!!(at||M("debugowner"));var zn=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||(Za&&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 Za&&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?(Za&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(Za&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}},$a=class{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new Ka),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return at}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(),at&&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]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(e){at&&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&&at&&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;at&&console.log("connecting");let e=this.netWebSocketUrlProvider?.getWebsocketUrl();e?Ja=e:Vh()&&(Ja="wss://"+window.location.host+"/socket"),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 "+Ja);let e=new Ib(Ja).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{at&&i==="pong"&&console.log("<<",i)}}async handleIncomingBinaryMessage(e){let t=await e.arrayBuffer();var i=new Uint8Array(t);let n=new Mi(i),r=n.getBufferIdentifier(),s=this._listenersBinary[r],a=Vp(n),c=zp(a);if(c&&typeof c=="string"&&(this._state[c]=a),!s)return;let d=a??n;for(let l of s)l(d)}handleIncomingStringMessage(e){if(at&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){let s=e.data;s&&(console.assert(s.id!==void 0&&s.id!==null&&s.id.length>0,"server did not send connection id",s.id),console.log("Your id is: "+s.id,this.context.alias??""),this._connectionId=s.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(at&&console.log(e),e){this._isInRoom=!0;let s=e;this._currentRoomName=s.room,this._currentRoomViewId=s.viewId,this._currentRoomAllowEditing=s.allowEditing??!0,console.log("Room view id",this._currentRoomViewId),this._currentInRoom.length=0,this._currentInRoom.push(...s.inRoom),at&&console.log("joined room with",this._currentInRoom,this.context.alias??"")}this.onSendQueued(1);break;case"left-room":e.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(e.data){let s=e.data;this._currentInRoom.push(s.userId),at&&console.log(s.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){let s=e.data,a=this._currentInRoom.indexOf(s.userId);a>=0&&(console.log(s.userId+" left",this.context.alias??""),this._currentInRoom.splice(a,1)),s.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":at&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":let r=e.data?.time;r&&(this._currentDelay=this.context.time.time-r),at&&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));at&&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 nv}from"three/examples/jsm/postprocessing/EffectComposer.js";import{RenderPass as rv}from"three/examples/jsm/postprocessing/RenderPass";import*as Wn from"three";var $p=ba(Zp(),1),el=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 ef(o,e){let t=await o.arrayBuffer(),i=tf(t),n=o.name.split(".").pop(),r=i+"."+n,s=o.name.split(".").shift();console.assert(s!==void 0);let a={alias:s,filename:r},d=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(a)})).json();if(d.success||console.warn("exists check did fail"),d.exists)return console.log("file already exists",i),new el(!0,r,i,o.size);console.log("begin uploading file",s,o.size);let l=new FormData;l.append("file",o);let u={};u.filesize=o.size,s&&(u.alias=s);let b=await(await fetch(e+"/upload/file",{method:"POST",body:l,headers:u})).json();if(b?.success===!1)return b.message!==void 0?console.error("Upload failed:",b.message):console.error("Upload failed"),null;console.assert(b.hash_sum===i,"hash sum did not match","received:",b.hash_sum,"expected:",i),b.success&&console.log("successfully uploaded",i,b.id);let w=new el(b.success,r,i,o.size);return w.url=e,w}function tf(o){return(0,$p.default)(new Uint8Array(o))}async function tl(o,e,t,i,n=!1){try{let r=await fetch(i+"/download/file",{method:"POST",body:o});if(r.status!==200)return console.error("download failed",r),null;let s=await r.blob(),a=await s.arrayBuffer();n||console.assert(s.size===t,"size mismatch","expected:",t,"got:",s.size);let c=tf(a);return n||console.assert(c===e,"hash mismatch, downloaded file is invalid"),s.arrayBuffer()}catch(r){console.error(r)}return null}async function nf(o,e){let t=await fetch(o),i=t.body?.getReader(),n=t.headers.get("Content-Length"),r=n?parseInt(n):0;if(!i)return null;let s=0,a=[];for(;;){let{done:l,value:u}=await i.read();if(u&&(a.push(u),s+=u.length,e.call(null,new ProgressEvent("progress",{loaded:s,total:r}))),l)break}let c=new Uint8Array(s),d=0;for(let l of a)c.set(l,d),d+=l.length;return c}function il(o,e,t){console.warn("Adding components on object has been temporarily disabled")}var of,rf=null;function Ne(){return of}function nl(o){rf!==o&&(rf=o,of=new o)}var fd=class{guid;file_name;file_hash;file_size;position;seed;sender;serverUrl;parentGuid;boundsSize;constructor(e,t,i,n,r,s,a,c){this.seed=t,this.guid=i,this.file_name=n,this.file_hash=r,this.file_size=s,this.position=a,this.sender=e,this.serverUrl=c}};async function sf(o,e,t){let i=o.name;return i.endsWith(".gltf")||i.endsWith(".glb")?new Promise((n,r)=>{let s=new FileReader;s.readAsDataURL(o),s.onloadend=async a=>{let c=s.result,d=Fa(),l=new Ie(d),u=await Ne().loadSync(e,c,l,!0);if(u&&u.scene){let h=u.scene;if(!h.guid){let b=new Ie(d);h.guid=b.generateUUID()}t&&jb(e.connection,o,d,h,t),il(h,l,u),n(u)}}}):(console.warn("Unsupported file type: "+i),console.log(o),null)}async function af(o,e){return new Promise(async(t,i)=>{let n=Fa(),r=new Ie(n),s=await Ne().loadSync(e,o.toString(),r,!0);if(s&&s.scene){let a=s.scene;il(a,r,s),t(s)}else console.warn("Unsupported file type: "+o.toString())})}function lf(o){o.connection.beginListen("file-spawned",async e=>{if(e.sender!==o.connection.connectionId){console.log("received file event",e),Hb(e,o);let t=null;try{t=await tl(e.file_name,e.file_hash,e.file_size,e.serverUrl)}finally{Fb(e,o)}if(t){let i=new Ie(e.seed),n=await Ne().parseSync(o,t,null,i);if(n&&n.scene){let r=n.scene;if(il(r,i,n),e.parentGuid){let s=Tr(e.parentGuid,o.scene);"add"in s&&s.add(r)}r.parent||o.scene.add(r),e.position!==null&&r.position.copy(e.position)}}else console.error("download didnt return file")}})}async function jb(o,e,t,i,n){if(!o.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 ef(e,n);if(!r)return;if(!r.filename){console.error("Can not send upload event - no filename",e.name);return}if(!r.hash){console.error("Can not send upload event - no hash",e.name);return}let s=new fd(o.connectionId,t,i.guid,r.filename,r.hash,e.size,i.position,r.url??n);i.parent&&(s.parentGuid=i.parent.guid),o.send("file-spawned",s)}var md={};function Hb(o,e){let t=new Wn.BoxGeometry,i=new Wn.Mesh(t,new Wn.MeshBasicMaterial({color:65280})),n=new Wn.BoxHelper(i,5592405);if(md[o.guid]=n,e.scene.add(n),o.parentGuid){let r=Tr(o.parentGuid,e.scene);r&&r.add(n)}o.position&&n.position.copy(o.position)}function Fb(o,e){let t=o.guid,i=md[t];i&&(delete md[t],i.removeFromParent())}import*as cf from"three";var sT=M("debugassets");var rl=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:
152
- `+i.src),e.preventDefault())}})}texturesLoader=new cf.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 vf from"three/examples/jsm/libs/stats.module";import{Vector4 as Xb,EquirectangularReflectionMapping as sl,sRGBEncoding as al,WebGLCubeRenderTarget as Qb}from"three";import{LightProbeGenerator as qb}from"three/examples/jsm/lights/LightProbeGenerator.js";import*as df from"three";var Ub=new df.FileLoader;async function gd(o){return new Promise((e,t)=>{Ub.load(o,e,void 0,t)})}import{Vector4 as Nn,FileLoader as Vb,DataTexture as xd,RGBAFormat as zb,Color as Wb}from"three";var Fs=new Uint8Array(4);Fs[0]=255;Fs[1]=255;Fs[2]=255;Fs[3]=255;var pf=new xd(Fs,1,1,zb);function ol(o,e=1){let t="alpha"in o,i=e*e,n=new Uint8Array(4*i),r=Math.floor(o.r*255),s=Math.floor(o.g*255),a=Math.floor(o.b*255);for(let d=0;d<i;d++){let l=d*4;n[l+0]=r,n[l+1]=s,n[l+2]=a,t?n[l+3]=Math.floor(o.alpha*255):n[l+3]=255}let c=new xd(n,e,e);return c.needsUpdate=!0,c}function ff(o,e,t,i=1,n=3){let a=i*n,c=[o,e,t],d=c.length,l=new Uint8Array(4*d*a),u=new Wb;for(let b=0;b<n;b++){let w=Math.floor(b/n*d),v=H.clamp(w+1,0,d-1),x=c[w],m=c[v],f=b/n*d%1;u.lerpColors(x,m,f);let p=Math.floor(u.r*255),g=Math.floor(u.g*255),E=Math.floor(u.b*255);for(let C=0;C<i;C++){let T=(b*i+C)*4;l[T+0]=p,l[T+1]=g,l[T+2]=E,l[T+3]=255}}let h=new xd(l,i,n);return h.needsUpdate=!0,h}var vd=class{stage;code;constructor(e,t){this.stage=e,this.code=t}},yd=class{loaded=new Map;async loadShader(e){let t=await gd(e);return JSON.parse(t)}async load(e,t){if(this.loaded.has(t))return new Promise((r,s)=>{let a=this.loaded.get(t);a?r(a):s("Shader not found")});let i=await gd(t),n=new vd(e,i);return this.loaded.set(t,n),n}},uT=new yd;function Bs(o,e){let t=o.elements;e||(e=[]),e.length=0;for(let i=0;i<16;i+=4){let n=t[i],r=t[i+1],s=t[i+2],a=t[i+3],c=new Nn(n,r,s,a);e.push(c)}return e}var bd=[],uf=[];function wd(o,e){if(bd.length===0)for(let t=0;t<27;t++)bd.push(0);e||(e=bd);for(let t=0;t<27;t++)uf[t]=e[t];e=uf,o.unity_SHAr={value:new Nn(e[9],e[3],e[6],e[0])},o.unity_SHBr={value:new Nn(e[12],e[15],e[18],e[21])},o.unity_SHAg={value:new Nn(e[10],e[4],e[7],e[1])},o.unity_SHBg={value:new Nn(e[13],e[16],e[19],e[22])},o.unity_SHAb={value:new Nn(e[11],e[5],e[8],e[2])},o.unity_SHBb={value:new Nn(e[14],e[17],e[20],e[23])},o.unity_SHC={value:new Nn(e[24],e[25],e[26],1)}}var _d=class{vertexShader;fragmentShader;technique;constructor(e,t,i){this.vertexShader=e,this.fragmentShader=t,this.technique=i}};async function mf(o,e){if(!o)return console.error("Can not find technique: no shader data"),null;let t=o.programs[e],i=t.vertexShader,n=t.fragmentShader;if(i!==void 0&&n!==void 0){let r=o.shaders[i],s=o.shaders[n];if(r.uri&&s.uri||r.code&&s.code){if(!r.code&&r.uri&&await hf(r),!s.code&&s.uri&&await hf(s),!r.code||!s.code)return null;let a=o.techniques[e];return new _d(r.code,s.code,a)}}return console.error("Shader technique not found",e),null}async function hf(o){let e=o.uri;if(!!e)if(e.endsWith(".glsl")){let i=await new Vb().loadAsync(e);o.code=i.toString()}else o.code=Nb(o.uri)}function Nb(o){return decodeURIComponent(Array.prototype.map.call(atob(o),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}var Ed=M("debugenvlight"),Td=(n=>(n[n.Skybox=0]="Skybox",n[n.Trilight=1]="Trilight",n[n.Flat=3]="Flat",n[n.Custom=4]="Custom",n))(Td||{});var ll=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 Xb;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 Cd(this.context,t,1);this._lighting[e]=i}getReflection(e){return this._lighting[e]}enableReflection(e){switch(Ed&&console.log(this.sceneLightSettings?Td[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=al,n.mapping=sl,i.environment=n;return}break}if(this.sceneLightSettings?.environmentReflectionSource===1)switch(this.sceneLightSettings?.ambientMode){case 1:if(this.sceneLightSettings.ambientTrilight){let t=this.sceneLightSettings.ambientTrilight,i=ff(t[0],t[1],t[2],64,64);i.encoding=al,i.mapping=sl,this.context.scene.environment=i}else console.error("Missing ambient trilight",this.sceneLightSettings.sourceId);return;case 3:if(this.sceneLightSettings.ambientLight){let t=ol(this.sceneLightSettings.ambientLight,64);t.encoding=al,t.mapping=sl,this.context.scene.environment=t}else console.error("Missing ambientlight",this.sceneLightSettings.sourceId);return;default:return}}disableReflection(){let e=this.context.scene;e.environment=null}async getSceneLightingData(e){return Ed&&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={}},Cd=class{get Source(){return this._source}get Array(){return this._sphericalHarmonicsArray}_context;_source;_sphericalHarmonics=null;_sphericalHarmonicsArray;_ambientScale=1;_lightProbe;constructor(e,t,i=1){this._context=e,this._source=t,this._ambientScale=i,t.mapping=sl,t.encoding=al}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){Ed&&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=qb.fromCubeRenderTarget(this._context.renderer,i);this._lightProbe=n;let r=this._ambientScale*(e*e*Math.PI*.5)-1;this._sphericalHarmonics=n.sh,this._sphericalHarmonicsArray=this._sphericalHarmonics.toArray();let s=e/(Math.PI*.5);for(let a=0;a<this._sphericalHarmonicsArray.length;a++)this._sphericalHarmonicsArray[a]*=s;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 Yb}from"three";var Ar=M("debugaddressables"),cl=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}},Ro=class{static getOrCreate(e,t,i){let n=Ri(e,t);Ar&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",n);let r=i.addressables,s=r.findAssetReference(n);if(s)return s;let a=new Ro(n,i.hash);return r.registerAssetReference(a),a}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=[];_hash;_hashedUri;_isLoadingRawBinary=!1;_rawBinary;constructor(e,t){this._uri=e,this._hash=t,e.includes("?v=")?this._hashedUri=e:this._hashedUri=t?e+"?v="+t:e,xp(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?ni(this.asset.scene):ni(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._hashedUri);let e=await nf(this._hashedUri,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=G.Current;this._rawBinary?(this._loading=Ne().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=Ne().loadSync(t,this._hashedUri,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 dn(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=G.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 Fe?e:null;if(r||(r=new Fe),typeof e=="object"&&(e instanceof Yb?r.parent=e:Object.assign(r,e)),Ro.currentlyInstantiating.indexOf(this.uri)>=0)return console.error("Recursive instantiation of",this.uri),null;try{if(Ro.currentlyInstantiating.push(this.uri),t){r.context=n;let s=this.asset;s.guid=this.uri;let a=Ha(s,r,void 0,i);if(a)return a}else{let s=Rr(this.asset,r);if(s)return s}}finally{n.post_render_callbacks.push(()=>Ro.currentlyInstantiating.pop())}}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}},Ze=Ro;A(Ze,"currentlyInstantiating",[]);var Rd=class extends rn{constructor(){super([Ze])}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?Ze.getOrCreate(t.gltfId,e,t.context):(console.error("Missing spurce id"),null):(console.error("Missing context"),null):null}};new Rd;var dl=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 Kb,HalfFloatType as Jb,sRGBEncoding as Zb}from"three";var gf="NEEDLE_lightmaps",$b=M("debuglightmapsextension"),Us=(i=>(i[i.Lightmap=0]="Lightmap",i[i.Skybox=1]="Skybox",i[i.Reflection=2]="Reflection",i))(Us||{}),ul=class{get name(){return gf}parser;registry;source;constructor(e,t,i){this.parser=e,this.registry=t,this.source=i}afterRoot(e){let t=this.parser.json.extensions;if(t){let i=t[gf];if(i){let n=i.textures;return n?.length?($b&&console.log(i),new Promise(async(r,s)=>{let a=[];for(let c of n)if(c.pointer){let d=uo(this.parser,c.pointer).then(l=>{let u=l;u?.isTexture&&(this.registry?(c.type!==0&&(u.encoding=Zb),c.type===1&&(u.type==Kb||u.type==Jb)&&(u.flipY=!0),this.registry.registerTexture(this.source,c.type,u,c.index)):console.log(Us[c.type],c.pointer,u))});a.push(d)}await Promise.all(a),r()})):null}}return null}};import*as Ii from"three";var bf=!!M("debuglightmaps"),hl=class{_context;_lightmaps=new Map;constructor(e){this._context=e}registerTexture(e,t,i,n){bf&&console.log("Registering lightmap",e,Us[t],i),this._lightmaps.has(e)||this._lightmaps.set(e,new Map);let r=this._lightmaps.get(e),s=r?.get(t)??[];s.length<n&&(s.length=n+1),s[n]=i,r?.set(t,s)}tryGetLightmap(e,t=0){return this.tryGet(e,0,t)}tryGetSkybox(e){return this.tryGet(e,1,0)}tryGetReflection(e){return this.tryGet(e,2,0)}tryGet(e,t,i){if(!e)return bf&&console.warn("Missing source id"),null;let n=this._lightmaps.get(e)?.get(t)??null;return!n?.length||n.length<=i?null:n[i]}};Ii.ShaderChunk.lights_fragment_maps=Ii.ShaderChunk.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vUv2 );",`
151
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis`))),od&&console.log("FIND",e),e!=null){for(let i=0;i<o.userData.components.length;i++){let n=o.userData.components[i];if(e===null||n.constructor.name===e.name||n.constructor.name===e)if(od&&console.log("MATCH BY NAME",n),t)t.push(n);else return n}for(let i=0;i<o.userData.components.length;i++){let n=o.userData.components[i],r=Object.getPrototypeOf(n.constructor);do{if(r===e)if(od&&console.log("MATCH BY PROTOYPE",r),t)t.push(n);else return n;r=Object.getPrototypeOf(r)}while(r)}return t}}}function Or(o,e){return jp(o,e)}function yo(o,e,t){return t||(t=[]),jp(o,e,t)}function kr(o,e,t){let i=Or(o,e);if(t===!1&&i.enabled===!1)return null;if(i)return i;for(let n=0;n<o?.children?.length;n++){let r=kr(o.children[n],e);if(r)return r}return null}function _o(o,e,t){t||(t=[]),yo(o,e,t);for(let i=0;i<o?.children?.length;i++)_o(o.children[i],e,t);return t}function vo(o,e){if(!o)return null;if(Array.isArray(o)){for(let i=0;i<o.length;i++){let n=ob(o[i]),r=vo(n,e);if(r)return r}return null}let t=Or(o,e);return t||(o.parent?vo(o.parent,e):null)}function Hs(o,e,t){return t||(t=[]),o?(yo(o,e,t),o.parent?Hs(o.parent,e,t):t):t}function Hp(o,e,t){if(!o)return null;if(!e&&(e=G.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[Ii]===!1)continue;if(r.constructor==o)return r;let s=kr(r,o);if(s)return s}return null}function Fp(o,e,t){if(!o)return e;if(!t&&(t=G.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==o)return r;_o(r,o,e)}return e}function xo(o){o&&o.isObject3D===!0&&Mp(o,at)}at.prototype.SetActive=function(o){this.visible=o};at.prototype.addNewComponent=function(o){return Vn(this,new o)};at.prototype.removeComponent=function(o){return Wa(this,o)};at.prototype.getOrAddComponent=function(o){return Na(this,o)};at.prototype.getComponent=function(o){return Or(this,o)};at.prototype.getComponents=function(o,e){return yo(this,o,e)};at.prototype.getComponentInChildren=function(o){return kr(this,o)};at.prototype.getComponentsInChildren=function(o,e){return _o(this,o,e)};at.prototype.getComponentInParent=function(o){return vo(this,o)};at.prototype.getComponentsInParent=function(o,e){return Hs(this,o,e)};Object.getOwnPropertyDescriptor(at.prototype,"activeSelf")||Object.defineProperty(at.prototype,"activeSelf",{get:function(){return pn(this)},set:function(o){wo(this,o,!0)}});Ip(at);var Qa=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),oe=class{static isUsingInstancing(e){return e.__isUsingInstancing===!0}static markDirty(e,t=!0){if(!!e&&(this.isUsingInstancing(e)&&(e[Qa]=!0,e.matrixWorldNeedsUpdate=!0),t))for(let i of e.children)oe.markDirty(i,!0)}};var Mr=O("debuggetcomponent"),sb=(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))(sb||{}),Fe=class{idProvider;parent;keepWorldPosition;position;rotation;scale;visible;context},Fs=Symbol("isActive");function pn(o){let e=o.visible||qa(o);return o[Fs]===void 0&&(o[Fs]=!0),o[Fs]&&e}function wo(o,e,t=!0){return typeof e=="number"&&(e=e>.5),o[Fs]=e,t&&(o.visible=e),o[Fs]}function Up(o){return o[Ii]||qa(o)}function Gp(o,e){o.__isUsingInstancing=e}function qa(o){return oe.isUsingInstancing(o)}function Sr(o,e){return Un(o,e,!0,!0)}function ri(o,e=!0,t=!0){let i=o;if(i.isComponent){i.__internalDisable(),i.__internalDestroy();return}let n=o;if(Mr&&console.log(n),e&&n.children)for(let s of n.children)ri(s,e,!1);let r=n.userData.components;if(r){let s=r.length;for(let a=0;a<r.length;a++){let c=r[a];c.__internalDisable(),c.__internalDestroy(),r.length<s&&(s=r.length,a--)}}t&&n.removeFromParent()}function oi(o,e,t=!0){if(!!o){if(o.isObject3D||new Error("Expected Object3D but got "+o),o.userData?.components)for(let i=0;i<o.userData.components.length;i++){let n=o.userData.components[i];if(n?.isComponent===!0){let r=e(n);if(r!==void 0)return r}}if(t&&o.children)for(let i=0;i<o.children.length;i++){let n=o.children[i];if(!n)continue;let r=oi(n,e,t);if(r!==void 0)return r}}}function Pr(o,e=null){if(o===null)return null;let t=null;e!==null&&(e.x!==void 0?(t=new Fe,t.position=e):t=e);let i=G.Current;t?.context&&(i=t.context),Mr&&i.alias&&console.log("context",i.alias),t&&!t.idProvider&&(t.idProvider=new Ie(Date.now()));let n=[],r={},s={},a=Vp(i,o,t,n,r,s);a&&(lb(r),ab(s,r)),Mr&&(Ds(o,!0),Ds(a,!0));let c={};for(let d in n){let l=n[d],u=l.guid;t&&t.idProvider&&(l.guid=t.idProvider.generateUUID(),c[u]=l.guid,Mr&&console.log(l.name,l.guid)),Xa(l,i),l.__internalNewInstanceCreated&&l.__internalNewInstanceCreated()}for(let d in n){let l=n[d];l.resolveGuids&&l.resolveGuids(c),l.enabled!==!1&&(l.enabled=!0)}return fn(i),a}function Vp(o,e,t,i,n,r){if(!e)return null;let s=e.userData;e.userData={};let a=e.children;e.children=[];let c;if(c=e.clone(!1),xo(c),e.userData=s,e.children=a,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 l=c;l&&(l.guid=c.uuid)}e.animations&&e.animations.length>0&&(c.animations=[...e.animations]);let d=e.parent;if(d&&d.add(c),t?.position?ie(c,t.position):c.position.copy(e.position),t?.rotation?Je(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 l=null;if(typeof t.parent=="string"?l=Un(t.parent,o.scene,!0):l=t.parent,l){let u=t.keepWorldPosition===!0?l.attach:l.add;u?u.call(l,c):console.error("Invalid parent object",l,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(let[l,u]of Object.entries(e.userData))l!=="components"&&(c.userData[l]=u);if(e.userData?.components){let l=e.userData.components,u=[];c.userData.components=u;for(let h=0;h<l.length;h++){let b=l[h],w=Object.create(b);It(w,b),u.push(w),w.gameObject=c,i.push(w)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0);for(let l in e.children){let u=e.children[l],h=Vp(o,u,t,i,n,r);h&&c.add(h)}return c}function ab(o,e){for(let t in o){let i=o[t],n=i.original,r=n.skeleton,s=i.clone;if(!r){console.warn("Skinned mesh has no skeleton?",i);continue}let a=r.bones,c=s.skeleton.clone();s.skeleton=c,s.bindMatrix.clone().copy(n.bindMatrix),s.bindMatrixInverse.copy(n.bindMatrixInverse);let d=[];c.bones=d;for(let l=0;l<a.length;l++){let u=a[l],b=e[u.uuid].clone;d.push(b)}}for(let t in o){let i=o[t].clone;i.skeleton.update(),i.bind(i.skeleton,i.bindMatrix),i.updateMatrixWorld(!0)}}function lb(o){for(let e in o){let i=o[e].clone;if(i.userData?.components)for(let n=0;n<i.userData.components.length;n++){let r=i.userData.components[n],s=Object.entries(r);for(let[a,c]of s)if(Array.isArray(c)){let d=[];r[a]=d;for(let l=0;l<c.length;l++){let u=c[l];if(typeof u!="object"){d.push(u);continue}let h=Bp(r,a,u,o);h!==void 0?d.push(h):d.push(u)}}else if(typeof c=="object"){let d=Bp(r,a,c,o);d!==void 0&&(r[a]=d)}}}}function Bp(o,e,t,i){if(t!=null){if(t.isComponent===!0){let n=t.gameObject;if(n){let r=n.uuid,s=i[r]?.clone;if(!s){Mr&&console.log("reference did not change",e,o,t);return}let a=n.userData.components.indexOf(t);if(a>=0)return Mr&&console.log(e,r),s.userData.components[a];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,s=i[r]?.clone;if(s)return Mr&&console.log(e,"old",t,"new",s),s}}else if(t.isVector4||t.isVector3||t.isVector2||t.isQuaternion||t.isEuler)return t.clone()}}import mn,{ActiveEvents as kb,Collider as Mb,ColliderDesc as Bs,EventQueue as Ib,JointData as Db,RigidBody as Ab,RigidBodyType as ad,World as Lb}from"@dimforge/rapier3d-compat";import{BufferAttribute as cb,Line as db,BoxGeometry as Xp,EdgesGeometry as ub,Color as hb,LineSegments as pb,LineBasicMaterial as fb,Mesh as zp,SphereGeometry as mb,Vector3 as gb,Quaternion as bb}from"three";var vt=new gb,Wp=new bb,Ir=8947848,Dr=class{static DrawRay(e,t,i=Ir,n=0,r=!0){let s=Ze.getLine(n),a=s.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),vt.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+vt.x,e.y+vt.y,e.z+vt.z),a.needsUpdate=!0,s.material.color.set(i),s.material.depthTest=r}static DrawDirection(e,t,i=Ir,n=0,r=!0,s=1){let a=Ze.getLine(n),c=a.geometry.getAttribute("position");c.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(vt.set(0,0,-s),Wp.set(t.x,t.y,t.z,t.w),vt.applyQuaternion(Wp)):(vt.set(t.x,t.y,t.z),vt.multiplyScalar(s)),c.setXYZ(1,e.x+vt.x,e.y+vt.y,e.z+vt.z),c.needsUpdate=!0,a.material.color.set(i),a.material.depthTest=r}static DrawLine(e,t,i=Ir,n=0,r=!0){let s=Ze.getLine(n),a=s.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),a.setXYZ(1,t.x,t.y,t.z),a.needsUpdate=!0,s.material.color.set(i),s.material.depthTest=r}static DrawWireSphere(e,t,i=Ir,n=0,r=!0){let s=Ze.getSphere(t,n,!0);dn(s,e.x,e.y,e.z),s.material.color.set(i),s.material.depthTest=r}static DrawSphere(e,t,i=Ir,n=0,r=!0){let s=Ze.getSphere(t,n,!1);dn(s,e.x,e.y,e.z),s.material.color.set(i),s.material.depthTest=r}static DrawBox(e,t,i=Ir,n=0,r=!0){let s=Ze.getBox(n);s.position.set(e.x,e.y,e.z),s.scale.set(t.x,t.y,t.z),s.material.color.set(i),s.material.depthTest=r,s.material.wireframe=!0}static DrawBox3(e,t=Ir,i=0,n=!0){let r=Ze.getBox(i);r.position.copy(e.getCenter(vt)),r.scale.copy(e.getSize(vt)),r.material.color.set(t),r.material.depthTest=n,r.material.wireframe=!0}},vb=new Xp(1,1,1);function Ya(o=null){let e=new hb(o??14540253),t=new ub(vb);return new pb(t,new fb({color:e}))}var Np=Symbol("GizmoCache"),Ze=class{static getBox(e){let t=this.boxesCache.pop();if(!t){let i=new Xp(1,1,1);t=new zp(i)}return this.registerTimedObject(G.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new db;let i=t.geometry.getAttribute("position");i||(i=new cb(new Float32Array(2*3),3),t.geometry.setAttribute("position",i))}return this.registerTimedObject(G.Current,t,e,this.linesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new zp(new mb(.5,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(G.Current,n,t,this.spheresCache),n}static registerTimedObject(e,t,i,n){if(!this.contextPostRenderCallbacks.get(e)){let r=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,r),e.post_render_callbacks.push(r)}t[Np]=n,this.timedObjectsBuffer.push(t),this.timesBuffer.push(G.Current.time.time+i),e.scene.add(t)}static onPostRender(e,t,i){let n=e.time.time;for(let r=0;r<t.length;r++)if(n>i[r]){let s=t[r];s[Np].push(s),e.scene.remove(s),t.splice(r,1),i.splice(r,1)}}};D(Ze,"linesCache",[]),D(Ze,"spheresCache",[]),D(Ze,"boxesCache",[]),D(Ze,"timedObjectsBuffer",new Array),D(Ze,"timesBuffer",new Array),D(Ze,"contextPostRenderCallbacks",new Map);var Eo=O("debugphysics"),ld=O("debugphysicscolliders"),cd=O("debugcollisions"),jb=O("showcolliders"),Co=Symbol("needle component"),Dt=Symbol("physics body"),Hb=Symbol("rigidbody"),ge=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 Ob),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setMask(e){this.layerMask||(this.layerMask=new dd);let t=this.layerMask;t?t.mask=e:this.layerMask=e}};D(ge,"AllLayers",4294967295);var ud=class{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}},Ar=class{raycaster=new Sb;defaultRaycastOptions=new ge;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:0},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new dd;sphereOverlap(e,t,i=!0){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;let n=new Pb(e,t),r=this.sphereMask;r.enableAll(),r.disable(2);for(let s of this.context.scene.children)this.onSphereOverlap(s,n,r,this.sphereResults,i);return this.sphereResults.sort((s,a)=>s.distance-a.distance)}tempBoundingBox=new xb;onSphereOverlap(e,t,i,n,r){if(e.type==="Mesh"&&e.layers.test(i)){let s=e,a=s.geometry;if(a.boundingBox||a.computeBoundingBox(),a.boundingBox){s.matrixWorldNeedsUpdate&&s.updateMatrixWorld();let c=this.tempBoundingBox.copy(a.boundingBox).applyMatrix4(s.matrixWorld);if(t.intersectsBox(c)){let l=B(e).distanceTo(t.center),u=new ud(e,l,t.center.clone());if(n.push(u),!r)return}}}if(e.children)for(let s of e.children){let a=n.length;if(this.onSphereOverlap(s,t,i,n,r),a!=n.length&&!r)return}}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 a=e.cam??this.context.mainCamera;if(!a)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,a)}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 dd?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),r.length=0,i.intersectObjects(n,e.recursive,r);let s=e.ignore;return s!==void 0&&s.length>0&&(r=r.filter(a=>!s.includes(a.object))),r}rapierRay=new mn.Ray({x:0,y:0,z:0},{x:0,y:0,z:1});raycastVectorsBuffer=new Pi(()=>new sd,10);raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){let r=this.getPhysicsRay(this.rapierRay,e,t);if(!r)return null;let s=this.world?.castRay(r,i,n);if(s){let a=r.pointAt(s.toi),c=this.raycastVectorsBuffer.get();return c.set(a.x,a.y,a.z),{point:c,collider:s.collider[Co]}}return null}getPhysicsRay(e,t,i=void 0){let n=this.context.mainCamera;if(t.z===void 0){if(!n)return console.error("Can not perform raycast from 2d point - no main camera found"),null;let a=this.raycastVectorsBuffer.get();(t.x>1||t.y>1||t.y<-1||t.x<-1)&&this.context.input.convertScreenspaceToRaycastSpace(t),a.set(t.x,t.y,-1),a.unproject(n),t=a}let r=t;e.origin.x=r.x,e.origin.y=r.y,e.origin.z=r.z;let s=this.raycastVectorsBuffer.get();if(i)s.set(i.x,i.y,i.z);else{if(!n)return console.error("Can not perform raycast - no camera found"),null;s.set(e.origin.x,e.origin.y,e.origin.z);let a=B(n);s.sub(a)}return s.normalize(),e.dir.x=s.x,e.dir.y=s.y,e.dir.z=s.z,e}_tempPosition=new sd;_tempQuaternion=new Rb;_tempScale=new sd;_tempMatrix=new Tb;_isUpdatingPhysicsWorld=!1;get isUpdating(){return this._isUpdatingPhysicsWorld}context;world;_hasCreatedWorld=!1;eventQueue;collisionHandler;objects=[];bodies=[];_meshCache=new Map;constructor(e){this.context=e}async createWorld(){if(this._hasCreatedWorld){console.error("Invalid call to create physics world: world is already created");return}this._hasCreatedWorld=!0,Ar._didLoadPhysicsEngine||(await mn.init().then(()=>mn),Ar._didLoadPhysicsEngine=!0);let e={x:0,y:-9.81,z:0};this.world=new Lb(e)}clearCaches(){this._meshCache.clear()}addBoxCollider(e,t,i){let n=e.gameObject,r=Me(n,this._tempPosition).multiply(i);r.multiplyScalar(.5);let s=Bs.cuboid(r.x,r.y,r.z);this.createCollider(e,s,t)}addSphereCollider(e,t,i){let n=e.gameObject,r=Me(n,this._tempPosition).multiplyScalar(i),s=Bs.ball(r.x);this.createCollider(e,s,t)}addCapsuleCollider(e,t,i,n){let r=e.gameObject,s=Me(r,this._tempPosition);Eo&&console.log("capsule scale",s,i,n);let a=Bs.capsule(i*.5*s.y-n,n*s.x);this.createCollider(e,a,t)}addMeshCollider(e,t,i,n){let r=t.geometry;if(!r){Eo&&console.warn("Missing mesh geometry",t.name);return}let s=r.getAttribute("position").array,a=r.index?.array;if(Math.abs(n.x-1)>1e-4||Math.abs(n.y-1)>1e-4||Math.abs(n.z-1)>1e-4){let d=r.uuid+"_"+n.x+"_"+n.y+"_"+n.z+"_"+i;if(this._meshCache.has(d))s=this._meshCache.get(d);else{console.warn("Your model is using scaled mesh colliders which is not optimal for performance",t.name,Object.assign({},n),t);let l=new Float32Array(s.length);for(let u=0;u<s.length;u+=3)l[u]=s[u]*n.x,l[u+1]=s[u+1]*n.y,l[u+2]=s[u+2]*n.z;s=l,this._meshCache.set(d,l)}}let c=i?Bs.convexMesh(s):Bs.trimesh(s,a);c&&this.createCollider(e,c)}createCollider(e,t,i){if(!this.world)throw new Error("Physics world not initialized");let n=this._tempMatrix,{rigidBody:r,useExplicitMassProperties:s}=this.getRigidbody(e,this._tempMatrix);n.decompose(this._tempPosition,this._tempQuaternion,this._tempScale),Me(e.gameObject,this._tempScale),i&&(i.multiply(this._tempScale),this._tempPosition.x-=i.x,this._tempPosition.y+=i.y,this._tempPosition.z+=i.z),t.setTranslation(this._tempPosition.x,this._tempPosition.y,this._tempPosition.z),t.setRotation(this._tempQuaternion),t.setSensor(e.isTrigger);let a=this.world.createCollider(t,r);return a[Co]=e,e[Dt]=a,a.setActiveEvents(kb.COLLISION_EVENTS),this.objects.push(e),this.bodies.push(a),a}getRigidbody(e,t){if(!this.world)throw new Error("Physics world not initialized");let i=null,n=!1;if(e.attachedRigidbody){let r=e.attachedRigidbody;if(i=r[Dt],n=!0,!i){let s=r.isKinematic&&!ld;Eo&&console.log("Create rigidbody",s);let a=s?mn.RigidBodyDesc.kinematicPositionBased():mn.RigidBodyDesc.dynamic(),c=B(e.attachedRigidbody.gameObject);a.setTranslation(c.x,c.y,c.z),a.setRotation(fe(e.attachedRigidbody.gameObject)),i=this.world.createRigidBody(a),this.bodies.push(i),this.objects.push(r)}i[Co]=r,r[Dt]=i,this.internalUpdateProperties(r,i),this.getRigidbodyRelativeMatrix(e.gameObject,r.gameObject,t)}else{let r=mn.RigidBodyDesc.kinematicPositionBased(),s=B(e.gameObject);r.setTranslation(s.x,s.y,s.z),r.setRotation(fe(e.gameObject)),i=this.world.createRigidBody(r),t.identity(),i[Co]=null}return e[Hb]=i,{rigidBody:i,useExplicitMassProperties:n}}removeBody(e){let t=e[Dt];if(e[Dt]=null,t&&this.world){let i=this.objects.findIndex(n=>n===e);if(i>=0){let n=this.bodies[i];if(this.bodies.splice(i,1),this.objects.splice(i,1),n instanceof Mb){let r=n;this.world?.removeCollider(r,!0);let s=r.parent();s&&s.numColliders()<=0&&this.world?.removeRigidBody(s)}else n instanceof Ab}}}updateBody(e,t,i){if(!(e.destroyed||!e.gameObject)&&!(!t&&!i))if(e.isCollider===!0)console.warn("TODO: implement updating collider position");else{let n=e,r=n[Dt];r&&this.syncPhysicsBody(n.gameObject,r,t,i)}}updateProperties(e){let t=e[Dt];t&&this.internalUpdateProperties(e,t)}internal_getRigidbody(e){return e[Dt]}internalUpdateProperties(e,t){t.enableCcd(e.collisionDetectionMode!==0),t.setLinearDamping(e.drag),t.setAngularDamping(e.angularDrag),t.setGravityScale(e.useGravity?1:0,!0),t.setEnabledRotations(!e.lockRotationX,!e.lockRotationY,!e.lockRotationZ,!0),t.setEnabledTranslations(!e.lockPositionX,!e.lockPositionY,!e.lockPositionZ,!0),e.isKinematic?t.setBodyType(mn.RigidBodyType.KinematicPositionBased):t.setBodyType(mn.RigidBodyType.Dynamic)}lines;step(e){!this.world||(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new Ib(!1)),this.world.step(this.eventQueue),this._isUpdatingPhysicsWorld=!1,this.updateDebugRendering(this.world))}updateDebugRendering(e){if(Eo||ld||jb){if(!this.lines){let i=new Eb({color:2258688}),n=new wb;this.lines=new Cb(n,i),this.context.scene.add(this.lines)}let t=e.debugRender();this.lines.geometry.setAttribute("position",new Qp(t.vertices,3)),this.lines.geometry.setAttribute("color",new Qp(t.colors,4))}}postStep(){!this.world||(this._isUpdatingPhysicsWorld=!0,this.syncObjects(),this._isUpdatingPhysicsWorld=!1,this.eventQueue&&!this.collisionHandler&&(this.collisionHandler=new hd(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()))}syncObjects(){if(!ld)for(let e=0;e<this.bodies.length;e++){let t=this.objects[e],i=this.bodies[e],n=t;if(n?.isCollider===!0&&!n.attachedRigidbody){let c=i.parent();c&&this.syncPhysicsBody(t.gameObject,c,!0,!0);continue}let r=i.translation(),s=i.rotation(),a=t.center;if(a&&a.isVector3){this._tempQuaternion.set(s.x,s.y,s.z,s.w);let c=this._tempPosition.copy(a).applyQuaternion(this._tempQuaternion),d=Me(t.gameObject);c.multiply(d),r.x-=c.x,r.y-=c.y,r.z-=c.z}dn(t.gameObject,r.x,r.y,r.z),up(t.gameObject,s.x,s.y,s.z,s.w)}}syncPhysicsBody(e,t,i,n){let r=B(e,this._tempPosition),s=fe(e,this._tempQuaternion);switch(t.bodyType()){case ad.Fixed:case ad.KinematicPositionBased:case ad.KinematicVelocityBased:i&&t.setNextKinematicTranslation(r),n&&t.setNextKinematicRotation(s);break;default:i&&t.setTranslation(r,!1),n&&t.setRotation(s,!1);break}t.wakeUp()}getRigidbodyRelativeMatrix(e,t,i,n){if(n===void 0&&(n=Ar._matricesBuffer,n.length=0),e===t){let r=Me(e,this._tempPosition);i.makeScale(r.x,r.y,r.z);for(let s=n.length-1;s>=0;s--)i.multiply(n[s]);return i}return n.push(e.matrix),e.parent&&this.getRigidbodyRelativeMatrix(e.parent,t,i,n),i}addFixedJoint(e,t){if(!this.world){console.error("Physics world not initialized");return}let i=e[Dt],n=t[Dt];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);let r=Db.fixed(Ar.centerConnectionPos,Ar.centerConnectionRot,this._tempPosition,this._tempQuaternion),s=this.world.createImpulseJoint(r,i,n,!0);Eo&&console.log("ADD FIXED JOINT",s)}addHingeJoint(e,t,i,n){if(!this.world){console.error("Physics world not initialized");return}let r=e[Dt],s=t[Dt];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);let a=mn.JointData.revolute(i,this._tempPosition,n),c=this.world.createImpulseJoint(a,r,s,!0);Eo&&console.log("ADD HINGE JOINT",c)}calculateJointRelativeMatrices(e,t,i){e.updateWorldMatrix(!0,!1),t.updateWorldMatrix(!0,!1);let n=e.matrixWorld,r=t.matrixWorld;n.elements[0]=1,n.elements[5]=1,n.elements[10]=1,r.elements[0]=1,r.elements[5]=1,r.elements[10]=1,i.copy(r).premultiply(n.invert()).invert()}},zn=Ar;D(zn,"_didLoadPhysicsEngine",!1),D(zn,"_matricesBuffer",[]),D(zn,"centerConnectionPos",{x:0,y:0,z:0}),D(zn,"centerConnectionRot",{x:0,y:0,z:0,w:1});var hd=class{world;eventQueue;constructor(e,t){this.world=e,this.eventQueue=t}activeCollisions=[];activeCollisionsStay=[];activeTriggers=[];handleCollisionEvents(){!this.eventQueue||!this.world||this.eventQueue.drainCollisionEvents((e,t,i)=>{let n=this.world.getCollider(e),r=this.world.getCollider(t),s=n[Co],a=r[Co];cd&&console.log("EVT",s.name,a.name,i,n,r),s&&a&&(i?(this.onCollisionStarted(s,n,a,r),this.onCollisionStarted(a,r,s,n)):(this.onCollisionEnded(s,a),this.onCollisionEnded(a,s)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(e,t,i,n){let r=null;if(e.isTrigger||i.isTrigger)oi(e.gameObject,s=>{s.onTriggerEnter&&s.onTriggerEnter(i),this.activeTriggers.push({collider:e,component:s,otherCollider:i})});else{let s=e.gameObject;this.world.contactPair(t,n,(a,c)=>{oi(s,d=>{let l=d.onCollisionEnter||d.onCollisionStay||d.onCollisionExit;if(l||cd){if(!r){let u=[],h=a.normal();for(let b=0;b<a.numSolverContacts();b++){let w=a.solverContactPoint(b),v=a.contactImpulse(b);if(w){let x=a.contactDist(b),m=a.solverContactFriction(b),f=new Ha(w,x,h,v,m);u.push(f),cd&&Dr.DrawDirection(w,h,16711680,3,!0)}}r=new As(s,i,u)}if(l){let u={collider:e,component:d,collision:r};this.activeCollisions.push(u),d.onCollisionStay&&this.activeCollisionsStay.push(u),d.onCollisionEnter?.call(d,r)}}})})}}onHandleCollisionStay(){for(let e of this.activeCollisionsStay){let t=e.component;if(t.activeAndEnabled&&t.onCollisionStay){let i=e.collision;t.onCollisionStay(i)}}for(let e of this.activeTriggers){let t=e.component;if(t.activeAndEnabled&&t.onTriggerStay){let i=e.otherCollider;t.onTriggerStay(i)}}}onCollisionEnded(e,t){for(let i=0;i<this.activeCollisions.length;i++){let n=this.activeCollisions[i];if(n.collider===e&&n.collision.collider===t){let s=n.component;if(this.activeCollisions.splice(i,1),i--,s.activeAndEnabled&&s.onCollisionExit){let a=n.collision;s.onCollisionExit(a)}}}for(let i=0;i<this.activeCollisionsStay.length;i++){let n=this.activeCollisionsStay[i];if(n.collider===e&&n.collision.collider===t){let s=n.component;if(this.activeCollisionsStay.splice(i,1),i--,s.activeAndEnabled&&s.onCollisionExit){let a=n.collision;s.onCollisionExit(a)}}}for(let i=0;i<this.activeTriggers.length;i++){let n=this.activeTriggers[i];if(n.collider===e&&n.otherCollider===t){let s=n.component;if(this.activeTriggers.splice(i,1),i--,s.activeAndEnabled&&s.onTriggerExit){let a=n.otherCollider;s.onTriggerExit(a)}}}}};import{Clock as Fb}from"three";var Ka=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 Fb;_smoothedFps=0;_fpsSamples=[];_fpsSampleIndex=0;update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this.deltaTime<=0&&(this.deltaTime=1e-12),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 Ub}from"websocket-ts";var Di=new Int32Array(2),Ja=new Float32Array(Di.buffer),Za=new Float64Array(Di.buffer),To=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;var Ne=class{constructor(e,t){this.low=e|0,this.high=t|0}static create(e,t){return e==0&&t==0?Ne.ZERO:new Ne(e,t)}toFloat64(){return(this.low>>>0)+this.high*4294967296}equals(e){return this.low==e.low&&this.high==e.high}};Ne.ZERO=new Ne(0,0);var Us;(function(o){o[o.UTF8_BYTES=1]="UTF8_BYTES",o[o.UTF16_STRING=2]="UTF16_STRING"})(Us||(Us={}));var Ai=class{constructor(e){this.bytes_=e,this.position_=0}static allocate(e){return new Ai(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 Ne(this.readInt32(e),this.readInt32(e+4))}readUint64(e){return new Ne(this.readUint32(e),this.readUint32(e+4))}readFloat32(e){return Di[0]=this.readInt32(e),Ja[0]}readFloat64(e){return Di[To?0:1]=this.readInt32(e),Di[To?1:0]=this.readInt32(e+4),Za[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){Ja[0]=t,this.writeInt32(e,Di[0])}writeFloat64(e,t){Za[0]=t,this.writeInt32(e,Di[To?0:1]),this.writeInt32(e+4,Di[To?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===Us.UTF8_BYTES)return this.bytes_.subarray(e,e+i);for(;r<i;){let s,a=this.readUint8(e+r++);if(a<192)s=a;else{let c=this.readUint8(e+r++);if(a<224)s=(a&31)<<6|c&63;else{let d=this.readUint8(e+r++);if(a<240)s=(a&15)<<12|(c&63)<<6|d&63;else{let l=this.readUint8(e+r++);s=(a&7)<<18|(c&63)<<12|(d&63)<<6|l&63}}}s<65536?n+=String.fromCharCode(s):(s-=65536,n+=String.fromCharCode((s>>10)+55296,(s&(1<<10)-1)+56320))}return n}__union_with_string(e,t){return typeof e=="string"?this.__string(t):this.__union(e,t)}__indirect(e){return e+this.readInt32(e)}__vector(e){return e+this.readInt32(e)+4}__vector_len(e){return this.readInt32(e+this.readInt32(e))}__has_identifier(e){if(e.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let t=0;t<4;t++)if(e.charCodeAt(t)!=this.readInt8(this.position()+4+t))return!1;return!0}createLong(e,t){return Ne.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 yt=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=Ai.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=yt.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=Ai.allocate(i);return n.setPosition(i-t),n.bytes().set(e.bytes(),i-t),n}addOffset(e){this.prep(4,0),this.writeInt32(this.offset()-e+4)}startObject(e){this.notNested(),this.vtable==null&&(this.vtable=[]),this.vtable_in_use=e;for(let t=0;t<e;t++)this.vtable[t]=0;this.isNested=!0,this.object_start=this.offset()}endObject(){if(this.vtable==null||!this.isNested)throw new Error("FlatBuffers: endObject called without startObject");this.addInt32(0);let e=this.offset(),t=this.vtable_in_use-1;for(;t>=0&&this.vtable[t]==0;t--);let i=t+1;for(;t>=0;t--)this.addInt16(this.vtable[t]!=0?e-this.vtable[t]:0);let n=2;this.addInt16(e-this.object_start);let r=(i+n)*2;this.addInt16(r);let s=0,a=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(a+d)!=this.bb.readInt16(c+d))continue e;s=this.vtables[t];break}}return s?(this.space=this.bb.capacity()-e,this.bb.writeInt32(this.space,s-e)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-e,this.offset()-e)),this.isNested=!1,e}finish(e,t,i){let n=i?4:0;if(t){let r=t;if(this.prep(this.minalign,4+4+n),r.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let s=4-1;s>=0;s--)this.writeInt8(r.charCodeAt(s))}this.prep(this.minalign,4+n),this.addOffset(e),n&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(e,t){this.finish(e,t,!0)}requiredField(e,t){let i=this.bb.capacity()-e,n=i-this.bb.readInt32(i);if(!(this.bb.readInt16(n+t)!=0))throw new Error("FlatBuffers: field "+t+" must be set")}startVector(e,t,i){this.notNested(),this.vector_num_elems=t,this.prep(4,e*t),this.prep(i,e*t)}endVector(){return this.writeInt32(this.vector_num_elems),this.offset()}createSharedString(e){if(!e)return 0;if(this.string_maps||(this.string_maps=new Map),this.string_maps.has(e))return this.string_maps.get(e);let t=this.createString(e);return this.string_maps.set(e,t),t}createString(e){if(!e)return 0;let t;if(e instanceof Uint8Array)t=e;else{t=[];let i=0;for(;i<e.length;){let n,r=e.charCodeAt(i++);if(r<55296||r>=56320)n=r;else{let s=e.charCodeAt(i++);n=(r<<10)+s+(65536-(55296<<10)-56320)}n<128?t.push(n):(n<2048?t.push(n>>6&31|192):(n<65536?t.push(n>>12&15|224):t.push(n>>18&7|240,n>>12&63|128),t.push(n>>6&63|128)),t.push(n&63|128))}}this.addInt8(0),this.startVector(1,t.length,1),this.bb.setPosition(this.space-=t.length);for(let i=0,n=this.space,r=this.bb.bytes();i<t.length;i++)r[n++]=t[i];return this.endVector()}createLong(e,t){return Ne.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 qp={};function So(o,e){qp[o]=e}function Yp(o){let e=o.getBufferIdentifier(),t=qp[e];return t(o)}function Kp(o){return typeof o.guid=="function"?o.guid():null}var fd=wa(el(),1);var tl=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 fd.default(e);t.on("error",i=>{console.error(i),this._host=void 0,this.trySetupClient(e)}),t.on("open",i=>{this._host=new gd(t)})}trySetupClient(e){this._client=new fd.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)})})}},md=class{_peer;constructor(e){this._peer=e}};var gd=class extends md{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 il="wss://needle-tiny-starter.glitch.me/socket",lt=!!O("debugnet"),nl=!!(lt||O("debugowner"));var Nn=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||(nl&&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 nl&&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?(nl&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(nl&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}},rl=class{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new tl),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return lt}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(),lt&&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]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(e){lt&&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&&lt&&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;lt&&console.log("connecting");let e=this.netWebSocketUrlProvider?.getWebsocketUrl();e?il=e:Yh()&&(il="wss://"+window.location.host+"/socket"),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 "+il);let e=new Ub(il).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{lt&&i==="pong"&&console.log("<<",i)}}async handleIncomingBinaryMessage(e){let t=await e.arrayBuffer();var i=new Uint8Array(t);let n=new Ai(i),r=n.getBufferIdentifier(),s=this._listenersBinary[r],a=Yp(n),c=Kp(a);if(c&&typeof c=="string"&&(this._state[c]=a),!s)return;let d=a??n;for(let l of s)l(d)}handleIncomingStringMessage(e){if(lt&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){let s=e.data;s&&(console.assert(s.id!==void 0&&s.id!==null&&s.id.length>0,"server did not send connection id",s.id),console.log("Your id is: "+s.id,this.context.alias??""),this._connectionId=s.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(lt&&console.log(e),e){this._isInRoom=!0;let s=e;this._currentRoomName=s.room,this._currentRoomViewId=s.viewId,this._currentRoomAllowEditing=s.allowEditing??!0,console.log("Room view id",this._currentRoomViewId),this._currentInRoom.length=0,this._currentInRoom.push(...s.inRoom),lt&&console.log("joined room with",this._currentInRoom,this.context.alias??"")}this.onSendQueued(1);break;case"left-room":e.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(e.data){let s=e.data;this._currentInRoom.push(s.userId),lt&&console.log(s.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){let s=e.data,a=this._currentInRoom.indexOf(s.userId);a>=0&&(console.log(s.userId+" left",this.context.alias??""),this._currentInRoom.splice(a,1)),s.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":lt&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":let r=e.data?.time;r&&(this._currentDelay=this.context.time.time-r),lt&&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));lt&&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 uv}from"three/examples/jsm/postprocessing/EffectComposer.js";import{RenderPass as hv}from"three/examples/jsm/postprocessing/RenderPass";import*as Xn from"three";var af=wa(sf(),1),ol=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 lf(o,e){let t=await o.arrayBuffer(),i=cf(t),n=o.name.split(".").pop(),r=i+"."+n,s=o.name.split(".").shift();console.assert(s!==void 0);let a={alias:s,filename:r},d=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(a)})).json();if(d.success||console.warn("exists check did fail"),d.exists)return console.log("file already exists",i),new ol(!0,r,i,o.size);console.log("begin uploading file",s,o.size);let l=new FormData;l.append("file",o);let u={};u.filesize=o.size,s&&(u.alias=s);let b=await(await fetch(e+"/upload/file",{method:"POST",body:l,headers:u})).json();if(b?.success===!1)return b.message!==void 0?console.error("Upload failed:",b.message):console.error("Upload failed"),null;console.assert(b.hash_sum===i,"hash sum did not match","received:",b.hash_sum,"expected:",i),b.success&&console.log("successfully uploaded",i,b.id);let w=new ol(b.success,r,i,o.size);return w.url=e,w}function cf(o){return(0,af.default)(new Uint8Array(o))}async function sl(o,e,t,i,n=!1){try{let r=await fetch(i+"/download/file",{method:"POST",body:o});if(r.status!==200)return console.error("download failed",r),null;let s=await r.blob(),a=await s.arrayBuffer();n||console.assert(s.size===t,"size mismatch","expected:",t,"got:",s.size);let c=cf(a);return n||console.assert(c===e,"hash mismatch, downloaded file is invalid"),s.arrayBuffer()}catch(r){console.error(r)}return null}async function df(o,e){let t=await fetch(o),i=t.body?.getReader(),n=t.headers.get("Content-Length"),r=n?parseInt(n):0;if(!i)return null;let s=0,a=[];for(;;){let{done:l,value:u}=await i.read();if(u&&(a.push(u),s+=u.length,e.call(null,new ProgressEvent("progress",{loaded:s,total:r}))),l)break}let c=new Uint8Array(s),d=0;for(let l of a)c.set(l,d),d+=l.length;return c}function al(o,e,t){console.warn("Adding components on object has been temporarily disabled")}var hf,uf=null;function Xe(){return hf}function ll(o){uf!==o&&(uf=o,hf=new o)}var yd=class{guid;file_name;file_hash;file_size;position;seed;sender;serverUrl;parentGuid;boundsSize;constructor(e,t,i,n,r,s,a,c){this.seed=t,this.guid=i,this.file_name=n,this.file_hash=r,this.file_size=s,this.position=a,this.sender=e,this.serverUrl=c}};async function pf(o,e,t){let i=o.name;return i.endsWith(".gltf")||i.endsWith(".glb")?new Promise((n,r)=>{let s=new FileReader;s.readAsDataURL(o),s.onloadend=async a=>{let c=s.result,d=za(),l=new Ie(d),u=await Xe().loadSync(e,c,l,!0);if(u&&u.scene){let h=u.scene;if(!h.guid){let b=new Ie(d);h.guid=b.generateUUID()}t&&Wb(e.connection,o,d,h,t),al(h,l,u),n(u)}}}):(console.warn("Unsupported file type: "+i),console.log(o),null)}async function ff(o,e){return new Promise(async(t,i)=>{let n=za(),r=new Ie(n),s=await Xe().loadSync(e,o.toString(),r,!0);if(s&&s.scene){let a=s.scene;al(a,r,s),t(s)}else console.warn("Unsupported file type: "+o.toString())})}function mf(o){o.connection.beginListen("file-spawned",async e=>{if(e.sender!==o.connection.connectionId){console.log("received file event",e),Nb(e,o);let t=null;try{t=await sl(e.file_name,e.file_hash,e.file_size,e.serverUrl)}finally{Xb(e,o)}if(t){let i=new Ie(e.seed),n=await Xe().parseSync(o,t,null,i);if(n&&n.scene){let r=n.scene;if(al(r,i,n),e.parentGuid){let s=Sr(e.parentGuid,o.scene);"add"in s&&s.add(r)}r.parent||o.scene.add(r),e.position!==null&&r.position.copy(e.position)}}else console.error("download didnt return file")}})}async function Wb(o,e,t,i,n){if(!o.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 lf(e,n);if(!r)return;if(!r.filename){console.error("Can not send upload event - no filename",e.name);return}if(!r.hash){console.error("Can not send upload event - no hash",e.name);return}let s=new yd(o.connectionId,t,i.guid,r.filename,r.hash,e.size,i.position,r.url??n);i.parent&&(s.parentGuid=i.parent.guid),o.send("file-spawned",s)}var _d={};function Nb(o,e){let t=new Xn.BoxGeometry,i=new Xn.Mesh(t,new Xn.MeshBasicMaterial({color:65280})),n=new Xn.BoxHelper(i,5592405);if(_d[o.guid]=n,e.scene.add(n),o.parentGuid){let r=Sr(o.parentGuid,e.scene);r&&r.add(n)}o.position&&n.position.copy(o.position)}function Xb(o,e){let t=o.guid,i=_d[t];i&&(delete _d[t],i.removeFromParent())}import*as gf from"three";var g0=O("debugassets");var cl=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:
152
+ `+i.src),e.preventDefault())}})}texturesLoader=new gf.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 Tf from"three/examples/jsm/libs/stats.module";import{Vector4 as ev,EquirectangularReflectionMapping as ul,sRGBEncoding as hl,WebGLCubeRenderTarget as tv}from"three";import{LightProbeGenerator as iv}from"three/examples/jsm/lights/LightProbeGenerator.js";import*as bf from"three";var qb=new bf.FileLoader;async function xd(o){return new Promise((e,t)=>{qb.load(o,e,void 0,t)})}import{Vector4 as Qn,FileLoader as Kb,DataTexture as Rd,RGBAFormat as Jb,Color as Zb}from"three";var Gs=new Uint8Array(4);Gs[0]=255;Gs[1]=255;Gs[2]=255;Gs[3]=255;var _f=new Rd(Gs,1,1,Jb);function dl(o,e=1){let t="alpha"in o,i=e*e,n=new Uint8Array(4*i),r=Math.floor(o.r*255),s=Math.floor(o.g*255),a=Math.floor(o.b*255);for(let d=0;d<i;d++){let l=d*4;n[l+0]=r,n[l+1]=s,n[l+2]=a,t?n[l+3]=Math.floor(o.alpha*255):n[l+3]=255}let c=new Rd(n,e,e);return c.needsUpdate=!0,c}function xf(o,e,t,i=1,n=3){let a=i*n,c=[o,e,t],d=c.length,l=new Uint8Array(4*d*a),u=new Zb;for(let b=0;b<n;b++){let w=Math.floor(b/n*d),v=H.clamp(w+1,0,d-1),x=c[w],m=c[v],f=b/n*d%1;u.lerpColors(x,m,f);let p=Math.floor(u.r*255),g=Math.floor(u.g*255),E=Math.floor(u.b*255);for(let C=0;C<i;C++){let T=(b*i+C)*4;l[T+0]=p,l[T+1]=g,l[T+2]=E,l[T+3]=255}}let h=new Rd(l,i,n);return h.needsUpdate=!0,h}var Ed=class{stage;code;constructor(e,t){this.stage=e,this.code=t}},Cd=class{loaded=new Map;async loadShader(e){let t=await xd(e);return JSON.parse(t)}async load(e,t){if(this.loaded.has(t))return new Promise((r,s)=>{let a=this.loaded.get(t);a?r(a):s("Shader not found")});let i=await xd(t),n=new Ed(e,i);return this.loaded.set(t,n),n}},x0=new Cd;function Vs(o,e){let t=o.elements;e||(e=[]),e.length=0;for(let i=0;i<16;i+=4){let n=t[i],r=t[i+1],s=t[i+2],a=t[i+3],c=new Qn(n,r,s,a);e.push(c)}return e}var wd=[],vf=[];function Sd(o,e){if(wd.length===0)for(let t=0;t<27;t++)wd.push(0);e||(e=wd);for(let t=0;t<27;t++)vf[t]=e[t];e=vf,o.unity_SHAr={value:new Qn(e[9],e[3],e[6],e[0])},o.unity_SHBr={value:new Qn(e[12],e[15],e[18],e[21])},o.unity_SHAg={value:new Qn(e[10],e[4],e[7],e[1])},o.unity_SHBg={value:new Qn(e[13],e[16],e[19],e[22])},o.unity_SHAb={value:new Qn(e[11],e[5],e[8],e[2])},o.unity_SHBb={value:new Qn(e[14],e[17],e[20],e[23])},o.unity_SHC={value:new Qn(e[24],e[25],e[26],1)}}var Td=class{vertexShader;fragmentShader;technique;constructor(e,t,i){this.vertexShader=e,this.fragmentShader=t,this.technique=i}};async function wf(o,e){if(!o)return console.error("Can not find technique: no shader data"),null;let t=o.programs[e],i=t.vertexShader,n=t.fragmentShader;if(i!==void 0&&n!==void 0){let r=o.shaders[i],s=o.shaders[n];if(r.uri&&s.uri||r.code&&s.code){if(!r.code&&r.uri&&await yf(r),!s.code&&s.uri&&await yf(s),!r.code||!s.code)return null;let a=o.techniques[e];return new Td(r.code,s.code,a)}}return console.error("Shader technique not found",e),null}async function yf(o){let e=o.uri;if(!!e)if(e.endsWith(".glsl")){let i=await new Kb().loadAsync(e);o.code=i.toString()}else o.code=$b(o.uri)}function $b(o){return decodeURIComponent(Array.prototype.map.call(atob(o),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}var Pd=O("debugenvlight"),kd=(n=>(n[n.Skybox=0]="Skybox",n[n.Trilight=1]="Trilight",n[n.Flat=3]="Flat",n[n.Custom=4]="Custom",n))(kd||{});var pl=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 ev;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 Od(this.context,t,1);this._lighting[e]=i}getReflection(e){return this._lighting[e]}enableReflection(e){switch(Pd&&console.log(this.sceneLightSettings?kd[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=hl,n.mapping=ul,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=xf(t[0],t[1],t[2],64,64);i.encoding=hl,i.mapping=ul,this.context.scene.environment=i}else console.error("Missing ambient trilight",this.sceneLightSettings.sourceId);return;case 3:if(this.sceneLightSettings.ambientLight){let t=dl(this.sceneLightSettings.ambientLight,64);t.encoding=hl,t.mapping=ul,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 Pd&&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={}},Od=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=ul,t.encoding=hl}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){Pd&&console.log("GENERATING LIGHT PROBE",t);let n=Math.min(t.image.width,512);i=new tv(n).fromEquirectangularTexture(this._context.renderer,t),this._source=i.texture}if(this._sphericalHarmonicsArray=[],i){let n=iv.fromCubeRenderTarget(this._context.renderer,i);this._lightProbe=n;let r=this._ambientScale*(e*e*Math.PI*.5)-1;this._sphericalHarmonics=n.sh,this._sphericalHarmonicsArray=this._sphericalHarmonics.toArray();let s=e/(Math.PI*.5);for(let a=0;a<this._sphericalHarmonicsArray.length;a++)this._sphericalHarmonicsArray[a]*=s;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 nv}from"three";var Lr=O("debugaddressables"),fl=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}},Po=class{static getOrCreate(e,t,i){let n=Oi(e,t);Lr&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",n);let r=i.addressables,s=r.findAssetReference(n);if(s)return s;let a=new Po(n,i.hash);return r.registerAssetReference(a),a}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=[];_hash;_hashedUri;_isLoadingRawBinary=!1;_rawBinary;constructor(e,t){this._uri=e,this._hash=t,e.includes("?v=")?this._hashedUri=e:this._hashedUri=t?e+"?v="+t:e,Pp(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&&(Lr&&console.log("Unload",this.asset),this.asset.scene?ri(this.asset.scene):ri(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,Lr&&console.log("Preload",this._hashedUri);let e=await df(this._hashedUri,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=G.Current;this._rawBinary?(this._loading=Xe().parseSync(t,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(Lr&&console.log("Load async",this.uri),this._loading=Xe().loadSync(t,this._hashedUri,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 fn(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=G.Current;if(e||(e=n.scene),this.mustLoad&&await this.loadAssetAsync(),Lr&&console.log("Instantiate",this.uri,"parent:",e),this.asset){Lr&&console.log("Add to scene",this.asset);let r=e instanceof Fe?e:null;if(r||(r=new Fe),typeof e=="object"&&(e instanceof nv?r.parent=e:Object.assign(r,e)),Po.currentlyInstantiating.indexOf(this.uri)>=0)return console.error("Recursive instantiation of",this.uri),null;try{if(Po.currentlyInstantiating.push(this.uri),t){r.context=n;let s=this.asset;s.guid=this.uri;let a=Va(s,r,void 0,i);if(a)return a}else{let s=Pr(this.asset,r);if(s)return s}}finally{n.post_render_callbacks.push(()=>Po.currentlyInstantiating.pop())}}else Lr&&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}},$e=Po;D($e,"currentlyInstantiating",[]);var Md=class extends ln{constructor(){super([$e])}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?$e.getOrCreate(t.gltfId,e,t.context):(console.error("Missing spurce id"),null):(console.error("Missing context"),null):null}};new Md;var ml=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 rv,HalfFloatType as ov,sRGBEncoding as sv}from"three";var Ef="NEEDLE_lightmaps",av=O("debuglightmapsextension"),zs=(i=>(i[i.Lightmap=0]="Lightmap",i[i.Skybox=1]="Skybox",i[i.Reflection=2]="Reflection",i))(zs||{}),gl=class{get name(){return Ef}parser;registry;source;constructor(e,t,i){this.parser=e,this.registry=t,this.source=i}afterRoot(e){let t=this.parser.json.extensions;if(t){let i=t[Ef];if(i){let n=i.textures;return n?.length?(av&&console.log(i),new Promise(async(r,s)=>{let a=[];for(let c of n)if(c.pointer){let d=po(this.parser,c.pointer).then(l=>{let u=l;u?.isTexture&&(this.registry?(c.type!==0&&(u.encoding=sv),c.type===1&&(u.type==rv||u.type==ov)&&(u.flipY=!0),this.registry.registerTexture(this.source,c.type,u,c.index)):console.log(zs[c.type],c.pointer,u))});a.push(d)}await Promise.all(a),r()})):null}}return null}};import*as Li from"three";var Cf=!!O("debuglightmaps"),bl=class{_context;_lightmaps=new Map;constructor(e){this._context=e}registerTexture(e,t,i,n){Cf&&console.log("Registering lightmap",e,zs[t],i),this._lightmaps.has(e)||this._lightmaps.set(e,new Map);let r=this._lightmaps.get(e),s=r?.get(t)??[];s.length<n&&(s.length=n+1),s[n]=i,r?.set(t,s)}tryGetLightmap(e,t=0){return this.tryGet(e,0,t)}tryGetSkybox(e){return this.tryGet(e,1,0)}tryGetReflection(e){return this.tryGet(e,2,0)}tryGet(e,t,i){if(!e)return Cf&&console.warn("Missing source id"),null;let n=this._lightmaps.get(e)?.get(t)??null;return!n?.length||n.length<=i?null:n[i]}};Li.ShaderChunk.lights_fragment_maps=Li.ShaderChunk.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vUv2 );",`
153
153
 
154
154
  vec2 lUv = vUv2.xy * lightmapScaleOffset.xy + vec2(lightmapScaleOffset.z, (1. - (lightmapScaleOffset.y + lightmapScaleOffset.w)));
155
155
  vec4 lightMapTexel = texture2D( lightMap, lUv);
@@ -157,7 +157,7 @@ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
157
157
  lightMapTexel.rgb *= lightMapTexel.a * 8.; // no idea where that "8" comes from... heuristically derived
158
158
  lightMapTexel.a = 1.;
159
159
  lightMapTexel = conv_sRGBToLinear(lightMapTexel);
160
- `);Ii.ShaderChunk.lightmap_pars_fragment=`
160
+ `);Li.ShaderChunk.lightmap_pars_fragment=`
161
161
  #ifdef USE_LIGHTMAP
162
162
  uniform sampler2D lightMap;
163
163
  uniform float lightMapIntensity;
@@ -168,12 +168,12 @@ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
168
168
  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 );
169
169
  }
170
170
  #endif
171
- `;Ii.ShaderChunk.lights_fragment_begin=Ii.ShaderChunk.lights_fragment_begin.replace("irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );",`
171
+ `;Li.ShaderChunk.lights_fragment_begin=Li.ShaderChunk.lights_fragment_begin.replace("irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );",`
172
172
  #if defined(USE_LIGHTMAP)
173
173
  irradiance += 0.;
174
174
  #else
175
175
  irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
176
- #endif`);Ii.UniformsLib.lightmap.lightmapScaleOffset={value:new Ii.Vector4(1,1,0,0)};var ev=M("debugplayerview");var Sd=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}},pl=class{context;playerViews=new Map;constructor(e){this.context=e}setPlayerView(e,t,i){let n=this.playerViews.get(e);n||(n=new Sd(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&&(ev&&console.log("REMOVE",e),i.removed=!0,this.playerViews.delete(e))}};var ov=M("debugSetup"),sv=M("stats"),av=M("debugactive"),fl={};var Dt=(a=>(a[a.EarlyUpdate=0]="EarlyUpdate",a[a.Update=1]="Update",a[a.LateUpdate=2]="LateUpdate",a[a.OnBeforeRender=3]="OnBeforeRender",a[a.OnAfterRender=4]="OnAfterRender",a[a.PrePhysicsStep=9]="PrePhysicsStep",a[a.PostPhysicsStep=10]="PostPhysicsStep",a))(Dt||{});function Ga(o,e){if(!o)return;let t=e?.new_scripts??G.Current.new_scripts;t.includes(o)||t.push(o)}var lt=class{static get Current(){return this._current}static set Current(e){this._current=e}name;alias;isManagedExternally=!1;isPaused=!1;runInBackground=!1;hash;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;_boundingClientRectFrame=-1;_boundingClientRect=null;_domX;_domY;calculateBoundingClientRect(){if(this.isInAR){this._domX=window.innerWidth,this._domY=window.innerHeight;return}this._boundingClientRectFrame!==this.time.frame&&(this._boundingClientRectFrame=this.time.frame,this._boundingClientRect=this.domElement.getBoundingClientRect(),this._domX=this._boundingClientRect.x,this._domY=this._boundingClientRect.y)}get domWidth(){return this.isInAR?window.innerWidth:this.domElement.clientWidth}get domHeight(){return this.isInAR?window.innerHeight:this.domElement.clientHeight}get domX(){return this.calculateBoundingClientRect(),this._domX}get domY(){return this.calculateBoundingClientRect(),this._domY}get isInXR(){return this.renderer.xr?.isPresenting||!1}xrSessionMode=void 0;get isInVR(){return this.xrSessionMode==="immersive-vr"}get isInAR(){return this.xrSessionMode==="immersive-ar"}get xrSession(){return this.renderer.xr?.getSession()}get arOverlayElement(){let e=this.domElement;return typeof e.getAROverlayContainer=="function"?e.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}_currentFrameEvent=-1;scene;renderer;composer=null;scripts=[];scripts_pausedChanged=[];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;_isVisible=!1;_stats=sv?vf.default():null;constructor(e){if(this.name=e?.name||"",this.alias=e?.alias,this.domElement=e?.domElement||document.body,this.hash=e?.hash,e?.renderer)this.renderer=e.renderer,this.isManagedExternally=!0;else{let r=M("postfx");this.renderer=new iv({antialias:!0}),this.renderer.toneMappingExposure=1,this.renderer.toneMapping=Re.NoToneMapping,this.renderer.setClearColor(new Re.Color("lightgrey"),0),this.renderer.antialias=!0,this.renderer.alpha=!1,this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=Re.PCFSoftShadowMap,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputEncoding=Re.sRGBEncoding,this.renderer.physicallyCorrectLights=!0,this.composer=r?new nv(this.renderer):null}this.scene=new Re.Scene,this.application=new dl(this),this.time=new Na,this.input=new Pa(this),this.physics=new Gn(this),this.connection=new $a(this),this.assets=new rl,this.rendererData=new ll(this),this.addressables=new cl(this),this.lightmaps=new hl(this),this.players=new pl(this);let t=()=>this._sizeChanged=!0;window.addEventListener("resize",t),this._disposeCallbacks.push(()=>window.removeEventListener("resize",t));let i=new ResizeObserver(r=>this._sizeChanged=!0);i.observe(this.domElement),this._disposeCallbacks.push(()=>i.disconnect());let n=new IntersectionObserver(r=>{this._isVisible=r[0].isIntersecting});n.observe(this.domElement),this._disposeCallbacks.push(()=>n.disconnect())}_disposeCallbacks=[];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(){if(!!this._isCreated){this._isCreated=!1,ni(this.scene,!0),this.renderer?.setAnimationLoop(null),this.isManagedExternally||this.renderer?.dispose();for(let e of this._disposeCallbacks)try{e()}catch(t){console.error("Error in on dispose callback:",t,e)}this.domElement?.parentElement&&this.domElement.parentElement.removeChild(this.domElement)}}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,s,a,c,d)=>{let l=this._onBeforeRenderListeners[e.uuid];if(!!l)for(let u=0;u<l.length;u++){let h=l[u];h(n,r,s,a,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}get isVisibleToUser(){if(this.isInXR)return!0;if(!this._isVisible)return!1;let e=getComputedStyle(this.domElement);return e.visibility!=="hidden"&&e.display!=="none"&&e.opacity!=="0"}async internalOnCreate(e,t){await this.physics.createWorld();let i=!0;try{lt.Current=this,e&&await e(this,t)}catch(n){console.error(n),i=!1}if(!!i){this.isManagedExternally||this.domElement.prepend(this.renderer.domElement),yp(this),vp(this),lf(this),lt._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 s=r.gameObject.userData.components;s.includes(r)||s.push(r)}}if(this.post_setup_callbacks)for(let n=0;n<this.post_setup_callbacks.length;n++)lt._current=this,await this.post_setup_callbacks[n](this);if(!this.mainCamera){lt._current=this;let n=null;ri(this.scene,r=>{let s=r;if(s?.isCamera){if(s.tag==="MainCamera")return n=s,!0;n=s}}),n?this.setCurrentCamera(n):console.error("MISSING camera",this)}if(lt._current=this,dn(this),!this.isManagedExternally&&this.composer&&this.mainCamera){let n=new rv(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)),ov&&ks(this.scene,!0)}}render(e,t){if(this._currentFrameEvent=-1,this.onHandlePaused())return;for(this._stats?.begin(),lt._current=this,this.time.update(),dn(this),fo(),Aa(this);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);let r=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(r)}if(this.pre_update_callbacks)for(let r in this.pre_update_callbacks)this.pre_update_callbacks[r]();this._currentFrameEvent=0;for(let r=0;r<this.scripts_earlyUpdate.length;r++){let s=this.scripts_earlyUpdate[r];!s.activeAndEnabled||s.earlyUpdate!==void 0&&(lt._current=this,s.earlyUpdate())}if(this.executeCoroutines(0),this.onHandlePaused())return;this._currentFrameEvent=1;for(let r=0;r<this.scripts_update.length;r++){let s=this.scripts_update[r];!s.activeAndEnabled||s.update!==void 0&&(lt._current=this,s.update())}if(this.executeCoroutines(1),this.onHandlePaused())return;this._currentFrameEvent=2;for(let r=0;r<this.scripts_lateUpdate.length;r++){let s=this.scripts_lateUpdate[r];!s.activeAndEnabled||s.lateUpdate!==void 0&&(lt._current=this,s.lateUpdate())}if(this.executeCoroutines(2),this.onHandlePaused())return;let i=1,n=this.time.deltaTime/i;for(let r=0;r<i;r++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.step(n),this._currentFrameEvent=10,this.executeCoroutines(10);if(this.physics.postStep(),!this.onHandlePaused()){if(this.isVisibleToUser){this._currentFrameEvent=3;for(let r=0;r<this.scripts_onBeforeRender.length;r++){let s=this.scripts_onBeforeRender[r];!s.activeAndEnabled||s.onBeforeRender!==void 0&&(lt._current=this,s.onBeforeRender(t))}if(this.executeCoroutines(3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(let r in this.pre_render_callbacks)this.pre_render_callbacks[r]();this._currentFrameEvent=-10,this._isRendering=!0,this.renderRequiredTextures(),this.isManagedExternally||(this.composer&&!this.isInXR?this.composer.render():this.mainCamera&&this.renderer.render(this.scene,this.mainCamera)),this._isRendering=!1,this._currentFrameEvent=4;for(let r=0;r<this.scripts_onAfterRender.length;r++){let s=this.scripts_onAfterRender[r];!s.activeAndEnabled||s.onAfterRender!==void 0&&(lt._current=this,s.onAfterRender())}if(this.executeCoroutines(4),this.post_render_callbacks)for(let r in this.post_render_callbacks)this.post_render_callbacks[r]()}this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),this._stats?.end()}}_wasPaused=!1;onHandlePaused(){let e=this.evaluatePaused();if(this._wasPaused!==e){av&&console.log("Paused?",e,"context:"+this.alias);for(let t=0;t<this.scripts_pausedChanged.length;t++){let i=this.scripts_pausedChanged[t];!i.activeAndEnabled||i.onPausedChanged!==void 0&&(lt._current=this,i.onPausedChanged(e,this._wasPaused))}}return this._wasPaused=e,e}evaluatePaused(){return this.isInXR?!1:this.isPaused?!0:this.runInBackground?!1:!this.isVisibleToUser}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new Re.WebGLRenderTarget(this.domWidth,this.domHeight),this._requireDepthTexture){let i=new tv(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new Re.Texture,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=Re.NearestFilter,this._renderTarget.texture.magFilter=Re.NearestFilter,this._renderTarget.texture.format=Re.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 a=r.chained;if(a&&a.length>0){let u=a[a.length-1].next();if(u.done&&a.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)}}},G=lt;A(G,"_current");var Ai="ar",yf="quit-ar",ml=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(`.${Ai}`).forEach(s=>{!s||s!==this.arContainer&&(this._reparentedObjects.push({el:s,previousParent:s.parentElement}),this.arContainer?.appendChild(s))});let r=t.getElementsByClassName(yf);if(!r||r.length<=0)console.warn(`Missing quit AR elements, creating fallback X button. Use class name '${yf}' to override.`),this.createFallbackCloseARButton(this.arContainer);else for(let s=0;s<r.length;s++){let a=r[s];!a||(a.addEventListener("click",this.closeARCallback),this.registeredCloseEventElements.push(a))}}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,ya()&&setTimeout(()=>{let t=e.renderer.domElement;t&&e.domElement.insertBefore(t,e.domElement.firstChild);let i=document.querySelectorAll("*");for(var n=0;n<i.length;n++){let r=i[n];r&&r._displayChanged!==void 0&&r._displayWas!==void 0&&(r.style.display=r._displayWas)}},10)}findOrCreateARContainer(e){if(e.classList.contains(Ai))return e;if(e.children)for(let n=0;n<e.children.length;n++){let r=e.children[n];if(!(!r||!r.classList)&&r.classList.contains(Ai))return r}let t=document.getElementsByClassName(Ai);if(t&&t.length>0)return t[0];console.log("No overlay container found in document - generating new ony");let i=document.createElement("div");return i.classList.add(Ai),i.style.position="absolute",i.style.width="100%",i.style.height="100%",i.style.display="flex",i.style.visibility="visible",e.appendChild(i)}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","#ddd"),i.setAttribute("stroke-width","3px"),t.appendChild(i),this._createdAROnlyElements.push(i)}};var lv=M("debugdebug"),_f=M("noerrors"),Pd=new Map,w0=new RegExp(" at .+/(.+?.ts)","g"),Ts=(i=>(i[i.Log=0]="Log",i[i.Warn=1]="Warn",i[i.Error=2]="Error",i))(Ts||{});function jc(){return wf}function xf(){if(_f)return;if(ei()){lv&&console.log(window.location.hostname);let e=console.error;console.error=(...t)=>{e.apply(console,t),Rs(2,t,null,null),Od()},window.addEventListener("error",t=>{!t||(Rs(2,t.error,t.filename,t.lineno),Od())},!0),window.addEventListener("unhandledrejection",t=>{!t||(Rs(2,t.reason.message,t.reason.stack),Od())})}}var wf=0;function Od(){wf+=1}function Rs(o,e,t,i){if(_f)return;let r=G.Current?.domElement??document.querySelector("needle-engine");if(!!r){if(Array.isArray(e)){let s="";for(let a=0;a<e.length;a++)typeof e[a]!="object"&&(a>0&&(s+=" "),s+=e[a]);e=s}cv(o,r,e)}}var kd=new Set;function cv(o,e,t){let i=uv(e);if(i.childElementCount>=20||kd.has(t))return;kd.add(t);let n=pv(o,t);i.prepend(n),setTimeout(()=>{kd.delete(t),hv(n)},1e4)}var dv=`
176
+ #endif`);Li.UniformsLib.lightmap.lightmapScaleOffset={value:new Li.Vector4(1,1,0,0)};var lv=O("debugplayerview");var Id=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}},vl=class{context;playerViews=new Map;constructor(e){this.context=e}setPlayerView(e,t,i){let n=this.playerViews.get(e);n||(n=new Id(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&&(lv&&console.log("REMOVE",e),i.removed=!0,this.playerViews.delete(e))}};var pv=O("debugSetup"),fv=O("stats"),mv=O("debugactive"),yl={};var _t=(a=>(a[a.EarlyUpdate=0]="EarlyUpdate",a[a.Update=1]="Update",a[a.LateUpdate=2]="LateUpdate",a[a.OnBeforeRender=3]="OnBeforeRender",a[a.OnAfterRender=4]="OnAfterRender",a[a.PrePhysicsStep=9]="PrePhysicsStep",a[a.PostPhysicsStep=10]="PostPhysicsStep",a))(_t||{});function Xa(o,e){if(!o)return;let t=e?.new_scripts??G.Current.new_scripts;t.includes(o)||t.push(o)}var ct=class{static get Current(){return this._current}static set Current(e){this._current=e}name;alias;isManagedExternally=!1;isPaused=!1;runInBackground=!1;hash;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;_boundingClientRectFrame=-1;_boundingClientRect=null;_domX;_domY;calculateBoundingClientRect(){if(this.isInAR){this._domX=window.innerWidth,this._domY=window.innerHeight;return}this._boundingClientRectFrame!==this.time.frame&&(this._boundingClientRectFrame=this.time.frame,this._boundingClientRect=this.domElement.getBoundingClientRect(),this._domX=this._boundingClientRect.x,this._domY=this._boundingClientRect.y)}get domWidth(){return this.isInAR?window.innerWidth:this.domElement.clientWidth}get domHeight(){return this.isInAR?window.innerHeight:this.domElement.clientHeight}get domX(){return this.calculateBoundingClientRect(),this._domX}get domY(){return this.calculateBoundingClientRect(),this._domY}get isInXR(){return this.renderer.xr?.isPresenting||!1}xrSessionMode=void 0;get isInVR(){return this.xrSessionMode==="immersive-vr"}get isInAR(){return this.xrSessionMode==="immersive-ar"}get xrSession(){return this.renderer.xr?.getSession()}get arOverlayElement(){let e=this.domElement;return typeof e.getAROverlayContainer=="function"?e.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}_currentFrameEvent=-1;scene;renderer;composer=null;scripts=[];scripts_pausedChanged=[];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;_isVisible=!1;_stats=fv?Tf.default():null;constructor(e){if(this.name=e?.name||"",this.alias=e?.alias,this.domElement=e?.domElement||document.body,this.hash=e?.hash,e?.renderer)this.renderer=e.renderer,this.isManagedExternally=!0;else{let r=O("postfx");this.renderer=new dv({antialias:!0}),this.renderer.toneMappingExposure=1,this.renderer.toneMapping=Re.NoToneMapping,this.renderer.setClearColor(new Re.Color("lightgrey"),0),this.renderer.antialias=!0,this.renderer.alpha=!1,this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=Re.PCFSoftShadowMap,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputEncoding=Re.sRGBEncoding,this.renderer.physicallyCorrectLights=!0,this.composer=r?new uv(this.renderer):null}this.scene=new Re.Scene,this.application=new ml(this),this.time=new Ka,this.input=new Da(this),this.physics=new zn(this),this.connection=new rl(this),this.assets=new cl,this.rendererData=new pl(this),this.addressables=new fl(this),this.lightmaps=new bl(this),this.players=new vl(this);let t=()=>this._sizeChanged=!0;window.addEventListener("resize",t),this._disposeCallbacks.push(()=>window.removeEventListener("resize",t));let i=new ResizeObserver(r=>this._sizeChanged=!0);i.observe(this.domElement),this._disposeCallbacks.push(()=>i.disconnect());let n=new IntersectionObserver(r=>{this._isVisible=r[0].isIntersecting});n.observe(this.domElement),this._disposeCallbacks.push(()=>n.disconnect())}_disposeCallbacks=[];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(){if(!!this._isCreated){this._isCreated=!1,ri(this.scene,!0),this.renderer?.setAnimationLoop(null),this.isManagedExternally||this.renderer?.dispose();for(let e of this._disposeCallbacks)try{e()}catch(t){console.error("Error in on dispose callback:",t,e)}this.domElement?.parentElement&&this.domElement.parentElement.removeChild(this.domElement)}}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,s,a,c,d)=>{let l=this._onBeforeRenderListeners[e.uuid];if(!!l)for(let u=0;u<l.length;u++){let h=l[u];h(n,r,s,a,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}get isVisibleToUser(){if(this.isInXR)return!0;if(!this._isVisible)return!1;let e=getComputedStyle(this.domElement);return e.visibility!=="hidden"&&e.display!=="none"&&e.opacity!=="0"}async internalOnCreate(e,t){await this.physics.createWorld();let i=!0;try{ct.Current=this,e&&await e(this,t)}catch(n){console.error(n),i=!1}if(!!i){this.isManagedExternally||this.domElement.prepend(this.renderer.domElement),Rp(this),Tp(this),mf(this),ct._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 s=r.gameObject.userData.components;s.includes(r)||s.push(r)}}if(this.post_setup_callbacks)for(let n=0;n<this.post_setup_callbacks.length;n++)ct._current=this,await this.post_setup_callbacks[n](this);if(!this.mainCamera){ct._current=this;let n=null;oi(this.scene,r=>{let s=r;if(s?.isCamera){if(s.tag==="MainCamera")return n=s,!0;n=s}}),n?this.setCurrentCamera(n):console.error("MISSING camera",this)}if(ct._current=this,fn(this),!this.isManagedExternally&&this.composer&&this.mainCamera){let n=new hv(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)),pv&&Ds(this.scene,!0)}}render(e,t){if(this._currentFrameEvent=-1,this.onHandlePaused())return;for(this._stats?.begin(),ct._current=this,this.time.update(),fn(this),go(),Fa(this);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);let r=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(r)}if(this.pre_update_callbacks)for(let r in this.pre_update_callbacks)this.pre_update_callbacks[r]();this._currentFrameEvent=0;for(let r=0;r<this.scripts_earlyUpdate.length;r++){let s=this.scripts_earlyUpdate[r];!s.activeAndEnabled||s.earlyUpdate!==void 0&&(ct._current=this,s.earlyUpdate())}if(this.executeCoroutines(0),this.onHandlePaused())return;this._currentFrameEvent=1;for(let r=0;r<this.scripts_update.length;r++){let s=this.scripts_update[r];!s.activeAndEnabled||s.update!==void 0&&(ct._current=this,s.update())}if(this.executeCoroutines(1),this.onHandlePaused())return;this._currentFrameEvent=2;for(let r=0;r<this.scripts_lateUpdate.length;r++){let s=this.scripts_lateUpdate[r];!s.activeAndEnabled||s.lateUpdate!==void 0&&(ct._current=this,s.lateUpdate())}if(this.executeCoroutines(2),this.onHandlePaused())return;let i=1,n=this.time.deltaTime/i;for(let r=0;r<i;r++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.step(n),this._currentFrameEvent=10,this.executeCoroutines(10);if(this.physics.postStep(),!this.onHandlePaused()){if(this.isVisibleToUser){this._currentFrameEvent=3;for(let r=0;r<this.scripts_onBeforeRender.length;r++){let s=this.scripts_onBeforeRender[r];!s.activeAndEnabled||s.onBeforeRender!==void 0&&(ct._current=this,s.onBeforeRender(t))}if(this.executeCoroutines(3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(let r in this.pre_render_callbacks)this.pre_render_callbacks[r]();this._currentFrameEvent=-10,this._isRendering=!0,this.renderRequiredTextures(),this.isManagedExternally||(this.composer&&!this.isInXR?this.composer.render():this.mainCamera&&this.renderer.render(this.scene,this.mainCamera)),this._isRendering=!1,this._currentFrameEvent=4;for(let r=0;r<this.scripts_onAfterRender.length;r++){let s=this.scripts_onAfterRender[r];!s.activeAndEnabled||s.onAfterRender!==void 0&&(ct._current=this,s.onAfterRender())}if(this.executeCoroutines(4),this.post_render_callbacks)for(let r in this.post_render_callbacks)this.post_render_callbacks[r]()}this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),this._stats?.end()}}_wasPaused=!1;onHandlePaused(){let e=this.evaluatePaused();if(this._wasPaused!==e){mv&&console.log("Paused?",e,"context:"+this.alias);for(let t=0;t<this.scripts_pausedChanged.length;t++){let i=this.scripts_pausedChanged[t];!i.activeAndEnabled||i.onPausedChanged!==void 0&&(ct._current=this,i.onPausedChanged(e,this._wasPaused))}}return this._wasPaused=e,e}evaluatePaused(){return this.isInXR?!1:this.isPaused?!0:this.runInBackground?!1:!this.isVisibleToUser}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new Re.WebGLRenderTarget(this.domWidth,this.domHeight),this._requireDepthTexture){let i=new cv(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new Re.Texture,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=Re.NearestFilter,this._renderTarget.texture.magFilter=Re.NearestFilter,this._renderTarget.texture.format=Re.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 a=r.chained;if(a&&a.length>0){let u=a[a.length-1].next();if(u.done&&a.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)}}},G=ct;D(G,"_current");var ji="ar",Rf="quit-ar",_l=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(`.${ji}`).forEach(s=>{!s||s!==this.arContainer&&(this._reparentedObjects.push({el:s,previousParent:s.parentElement}),this.arContainer?.appendChild(s))});let r=t.getElementsByClassName(Rf);if(!r||r.length<=0)console.warn(`Missing quit AR elements, creating fallback X button. Use class name '${Rf}' to override.`),this.createFallbackCloseARButton(this.arContainer);else for(let s=0;s<r.length;s++){let a=r[s];!a||(a.addEventListener("click",this.closeARCallback),this.registeredCloseEventElements.push(a))}}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,Ca()&&setTimeout(()=>{let t=e.renderer.domElement;t&&e.domElement.insertBefore(t,e.domElement.firstChild);let i=document.querySelectorAll("*");for(var n=0;n<i.length;n++){let r=i[n];r&&r._displayChanged!==void 0&&r._displayWas!==void 0&&(r.style.display=r._displayWas)}},10)}findOrCreateARContainer(e){if(e.classList.contains(ji))return e;if(e.children)for(let n=0;n<e.children.length;n++){let r=e.children[n];if(!(!r||!r.classList)&&r.classList.contains(ji))return r}let t=document.getElementsByClassName(ji);if(t&&t.length>0)return t[0];console.log("No overlay container found in document - generating new ony");let i=document.createElement("div");return i.classList.add(ji),i.style.position="absolute",i.style.width="100%",i.style.height="100%",i.style.display="flex",i.style.visibility="visible",e.appendChild(i)}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","#ddd"),i.setAttribute("stroke-width","3px"),t.appendChild(i),this._createdAROnlyElements.push(i)}};var gv=O("debugdebug"),Sf=O("noerrors"),Dd=new Map,IT=new RegExp(" at .+/(.+?.ts)","g"),Ps=(i=>(i[i.Log=0]="Log",i[i.Warn=1]="Warn",i[i.Error=2]="Error",i))(Ps||{});function Gc(){return Of}function Pf(){if(Sf)return;if(ti()){gv&&console.log(window.location.hostname);let e=console.error;console.error=(...t)=>{e.apply(console,t),Os(2,t,null,null),Ad()},window.addEventListener("error",t=>{!t||(Os(2,t.error,t.filename,t.lineno),Ad())},!0),window.addEventListener("unhandledrejection",t=>{!t||(Os(2,t.reason.message,t.reason.stack),Ad())})}}var Of=0;function Ad(){Of+=1}function Os(o,e,t,i){if(Sf)return;let r=G.Current?.domElement??document.querySelector("needle-engine");if(!!r){if(Array.isArray(e)){let s="";for(let a=0;a<e.length;a++)typeof e[a]!="object"&&(a>0&&(s+=" "),s+=e[a]);e=s}bv(o,r,e)}}var Ld=new Set;function bv(o,e,t){let i=yv(e);if(i.childElementCount>=20||Ld.has(t))return;Ld.add(t);let n=xv(o,t);i.prepend(n),setTimeout(()=>{Ld.delete(t),_v(n)},1e4)}var vv=`
177
177
 
178
178
  @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');
179
179
 
@@ -210,9 +210,9 @@ a:hover {
210
210
  color: rgba(255,100,120, 1);
211
211
  }
212
212
 
213
- `;function uv(o){if(Pd.has(o))return Pd.get(o);{let e=document.createElement("div");e.classList.add(Ai),e.classList.add("desktop"),e.classList.add("debug-container"),e.style.position="absolute",e.style.top="0",e.style.right="5px",e.style.paddingTop="0px",e.style.maxWidth="70%",e.style.maxHeight="calc(100% - 5px)",e.style.zIndex="1000",e.style.pointerEvents="scroll",e.style.display="flex",e.style.alignItems="end",e.style.flexDirection="column",e.style.color="white",e.style.overflow="auto",o.appendChild(e),Pd.set(o,e);let t=document.createElement("style");return t.innerHTML=dv,e.appendChild(t),e}}var Ef=Symbol("logtype"),gl=new Map;function hv(o){o.remove();let e=o[Ef],t=gl.get(e)??[];t.push(o),gl.set(e,t)}function pv(o,e){if(gl.has(o)){let i=gl.get(o);if(i.length>0)return i.pop()}let t=document.createElement("div");switch(t.style.marginRight="5px",t.style.padding=".5em",t.style.backgroundColor="rgba(0,0,0,.9)",t.style.marginTop="5px",t.style.marginBottom="3px",t.style.borderRadius="8px",t.style.pointerEvents="all",t.style.userSelect="text",t.style.maxWidth="250px",t.style.whiteSpace="pre-wrap",t.style["backdrop-filter"]="blur(10px)",t.style.backgroundColor="rgba(20,20,20,.8)",t.style.boxShadow="inset 0 0 80px rgba(0,0,0,.2), 0 0 5px rgba(0,0,0,.2)",t.style.border="1px solid rgba(160,160,160,.2)",t[Ef]=o,o){case 0:t.classList.add("log"),t.style.color="rgba(200,200,200,.7)",t.style.backgroundColor="rgba(40,40,40,.7)";break;case 1:t.classList.add("warn"),t.style.color="rgb(255, 255, 150)",t.style.backgroundColor="rgba(50,50,20,.8)";break;case 2:t.classList.add("error"),t.style.color="rgb(255, 50, 50",t.style.backgroundColor="rgba(50,20,20,.8)";break}return t.title="Open the browser console (F12) for more information",t.innerHTML=e,t}var Md={};Dh(Md,{Behaviour:()=>k,Component:()=>yt,GameObject:()=>R});import*as $e from"three";var R=class extends $e.Object3D{guid;static setActive(e,t,i=!0,n=!0){!e||(_o(e,t,n),fo(e),t&&i&&Aa(G.Current,e))}static isActiveSelf(e){return cn(e)}static isActiveInHierarchy(e){return Ap(e)}static markAsInstancedRendered(e,t){Dp(e,t)}static isUsingInstancing(e){return za(e)}static foreachComponent(e,t,i=!0){return ri(e,t,i)}static instantiateSynced(e,t){return e?Ha(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??G.Current,mo(n,t.connection,i)}static destroy(e,t=!0,i=!0){return ni(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=G.Current),t.add(e),_o(e,!0),fo(e),i?R.foreachComponent(e,n=>{qc(n,i),!n.__internalDidAwakeAndStart&&i.new_script_start.includes(n)===!1&&i.new_script_start.push(n)},!0):console.warn("Missing context")}}static remove(e){!e||(e.parent?.remove(e),_o(e,!1),fo(e),R.foreachComponent(e,t=>{lp(t)},!0))}static invokeOnChildren(e,t,...i){this.invoke(e,t,!0,i)}static invoke(e,t,i=!1,...n){!e||this.foreachComponent(e,r=>{let s=r[t];s&&typeof s=="function"&&s.bind(r)(...n)},i)}static addNewComponent(e,t,i=!0){let n=new t;return Un(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");Sp(e,t)}static removeComponent(e){return Ba(e.gameObject,e),e}static getOrAddComponent(e,t){return Ua(e,t)}static getComponent(e,t){return e===null?null:Sr(e,t)}static getComponents(e,t,i=null){return e===null?i??[]:bo(e,t,i)}static findByGuid(e,t){return Tr(e,t)}static findObjectOfType(e,t,i=!0){return kp(e,t??G.Current,i)}static findObjectsOfType(e,t){let i=[];return Mp(e,i,t),i}static getComponentInChildren(e,t){return Pr(e,t)}static getComponentsInChildren(e,t,i=null){return vo(e,t,i??void 0)}static getComponentInParent(e,t){return go(e,t)}static getComponentsInParent(e,t,i=null){return Ds(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]}},si=class{get isComponent(){return!0}__context;get context(){return this.__context??G.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[Oi];return e===void 0?!0:e}set __isActiveInHierarchy(e){!this.gameObject||(this.gameObject[Oi]=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;get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}constructor(){this.__internalNewInstanceCreated()}__internalNewInstanceCreated(){this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(){return this.__didEnable?!1:(this.__didEnable=!0,this.onEnable(),this.__isEnabled=!0,!0)}__internalDisable(){!this.__didEnable||(this.__didEnable=!1,this.onDisable(),this.__isEnabled=!1)}__internalDestroy(){this.__destroyed||(this.__destroyed=!0,this.destroy?.call(this),Pp(this))}get enabled(){return this.__isEnabled??!0}set enabled(e){if(typeof e=="number"&&(e>=.5?e=!0:e=!1),!this.__didAwake){this.__isEnabled=e;return}e?this.__internalEnable():this.__internalDisable()}_worldPosition=void 0;_worldQuaternion=void 0;_worldEuler=void 0;_worldRotation=void 0;get worldPosition(){return this._worldPosition||(this._worldPosition=new $e.Vector3),B(this.gameObject,this._worldPosition),this._worldPosition}set worldPosition(e){te(this.gameObject,e)}setWorldPosition(e,t,i){si._worldPositionBuffer.set(e,t,i),this.worldPosition=si._worldPositionBuffer}get worldQuaternion(){return this._worldQuaternion||(this._worldQuaternion=new $e.Quaternion),pe(this.gameObject,this._worldQuaternion)}set worldQuaternion(e){Ke(this.gameObject,e)}setWorldQuaternion(e,t,i,n){si._worldQuaternionBuffer.set(e,t,i,n),this.worldQuaternion=si._worldQuaternionBuffer}get worldEuler(){return this._worldEuler||(this._worldEuler=new $e.Euler),this._worldEuler.setFromQuaternion(this.worldQuaternion),this._worldEuler}set worldEuler(e){this._worldQuaternion||(this._worldQuaternion=new $e.Quaternion),this._worldQuaternion?.setFromEuler(e),this.worldQuaternion=this._worldQuaternion}get worldRotation(){let e=this.worldEuler;this._worldRotation||(this._worldRotation=new $e.Vector3);let t=this._worldRotation;return t.set(e.x,e.y,e.z),t.x=H.toDegrees(t.x),t.y=H.toDegrees(t.y),t.z=H.toDegrees(t.z),t}set worldRotation(e){this.setWorldRotation(e.x,e.y,e.z,!0)}setWorldRotation(e,t,i,n=!0){n&&(e=H.toRadians(e),t=H.toRadians(t),i=H.toRadians(i)),si._worldEulerBuffer.set(e,t,i),si._worldQuaternionBuffer.setFromEuler(si._worldEulerBuffer),this.worldQuaternion=si._worldQuaternionBuffer}get forward(){return si._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}},yt=si;A(yt,"_worldPositionBuffer",new $e.Vector3),A(yt,"_worldQuaternionBuffer",new $e.Quaternion),A(yt,"_worldEulerBuffer",new $e.Euler),A(yt,"_tempQuaternionBuffer2",new $e.Quaternion),A(yt,"_forward",new $e.Vector3);var k=class extends yt{};var ai=function(o,e){return function(t,i,n){fv(t,i,n,o,e)}};function fv(o,e,t,i,n){if(!(!n&&!i&&!o.onValidate)){if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",o,e,t),Ye("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,2);return}if(o.__internalAwake){let r=Symbol(e),s=o.__internalAwake;o.__internalAwake=function(){this[r]===void 0&&(this[r]=this[e],Object.defineProperty(this,e,{set:function(a){if(this[Sa]===!0)this[r]=a;else{i?.call(this,a);let c=this[r];this[r]=a,this.onValidate?.call(this,e,c)}},get:function(){return n?.call(this),this[r]}})),s.call(this)}}}}var Cf=M("debugloadingbar");var Gs=0,Tf;function Id(o){Cf&&console.log(o.progress.loaded.toFixed(0)+"/"+o.progress.total.toFixed(0),o);let e=o.count,t=o.progress.total;t===0||t===void 0?(Tf!==o.name&&(Gs=0),Tf=o.name,Gs+=(1-Gs)*.001,Cf&&_a("Loading "+o.name+" did not report total size")):Gs=o.progress.loaded/t;let i=o.index/e+Gs/e;return H.clamp01(i)}var bl=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){console.warn("Custom loading container is not allowed"),this.container.removeChild(i);continue}this._loadingElement=this.createLoadingElement(i);return}}this._loadingElement=this.createLoadingElement()}this._progress=0,this.loadingProgress=0,this._loadingElement.style.display="flex",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=Id(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,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=H.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"),e||(this._loadingElement.style.position="fixed",this._loadingElement.style.width="100%",this._loadingElement.style.height="100%",this._loadingElement.style.left="0",this._loadingElement.style.top="0",this._loadingElement.style.backgroundColor="#000000",this._loadingElement.style.display="flex",this._loadingElement.style.alignItems="center",this._loadingElement.style.justifyContent="center",this._loadingElement.style.zIndex="1000",this._loadingElement.style.flexDirection="column",this._loadingElement.style.pointerEvents="none",this._loadingElement.style.color="white");let t=this._loadingElementOptions?.className??"loading";if(this._loadingElement.classList.add(t),this._loadingElementOptions?.additionalClasses)for(let a of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(a);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(a){return H.lerp(n*.5,100-n*.5,a)+"%"};this._loadingBar.style.background=`linear-gradient(90deg, #02022B ${r(0)}, #0BA398 ${r(.4)}, #99CC33 ${r(.5)}, #D7DB0A ${r(1)})`,this._loadingBar.style.backgroundAttachment="fixed",this._loadingBar.style.width="0%",this._loadingBar.style.height="100%",this._loadingTextContainer=document.createElement("div"),this._loadingTextContainer.style.display="flex",this._loadingTextContainer.style.justifyContent="center",this._loadingTextContainer.style.marginTop=".9em",this._loadingElement.appendChild(this._loadingTextContainer);let s=document.createElement("div");return this._messageContainer=s,s.style.display="flex",s.style.fontSize=".8em",s.style.paddingTop=".5em",s.style.color="rgba(255,255,255,.5)",s.style.justifyContent="center",this._loadingElement.appendChild(s),this._loadingElement}};import{DRACOLoader as Ad}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as Rf}from"three/examples/jsm/loaders/KTX2Loader.js";var Vs=M("debugdecoders"),li,Xn;function Dd(o){o!==void 0&&typeof o=="string"&&(li||(li=new Ad),Vs&&console.log("Setting draco decoder path to",o),li.setDecoderPath(o))}function Ld(o){o!==void 0&&typeof o=="string"&&(li||(li=new Ad),Vs&&console.log("Setting draco decoder type to",o),li.setDecoderConfig({type:o}))}function jd(o){o!==void 0&&typeof o=="string"&&(Xn||(Xn=new Rf),Vs&&console.log("Setting ktx2 transcoder path to",o),Xn.setTranscoderPath(o))}function hn(o,e){li||(li=new Ad,li.setDecoderPath("./include/draco/"),li.setDecoderConfig({type:"js"}),Vs&&console.log("Setting draco decoder path to","./include/draco/")),Xn||(Xn=new Rf,Xn.setTranscoderPath("./include/ktx2/"),Vs&&console.log("Setting ktx2 transcoder path to","./include/ktx2/"),e.renderer&&Xn.detectSupport(e.renderer)),o.setDRACOLoader(li),o.setKTX2Loader(Xn)}import{AnimationClip as mv,MathUtils as gv}from"three";var So=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 Pf(o,e){return{name:"",isLooping:!1,guid:e?.generateUUID()??gv.generateUUID(),index:-1,clip:new mv(o,1,[])}}import{AnimationClip as bv,AnimationMixer as vv,AxesHelper as yv,Euler as Of,LoopOnce as _v,Quaternion as ci,Vector3 as zs}from"three";import*as yl from"three";var Di=M("debuganimatorcontroller"),Hd=M("debugrootmotion"),ui=class{Play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}let s=this.model.layers[t].stateMachine;for(let a of s.states)if(a.name===e||a.hash===e){Di&&console.log("transition to ",a),this.transitionTo(a,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){Di&&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 vv(this.animator.gameObject),this.createActions(this.animator)}clone(){let e=Cs(this.model,(i,n,r)=>r==null?!0:!(r.type==="Object3D"||r.isObject3D===!0||sp(r)||r.tracks!==void 0));return console.assert(e!==this.model),new ui(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,Di&&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()&&(Di&&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;t.defaultState===void 0&&(Di&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",e),t.defaultState=0);let i=t.states[t.defaultState];this.transitionTo(i,0,this.normalizedStartOffset)}}evaluateTransitions(){let t=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;t=!0}let i=this._activeState,n=i.motion.action,r=0;for(let a of i.transitions){if(++r,!a.hasExitTime&&a.conditions.length<=0)continue;let c=!0;for(let d of a.conditions)if(!this.evaluateCondition(d)){c=!1;break}if(!!c){for(let d of a.conditions){let l=this.model.parameters.find(u=>u.name===d.parameter);l?.type===9&&(l.value=!1)}if(n){let d=i.motion.clip.duration,l=d<=0?1:n.time/d;if(a.hasExitTime?l>=a.exitTime:!0){n.clampWhenFinished=!0,Di&&console.log("transition to "+a.destinationState,a,l,a.exitTime,a.hasExitTime),this.transitionTo(a.destinationState,a.duration,a.offset);return}}else{this.transitionTo(a.destinationState,a.duration,a.offset);return}}}let s=!1;if(i.motion.isLooping&&n&&n.time>=n.getClip().duration&&(s=!0,n.reset(),n.time=0,n.play()),!s&&i&&!t&&n&&this.animator&&i.behaviours){let a=n?.getClip().duration,c=n.time/a,d=new So(this._activeState,c,a,this._speed);for(let l of i.behaviours)l.instance&&l.instance.onStateUpdate?.call(l.instance,this.animator,d,0)}}getState(e,t){return typeof e=="number"&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState,e===void 0&&(Di&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+t),e=0)),e=this.model.layers[t].stateMachine.states[e]),e}transitionTo(e,t,i){if(!this.animator)return;let n=0;if(e=this.getState(e,n),!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,l=this._activeState.motion.action.time/d,u=new So(this._activeState,l,d,this._speed);for(let h of this._activeState.behaviours)h.instance?.onStateExit?.call(h.instance,this.animator,u,n)}let s=this._activeState?.motion.action;s&&s.fadeOut(t),r&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=s);let a=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(_v,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 l=new So(e,i,d,this._speed);for(let u of this._activeState.behaviours)u.instance?.onStateEnter?.call(u.instance,this.animator,l,n)}}else console.warn("No action",e.motion,this);Di&&console.log("TRANSITION FROM "+a?.name+" TO "+e.name,t,s,c,c?.getEffectiveTimeScale(),c?.getEffectiveWeight(),c?.isRunning(),c?.isScheduled(),c?.paused)}createAction(e){if(this._mixer.existingAction(e)&&this._mixer.uncacheAction(e,this.animator?.gameObject),this.animator?.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new Fd(this));let i=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,i,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];r.transitions||(r.transitions=[]);for(let s of r.transitions)s.conditions||(s.conditions=[]);if(r.motion||(r.motion=Pf(r.name)),this.animator&&r.motion.clips){let s=r.motion.clips?.find(a=>a.node.name===this.animator?.gameObject?.name);r.motion.clip=s?.clip}if(!r.motion.clip){let s=new bv(void 0,void 0,[]);r.motion.clip=s}if(r.motion?.clip){let s=r.motion.clip,a=this.createAction(s);r.motion.action=a}if(r.behaviours&&Array.isArray(r.behaviours))for(let s of r.behaviours){if(!s?.typeName)continue;let a=P.get(s.typeName),c=new a;c.isStateMachineBehaviour&&(c._context=this.context??void 0,Mt(c,s.properties),s.instance=c),Di&&console.log("Created animator controller behaviour",r.name,s.typeName,s.properties,c)}}}}*enumerateActions(){for(let e of this.model.layers){let t=e.stateMachine;for(let i=0;i<t.states.length;i++){let n=t.states[i];n?.motion&&(n.motion.action&&(yield n.motion.action),n.motion.action_loopback&&(yield n.motion.action_loopback))}}}rootMotionHandler},vl=class{track;createdInterpolant;originalEvaluate;customEvaluate;constructor(e,t){this.track=e;let i=e,n=i.createInterpolant.bind(e);i.createInterpolant=()=>(i.createInterpolant=n,this.createdInterpolant=n(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=r=>{if(!this.originalEvaluate)return;let s=this.originalEvaluate(r);return t(r,s)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}evaluate(e){this.customEvaluate&&this.customEvaluate(e)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}},xe=class{set action(e){this._action=e}get action(){return this._action}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new zs;rotationChange=new ci;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 yl.Quaternion),r){let s=r.values;xe.firstKeyframeRotation[i.uuid].set(s[0],s[1],s[2],s[3])}xe.spaceRotation[i.uuid]||(xe.spaceRotation[i.uuid]=new ci),xe.effectiveSpaceRotation[i.uuid]||(xe.effectiveSpaceRotation[i.uuid]=new ci),xe.clipOffsetRotation[i.uuid]=new ci,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 yl.Euler().setFromQuaternion(t);console.log("START",this.clip.name,H.toDegrees(i.y))}}getClipRotationOffset(){return xe.clipOffsetRotation[this.clip.uuid]}handlePosition(e,t){if(t){let i=this.root;Hd&&i.add(new yv),xe.lastObjPosition[i.uuid]||(xe.lastObjPosition[i.uuid]=new zs);let n=new zs,r=new zs,s=0;this.positionWrapper=new vl(t,(a,c)=>{let d=this.action.getEffectiveWeight();if(Hd&&i.position.length()>8&&i.position.set(0,i.position.y,0),a>s){n.set(c[0],c[1],c[2]),n.sub(r),n.multiplyScalar(d),n.applyQuaternion(this.getClipRotationOffset());let l=this.clip.uuid;n.applyQuaternion(xe.spaceRotation[l]),this.positionChange.copy(n)}return r.fromArray(c),s=a,c[0]=0,c[1]=0,c[2]=0,c})}}handleRotation(e,t){if(t){if(Hd){let a=t.values,c=new Of().setFromQuaternion(new ci(a[0],a[1],a[2],a[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",H.toDegrees(c.y));let d=t.values.length-4,l=new ci().set(a[d],a[d+1],a[d+2],a[d+3]),u=new Of().setFromQuaternion(l);console.log(e.name,t.name,"LAST ROTATION IN TRACK",H.toDegrees(u.y))}let i=this.root;xe.lastObjRotation[i.uuid]||(xe.lastObjRotation[i.uuid]=new ci);let n=0,r=new ci,s=new ci;this.rotationWrapper=new vl(t,(a,c)=>(a>n&&(s.set(c[0],c[1],c[2],c[3]),r.invert(),s.multiply(r),this.rotationChange.copy(s)),r.fromArray(c),n=a,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(xe.identityQuaternion,1-e)}},di=xe;A(di,"lastObjPosition",{}),A(di,"lastObjRotation",{}),A(di,"firstKeyframeRotation",{}),A(di,"spaceRotation",{}),A(di,"effectiveSpaceRotation",{}),A(di,"clipOffsetRotation",{}),A(di,"identityQuaternion",new ci);var Fd=class{controller;handler=[];root;constructor(e){this.controller=e}createClip(e,t,i){this.root=t;let n="";t&&"name"in t&&(n=t.name);let r=this.findRootTrack(i,".position"),s=this.findRootTrack(i,".quaternion"),a=new di(this.controller.context,t,i,r,s);this.handler.push(a);let c=e.clipAction(i);return a.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 zs;summedRotation=new ci;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),di.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 Mf=function(o){return y(o)},y=function(o){if(o===void 0&&(o=null),!Array.isArray(o))o=kf(o);else for(let e=0;e<o.length;e++){let t=o[e];o[e]=kf(t)}return function(e,t){Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});let i=e.$serializedTypes=e.$serializedTypes||{};i[t]=o}};function kf(o){switch(o?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return o}var If=M("debuganimator"),et=class extends k{applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof ui?this._animatorController=e:(If&&console.log("Assign animator controller",e,this),this._animatorController=new ui(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=H.lerp(e.x,e.y,Math.random())}set minMaxOffsetNormalized(e){this.normalizedStartOffset=H.lerp(e.x,e.y,Math.random()),this.runtimeAnimatorController&&(this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset)}speed=1;normalizedStartOffset=0;_animatorController=null;awake(){if(If&&console.log("ANIMATOR",this.name,this),!!this.gameObject&&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}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.Reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}};_([y()],et.prototype,"applyRootMotion",2),_([y()],et.prototype,"hasRootMotion",2),_([y()],et.prototype,"keepAnimatorControllerStateOnDisable",2),_([y()],et.prototype,"runtimeAnimatorController",1);import*as Dr from"three";import{AnimationClip as xv}from"three";var _l=M("debuganimation"),Lt=class extends k{playAutomatically=!0;randomStartTime=!0;minMaxSpeed;minMaxOffsetNormalized;loop=!0;clampWhenFinished=!1;_tempAnimationClipBeforeGameObjectExisted=null;get clip(){return this.animations?.length?this.animations[0]:null}set clip(e){if(!this.__didAwake){_l&&console.log("Assign clip during serialization",e),this._tempAnimationClipBeforeGameObjectExisted=e;return}!e||(_l&&console.log("Assign clip",e,Boolean(this.gameObject)),this.gameObject.animations||(this.gameObject.animations=[]),!this.animations.includes(e)&&(this.animations.length>0?this.animations.splice(0,0,e):this.animations.push(e)))}set clips(e){this.animations=e}set animations(e){_l&&console.log("assign 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(){_l&&console.log(this),this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.playAutomatically&&this.init()}onEnable(){if(this.playAutomatically&&this.animations?.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)}get isPlaying(){for(let e=0;e<this._currentActions.length;e++)if(this._currentActions[e].isRunning())return!0;return!1}play(e,t){if(this.init(),!this.mixer)return;e===void 0&&(e=0);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}t||(t={}),t.minMaxOffsetNormalized||(t.minMaxOffsetNormalized=this.minMaxOffsetNormalized),t.minMaxSpeed||(t.minMaxSpeed=this.minMaxSpeed),t.loop||(t.loop=this.loop),t.clampWhenFinished||(t.clampWhenFinished=this.clampWhenFinished);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 a=this.tryFindHandle(e);if(a)return a.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;let r=e.getClip();t?.minMaxOffsetNormalized&&(e.time=H.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*r.duration),t?.minMaxSpeed&&(e.timeScale=H.lerp(t.minMaxSpeed.x,t.minMaxSpeed.y,Math.random())),t?.clampWhenFinished&&(e.clampWhenFinished=!0),t?.startTime!==void 0&&(e.time=t.startTime),t?.loop!==void 0?e.loop=t.loop?Dr.LoopRepeat:Dr.LoopOnce:e.loop=Dr.LoopOnce,e.play();let s=new Bd(e,this.mixer,t,a=>{this._handles.splice(this._handles.indexOf(s),1)});return this._handles.push(s),s.getPromise()}tryFindHandle(e){for(let t of this._handles)if(t.action===e)return t}_didInit=!1;init(){this._didInit||(this._didInit=!0,this.gameObject&&(this.actions=[],this.mixer=new Dr.AnimationMixer(this.gameObject)))}};_([y()],Lt.prototype,"playAutomatically",2),_([y()],Lt.prototype,"randomStartTime",2),_([y()],Lt.prototype,"loop",2),_([y()],Lt.prototype,"clampWhenFinished",2),_([y(xv)],Lt.prototype,"clips",1);var Bd=class{mixer;action;promise=null;resolve=null;reject=null;_options;_resolveCallback=null;_rejectCallback=null;_loopCallback;_finishedCallback;_resolvedOrRejectedCallback;constructor(e,t,i,n){this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=n,this._options=i}getPromise(){return this.promise?this.promise:(this.promise=new Promise((e,t)=>{this._resolveCallback=e,this._rejectCallback=t,this.resolve=this.onResolve.bind(this),this.reject=this.onReject.bind(this)}),this._loopCallback=this.onLoop.bind(this),this._finishedCallback=this.onFinished.bind(this),this.mixer.addEventListener("loop",this._loopCallback),this.mixer.addEventListener("finished",this._finishedCallback),this.promise)}_update(){!this._options||this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._resolveCallback?.call(this,this.action)}onReject(e){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._rejectCallback?.call(this,e)}onLoop(e){}onFinished(e){e.action===this.action&&this.onResolve()}dispose(){this._loopCallback&&this.mixer.removeEventListener("loop",this._loopCallback),this._finishedCallback&&this.mixer.removeEventListener("finished",this._finishedCallback),this._loopCallback=void 0,this._finishedCallback=void 0}};import{GLTFLoader as $m}from"three/examples/jsm/loaders/GLTFLoader.js";import*as X from"three";import{RawShaderMaterial as Ev}from"three";var pn=M("debugshaders"),Po="NEEDLE_techniques_webgl";var Ud=class{objectToWorldMatrix=new X.Matrix4;worldToObjectMatrix=new X.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),Bs(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),Bs(this.worldToObjectMatrix,this.worldToObject)}};var ce=class extends Ev{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){let e=super.clone();return Af(e),e}constructor(e,...t){super(...t),this.identifier=e,pn&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName]&&this.waitForLighting(),(this.depthTextureUniform||this.opaqueTextureUniform)&&G.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();let e=G.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&G.Current.pre_render_callbacks.splice(e,1)}async waitForLighting(){let e=G.Current;if(!e){console.error("Missing context");return}let t=await e.rendererData.getSceneLightingData(this.identifier);if(!t||!t.array){console.warn("Missing lighting data for custom shader, getSceneLightingData did not return anything");return}pn&&console.log(t);let i=t.array,n=t.texture;this.uniforms.unity_SpecCube0={value:n},wd(this.uniforms,i);let r=Math.sqrt(Math.PI*.5);this.uniforms.unity_SpecCube0_HDR={value:new X.Vector4(r,r,r,r)},pn&&console.log("Set environment lighting",this.uniforms)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";_rendererData=new Ud;get depthTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&G.Current.setRequireColor(!0),this.depthTextureUniform&&G.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,r,s){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,r)}onUpdateUniforms(e,t){let i=G.Current;e&&(ce.viewProjection&&this.uniforms[this._viewProjectionName]&&(ce.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),Bs(ce.viewProjection,ce._viewProjectionValues)),ce.viewMatrix&&this.uniforms[this._viewMatrixName]&&(ce.viewMatrix.copy(e.matrixWorldInverse),Bs(ce.viewMatrix,ce._viewMatrixValues)),this.uniforms[ce._worldSpaceCameraPosName]&&ce._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters?this.uniforms._TimeParameters.value=i.rendererData.timeVec4:this.uniforms._Time&&(this.uniforms._Time.value=i.rendererData.timeVec4);let n=i.mainLight;if(n){let a=B(n.gameObject,ce._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},ce._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:ce._mainLightColor};let c=n.intensity;ce._lightData.z=c,this.uniforms.unity_LightData={value:ce._lightData}}if(e&&(ce.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=ce._viewProjectionValues),ce.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=ce._viewMatrixValues),this.uniforms[ce._worldSpaceCameraPosName]&&(this.uniforms[ce._worldSpaceCameraPosName]={value:ce._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){let a=this.uniforms._ProjectionParams.value;a.x=1,a.y=i.mainCameraComponent.nearClipPlane,a.z=i.mainCameraComponent.farClipPlane,a.w=1/a.z,this.uniforms._ProjectionParams.value=a}if(this.uniforms._ZBufferParams){let a=this.uniforms._ZBufferParams.value,c=i.mainCameraComponent;a.x=1-c.farClipPlane/c.nearClipPlane,a.y=c.farClipPlane/c.nearClipPlane,a.z=a.x/c.farClipPlane,a.w=a.y/c.farClipPlane,this.uniforms._ZBufferParams.value=a}if(this.uniforms._ScreenParams){let a=this.uniforms._ScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScreenParams.value=a}}let r=this.depthTextureUniform;r&&(r.value=i.depthTexture);let s=this.opaqueTextureUniform;if(s&&(s.value=i.opaqueColorTexture),t){let a=this._rendererData;a.updateFrom(t),this.uniforms[this._worldToObjectName].value=a.worldToObject,this.uniforms[this._objToWorldName].value=a.objectToWorld}this.uniformsNeedUpdate=!0}},jt=ce;A(jt,"viewProjection",new X.Matrix4),A(jt,"_viewProjectionValues",[]),A(jt,"viewMatrix",new X.Matrix4),A(jt,"_viewMatrixValues",[]),A(jt,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),A(jt,"_worldSpaceCameraPos",new X.Vector3),A(jt,"_mainLightColor",new X.Vector4),A(jt,"_mainLightPosition",new X.Vector3),A(jt,"_lightData",new X.Vector4);var xl=class{get name(){return Po}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){let t=this.parser.json.materials[e];if(!t)return pn&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Po])return pn&&console.log("material "+e+" does not use NEEDLE_techniques_webgl"),null;let i=t.extensions[Po].technique;if(i<0)return null;let n=this.parser.json.extensions[Po];if(!n)return null;pn&&console.log(n);let r=n.techniques[i];return r?new Promise(async(s,a)=>{let c=await mf(n,r.program),d=c?.fragmentShader,l=c?.vertexShader;if(!d||!l)return a();pn&&console.log("loadMaterial",t,c);let u={},h=r.uniforms;l.includes("_Time")&&(u._Time={value:new X.Vector4(0,0,0,0)});for(let m in h){let f=m;switch(f){case"_TimeParameters":let p=new X.Vector4;u[f]={value:p};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":u[f]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":u[f]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":u[f]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":u[f]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":u[f]={value:null};break}}let b=!1;if(t.extensions&&t.extensions[Po]){let m=t.extensions[Po];if(m.technique===i){pn&&console.log(t.name,"Material Properties",m);for(let f in m.values){let p=m.values[f];if(typeof p=="string"){if(p.startsWith("/textures/")){let g=p.substring(10),E=Number.parseInt(g);if(E>=0){let C=await this.parser.getDependency("texture",E);C&&(C.encoding=X.LinearEncoding,C.needsUpdate=!0),u[f]={value:C};continue}}switch(f){case"alphaMode":p==="BLEND"&&(b=!0);continue}}if(Array.isArray(p)&&p.length===4){u[f]={value:new X.Vector4(p[0],p[1],p[2],p[3])};continue}u[f]={value:p}}}}let w=new jt(this.identifier,{name:t.name??"",uniforms:u,vertexShader:l,fragmentShader:d,lights:!1});switch(u._Cull?.value){case 0:w.side=X.DoubleSide;break;case 1:w.side=X.BackSide;break;case 2:w.side=X.FrontSide;break;default:w.side=X.FrontSide;break}switch(u._ZTest?.value){case 3:w.depthTest=!0,w.depthFunc=X.EqualDepth;break;case 6:w.depthTest=!0,w.depthFunc=X.NotEqualDepth;break;case 2:w.depthTest=!0,w.depthFunc=X.LessDepth;break;case 4:w.depthTest=!0,w.depthFunc=X.LessEqualDepth;break;case 5:w.depthTest=!0,w.depthFunc=X.GreaterDepth;break;case 7:w.depthTest=!0,w.depthFunc=X.GreaterEqualDepth;break;case 8:w.depthTest=!1,w.depthFunc=X.AlwaysDepth;break}w.transparent=b,b&&(w.depthWrite=!1),wd(u),w.onUpdateUniforms();for(let m in h){let f=m,p=h[m].type;if(u[f]?.value===void 0)switch(p){case 35678:u[f]={value:pf},console.warn("Missing/unassigned texture, fallback to white: "+f);break;default:console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+f,h[m]);break}}pn&&console.log(w.uuid,u),Af(w),s(w)}):null}};function Af(o){if(o.uniforms)for(let e in o.uniforms)Object.getOwnPropertyDescriptor(o,e)||Object.defineProperty(o,e,{get:()=>o.uniforms[e].value,set:t=>{o.uniforms[e].value=t,o.needsUpdate=!0}})}var Qn=Te,wl="$___Export_Components",Cv="NEEDLE_components",Gd=class{[Cr]},Vd=class{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}},Oo=class{get name(){return Cv}parser;nodeToObjectMap={};exportContext;objectToNodeMap={};context;writer;registerExport(e){e.register(t=>{if("serializeUserData"in t){let i=t.serializeUserData.bind(t);this.writer=t,t.serializeUserData=(n,r)=>{try{this.serializeUserData(n,r),i(n,r)}finally{this.afterSerializeUserData(n,r)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){let i=e.userData?.components;!i||i.length<=0||(delete e.userData.components,e[wl]=i)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Qn&&console.log("DONE",JSON.stringify(t)),e[wl]===void 0)return;let i=e[wl];delete e[wl],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 Vd(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){Qn&&console.log("AFTER",e);for(let t in this.exportContext){let i=this.exportContext[t],n=i.node,r=i.nodeDef,s=i.nodeIndex,a=n.userData?.components;if(!a||a.length<=0)continue;let c=new Gd;r.extensions=r.extensions||{},r.extensions[this.name]=c,this.context.object=n,this.context.nodeId=s,this.context.objectToNode=this.objectToNodeMap;let d=[];for(let l of a){this.context.target=l;let u=Ne().writeBuiltinComponentData(l,this.context);u!==null&&d.push(u)}d.length>0&&(c[Cr]=d,Qn&&console.log("DID WRITE",n,"nodeIndex",s,d))}}beforeRoot(){return Qn&&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];Qn&&console.log("After root",e,this.parser,i);let r=[];if(n===!0){let s=t.json.nodes;for(let a=0;a<s.length;a++){let c=await t.getDependency("node",a);this.nodeToObjectMap[a]=c}for(let a=0;a<s.length;a++){let c=s[a],d=a,l=c.extensions;if(!l)continue;let u=l[this.name];if(!u)continue;Qn&&console.log("NODE",c);let h=this.nodeToObjectMap[d];if(!h){console.error("Could not find object for node index: "+d,c,t);continue}yo(h),r.push(this.createComponents(h,u))}}await Promise.all(r)}async createComponents(e,t){if(!t)return;let i=t[Cr];if(i){let n=new Array;Qn&&console.log(e.name,i);for(let r in i){let s=i[r];Qn&&console.log("Serialized data",JSON.parse(JSON.stringify(s))),s&&this.parser&&n.push(uo(this.parser,s)),e.userData=e.userData||{},e.userData[Cr]=e.userData[Cr]||[],e.userData[Cr].push(s)}await Promise.all(n)}}};import{EXRLoader as Tv}from"three/examples/jsm/loaders/EXRLoader";var zd=M("debugexr"),El=class{parser;name;constructor(e){this.parser=e,this.name="EXT_texture_exr",zd&&console.log(e)}loadTexture(e){let t=this.name,i=this.parser,r=i.json.textures[e];if(zd&&console.log("EXT_texture_exr.loadTexture",e,r),!r.extensions||!r.extensions[t])return null;let s=r.extensions[t],a=new Tv(i.options.manager);return zd&&console.log("EXT_texture_exr.loadTexture",s,a),i.loadTextureImage(e,s.source,a)}};window.addEventListener("unhandledrejection",o=>{});var Df="NEEDLE_gameobject_data",Cl=class{get name(){return Df}parser;constructor(e){this.parser=e}afterRoot(e){let t=[];for(let i=0;i<this.parser.json.nodes.length;i++){let n=this.parser.json.nodes[i];if(n&&n.extensions){let r=n.extensions[Df];if(r){let s=this.findAndApplyExtensionData(i,r);t.push(s)}}}return Promise.all(t).then(()=>{})}async findAndApplyExtensionData(e,t){let i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(t.layers),e.userData.tag=t.tag,e.userData.hideFlags=t.hideFlags,e.userData.static=t.static,e.visible=t.activeSelf,e.guid=t.guid}};import{AmbientLight as Rv,Color as Lf,HemisphereLight as Sv}from"three";var jf="NEEDLE_lighting_settings",ko=M("debugenvlight"),Tl=class{get name(){return jf}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}afterRoot(e){let t=this.parser.json.extensions;if(t){let i=t[jf];if(i){ko&&console.log(i);let n=R.addNewComponent(e.scene,Wd,!1);n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new Lf().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(r=>new Lf().fromArray(r))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource,this.context&&this.context.rendererData.registerSceneLightSettings(n)}}return null}},Wd=class extends k{ambientMode=0;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=0;_hasReflection=!1;_ambientLightObj;_lightProbeObj;awake(){if(this.sourceId){let e=this.environmentReflectionSource===0?1:2,t=this.context.lightmaps.tryGet(this.sourceId,e,0);this._hasReflection=t!=null,t&&this.context.rendererData.registerReflection(this.sourceId,t)}ko&&window.addEventListener("keydown",e=>{switch(e.key){case"l":this.enabled=!this.enabled;break}})}onEnable(){let e=this.context.mainCameraComponent?.sourceId===this.sourceId;if(ko&&console.log("Enable scene lighting",this.sourceId,e,this,this.context.mainCameraComponent?.sourceId),e||ko&&console.warn("This is no active?!",this.context.mainCameraComponent?.sourceId),this.ambientMode==3)this.ambientLight&&!this._ambientLightObj&&(this._ambientLightObj=new Rv(this.ambientLight,Math.PI*this.ambientIntensity)),this._ambientLightObj&&this.gameObject.add(this._ambientLightObj),this._lightProbeObj&&this._lightProbeObj.removeFromParent();else if(this.ambientMode===1){if(this.ambientTrilight){let t=this.ambientTrilight[0],i=this.ambientTrilight[this.ambientTrilight.length-1],n=new Sv(i,t,this.ambientIntensity);this.gameObject.add(n)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._lightProbeObj?this.enabled&&this.destroyed&&this._lightProbeObj&&this.scene.add(this._lightProbeObj):this.sourceId&&this.context.rendererData.getSceneLightingData(this.sourceId).then(t=>{ko&&console.log(t),t&&(this._lightProbeObj=t.lightProbe,this.enabled&&!this.destroyed&&this._lightProbeObj&&this.scene.add(this._lightProbeObj))});this.sourceId&&this.context.rendererData.enableReflection(this.sourceId)}onDisable(){ko&&console.log("disable",this.sourceId,this),this._lightProbeObj&&this._lightProbeObj.removeFromParent(),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this.sourceId&&this.context.rendererData.disableReflection()}};import{NeverStencilFunc as Pv,LessStencilFunc as Ov,EqualStencilFunc as kv,LessEqualStencilFunc as Mv,GreaterStencilFunc as Iv,NotEqualStencilFunc as Av,GreaterEqualStencilFunc as Dv,AlwaysStencilFunc as Lv,ZeroStencilOp as jv,KeepStencilOp as Hv,ReplaceStencilOp as Fv,IncrementStencilOp as Bv,DecrementStencilOp as Uv,IncrementWrapStencilOp as Gv,DecrementWrapStencilOp as Vv,InvertStencilOp as zv}from"three";var Nd=M("debugstencil");function Wv(o,e){return(o&1<<e.layer)!=0}var Lr=class{static applyStencil(e){if(!e)return;let t=e.sourceId;if(Nd&&console.log(t,Lr.stencils),!t)return;let i=Lr.stencils[t];if(!!i)for(let n=i.length-1;n>=0;n--){let r=i[n];if(Wv(r.layer,e)){Nd&&console.log(r);let s=e.sharedMaterial?.clone();s&&(e.sharedMaterial=s,e.gameObject.renderOrder=r.event*1e3+r.index*50,s.stencilWrite=!0,s.stencilWriteMask=255,s.stencilFuncMask=255,s.stencilRef=r.value,s.stencilFunc=r.compareFunc,s.stencilZPass=r.passOp,s.stencilFail=r.failOp,s.stencilZFail=r.zFailOp);break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){let t=this.parser.json.extensions;if(t){let i=t[Xv];if(i){Nd&&console.log(i);let n=i.stencil;if(n&&Array.isArray(n))for(let r of n){let s={...r};s.compareFunc=Nv(s.compareFunc),s.passOp=Xd(s.passOp),s.failOp=Xd(s.failOp),s.zFailOp=Xd(s.zFailOp),Lr.stencils[this.source]||(Lr.stencils[this.source]=[]),Lr.stencils[this.source].push(s)}}}return null}},jr=Lr;A(jr,"stencils",{});function Xd(o){switch(o){case 0:return Hv;case 1:return jv;case 2:return Fv;case 3:return Bv;case 4:return Uv;case 6:return Gv;case 7:return Vv;case 5:return zv}return 0}function Nv(o){switch(o){case 1:return Pv;case 2:return Ov;case 3:return kv;case 4:return Mv;case 5:return Iv;case 6:return Av;case 7:return Dv;case 8:return Lv}return 0}var Xv="NEEDLE_render_objects";import{TextureLoader as Qv}from"three";import{GLTFLoader as qv}from"three/examples/jsm/loaders/GLTFLoader";var Qd="NEEDLE_deferred_texture",ct=M("debugprogressive"),Yd=new Map,qd=!1;ct&&window.addEventListener("keyup",o=>{o.key==="p"&&(Yd.forEach((e,t)=>{Object.entries(e).forEach(([i,n])=>{qd?t[i]=n.lod0:t[i]=n.original,t.needsUpdate=!0})}),qd=!qd)});var Ws=class{static assignTextureLOD(e,t,i,n=0){if(!!i)for(let r of Object.keys(i)){let s=i[r];s?.isTexture===!0&&(ct&&console.log(`-----------
214
- `,"FIND",i.name,r,s?.name,s?.userData,s),Ws.getOrLoadTexture(e,t,i,r,s,n).then(a=>{if(a?.isTexture===!0&&(a.needsUpdate=!0,ct&&console.log("Assign LOD",i.name,r,a.name,a.guid,i,"Prev:",s,"Now:",a,`
215
- --------------`),i[r]=a,i.needsUpdate=!0,ct)){let c=Yd.get(i);c||(c={},Yd.set(i,c));let d=c[r];d||(d=c[r]={original:s,lod0:a}),d.lod0=a}}))}}get name(){return Qd}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}_loading=[];afterRoot(e){return ct&&console.log("AFTER",this.sourceId,e),this.parser.json.textures?.forEach((t,i)=>{if(t?.extensions){let n=t?.extensions[Qd];if(n){let r=this.parser.getDependency("texture",i);this._loading.splice(this._loading.indexOf(i),1),r.then(s=>{ct&&console.log("register texture",s.name,s.uuid,n),s.userData.deferred=n,Ws.cache.set(s.uuid,n)})}}}),null}static async getOrLoadTexture(e,t,i,n,r,s){let a=r.uuid,c=Ws.cache.get(a);if(c){ct&&console.log(a,c.uri,c.guid);let d=Ri(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 l=d+"_"+c.guid;if(this.resolved[l])return ct&&console.log("Texture has already been loaded: "+l,i.name,n,r.name),this.resolved[l];let u=new qv;hn(u,e),ct&&console.log("Load "+d,i.name,n,c.guid);let h=await u.loadAsync(d),b=h.parser;ct&&console.log("Loading finished "+d,i.name,n,c.guid);let w=-1,v=!1;for(let m of h.parser.json.textures)if(w++,m?.extensions){let f=m?.extensions[Qd];if(f?.guid&&f.guid===c.guid){v=!0;break}}if(!v)return null;let x=await b.getDependency("texture",w);return x&&(x.guid=c.guid),this.resolved[l]=x,ct&&console.log(i.name,n,'change "'+r.name+'" \u2192 "'+x.name+'"',d,w,x,i,l),x}else{ct&&console.log("Load texture from uri: "+d);let u=await new Qv().loadAsync(d);return u&&ct?console.log(c,u):console.warn("failed loading",d),u}}else ct&&console.warn("unknown uuid",r.name,r.uuid,r);return null}},fn=Ws;A(fn,"cache",new Map),A(fn,"resolved",{});function Jd(o){let e=new Oo;return o.register(t=>(e.parser=t,e)),e}var Kd=class{resolvePath(e){return e.includes("/extensions/builtin_components/")?e.replace("/extensions/builtin_components/","/userData/components/"):e.includes("extensions/builtin_components/")?e.replace("extensions/builtin_components/","/userData/components/"):e}};function Zd(o,e,t){o.register(n=>new Cl(n)),o.register(n=>new Ea(n)),o.register(n=>new ul(n,e.lightmaps,t)),o.register(n=>new Tl(n,t,e)),o.register(n=>new xl(n,t)),o.register(n=>new jr(n,t)),o.register(n=>new fn(n,t,e)),o.register(n=>new El(n));let i=o.setAnimationPointerResolver;typeof i=="function"&&i.bind(o)(new Kd)}import{Vector3 as Yv}from"three";var qn=class extends k{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new Yv}update(){if(!this.from||!this.to)return;let e=B(this.from).clone(),t=B(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),te(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(B(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}};_([y(R)],qn.prototype,"from",2),_([y(R)],qn.prototype,"to",2);var Li=class{time;value;inTangent;inWeight;outTangent;outWeight;weightedMode};_([y()],Li.prototype,"time",2),_([y()],Li.prototype,"value",2),_([y()],Li.prototype,"inTangent",2),_([y()],Li.prototype,"inWeight",2),_([y()],Li.prototype,"outTangent",2),_([y()],Li.prototype,"outWeight",2),_([y()],Li.prototype,"weightedMode",2);var hi=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;if(this.keys[0].time>=e)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){let i=this.keys[t];if(i.time<=e)if(t+1<this.keys.length){let r=this.keys[t+1];if(r.time<e)continue;let s=H.remap(e,i.time,r.time,0,1);return H.lerp(i.value,r.value,s)}else return i.value}return this.keys[this.keys.length-1].value}};_([y(Li)],hi.prototype,"keys",2);import*as Hf from"three";import*as Ns from"three";import{PositionalAudioHelper as Kv}from"three/examples/jsm/helpers/PositionalAudioHelper.js";var dt=M("debugaudio");var Ae=class extends k{static get userInteractionRegistered(){return Ae._didCallBeginWaitForUserInteraction||(Ae._didCallBeginWaitForUserInteraction=!0,Ae._beginWaitForUserInteraction()),Ae._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),Ae._didCallBeginWaitForUserInteraction||(Ae._didCallBeginWaitForUserInteraction=!0,Ae._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);let i=(()=>{if(i!=null&&!Ae._userInteractionRegistered){Ae._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&&(dt&&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&&Ae._userInteractionRegistered){let e=R.getComponent(this.context.mainCamera,pi)??R.findObjectOfType(pi,this.context);e?.listener&&(this.sound=new Ns.PositionalAudio(e.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}_focusCallback;awake(){this.audioLoader=new Ns.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&&Ae._userInteractionRegistered&&this.play()},this.context.application.addEventListener("application-visible",this._focusCallback)}onDestroy(){this.context.application.removeEventListener("application-visible",this._focusCallback)}onEnable(){Ae._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Ae._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){dt&&console.log("audio buffer loaded"),Ae.registerWaitForAllowAudio(()=>{dt&&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(),dt&&console.log(this.name,this.shouldPlay,Ae.userInteractionRegistered,this),this.shouldPlay&&Ae._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(dt&&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?dt&&!this.helper&&(this.helper=new Kv(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&(dt&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new Ns.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){dt&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,dt&&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,dt&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying&&this.sound.play()}pause(){dt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause())}stop(){dt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,dt&&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,dt&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},oe=Ae;A(oe,"_didCallBeginWaitForUserInteraction",!1),A(oe,"callbacks",[]),A(oe,"_userInteractionRegistered",!1),_([y()],oe.prototype,"clip",2),_([y()],oe.prototype,"playOnAwake",2),_([y()],oe.prototype,"loop",1),_([y()],oe.prototype,"spatialBlend",1),_([y()],oe.prototype,"minDistance",1),_([y()],oe.prototype,"maxDistance",1),_([y()],oe.prototype,"volume",1),_([y()],oe.prototype,"rollOffMode",2);import*as Ht from"three";import{Color as Jv}from"three";var Z=class extends Jv{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=H.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}lerpColors(e,t,i){let n=e,r=t;return n.alpha&&r.alpha&&(this.alpha=H.lerp(n.alpha,r.alpha,i)),super.lerpColors(e,t,i)}multiply(e){let t=e;return t.alpha&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}};import{PerspectiveCamera as $v,Ray as ey}from"three";var Rl=M("debugcam"),Sl=class extends k{get isCamera(){return!0}get aspect(){return this._cam instanceof $v?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 Ht.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;set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}_cullingMask=4294967295;_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()}e.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}_backgroundColor;_fov=60;_cam=null;_clearFlags=2;_skybox;get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(e,t,i){let n=Sl._origin;n.set(e,t,-1),this.context.input.convertScreenspaceToRaycastSpace(n),n.z=-1,n.unproject(this.cam);let r=Sl._direction.set(n.x,n.y,n.z),s=B(this.cam);return r.sub(s),r.normalize(),i?(i.set(s,r),i):new ey(s.clone(),r.clone())}awake(){this.sourceId||console.warn("Camera has no source - the camera should be exported inside a gltf",this.name)}onEnable(){Rl&&console.log(this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&this.context.setCurrentCamera(this),this.applyClearFlagsIfIsActiveCamera()}onDisable(){this.context.removeCamera(this)}buildCamera(){if(this._cam)return;let e=this.gameObject.isCamera,t=null;if(e?(t=this.gameObject,t?.layers.enableAll()):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 Ht.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),t.fov=this.fieldOfView;else{let i=this.orthographicSize*100;t=new Ht.OrthographicCamera(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,this._nearClipPlane,this._farClipPlane)}this._cam=t,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){if(Rl&&Ye("apply Camera clear flags"),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;Rl&&Ye("Environment blend mode: "+t+" on "+navigator.userAgent);let i=t==="additive"||t==="alpha-blend";if(this.context.xrSessionMode==="immersive-ar"&&t==="opaque"){if(navigator.userAgent?.includes("OculusBrowser"))return!0;if(navigator.userAgent?.includes("Mozilla")&&navigator.userAgent?.includes("Mobile WebXRViewer/v2"))return!0}return i}enableSkybox(){this._skybox||(this._skybox=new $d(this)),this._skybox.enable()}},se=Sl;A(se,"_origin",new Ht.Vector3),A(se,"_direction",new Ht.Vector3),_([y()],se.prototype,"fieldOfView",1),_([y()],se.prototype,"nearClipPlane",1),_([y()],se.prototype,"farClipPlane",1),_([y()],se.prototype,"clearFlags",1),_([y()],se.prototype,"orthographic",2),_([y()],se.prototype,"orthographicSize",2),_([y()],se.prototype,"ARBackgroundAlpha",2),_([y()],se.prototype,"cullingMask",1),_([y(Z)],se.prototype,"backgroundColor",1);var $d=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?this.context.scene.background!==this._skybox&&(Rl&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=Ht.sRGBEncoding,this._skybox.mapping=Ht.EquirectangularReflectionMapping,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this)}};var pi=class extends k{get listener(){return this._listener==null&&(this._listener=new Hf.AudioListener),this._listener}_listener=null;awake(){oe.registerWaitForAllowAudio(()=>{let e=this.listener;if(e==null||e.parent)return;let t=R.getComponentInParent(this.gameObject,se);t?t.cam.add(e):this.gameObject.add(e)})}};import{GLTFLoader as ty}from"three/examples/jsm/loaders/GLTFLoader";import*as Pl from"three";var Xs=M("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))}},Yn=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 Fe;i=R.instantiate(Fn(t,e.scene),r)}}else i=t;if(!i)return null;let n=this.findAvatar(i);return n.isValid?(Xs&&console.log("[Custom Avatar] valid config",t,Xs?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,Xs?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(Xs&&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 a=await n.blob();a&&(r=await a.arrayBuffer())}return!r&&(r=await tl(t,t,0,"no url here go away",!0),!r)?null:(await Ne().parseSync(e,r,null,0))?.scene??null}let i=new ty;return hn(i,e),new Promise((n,r)=>{let s=this.avatarRegistryUrl+"/"+t;i.load(s,async a=>{await Ne().createBuiltinComponents(e,s,a,null,void 0),n(a.scene)},a=>{Xs&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),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"]),s=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;let c=new Pl.Vector3;new Pl.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 Hr(t,n,r,s)}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 s=this.findAvatarPart(r,t);if(s)return s}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}};import{AxesHelper as iy}from"three";var mn=class extends k{length=1;depthTest=!0;isGizmo=!0;_axes=null;onEnable(){if(this.isGizmo&&!Pi)return;this._axes||(this._axes=new iy(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)}};_([y()],mn.prototype,"length",2),_([y()],mn.prototype,"depthTest",2),_([y()],mn.prototype,"isGizmo",2);import*as Ff from"three";var Mo=class extends k{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=B(this.to).clone(),t=B(this.from).clone(),i=e.distanceTo(t),n=e.clone();n.sub(t);let r=t.clone();r.add(e),r.multiplyScalar(.5);let s=B(this.hint).clone();s.sub(r);let a=new Ff.Vector3;a.crossVectors(s,n),a.crossVectors(n,a),a.normalize();let c=i*.5,d=Math.max(this.desiredDistance,c),l=Math.sqrt(d*d-c*c),u=a.clone();u.multiplyScalar(l),u.add(r),te(this.gameObject,u);let h=r.clone();h.sub(a),this.gameObject.lookAt(h)}};import*as Fr from"three";var ny=M("gizmos"),ry=M("debugboxhelper"),Ft=class extends k{box=null;_lastMatrixUpdateFrame=-1;isInBox(e,t){if(!e)return;if(this.box||(this.box=new Fr.Box3),e.type==="Mesh")Ft.testBox.setFromObject(e);else if(e.type==="Group"){if(Ft.testBox.makeEmpty(),e.children.length>0)for(let n=0;n<e.children.length;n++)e.children[n].type==="Mesh"&&Ft.testBox.expandByObject(e)}else{let n=B(e,Ft._position),r=Me(e,Ft._size);t!==void 0&&r.multiplyScalar(t),Ft.testBox.setFromCenterAndSize(n,r)}this.updateBox();let i=this.box?.intersectsBox(Ft.testBox);return i&&ry&&Mr.DrawBox3(Ft.testBox,16711680,5),i}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new Fr.Box3),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){let t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;let i=t,n=B(this.gameObject,Ft._position,i),r=Me(this.gameObject,Ft._size);this.box.setFromCenterAndSize(n,r)}return this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!ny&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=Wa(e),this.gameObject.add(this._helper)}}},Be=Ft;A(Be,"testBox",new Fr.Box3),A(Be,"_position",new Fr.Vector3),A(Be,"_size",new Fr.Vector3(.01,.01,.01));import{Quaternion as hy,Ray as py,Vector3 as Gr}from"three";import*as Bf from"three";var fi=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)}}},oy=o=>/^[A-Z]*$/.test(o),Br=class extends Event{args},be=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&&oy(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 Br(this.key);i.args=e,t.call(this.target,i)}}}finally{this._isInvoking=!1}}addEventListener(e){return this.methods.push(new fi(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}};import{Color as sy,Object3D as ay}from"three";var tu=class extends rn{constructor(){super([sy,Z])}onDeserialize(e){if(e!=null)return e.a!==void 0?new Z(e.r,e.g,e.b,e.a):e.alpha!==void 0?new Z(e.r,e.g,e.b,e.alpha):new Bf.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}}},ZP=new tu,iu=class extends rn{constructor(){super(ay)}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){let i=t.objectToNode[e.uuid];return Te&&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 Te&&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=R.findByGuid(e.guid,n)),i||(i=R.findByGuid(e.guid,t.context.scene)),i?Te&&console.log("Deserialized object reference?",e,i,t?.nodeToObject):console.warn("could not resolve reference",e,t.target,t.path,t.context.scene),i}}}},ly=new iu,nu=class extends rn{constructor(){super([yt,k])}onSerialize(e,t){if(e?.guid)return{guid:e.guid}}onDeserialize(e,t){if(e?.guid){Te&&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=R.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],s=this.findObjectForGuid(e,r);if(s)return s}}},eu=new nu,ru=class extends rn{constructor(){super([be])}onSerialize(e,t){console.log("TODO: SERIALIZE EVENT")}onDeserialize(e,t){if(typeof e=="function")return new be([new fi(e,!0)]);if(e&&e.type==="EventList"){Te&&console.log("DESERIALIZE EVENT",e);let i=new Array;if(e.calls&&Array.isArray(e.calls))for(let s of e.calls){Te&&console.log(s);let a=eu.findObjectForGuid(s.target,t.root);!a&&t.context?.scene&&(a=eu.findObjectForGuid(s.target,t.context?.scene));let c=s.method?.length>0;if(a&&c){let h=()=>console.warn(`Could not find method ${s.method} on object ${a.name}`,a,typeof a[s.method]);if(typeof a[s.method]!="function"){let b=!1;s.method.startsWith("set_")&&s.method.length>4&&(s.method=s.method.substring(4),a[s.method]!==void 0&&(b=!0)),b||h()}}let d,l=s.argument;s.argument!==void 0?(typeof l=="object"&&(l=ly.onDeserialize(s.argument,t),l||(l=eu.onDeserialize(s.argument,t))),d=new fi(c?(...h)=>u(...h):void 0,s.enabled)):d=new fi(c?(...h)=>u(...h):void 0,s.enabled);let u=(...h)=>{let b=a[s.method];typeof b=="function"?l!==void 0?b?.call(a,l):b?.call(a,...h):a[s.method]=l};if(d.method||(d.__debuginfo=t.object?.name),!a||!d.method){let h=t.object?"Current object: "+t.object.name+", "+t.object.guid:null;a?console.warn('EventList method not found: "'+s.method+'" on',a):console.warn("EventList is missing target - will be ignored",s.target,h,e)}else i.push(d)}let n=new be(i);Te&&console.log(n);let r=t.target;return r!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,r),n}}},$P=new ru;import*as Io from"three";import{Matrix4 as dy,Vector3 as Uf}from"three";var ou=class{get isDirty(){return this.positionChanged||this.rotationChanged}positionChanged=!1;rotationChanged=!1;position;quaternion;_positionKeys=["x","y","z"];_quaternionKeys=["_x","_y","_z","_w"];reset(e=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,e){if(this.position)for(let t of this._positionKeys)delete this.position[t];if(this.quaternion)for(let t of this._quaternionKeys)delete this.quaternion[t]}}syncValues(){for(let e of this._positionKeys)this.position[e]=this.obj.position[e];for(let e of this._quaternionKeys)this.quaternion[e]=this.obj.quaternion[e]}mute=!1;applyValues(){if(this.positionChanged&&this.position)for(let e of this._positionKeys){let t=this.position[e];t!==void 0&&(this.obj.position[e]=t)}if(this.rotationChanged&&this.quaternion)for(let e of this._quaternionKeys){let t=this.quaternion[e];t!==void 0&&(this.obj.quaternion[e]=t)}}context;obj;_positionWatch;_rotationWatch;constructor(e,t){this.context=t,this.obj=e}start(e,t){this.reset(),e&&(this._positionWatch||(this._positionWatch=new tn(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((r,s)=>{if(this.context.physics.isUpdating||this.mute)return;let a=this.position[s];Math.abs(a-r)<1e-5||(this.position[s]=r,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new tn(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((r,s)=>{if(this.context.physics.isUpdating||this.mute)return;let a=this.quaternion[s];Math.abs(a-r)<1e-5||(this.quaternion[s]=r,this.rotationChanged=!0)}));let i=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),n=new dy;this.obj.matrixWorld.multiplyMatrices=(r,s)=>(n.equals(r)||(this.positionChanged=!0,this.rotationChanged=!0,n.copy(r)),i(r,s))}stop(){this._positionWatch?.revoke(),this._rotationWatch?.revoke()}},Ol=class extends k{mass=1;useGravity=!0;constraints=0;isKinematic=!1;drag=0;angularDrag=1;detectCollisions=!0;sleepThreshold=.01;collisionDetectionMode=0;get lockPositionX(){return(this.constraints&2)!==0}get lockPositionY(){return(this.constraints&4)!==0}get lockPositionZ(){return(this.constraints&8)!==0}get lockRotationX(){return(this.constraints&16)!==0}get lockRotationY(){return(this.constraints&32)!==0}get lockRotationZ(){return(this.constraints&64)!==0}set lockPositionX(e){e?this.constraints|=2:this.constraints&=-3}set lockPositionY(e){e?this.constraints|=4:this.constraints&=-5}set lockPositionZ(e){e?this.constraints|=8:this.constraints&=-9}set lockRotationX(e){e?this.constraints|=16:this.constraints&=-17}set lockRotationY(e){e?this.constraints|=32:this.constraints&=-33}set lockRotationZ(e){e?this.constraints|=64:this.constraints&=-65}_propertiesChanged=!1;_currentVelocity=new Io.Vector3;_smoothedVelocity=new Io.Vector3;_smoothedVelocityGetter=new Io.Vector3;_lastPosition=new Io.Vector3;_watch;awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new ou(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),2)}onDisable(){this._watch?.stop(),this.context.physics.removeBody(this)}onDestroy(){this.context.physics.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,this.context.physics.updateProperties(this)),this._watch?.isDirty?(this._watch.mute=!0,this._watch.applyValues(),this.context.physics.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):this._watch?.syncValues(),this.captureVelocity(),yield}get body(){return this.context.physics.internal_getRigidbody(this)}teleport(e,t=!0){this._watch?.reset(!0),t?this.gameObject.position.set(e.x,e.y,e.z):this.setWorldPosition(e.x,e.y,e.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(){this.body?.resetForces(!0)}resetTorques(){this.body?.resetTorques(!0)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){this.body?.wakeUp()}applyForce(e,t){this.body?.addForce(e,!0)}applyImpulse(e){this.body?.applyImpulse(e,!0)}setForce(e,t,i){this.body?.resetForces(!0),this.body?.addForce({x:e,y:t,z:i},!0)}getVelocity(){let e=this.body?.linvel();return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(e,t,i){if(e instanceof Uf){let n=e;this.body?.setLinvel(n,!0);return}t===void 0||i===void 0||this.body?.setLinvel({x:e,y:t,z:i},!0)}setAngularVelocity(e,t,i){if(e instanceof Uf){let n=e;this.body?.setAngvel(n,!0);return}t===void 0||i===void 0||this.body?.setAngvel({x:e,y:t,z:i},!0)}setTorque(e,t,i){this.setAngularVelocity(e,t,i)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(e=null){this.gameObject&&this.destroyed}captureVelocity(){if(this.body){let e=B(this.gameObject);Ol.tempPosition.copy(e);let t=e.sub(this._lastPosition);this._lastPosition.copy(Ol.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}}},K=Ol;A(K,"tempPosition",new Io.Vector3),_([ai(),y()],K.prototype,"mass",2),_([ai(),y()],K.prototype,"useGravity",2),_([ai(),y()],K.prototype,"constraints",2),_([ai(),y()],K.prototype,"isKinematic",2),_([ai(),y()],K.prototype,"drag",2),_([ai(),y()],K.prototype,"angularDrag",2),_([ai(),y()],K.prototype,"detectCollisions",2),_([ai(),y()],K.prototype,"sleepThreshold",2),_([ai(),y()],K.prototype,"collisionDetectionMode",2);import{Mesh as uy,Vector3 as Kn}from"three";var Ut=class extends k{get isCollider(){return!0}attachedRigidbody=null;isTrigger=!1;awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(K))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(K))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(K))}onDisable(){this.context.physics.removeBody(this)}};_([y(K)],Ut.prototype,"attachedRigidbody",2),_([y()],Ut.prototype,"isTrigger",2);var Jn=class extends Ut{radius=.5;center=new Kn(0,0,0);onEnable(){super.onEnable(),this.context.physics.addSphereCollider(this,this.center,this.radius)}};_([y()],Jn.prototype,"radius",2),_([y(Kn)],Jn.prototype,"center",2);var Zn=class extends Ut{size=new Kn(1,1,1);center=new Kn(0,0,0);onEnable(){super.onEnable(),this.context.physics.addBoxCollider(this,this.center,this.size)}};_([y(Kn)],Zn.prototype,"size",2),_([y(Kn)],Zn.prototype,"center",2);var Ur=class extends Ut{sharedMesh;convex=!1;onEnable(){super.onEnable(),this.sharedMesh?.isMesh||this.gameObject instanceof uy&&(this.sharedMesh=this.gameObject),this.sharedMesh?.isMesh&&this.context.physics.addMeshCollider(this,this.sharedMesh,this.convex,Me(this.gameObject))}};_([y()],Ur.prototype,"convex",2);var Bt=class extends Ut{center=new Kn(0,0,0);radius=.5;height=2;onEnable(){super.onEnable(),this.context.physics.addCapsuleCollider(this,this.center,this.height,this.radius)}};_([y(Kn)],Bt.prototype,"center",2),_([y()],Bt.prototype,"radius",2),_([y()],Bt.prototype,"height",2);var ji=class extends k{center=new Gr(0,0,0);radius=.5;height=2;_rigidbody=null;get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(K),this._rigidbody||(this._rigidbody=this.gameObject.addNewComponent(K)),this.rigidbody)}onEnable(){let e=this.rigidbody,t=this.gameObject.getComponent(Bt);t||(t=this.gameObject.addNewComponent(Bt)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height,this.gameObject.rotation.x=0,this.gameObject.rotation.z=0,e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}_activeGroundCollisions=new Set;onCollisionEnter(e){for(let t of e.contacts)if(t.normal.y>.1){this._activeGroundCollisions.add(e);break}}onCollisionExit(e){this._activeGroundCollisions.delete(e)}get isGrounded(){return this._activeGroundCollisions.size>0}};_([y(Gr)],ji.prototype,"center",2),_([y()],ji.prototype,"radius",2),_([y()],ji.prototype,"height",2);var mi=class extends k{controller;movementSpeed=2;rotationSpeed=2;jumpForce=1;animator;lookForward=!0;_currentSpeed=new Gr(0,0,0);_currentAngularSpeed=new Gr(0,0,0);_temp=new Gr(0,0,0);_jumpCount=0;_currentRotation;awake(){this._currentRotation=new hy}update(){this.controller?.isGrounded&&(this._jumpCount=0,this.animator?.SetBool("doubleJump",!1));let e=this.context.input.isKeyPressed("w"),t=this.context.input.isKeyPressed("s"),i=this.context.input.isKeyPressed("a"),n=this.context.input.isKeyPressed("d"),r=this.context.input.isKeyDown(" "),s=e?1:0+t?-1:0;this._currentSpeed.z+=s*this.movementSpeed*this.context.time.deltaTime,this.animator?.SetBool("running",s!=0),this.animator?.SetBool("jumping",this.controller?.isGrounded===!0&&r),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp);let a=i?1:0+n?-1:0;if(this._currentAngularSpeed.y+=H.toRadians(a*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){let c=this.context.mainCameraComponent.forward;c.y=0,c.normalize(),this._currentRotation.setFromUnitVectors(new Gr(0,0,1),c),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&r&&this.jumpForce>0){let c=this.controller?.isGrounded;if(!this.controller?.isGrounded&&this._jumpCount===1&&(c=!0,this.animator?.SetBool("doubleJump",!0)),c){this._jumpCount+=1;let d=this.controller.rigidbody,l=this._jumpCount===2?2:1;d.applyImpulse(new Gr(0,1,0).multiplyScalar(this.jumpForce*l))}}if(this.controller){let c=this.controller?.rigidbody.getVelocity().y;if(c<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new py),this._raycastOptions.ray.origin.copy(B(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);let d=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);let l=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(d),(l.length&&l[0].distance>2||c<-10)&&this.animator?.SetBool("falling",!0)}else this.animator?.SetBool("falling",!1)}}_raycastOptions=new me};_([y(ji)],mi.prototype,"controller",2),_([y()],mi.prototype,"movementSpeed",2),_([y()],mi.prototype,"rotationSpeed",2),_([y()],mi.prototype,"jumpForce",2),_([y(et)],mi.prototype,"animator",2);var Gt=class extends k{canGrab=!0;onPointerClick(e){}},Vt=class extends k{isUsed=!0;usedBy=null};var Vr=class extends Be{},Ao=class extends k{deleteBoxes=[];awake(){this.deleteBoxes=R.findObjectsOfType(Vr,this.context)}update(){for(let e of this.deleteBoxes){let t=this.gameObject;e.isInBox(t)===!0&&(R.getComponentInParent(this.gameObject,Vt)||mo(this.gameObject,this.context.connection))}}};var zr=class extends k{visibleOn;onEnable(){this.apply()}apply(){this.test()||R.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:fy()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}};_([y()],zr.prototype,"visibleOn",2);var kl;function fy(){if(kl===!0||kl===!1)return kl;let o=!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)))&&(o=!0)}(navigator.userAgent||navigator.vendor||window.opera),kl=o,o}import*as gn from"three";var we=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 Do=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new we).__init(this.bb_pos,this.bb)}rotation(e){return(e||new we).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new we).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,n,r,s,a,c,d,l){return e.prep(4,36),e.prep(4,12),e.writeFloat32(l),e.writeFloat32(d),e.writeFloat32(c),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(s),e.writeFloat32(r),e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var zt=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 zt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+4),(t||new zt).__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 Do).__init(this.bb_pos+t,this.bb):null}dontSave(){let e=this.bb.__offset(this.bb_pos,10);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startSyncedTransformModel(e){e.startObject(4)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addFast(e,t){e.addFieldInt8(1,+t,0)}static addTransform(e,t){e.addFieldStruct(2,t,0)}static addDontSave(e,t){e.addFieldInt8(3,+t,0)}static endSyncedTransformModel(e){return e.endObject()}static finishSyncedTransformModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedTransformModelBuffer(e,t){e.finish(t,void 0,!0)}};var $n=M("debugsync"),Lo="STRS";To(Lo,zt.getRootAsSyncedTransformModel);var Hi=new vt;function su(o,e,t=!0){Hi.clear();let i=Hi.createString(o);zt.startSyncedTransformModel(Hi),zt.addGuid(Hi,i),zt.addFast(Hi,t);let n=e.worldPosition,r=e.worldEuler,s=e.gameObject.scale;zt.addTransform(Hi,Do.createTransform(Hi,n.x,n.y,n.z,r.x,r.y,r.z,s.x,s.y,s.z));let a=zt.endSyncedTransformModel(Hi);return Hi.finish(a,Lo),Hi.asUint8Array()}var _t=class extends k{overridePhysics=!0;interpolatePosition=!0;interpolateRotation=!0;fastMode=!1;syncDestroy=!1;_model=null;_needsUpdate=!0;rb=null;_wasKinematic=!1;_receivedDataBefore=!1;_targetPosition;_targetRotation;_receivedFastUpdate=!1;_shouldRequestOwnership=!1;requestOwnership(){$n&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){return this._model?.hasOwnership??void 0}isOwned(){return this._model?.isOwned}joinedRoomCallback=null;receivedDataCallback=null;awake(){$n&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new gn.Vector3,this._targetRotation=new gn.Quaternion,this.lastWorldPos=new gn.Vector3,this.lastWorldRotation=new gn.Quaternion,this.rb=R.getComponentInChildren(this.gameObject,K),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new zn(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(Lo,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&bp(this.guid,this.context.connection),this._model=null,this.context.connection.stopListening("joined-room",this.joinedRoomCallback),this.context.connection.stopListenBinary(Lo,this.receivedDataCallback)}tryGetLastState(){let e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new gn.Euler;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){$n&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();let t=e.transform();if(t){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)&&op(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}receivedUpdate=!1;lastWorldPos;lastWorldRotation;onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){$n&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());let e=this.worldPosition,t=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){let r=e.distanceTo(this.lastWorldPos),s=t.angleTo(this.lastWorldRotation),a=this._model.hasOwnership||this.fastMode?1e-4:.001;(r>a||s>a)&&(this._model.hasOwnership?this._needsUpdate=!0:($n&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,e.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,t.copy(this.lastWorldRotation),re.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){let s=this._receivedFastUpdate||this.fastMode?.5:.3,a=!1;if(this.interpolatePosition&&this._targetPosition){let c=this.worldPosition;c.lerp(this._targetPosition,s),this.worldPosition=c,a=!0}if(this.interpolateRotation&&this._targetRotation){let c=this.worldQuaternion;c.slerp(this._targetRotation,s),this.worldQuaternion=c,a=!0}a&&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&&($n&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new gn.Vector3(0,0,0))>1e3&&($n&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0),this.rb.setBodyFromGameObject()));let i=10,n=this.rb||this.fastMode;if(this._needsUpdate&&(i<=0||i>0&&this.context.time.frameCount%i===0||n)){$n&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this.overridePhysics&&this.rb&&this.rb.setBodyFromGameObject(),this._needsUpdate=!1;let r=su(this.guid,this,!!n);this.context.connection.sendBinary(r)}}};import*as q from"three";import{Euler as Uy,EventDispatcher as Gy,Group as Vy,Matrix4 as Kf,Mesh as zy,MeshBasicMaterial as Wy,Object3D as Yf,Quaternion as Bl,RingGeometry as Ny,Vector3 as gu}from"three";var Ml=class{static createButton(e,t={}){let i=document.createElement("button"),n=!1;function r(){if(t.domOverlay===void 0){var d=document.createElement("div");d.style.display="none",document.body.appendChild(d);var l=document.createElementNS("http://www.w3.org/2000/svg","svg");l.setAttribute("width",38),l.setAttribute("height",38),l.style.position="absolute",l.style.right="20px",l.style.top="20px",l.addEventListener("click",function(){h.end()}),d.appendChild(l);var u=document.createElementNS("http://www.w3.org/2000/svg","path");u.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),u.setAttribute("stroke","#fff"),u.setAttribute("stroke-width",2),l.appendChild(u),t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("dom-overlay"),t.domOverlay={root:d},n=!0}t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("local-floor"),t.optionalFeatures.push("hand-tracking"),t.optionalFeatures.push("layers");let h=null,b=null;async function w(x){if(/WebXRViewer\//i.test(navigator.userAgent))if(t.domOverlay?.root){let f=t.domOverlay.root;b=f.parentElement,b&&(console.log("Reparent DOM Overlay to body",f,f.style.display),f.style.display="",f.style.visibility="",document.body.appendChild(f))}else console.warn("WebXRViewer: No DOM Overlay found");x.addEventListener("end",v),await e.xr.setSession(x),i.textContent="STOP AR",n&&(t.domOverlay.root.style.display=""),h=x}function v(){h.removeEventListener("end",v),i.textContent="START AR",b&&b.appendChild(t.domOverlay.root),n&&(t.domOverlay.root.style.display="none"),h=null}i.style.display="",i.style.cursor="pointer",i.style.left="calc(50% - 50px)",i.style.width="100px",i.textContent="START AR",i.onmouseenter=function(){i.style.opacity="1.0"},i.onmouseleave=function(){i.style.opacity="0.5"},i.onclick=function(){h===null?navigator.xr.requestSession("immersive-ar",t).then(w):h.end()}}function s(){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 a(){s(),i.textContent="AR NOT SUPPORTED"}function c(d){d.style.position="absolute",d.style.bottom="20px",d.style.padding="12px 6px",d.style.border="1px solid #fff",d.style.borderRadius="4px",d.style.background="rgba(0,0,0,0.1)",d.style.color="#fff",d.style.font="normal 13px sans-serif",d.style.textAlign="center",d.style.opacity="0.5",d.style.outline="none",d.style.zIndex="999"}if("xr"in navigator)return i.id="ARButton",i.style.display="none",c(i),navigator.xr.isSessionSupported("immersive-ar").then(function(d){d?r():a()}).catch(a),i;{let d=document.createElement("a");return window.isSecureContext===!1?(d.href=document.location.href.replace(/^http:/,"https:"),d.innerHTML="WEBXR NEEDS HTTPS"):(d.href="https://immersiveweb.dev/",d.innerHTML="WEBXR NOT AVAILABLE"),d.style.left="calc(50% - 90px)",d.style.width="180px",d.style.textDecoration="none",c(d),d}}};var Il=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",l),await e.xr.setSession(u),i.textContent="EXIT VR",c=u}function l(){c.removeEventListener("end",l),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 s(){r(),i.textContent="VR NOT SUPPORTED"}function a(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",a(i),navigator.xr.isSessionSupported("immersive-vr").then(function(c){c?n():s(),Il.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",a(c),c}}static registerSessionGrantedListener(){if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent))return;navigator.xr.addEventListener("sessiongranted",()=>{Il.xrSessionIsGranted=!0})}}},Ho=Il;A(Ho,"xrSessionIsGranted",!1);Ho.registerSessionGrantedListener();import*as Al from"three";var Gf=ba(Ya(),1);import{AudioAnalyser as my}from"three";var Fo="noVoip",ut=M("debugvoip"),gy=M("voip");var au=class{id;constructor(e){this.id=e}};var lu=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(){ut&&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 tt.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}ut&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),ut&&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=>{ut&&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){ut&&console.log("call closed",e)}},cu=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,oe.userInteractionRegistered||ut&&console.log("Incoming call, waiting for user interaction before opening audio"),oe.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){ut&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);let t=new Al.AudioListener;this.audio=new Al.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}}}),ut&&console.log("call is setup, you should hear something now"),this.analyzer=new my(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()}},tt=class extends k{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(M(Fo)){console.log("VOIP is disabled by url parameter: "+Fo);return}if(this.requireParam&&!gy){console.debug("VOIP must be enabled explicitly by url parameter");return}this.peer=new Gf.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 lu(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];ut&&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){ut&&console.log("Peer connection established and received id"),this.model=new au(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){ut&&console.log("CONNECTION",t),t.on("data",function(i){ut&&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(),ut&&console.log("received call"),await tt.HasMicrophonePermissions()){let s=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(s)}else e.answer(null);this.currentIncomingCalls[i]=new cu(this,this.gameObject,e),e.on("stream",s=>{ut&&console.log("receive caller stream, will setup audio now"),this.currentIncomingCalls[i]?.openAudioStream(s)}),e.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}};import{Matrix4 as Qs}from"three";var Wt=class extends k{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 Qs;_selectStartFn=this.onSelectStart.bind(this);_selectEndFn=this.onSelectEnd.bind(this);start(){let e=R.findObjectOfType(V);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 Qs().fromArray(i.transform.matrix).invert()),!0):!1}placeAt(e,t){if(this._placementPose||(this._placementPose=new Qs),this._placementPose.copy(t),e){if(this.invertForward){let i=new Qs().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 Qs().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld(),console.log("Place",t.position))}};_([y()],Wt.prototype,"invertForward",2),_([y()],Wt.prototype,"arScale",1);import{BoxHelper as Cy,BufferGeometry as Ty,Color as Xf,Euler as Ry,Layers as Sy,Line as Py,Mesh as Oy,MeshBasicMaterial as ky,Quaternion as Hl,Ray as My,SphereGeometry as Iy,Vector2 as Ay,Vector3 as _i}from"three";import{OculusHandModel as Dy}from"three/examples/jsm/webxr/OculusHandModel.js";import{OculusHandPointerModel as Ly}from"three/examples/jsm/webxr/OculusHandPointerModel.js";import{XRControllerModelFactory as jy}from"three/examples/jsm/webxr/XRControllerModelFactory.js";import{GLTFLoader as Hy}from"three/examples/jsm/loaders/GLTFLoader.js";import*as Wf from"three";import{Quaternion as by,Vector3 as Dl}from"three";var Bo=M("debugflags");var du=class{Mask=17;Has(e){return(this.Mask&e)!==0}Set(e){Bo&&console.warn("Set XR flag state to",e),this.Mask=e,Ee.Apply()}Enable(e){this.Mask|=e,Ee.Apply()}Disable(e){this.Mask&=~e,Ee.Apply()}Toggle(e){this.Mask^=e,Ee.Apply()}EnableAll(){this.Mask=-1,Ee.Apply()}DisableAll(){this.Mask=0,Ee.Apply()}},xt=du;A(xt,"Global",new du);var Fi=class extends k{static Apply(){for(let e of this.registry)e.UpdateVisible(xt.Global)}awake(){Fi.registry.push(this)}onEnable(){Fi.firstApply||(Fi.firstApply=!0,Fi.Apply())}onDestroy(){let e=Fi.registry.indexOf(this);e>=0&&Fi.registry.splice(e,1)}visibleIn;get isOn(){return this.gameObject.visible}UpdateVisible(e=null){let t,i=e;i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),Bo&&console.log(i),Fi.buffer.Mask=i,e=Fi.buffer);let n=e;if(n?(Bo&&console.warn(this.name,"use passed in mask",n.Mask,this.visibleIn),t=n.Has(this.visibleIn)):(Bo&&console.log(this.name,"use global mask"),xt.Global.Has(this.visibleIn)),t!==void 0)if(t)Bo&&console.log(this.name,"is visible",this.gameObject.uuid),R.setActive(this.gameObject,!0);else{if(Bo&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},Ee=Fi;A(Ee,"registry",[]),A(Ee,"firstApply"),A(Ee,"buffer",new xt);import{Object3D as uu}from"three";var er=M("debugavatar"),gi=class extends k{static getAvatar(e){return e>=0&&e<gi.instances.length?gi.instances[e]:null}static onAvatarMarkerCreated(e){return gi._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return gi._onAvatarMarkerDestroyed.push(e),e}connectionId;avatar;awake(){gi.instances.push(this),er&&console.log(this);for(let e of gi._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){gi.instances.splice(gi.instances.indexOf(this),1);for(let e of gi._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):R.setActive(this.avatar,e))}},le=gi;A(le,"instances",[]),A(le,"_onNewAvatarMarkerAdded",[]),A(le,"_onAvatarMarkerDestroyed",[]);var qs=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 Dl(1,1,1);handLeftScale=new Dl(1,1,1);handRightScale=new Dl(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;this.context.isInVR?e|=4:this.context.isInAR?e|=2:e|=1;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 uu;_handLeftTarget=new uu;_handRightTarget=new uu;_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 s=this.isLocalAvatar?this.handLeft:this._handLeftTarget;s.position.set(e.posLeftHand.x,e.posLeftHand.y,e.posLeftHand.z),s.quaternion.set(e.rotLeftHand._x,e.rotLeftHand._y,e.rotLeftHand._z,e.rotLeftHand._w),s.quaternion.multiply(qs.invertRotation),s.scale.set(e.scale,e.scale,e.scale),s.scale.multiply(this.handLeftScale),re.markDirty(this.handLeft)}if(this.handRight){let s=this.isLocalAvatar?this.handRight:this._handRightTarget;s.position.set(e.posRightHand.x,e.posRightHand.y,e.posRightHand.z),s.quaternion.set(e.rotRightHand._x,e.rotRightHand._y,e.rotRightHand._z,e.rotRightHand._w),s.quaternion.multiply(qs.invertRotation),s.scale.set(e.scale,e.scale,e.scale),s.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(){er&&console.log("Destroy avatar",this.guid),this.root?.removeFromParent(),this.avatarMarker?.destroy(),this.lastAvatarId=null,this.head&&ve.Remove(this.context,this.head)}updateVisibility(){let e=this.root;e&&R.setActive(e,this._isVisible)}async setupCustomAvatar(e){if(er&&console.log("LOAD",e,this),!e||typeof e=="string"&&e.length<=0)return!1;this.head&&ve.Remove(this.context,this.head);let t=e;if(t?.loadAssetAsync!==void 0){await t.loadAssetAsync();let n=t.asset;R.setActive(n,!1),e=R.instantiate(n),R.setActive(e,!0)}er&&console.log(e);let i=await qs.loader.getOrCreateNewAvatarInstance(this.context,e);if(er&&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=R.addNewComponent(this.root,le),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&&ve.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(...R.getComponentsInChildren(this.root,Ee)),this.flags.length<=0&&this.head){let n=R.addNewComponent(this.head,Ee);n.visibleIn=20,this.flags.push(n),er&&console.log("Added flag to head: "+n.visibleIn,this.head.name)}return er&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return er&&console.warn("build avatar failed"),!1}},Nt=qs;A(Nt,"loader",new Yn),A(Nt,"invertRotation",new by().setFromAxisAngle(new Dl(0,1,0),Math.PI));var ve=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??G.Current?.time.time;return}}}};A(ve,"Pois",[]),A(ve,"LastChangeTime",0);var hu=class{guid;position=new Wf.Vector3},bn=class extends k{set controlledTarget(e){this.target=e;let t=P.get("MoveRandom");if(t&&this.target){let i=R.getComponent(this.target,t);i&&i.destroy()}}target=null;avatar=null;_model=null;_targetModel=new hu;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=R.getComponentInParent(this.gameObject,le),this.avatar){let e=R.getComponentInParent(this.gameObject,le);this._model=new zn(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&&te(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(ve.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=ve.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){let t=B(this._currentTargetObject);te(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=ve.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 jl from"three-mesh-ui";import{OrbitControls as yy}from"three/examples/jsm/controls/OrbitControls";import{Object3D as vy}from"three";var vn=class extends k{constraintActive=!0;locked=!1;sources=[]};_([y(vy)],vn.prototype,"sources",2);import*as Ys from"three";var Ll=M("freecam"),it=class extends k{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=!0;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 Ys.Vector3,this._startedListeningToKeyEvents=!1}onEnable(){this._enableTime=this.context.time.time;let t=R.getComponent(this.gameObject,se)?.cam;this._controls||(console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t),this._controls=new yy(t,this.context.renderer.domElement)),this._controls&&(Ll&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,va()&&(this.doubleClickToFocus=!0)),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"?Ll||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):Ll||(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=R.getComponent(this.gameObject,se);if(e&&!this.setFromTargetPosition()){this.debugLog&&console.log("NO TARGET");let t=new Ys.Vector3(0,0,-1).applyMatrix4(e.cam.matrixWorld);this.setTarget(t,!0)}}this.startCoroutine(this.startRaycastDelayed())}*startRaycastDelayed(){if(yield,!this.setFromTargetPosition()){let e=new me;e.screenPoint=new Ys.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;if(this._lerpCameraToTarget&&this._cameraTargetPosition&&this._cameraObject){if(this.useSlerp){let i=this._cameraObject?.position;np(i,this._cameraTargetPosition,t)}else this._cameraObject?.position.lerp(this._cameraTargetPosition,t);this._cameraObject.position.distanceTo(this._cameraTargetPosition)<1e-4&&(this._lerpCameraToTarget=!1)}this._lerpToTargetPosition&&(this.lerpTarget(this._lookTargetPosition,t),this._lookTargetPosition.distanceTo(this._controls.target)<1e-5&&(this._lerpToTargetPosition=!1))}!Ll&&this.lookAtConstraint?.locked&&this.setFromTargetPosition(0,this.lookAtConstraint01),this._controls&&!this.context.isInXR&&(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&&R.isActiveInHierarchy(t.object)){if(this._lookTargetPosition.copy(t.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;let i=B(this.context.mainCamera);this._cameraTargetPosition=i.clone().sub(this.controls.target).add(this._lookTargetPosition),this._cameraObject?.parent?.worldToLocal(this._cameraTargetPosition)}break}}};_([y(vn)],it.prototype,"lookAtConstraint",2);var bi=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 xy}from"three";var wy=M("debugeventsystem"),Bi=class extends k{static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Bi.systems.length<=0&&Bi.systems.push(...R.findObjectsOfType(Bi,e)));for(let i of Bi.systems)if(i.context===e)return;let t=new xy;R.addNewComponent(t,Bi),e.scene.add(t)}static get systems(){let e=G.Current;return this._eventSystemMap.has(e)||this._eventSystemMap.set(e,[]),this._eventSystemMap.get(e)}static ensureUpdateMeshUI(e,t){vi.update(e,t)}static markUIDirty(e){vi.markDirty()}static get instance(){return this.systems[0]}orbitControl=null;orbitControlWasEnabled=!1;raycaster=[];constructor(){super(),Bi.systems.push(this)}onDestroy(){Bi.systems.splice(Bi.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(){let e=new Map;this._selectStartFn??=(i,n)=>{if(!n.grab)return;vi.resetLastSelected();let r=new bi;r.inputSource=i,r.isDown=i.selectionDown,r.isUp=i.selectionUp,r.isPressed=i.selectionPressed,r.isClicked=!1,e.set(i,n.grab),n.grab&&!this.handleEvents(n.grab,r)&&(n.grab=null)},this._selectEndFn??=(i,n)=>{if(!n.grab)return;let r=new bi;r.inputSource=i,r.isDown=i.selectionDown,r.isUp=i.selectionUp,r.isPressed=i.selectionPressed,r.isClicked=i.selectionClick,this.handleEvents(n.grab,r);let s=e.get(i);if(e.set(i,null),s)for(let a=0;a<this.raisedPointerDownEvents.length;a++){let c=this.raisedPointerDownEvents[a];this.raisedPointerDownObjects[a]===s&&c&&(c.onPointerUp?.call(c,r),this.raisedPointerDownEvents.splice(a,1),this.raisedPointerDownObjects.splice(a,1),a--)}};let t=new me;this._selectUpdateFn??=i=>{t.ray=i.getRay();let n=this.performRaycast(t);if(!n)return;let r=new bi;r.inputSource=i,this.handleIntersections(n,r)},J.addEventListener("select-start",this._selectStartFn),J.addEventListener("select-end",this._selectEndFn),J.addEventListener("update",this._selectUpdateFn),this.context.pre_update_callbacks.push(this.onBeforeUpdate.bind(this)),this.context.input.addEventListener("pointerdown",this.onPointerDown.bind(this))}onDisable(){J.removeEventListener("select-start",this._selectStartFn),J.removeEventListener("select-end",this._selectEndFn),J.removeEventListener("update",this._selectUpdateFn)}onPointerDown(){this.onBeforeUpdate()}lastPointerEvent=null;objectsHoveredThisFrame=[];objectsHoveredLastFrame=[];raisedPointerDownEvents=[];raisedPointerDownObjects=[];_didMove=!1;onBeforeUpdate(){if(this.objectsHoveredThisFrame.length=0,this.resetMeshUIStates(),V.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 bi(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=R.getComponent(this.context.mainCameraComponent.gameObject,it)??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,this.raisedPointerDownObjects.length=0}for(let t of this.objectsHoveredLastFrame)if(this.objectsHoveredThisFrame.indexOf(t)<0){this._tempComponentsArray.length=0;let i=R.getComponentsInParent(t,k,this._tempComponentsArray);this.lastPointerEvent.object=t;for(let n=0;n<i.length;n++){let r=i[n];if(!r.gameObject||r.destroyed)continue;let s=r;s.onPointerExit&&s.onPointerExit(this.lastPointerEvent)}}let e=this.objectsHoveredLastFrame;this.objectsHoveredLastFrame=this.objectsHoveredThisFrame,this.objectsHoveredThisFrame=e}_sortedHits=[];performRaycast(e){if(!this.raycaster)return null;this._sortedHits.length=0;for(let t of this.raycaster){if(!t.activeAndEnabled)continue;let i=t.performRaycast(e);i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}handleIntersections(e,t){if(!e||e.length<=0)return!1;e=this.sortCandidates(e);for(let i of e){let{object:n}=i;if(this.handleEvents(n,t))return!0}return!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){let i=e[t],n=i.object;if(n.material&&n.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(let t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventsArray=[];out={};handleEvents(e,t){if(!this.testIsVisible(e))return t.isClicked&&wy&&console.log("not allowed",e),!1;let i=e;t.object=e,this.lastPointerEvent=t;let n=e.parent,r=!1,s=t.isClicked??!1,a=null;if(n&&n.isUI){let c=(t.isPressed||t.isClicked)??!1;if(n[wt]){let d=n[wt].gameObject;if(d){if(!yi.isInteractable(d,this.out))return this.out.canvasGroup?.interactable??!1;a=this.out.canvasGroup??null;let u=this.handleMeshUIIntersection(e,c);e=d,r=!0}}if(!r&&this.handleMeshUiObjectWithoutShadowDom(n,c))return!0}if(this.objectsHoveredThisFrame.push(e),a===null||a.interactable){let c=this.objectsHoveredLastFrame.indexOf(e)>=0;this.handleEventsArray.length=0;let d=R.getComponentsInParent(e,k,this.handleEventsArray);for(let l=0;l<d.length;l++){if(t.used)return!0;if(d[l].destroyed)continue;let u=d[l];u.interactable!==!1&&(u.onPointerEnter&&(c||u.onPointerEnter(t)),t.isDown&&u.onPointerDown&&!this.raisedPointerDownEvents.includes(u)&&(u.onPointerDown(t),this.raisedPointerDownEvents.push(u),this.raisedPointerDownObjects.push(i)),t.isUp&&u.onPointerUp&&u.onPointerUp(t),t.isClicked&&u.onPointerClick&&u.onPointerClick(t))}}return!0}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){let i=vi.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&vi.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){let t=this.currentActiveMeshUIComponents[e];vi.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?R.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}},Xe=Bi;A(Xe,"_eventSystemMap",new Map),A(Xe,"didSearchEventSystem",!1);var vi=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}};A(vi,"lastSelected",null),A(vi,"lastUpdateFrame",[]),A(vi,"needsUpdate",!1);import{AxesHelper as Ey}from"three";var Uo="./include";jl.Block.prototype.interactable={get(){return this.interactive},set(o){this.interactable=o}};var wt=Symbol("shadowDomOwner"),Ue=class extends k{isRoot(){return this.Root?.gameObject===this.gameObject}markDirty(){Xe.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=R.getComponentInParent(this.gameObject,yn)),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=R.getComponentInParent(i,Ue),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have a UI element outside a Canvas?`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[wt]=this,e.traverse(r=>{r[wt]===void 0&&(r[wt]=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),Pi&&e.add(new Ey(.5)),this.onAfterAddedToScene(),n&&jl.update()}set(e){}traverseOwnedShadowComponents(e,t,i){if(!!e&&e[wt]===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)}},yn=class extends Ue{awake(){super.awake()}};var yi=class{static getObject(e){let t=e[wt];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=ri(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=ri(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 Ks=M("debugwebxrcontroller");var Wr=class extends k{},De=class extends k{static CreateRaycastLine(){let e=new Py(this.geometry),t=e.material;return t.color=this.raycastColor,e.layers.set(2),e.name="line",e.scale.z=1,e}static CreateRaycastHitPoint(){let e=new Iy(.5,22,22),t=new ky({color:this.raycastColor}),i=new Oy(e,t);return i.visible=!1,i.layers.set(2),i}static Create(e,t,i,n){let r=i?R.addNewComponent(i,De,!1):new De;r.webXR=e,r.index=t,r.type=n;let s=e.context;r.controller=s.renderer.xr.getController(t),r.controllerGrip=s.renderer.xr.getControllerGrip(t),r.controllerModel=this.Factory.createControllerModel(r.controller),r.controllerGrip.add(r.controllerModel),r.hand=s.renderer.xr.getHand(t);let a=new Hy;hn(a,s),r.webXR.handModelPath&&r.webXR.handModelPath!==""?a.setPath(Ri(e.sourceId,r.webXR.handModelPath)):a.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/");let c=new Dy(r.hand,a);return r.hand.add(c),r.hand.traverse(d=>d.layers.set(2)),r.handPointerModel=new Ly(r.hand,r.controller),r.controller.addEventListener("connected",d=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),r.setControllerLayers(r.hand,2),setTimeout(()=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),r.setControllerLayers(r.hand,2)},1e3)}),r.hand.addEventListener("connected",d=>{if(d.data.hand){e.Rig&&e.Rig.add(r.hand),r.type=0,r.handPointerModel.traverse(h=>h.layers.set(2)),r.handPointerModel.pointerObject?.traverse(h=>h.layers.set(2));let u=r.hand.joints;if(u)for(let h of Object.keys(u)){let b=u[h];b.parent||r.hand.add(b)}}}),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;showRaycastLine=!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 Hl),pe(e).multiply(this._wristQuaternion.setFromEuler(new Ry(-Math.PI/4,0,0)))):null}movementVector=new _i;worldRot=new Hl;joystick=new Ay;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),Ks&&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({clientX:0,clientY:0,button:this.index,pointerType:"touch"});break;case"move":break;case"up":this.context.input.createPointerUp({clientX:0,clientY:0,button:this.index,pointerType:"touch"});break}}rayRotation=new Hl;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=B(this.controller);if(this.isUsingHands&&this.handPointerModel.cursorObject&&(this.handPointerModel.cursorObject.visible=!1),this.raycastLine){let n=this.showRaycastLine&&this.context.isInVR;if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed&&n,te(this.raycastLine,i);let r=this.hand.joints;if(r&&r.wrist&&this.grabbed&&this.grabbed.isCloseGrab){let a=this.getWristQuaternion();a&&this.rayRotation.copy(a)}Ke(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=n,Ke(this.raycastLine,this.rayRotation),te(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,s=H.clamp01(this.joystick.length()*2),a=this.joystick.x>0?1:-1,c=Math.pow(this.joystick.x,r);c*=a,c*=s;let d=this.joystick.y>0?1:-1,l=Math.pow(this.joystick.y,r);l*=d,c*=s,t.getWorldQuaternion(this.worldRot),this.movementVector.set(c,0,l),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 b=u>0?-1:1;t.rotateY(H.toRadians(30*b)),this.didRotate=!0}this.runTeleport(t,i);break}}runTeleport(e,t){let i=-this.joystick.y;if(this.hand?.visible&&!this.grabbed){let a=this.handPointerModel.isPinched();a&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),a&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(i=this.handPointerModel.isPinched()?1:0),a||(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,s=null;if(t&&this.input&&!this.input.hand)for(let a=0;a<t.length;a++){let c=t[a];if(a===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),s=1,De.MovementSpeedFactor=1;let l=this.context.mainCamera;De.PreviousCameraFarDistance&&(l.far=De.PreviousCameraFarDistance)}else{r=!0,n=!0,s=.1,De.MovementSpeedFactor=s*2;let l=this.context.mainCamera;De.PreviousCameraFarDistance=l.far,l.far/=s}}else c.pressed||(this.didChangeScale=!1)}if(n){if(!this.didTeleport){let a=this.raycast();if(this.didTeleport=!0,a&&a.length>0){let c=a[0];if(r||this.isValidTeleportTarget(c.object)){let d=c.point;te(e,d)}}}}else i<.1&&(this.didTeleport=!1);s!==null&&(e.scale.set(s,s,s),e.updateMatrixWorld())}isValidTeleportTarget(e){return R.getComponentInParent(e,Wr)!=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=H.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(),Ks&&console.log("onHandleSelectStart","close grab? "+t,"intersections",e),e&&e.length>0)for(let i of e){let n=i.object;this.lastSelectStartObject=n;let r={selected:n,grab:n},s=De.eventSubs["select-start"];if(s&&s.length>0)for(let a of s)a(this,r);r.grab!==n&&Ks&&console.log("Grabbed object changed","original",n,"new",r.grab),r.grab&&(this.grabbed=ht.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||R.isActiveInHierarchy(e)===!1||yi.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 My;return e.origin.copy(B(this.controller)),e.direction.set(0,0,-1).applyQuaternion(this.rayRotation),e}closeGrabBoundingBoxHelper;overlap(){let e=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(Ks&&(!this.closeGrabBoundingBoxHelper&&e&&(this.closeGrabBoundingBoxHelper=new Cy(e,16776960),this.scene.add(this.closeGrabBoundingBoxHelper)),this.closeGrabBoundingBoxHelper&&e&&this.closeGrabBoundingBoxHelper.setFromObject(e)),!e)return new Array;let t=B(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){let e=new me;e.layerMask=new Sy,e.layerMask.set(0),e.layerMask.disable(2),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=yi.getObject(r);break}return t}},J=De;A(J,"Factory",new jy),A(J,"raycastColor",new Xf(.9,.3,.3)),A(J,"raycastNoHitColor",new Xf(.6,.6,.6)),A(J,"geometry",new Ty().setFromPoints([new _i(0,0,0),new _i(0,0,-1)])),A(J,"handModels",{}),A(J,"eventSubs",{}),A(J,"PreviousCameraFarDistance"),A(J,"MovementSpeedFactor",1);var nt=class{static AddEventListener(e,t){return nt.Events[e]||(nt.Events[e]=[]),nt.Events[e].push(t),t}static RemoveEventListener(e,t){if(!t||!nt.Events[e])return;let i=nt.Events[e].indexOf(t);i>=0&&nt.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=R.getComponentInParent(t,Gt);if(r)t=r.gameObject;else return Ks&&console.warn("Prevented taking object that is not interactable",t),null;let s=t,a=R.getComponentInParent(t,_t);a&&(a.requestOwnership(),s=a.gameObject);for(let d of this.Current)if(d.selected===s)return d.controller===e||(d.free(),d.Take(e,s,t,a,r,i,n)),d;let c=new nt;return c.Take(e,s,t,a,r,i,n),c}sync=null;selected=null;selectedParent=null;selectedMesh=null;controller=null;grabTime=0;grabUUID="";isCloseGrab=!1;originalMaterial=null;usageMarker=null;rigidbodies=null;didReparent=!1;grabDistance=0;interactable=null;positionSource=null;Take(e,t,i,n,r,s,a){if(console.assert(t!==null,"Expected object to be taken but was",t),e.isUsingHands?this.positionSource=a?e.wrist:e.controller:this.positionSource=e.controller,!this.positionSource)return console.warn("No position source"),this;let c={controller:e,take:t,hit:i,sync:n,interactable:r};nt.Events.WillTake?.forEach(b=>b(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=a,this.didReparent=!1,this.sync=n,this.grabTime=e.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=R.addNewComponent(this.selected,Vt),this.rigidbodies=R.getComponentsInChildren(this.selected,K),B(this.positionSource,this.lastControllerWorldPos);let l=()=>a?this.lastControllerWorldPos.clone():s.point.clone();this.grabDistance=l().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(l());let u=e.isUsingHands&&a?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(B(h)),ve.Add(e.context,this.selected),nt.Register(this),this.sync&&(this.sync.fastMode=!0),nt.Events.DidTake?.forEach(b=>b(this,c)),this}free(){if(!this.selected)return;let e={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};nt.Events.WillFree?.forEach(n=>n(this,e)),ve.Remove(this.controller.context,this.selected),nt.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.setVelocity(n.smoothedVelocity);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,nt.Events.DidFree?.forEach(n=>n(this,e))}grabPoint=new _i;localPositionOffsetToGrab=null;localPositionOffsetToGrab_worldSpace=new _i;localQuaternionToGrab=new Hl(0,0,0,1);targetDir=null;quaternionLerp=null;controllerDir=new _i;controllerWorldPos=new _i;lastControllerWorldPos=new _i;controllerPosDelta=new _i;totalChangeAlongDirection=0;rigPositionLastFrame=new _i;controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),B(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=B(e),n=this.rigPositionLastFrame.sub(i);this.controllerPosDelta.add(n),this.rigPositionLastFrame.copy(i)}return this.controllerDir.dot(this.controllerPosDelta)}update(){if(this.rigidbodies)for(let e of this.rigidbodies)e.resetVelocities();if(this.sync&&this.controller&&this.controller.context.connection.isInRoom&&this.controller.context.time.time-this.grabTime>3&&this.sync.hasOwnership()===!1&&(console.log("no ownership, will leave",this.sync.guid),this.free()),!(this.interactable&&!this.interactable.canGrab)){if(!this.didReparent&&this.selected&&this.controller){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 _i),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),Ke(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(B(this.selected)),i.sub(this.localPositionOffsetToGrab_worldSpace)),te(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)}}},ht=nt;A(ht,"Events",{}),A(ht,"Current",[]);var tr=class extends k{awake(){}};import{Quaternion as Js,Vector3 as Fl,Vector4 as Fy}from"three";var Ui=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 Se=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 Se).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+4),(t||new Se).__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 we).__init(this.bb_pos+t,this.bb):null}rotation(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new Ui).__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 we).__init(this.bb_pos+t,this.bb):null}posRightHand(e){let t=this.bb.__offset(this.bb_pos,18);return t?(e||new we).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){let t=this.bb.__offset(this.bb_pos,20);return t?(e||new Ui).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){let t=this.bb.__offset(this.bb_pos,22);return t?(e||new Ui).__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 Qf=M("debugxr"),Zs=M("debugavatar");var mu="VRUS";To(mu,Se.getRootAsVrUserStateBuffer);function fu(){return new Date().getTime()}function By(o){let e=o&4294967295,t=o/Math.pow(2,32)&1048575;return We.create(e,t)}var $s=class{guid;time;avatarId;position=new Fl;rotation=new Fy;scale=1;posLeftHand=new Fl;posRightHand=new Fl;rotLeftHand=new Js;rotRightHand=new Js;constructor(e){this.guid=e}update(e,t,i,n,r){this.time=fu(),this.avatarId=r,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let s=$s.quat0,a=$s.quat1;s.set(i.x,i.y,i.z,i.w),s=s.multiplyQuaternions(s,$s.invertRotation),e&&(e.getWorldQuaternion(a),s.multiplyQuaternions(a,s)),this.rotation.set(s.x,s.y,s.z,s.w),this.scale=e.scale.x;let c=n.LeftController?.controllerGrip;c&&(c.getWorldPosition(this.posLeftHand),c.getWorldQuaternion(this.rotLeftHand));let d=n.RightController?.controllerGrip;if(d&&(d.getWorldPosition(this.posRightHand),d.getWorldQuaternion(this.rotRightHand)),n.LeftController?.hand?.visible){let l=n.LeftController.wrist;l&&(l.getWorldPosition(this.posLeftHand),l.getWorldQuaternion(this.rotLeftHand))}if(n.RightController?.hand?.visible){let l=n.RightController.wrist;l&&(l.getWorldPosition(this.posRightHand),l.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(e,t){e.clear();let i=e.createString(this.guid),n=e.createString(this.avatarId);Se.startVrUserStateBuffer(e),Se.addGuid(e,i),Se.addTime(e,By(this.time)),Se.addAvatarId(e,n),Se.addPosition(e,we.createVec3(e,this.position.x,this.position.y,this.position.z)),Se.addRotation(e,Ui.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),Se.addScale(e,this.scale),Se.addPosLeftHand(e,we.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),Se.addPosRightHand(e,we.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),Se.addRotLeftHand(e,Ui.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),Se.addRotRightHand(e,Ui.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));let r=Se.endVrUserStateBuffer(e);e.finish(r,mu);let s=e.asUint8Array();t.sendBinary(s)}setFromBuffer(e,t){if(!e)return;this.guid=e,this.time=t.time().toFloat64();let i=t.avatarId();i&&(this.avatarId=i);let n=t.position();n&&this.position.set(n.x(),n.y(),n.z());let r=t.rotation();r&&this.rotation.set(r.x(),r.y(),r.z(),r.w());let s=t.posLeftHand();s&&this.posLeftHand.set(s.x(),s.y(),s.z());let a=t.posRightHand();a&&this.posRightHand.set(a.x(),a.y(),a.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()}},Xt=$s;A(Xt,"invertRotation",new Js().setFromAxisAngle(new Fl(0,1,0),Math.PI)),A(Xt,"quat0",new Js),A(Xt,"quat1",new Js);var _n=class extends k{webXR=null;debugAvatarUser=null;voip=null;async awake(){if(this.webXR||(this.webXR=R.getComponent(this.gameObject,V)),this.webXR||(this.webXR=R.findObjectOfType(V,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=R.findObjectOfType(V,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=R.findObjectOfType(tt,this.context)),Zs){let e="debug-avatar-"+Zs,t=new Nt(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof Zs=="string"&&Zs.length>0)if(await t.setAvatarOverride(Zs)){let i=new Xt(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=R.getComponent(this.gameObject,V),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),V.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),V.addEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),V.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(mu,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 Xt("");onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;let i=new Date().getTime()-t;if(i>5e3)return Qf&&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 Nt(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),V.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),V.removeEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),V.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}update(){let e=fu();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=fu();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 Nt(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(){Qf&&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"}),this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null)}ownership=null;xrState=null;builder=new vt(1024);onXRSessionUpdate(e){this.xrState??=new Xt(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership??=new zn(this.context.connection,this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership.guid=this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid,this.buildLocalAvatar();let{frame:t,xr:i,rig:n}=e,r=t.getViewerPose(i.getReferenceSpace());if(!r)return;let s=r?.transform,a=s.position,c=s.orientation;this.xrState.update(n,a,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 M("avatar")??null}};async function Xy(){return ya()?!0:"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function Qy(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}var bu=!1,vu=!1;Xy().then(o=>bu=o);Qy().then(o=>vu=o);var Le=class extends k{enableVR=!0;enableAR=!0;defaultAvatar;handModelPath="";createVRButton=!0;createARButton=!0;static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(bu||vu)}static get IsARSupported(){return bu}static get IsVRSupported(){return vu}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?e.__internalAwake():console.warn("WebXR is not supported on this device");let i=Ho.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){e.__internalAwake();let i=e.webAR?.getAROverlayContainer(),n={};i?(n.domOverlay={root:i},n.optionalFeatures=["hit-test","dom-overlay"]):console.warn("No dom overlay root found, HTML overlays on top of screen-based AR will not work."),n.optionalFeatures.push("plane-detection"),n.optionalFeatures.push("anchors");let r=Ml.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=Ze.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!R.findObjectOfType(_n,this.context)){let e=R.addNewComponent(this.gameObject,_n,!1);e.webXR=this}this.webAR=new ir(this)}onEnable(){if(this.isInit||!this.enableAR&&!this.enableVR)return;this.isInit=!0,this.context.renderer.xr.enabled=!0;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&&(i=Le.createVRButton(this),this._vrButton=i,n.appendChild(i)),setTimeout(()=>{Le.resetButtonStyles(i),Le.resetButtonStyles(t)},1e3)}_transformOrientation=new Bl;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.captureStateBeforeXR())}onClickedVRButton(){if(!this._isInVR){if(this._requestedVR){this.onExitXR(null);return}this._requestedAR=!1,this._requestedVR=!0,this.captureStateBeforeXR(),this.ensureRig();for(let e=0;e<2;e++)J.Create(this,e,this.gameObject,0);Le.events.dispatchEvent({type:"requestVRSession"})}}captureStateBeforeXR(){this.context.mainCamera&&(this._originalCameraPosition.copy(B(this.context.mainCamera)),this._originalCameraRotation.copy(pe(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent),this.Rig&&(this._originalXRRigParent=this.Rig.parent,this._originalXRRigPosition.copy(this.Rig.position),this._originalXRRigRotation.copy(this.Rig.quaternion))}ensureRig(){if(!this.rig){let e=R.findObjectOfType(tr,this.context);e?(this.rig=e.gameObject,this.rig.rotateY(Math.PI)):(this.rig=new Vy,this.rig.rotateY(Math.PI),this.rig.name="XRRig",this.context.scene.add(this.rig))}}_originalCameraParent=null;_originalCameraPosition=new gu;_originalCameraRotation=new Bl;_originalXRRigParent=null;_originalXRRigPosition=new gu;_originalXRRigRotation=new Bl;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 a=t.getViewerPose(i)?.transform.orientation;if(a){let c=new Bl(a.x,a.y,a.z,a.w),d=new Uy().setFromQuaternion(c);this.rig.rotateY(d.y)}}let n=this.context.renderer.xr;if(this.context.mainCamera){let s=n.getCamera(this.context.mainCamera);for(let a of s.cameras)a.layers.enableAll();this.rig.add(this.context.mainCamera),this._requestedAR&&this.context.scene.add(this.rig)}let r=this._requestedAR?2:4;switch(xt.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){let t=this._isInAR;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),te(this.context.mainCamera,this._originalCameraPosition),Ke(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),t&&(this._originalXRRigParent?.add(this.rig),this.rig.position.copy(this._originalXRRigPosition),this.rig.quaternion.copy(this._originalXRRigRotation)),xt.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){!M("mirror")||setTimeout(()=>{if(!Le.IsInWebXR)return;let t=new URL(window.location.href);co(t.searchParams,Fo,1),co(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)}},V=Le;A(V,"_isInXr",!1),A(V,"events",new Gy),_([y()],V.prototype,"enableVR",2),_([y()],V.prototype,"enableAR",2),_([y(Ze)],V.prototype,"defaultAvatar",2),_([y()],V.prototype,"handModelPath",2),_([y()],V.prototype,"createVRButton",2),_([y()],V.prototype,"createARButton",2);var Go=class{get webxr(){return this._webxr}_webxr;reticle=null;reticleParent=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(){this.arDomOverlay=this.webxr.context.domElement;let e=this.arDomOverlay;return e.getAROverlayContainer?this.arOverlayElement=e.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,this.getAROverlayContainer();let i=navigator.userAgent?.includes("OculusBrowser")?0:1,n=i===1?4:2;for(let s=0;s<n;s++)J.Create(this.webxr,s,this.webxr.gameObject,i);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=R.findObjectOfType(Wt,t)),this.previousBackground=t.scene.background,this.previousEnvironment=t.scene.environment,t.scene.background=null,e.requestReferenceSpace("viewer").then(s=>{e.requestHitTestSource?.call(e,{space:s})?.then(a=>{this.hitTestSource=a}).catch(a=>{this.noHitTestAvailable=!0,console.warn("WebXR: Hit test not supported",a)})}),!this.reticle&&this.sessionRoot&&(this.reticle=new zy(new Ny(.07,.09,32).rotateX(-Math.PI/2),new Wy),this.reticle.name="AR Placement reticle",this.reticle.matrixAutoUpdate=!1,this.reticle.visible=!1,this.reticleParent=new Yf,this.reticleParent.name="AR Reticle Parent",this.reticleParent.matrixAutoUpdate=!1,this.reticleParent.add(this.reticle),this.reticleParent.matrix.copy(this.sessionRoot.gameObject.matrixWorld),this.webxr.scene?(this.context.scene.add(this.reticleParent),this.context.scene.visible=!0):console.warn("Could not found WebXR Rig")),this._previousParent=this.webxr.gameObject,Go.tempWebXRObject||(Go.tempWebXRObject=new Yf),this.context.scene.add(Go.tempWebXRObject),R.addComponent(Go.tempWebXRObject,this.webxr),this.sessionRoot?(this.sessionRoot.webAR=this,this.sessionRoot?.onBegin(e)):console.warn("No WebARSessionRoot found in scene");let r=this.context.domElement;r?.onEnterAR?.call(r,e,this.arOverlayElement),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onEnd(e){this._previousParent&&(R.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);let i=this.context.domElement;i.onExitAR?.call(i,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=qy.clone();if(n){let s=new gu(0,0,0).add(n.position).divideScalar(this.sessionRoot?.arScale??1);r.multiply(new Kf().makeTranslation(s.x,s.y,s.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 s=n.getPose(r);if(this.sessionRoot){let a=this.sessionRoot.onUpdate(this.webxr.Rig,e,s);this.didPlaceARSessionRoot=a}if(this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&s)){let a=s.transform.matrix;this.reticle.matrix.fromArray(a),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)}},ir=Go;A(ir,"tempWebXRObject");var qy=new Kf().identity().makeTranslation(0,-.5,0);var yu=!1;var xn=class extends Gt{static get HasAnySelected(){return this._active>0}transformSelf=!0;orbit=null;selectStartEventListener=[];selectEndEventListener=[];constructor(){super(),this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new q.Vector2}addDragEventListener(e,t){switch(e){case"selectstart":this.selectStartEventListener.push(t);break;case"selectend":this.selectEndEventListener.push(t);break}}_dragHelper=null;start(){this.orbit=R.findObjectOfType(it,this.context)}_draggingRigidbodies=[];allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||V.IsInWebXR)return;let t=R.getComponentInParent(e.object,xn);!t||t!==this||(xn.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){!this.allowEdit(this.gameObject)||V.IsInWebXR||xn.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}_waitingForDragStart=null;onPointerDown(e){!this.allowEdit(this.gameObject)||V.IsInWebXR||(xn._active+=1,this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation(),this.orbit&&(this.orbit.enabled=!1))}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&(xn._active>0&&(xn._active-=1),!V.IsInWebXR&&(this.onDragEnd(e),e.StopPropagation(),this.orbit&&(this.orbit.enabled=!0)))}update(){if(!V.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===!1&&this.onDragEnd(null)}}_isDragging=!1;_marker=null;_dragDelta;_didDrag=!1;onDragStart(e){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new Ul(this.context.mainCamera);else return;if(!e||!e.object)return;let t=R.getComponentInParent(e.object,xn);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),this.orbit&&(this.orbit.enabled=!1);let r=R.getComponentInChildren(i,_t);yu&&console.log("DRAG START",r,i),r&&(r.fastMode=!0,r?.requestOwnership()),this._marker=R.addNewComponent(i,Vt),this._draggingRigidbodies.length=0;let s=R.getComponentsInChildren(i,K);s&&this._draggingRigidbodies.push(...s);let a=Pc();R.invokeOnChildren(this._dragHelper.selected,a("onDragStart"))}onUpdateDrag(){if(!!this._dragHelper){this._dragHelper.onUpdate(this.context);for(let e of this._draggingRigidbodies)e.wakeUp(),e.resetVelocities()}}onDragEnd(e){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;for(let n of this._draggingRigidbodies)n.setVelocity(n.smoothedVelocity);this._draggingRigidbodies.length=0;let t=this._dragHelper.selected;if(yu&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context),this.orbit&&(this.orbit.enabled=!0),e?.object){let n=R.getComponentInChildren(e.object,_t);n&&(n.fastMode=!1),this._marker&&this._marker.destroy()}for(let n of this.selectEndEventListener)n(this);let i=Pc();R.invokeOnChildren(t,i("onDragEnd"))}},Gi=xn;A(Gi,"_active",0),A(Gi,"lastHovered");var _u=class{get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}_selected=null;_context=null;_camera;_cameraPlane=new q.Plane;_hasGroundPlane=!1;_groundPlane=new q.Plane;_groundOffset=new q.Vector3;_groundOffsetFactor=0;_groundDistance=0;_groundPlanePoint=new q.Vector3;_raycaster=new q.Raycaster;_cameraPlaneOffset=new q.Vector3;_intersection=new q.Vector3;_worldPosition=new q.Vector3;_inverseMatrix=new q.Matrix4;_rbs=[];_groundLine;_groundMarker;constructor(e){this._camera=e;let t=new q.Line(_u.geometry),i=t.material;i.color=new q.Color(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;let n=new q.SphereGeometry(.5,22,22),r=new q.MeshBasicMaterial({color:i.color}),s=new q.Mesh(n,r);s.visible=!1,s.layers.set(2),this._groundMarker=s}setSelected(e,t){if(this._selected&&t)for(let i of this._rbs)i.wakeUp(),i.setVelocity(0,0,0);if(this._selected&&ve.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}ve.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this.onUpdateScreenSpacePlane()}}_groundOffsetVector=new q.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),s=this._context.input.getTouchesPressedCount()>=2||r;if(s){let c=this._context.input.getPointerPositionDelta(0);c&&(this._groundOffsetVector.set(0,1,0),this._selected?.rotateOnWorldAxis(this._groundOffsetVector,c.x*this._context.time.deltaTime))}let a=this._context.input.getPointerPositionRC(0);if(!!a&&(this._raycaster.setFromCamera(a,this._camera),this._selected)){yu&&console.log("UPDATE DRAG",this._selected),this._groundOffsetVector.set(0,1,0);let c=B(this._camera).clone().sub(B(this._selected)).normalize(),d=Math.abs(c.dot(this._groundOffsetVector)),l=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(i),u=!s&&d>.2&&!l&&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 b=this._intersection.y;if(this._groundPlanePoint.copy(this._intersection).sub(this._groundOffset),this._groundPlanePoint.y=b,u){this._groundOffsetVector.set(0,1,0);let w=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(w,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=B(this._selected);n.y=e.y,e=n}if(te(this._selected,e),te(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=t!==null,t){let n=B(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(n,n,n),te(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=B(this._selected),t=new q.Ray(new q.Vector3(0,.1,0).add(e),new q.Vector3(0,-1,0)),i=new me;i.ignore=[this._selected];let n=this._context.physics.raycastFromRay(t,i);for(let r=0;r<n.length;r++){let s=n[r];if(!s.face||this.contains(this._selected,s.object))continue;let a=new q.Vector3(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(a,s.point);break}this._hasGroundPlane=!0,this._groundPlane.setFromNormalAndCoplanarPoint(t.direction.multiplyScalar(-1),t.origin),this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection),this._groundDistance=this._intersection.distanceTo(e),this._groundOffset.copy(this._intersection).sub(e)}onDidUpdate(){re.markDirty(this._selected);for(let e of this._rbs)e.wakeUp(),e.resetForcesAndTorques(),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}},Ul=_u;A(Ul,"geometry",new q.BufferGeometry().setFromPoints([new q.Vector3(0,0,0),new q.Vector3(0,-1,0)]));var xi=class extends k{url=null;urlParameterName=null;localhost=null;awake(){this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?xi.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){let r=M(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=xi.IsLocalNetwork()&&t;return n&&(i=t),e?.startsWith("/")&&(i=(n?i:window.location.origin)+e),i}static IsLocalNetwork(e=window.location.hostname){return ei(e)}};var nr=class extends k{filesBackendUrl;localhost;_dragOver;_drop;onEnable(){this.filesBackendUrl=this.filesBackendUrl?xi.GetUrl(this.filesBackendUrl,this.localhost):void 0,this._dragOver=this.onDrag.bind(this),this._drop=this.onDrop.bind(this),this.context.domElement.addEventListener("dragover",this._dragOver),this.context.domElement.addEventListener("drop",this._drop)}onDisable(){this.context.domElement.removeEventListener("dragover",this._dragOver),this.context.domElement.removeEventListener("drop",this._drop)}onDrag(e){e.preventDefault()}async onDrop(e){if(console.log(e),!e.dataTransfer)return;e.preventDefault();let t=e.dataTransfer.items;if(!!t)for(let i in t){let n=t[i];if(n.kind==="file"){let r=n.getAsFile();if(!r)continue;console.log("Register file "+r.name+" to",this.filesBackendUrl,r);let s=await sf(r,this.context,this.filesBackendUrl);s&&this.addObject(e,s)}else n.kind==="string"&&n.type=="text/plain"&&n.getAsString(async r=>{console.log("dropped url",r);try{let s=new URL(r);if(!s)return;let a=await af(s,this.context);a&&this.addObject(e,a)}catch{console.log("dropped string is not a valid URL!",r)}})}}async addObject(e,t){console.log("Dropped",t);let i=new me;i.setMask(16777215),i.screenPointFromOffset(e.offsetX,e.offsetY);let n=this.context.physics.raycast(i),r=t.scene;if(n&&n.length>0)for(let s of n){r.position.copy(s.point);break}this.gameObject.add(r),this.dispatchEvent(new CustomEvent("object-added",{detail:t}))}};_([y()],nr.prototype,"filesBackendUrl",2),_([y()],nr.prototype,"localhost",2);import{Vector3 as Yy,Quaternion as Ky,Object3D as Jf}from"three";var Vi=class extends Gt{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 Yy(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new Ky(0,0,0,1)}let e=R.getComponentInParent(this.gameObject,Gi);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),J.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 Fe;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=R.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}};_([y(Jf)],Vi.prototype,"parent",2),_([y(Jf)],Vi.prototype,"object",2),_([y()],Vi.prototype,"limitCount",2),_([y()],Vi.prototype,"limitInterval",2);var Vo=class extends k{};import{FlyControls as Jy}from"three/examples/jsm/controls/FlyControls";var zo=class extends k{_controls=null;onEnable(){let e=R.getComponent(this.gameObject,se)?.cam;this._controls=new Jy(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 Zf from"three";import{Color as Zy}from"three";var wn=class extends k{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!Pi||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new Zf.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}};_([y()],wn.prototype,"objectBounds",2),_([y(Zy)],wn.prototype,"color",2),_([y()],wn.prototype,"isGizmo",2);import{Color as Gl,GridHelper as $y}from"three";var En=class extends k{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!Pi)return;let e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new $y(e,t,this.color0??new Gl(.4,.4,.4),this.color1??new Gl(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset),this.gameObject.add(this.gridHelper))}};_([y()],En.prototype,"isGizmo",2),_([y(Gl)],En.prototype,"color0",2),_([y(Gl)],En.prototype,"color1",2);import{GroundProjectedEnv as e_}from"three/examples/jsm/objects/GroundProjectedEnv.js";var Cn=class extends k{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.context.time.frameCount>0&&this.updateAndCreate()}start(){this.updateAndCreate()}onDisable(){this._watcher?.revoke(),this.env?.removeFromParent()}updateAndCreate(){this.updateProjection(),this._watcher||(this._watcher=new tn(this.context.scene,"environment"),this._watcher.subscribeWrite(e=>{this.updateProjection()})),this._watcher.apply()}updateProjection(){if(!this.context.scene.environment){this.env?.removeFromParent();return}(!this.env||this.context.scene.environment!==this._lastEnvironment)&&(console.log("Create/Update Ground Projection",this.context.scene.environment.name),this.env=new e_(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)}};_([y()],Cn.prototype,"scale",1),_([y()],Cn.prototype,"radius",1),_([y()],Cn.prototype,"height",1);import{Vector3 as $f}from"three";var ea=class extends k{connectedBody;get rigidBody(){return this._rigidBody}_rigidBody=null;onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(K)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.createJoint(this.rigidBody,this.connectedBody)}};_([y(K)],ea.prototype,"connectedBody",2);var Wo=class extends ea{createJoint(e,t){this.context.physics.addFixedJoint(e,t)}},rr=class extends ea{anchor;axis;createJoint(e,t){this.axis&&this.anchor&&this.context.physics.addHingeJoint(e,t,this.anchor,this.axis)}};_([y($f)],rr.prototype,"anchor",2),_([y($f)],rr.prototype,"axis",2);import*as rt from"three";import{Color as t_}from"three";function xu(o){return o*Math.PI/180}var em=300,wu=M("debuglights");var Ge=class extends k{type=0;range=1;spotAngle=1;innerSpotAngle=1;color=new rt.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;_overrideShadowBiasSettings=!1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}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 rt.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=V.addEventListener("xrStarted",this.onWebXRStarted.bind(this)),this._webXREndedListener=V.addEventListener("xrStopped",this.onWebXREnded.bind(this)))}onDisable(){V.removeEventListener("xrStarted",this._webXRStartedListener),V.removeEventListener("xrStopped",this._webXREndedListener)}_webXRStartedListener;_webXREndedListener;_webARRoot;onWebXRStarted(){this._webARRoot=R.getComponentInParent(this.gameObject,Wt)??void 0,this.startCoroutine(this._updateLightIntensityInARRoutine())}*_updateLightIntensityInARRoutine(){for(;this.context.isInAR;){yield,this.updateIntensity();for(let e=0;e<30;e++)yield}}onWebXREnded(){this.updateIntensity()}createLight(){let e=this.selfIsLight;if(e&&!this.light)switch(this.light=this.gameObject,this.type){case 1:this.setDirectionalLight(this.light);break}else if(!this.light)switch(this.type){case 1:let t=new rt.DirectionalLight(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-em*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),sn(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),wu){let s=new rt.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(s)}break;case 0:let i=new rt.SpotLight(this.color,this.intensity*Math.PI,this.range,xu(this.spotAngle/2),1-xu(this.innerSpotAngle/2)/xu(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 rt.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=r;break}if(this.light){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),wu&&console.log("Override shadow bias?",this._overrideShadowBiasSettings,this.shadowBias,this.shadowNormalBias),this._overrideShadowBiasSettings===!0?(this.light.shadow.bias=this.shadowBias,this.light.shadow.normalBias=this.shadowNormalBias):(this.light.shadow.bias=this.shadowBias*1e-5,this.light.shadow.normalBias=this.shadowNormalBias*1e-4),this.updateShadowSoftHard();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=em*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,wu&&this.context.scene.add(new rt.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}}updateShadowSoftHard(){!this.light||this.shadows===2||(this.light.shadow.radius=1,this.light.shadow.blurSamples=1)}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}};A(Ge,"allowChangingRendererShadowMapType",!0),_([y()],Ge.prototype,"type",2),_([y(t_)],Ge.prototype,"color",2),_([y()],Ge.prototype,"shadowNearPlane",1),_([y()],Ge.prototype,"shadowBias",1),_([y()],Ge.prototype,"shadowNormalBias",1),_([y()],Ge.prototype,"shadows",1),_([y()],Ge.prototype,"lightmapBakeType",2),_([y()],Ge.prototype,"intensity",1),_([y()],Ge.prototype,"shadowDistance",1),_([y()],Ge.prototype,"shadowResolution",1);var SD=new rt.Vector3(0,0,0);import*as Vl from"three";import{Vector3 as i_}from"three";var No=M("debugLODs"),n_=M("noLODs");var zi=class{screenRelativeTransitionHeight;distance;renderers};_([y()],zi.prototype,"screenRelativeTransitionHeight",2),_([y()],zi.prototype,"distance",2),_([y()],zi.prototype,"renderers",2);var Eu=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):No&&console.warn("Renderer not found: "+i,e.gameObject)}}findRenderer(e,t){let i=R.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}},or=class extends k{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(!n_&&!this._lodsHandler&&!!this.gameObject&&(No&&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 Eu(this,n);this._lods.push(r);for(let s of r.renderers)t.includes(s)||t.push(s)}this._lodsHandler=new Array;for(let n=0;n<t.length;n++){let r=new Vl.LOD;this._lodsHandler.push(r),this.gameObject.add(r)}let i=new Vl.Object3D;No&&console.log(t);for(let n=0;n<t.length;n++){let r=t[n],s=this._lodsHandler[n],a=r.gameObject,c=0,d=0;No&&console.log(n,a.name);for(let u of this._lods){let h=null;u.renderers.includes(r)?h=a:h=i,No&&console.log("add",u.model.distance,h.name);let b=u.model.distance;d=b-c,c=Math.max(b,c),this.onAddLodLevel(s,h,b)}let l=c+d;No&&console.log("cull",l),this.onAddLodLevel(s,i,l)}}}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}}}};_([y(i_)],or.prototype,"localReferencePoint",2),_([y(zi)],or.prototype,"lodModels",2);var Cu=M("debugnestedgltf"),Nr=class extends k{filePath;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){this.filePath?.preload()}async start(){if(this._isLoadingOrDoneLoading)return;Cu&&console.log(this,this.guid);let e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;let t=new Fe;t.idProvider=new Ie(this.hash(this.guid)),t.parent=e,this.gameObject.updateMatrix();let i=this.gameObject.matrix;Cu&&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,n.layers.disableAll(),n.layers.set(this.layer)),this.destroy(),Cu&&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}};_([y(Ze)],Nr.prototype,"filePath",2);import{Quaternion as r_,Euler as o_,Vector3 as Xr,Plane as s_}from"three";var Wi=class extends k{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new Xr(0,0,0);rotationOffset=new Xr(0,0,0);offset=new Xr(0,0,0);update(){if(!this.from)return;var e=B(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 a=new s_(this.gameObject.up,0),c=B(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,c);let d=new Xr(0,0,0);a.projectPoint(e,d),e.copy(d)}this.affectPosition&&te(this.gameObject,e);let n=new o_(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),r=new r_().setFromEuler(n);this.affectRotation&&Ke(this.gameObject,t.multiply(r));let s=new Xr;this.from.getWorldDirection(s).multiplyScalar(50),this.levelLookDirection&&(s.y=0),this.alignLookDirection&&this.gameObject.lookAt(s)}};_([y(R)],Wi.prototype,"referenceSpace",2),_([y(R)],Wi.prototype,"from",2),_([y(Xr)],Wi.prototype,"positionOffset",2),_([y(Xr)],Wi.prototype,"rotationOffset",2);import*as qo from"three";import{Matrix4 as tm,Quaternion as a_,Vector3 as qe,Vector2 as im,Euler as l_}from"three";import{createNoise4D as c_}from"simplex-noise";var Ei=class{alphaKeys;colorKeys;get duration(){return 1}evaluate(e,t){let i,n=0,r=null,s=0;for(let a=0;a<this.alphaKeys.length;a++){let c=this.alphaKeys[a];(c.time<e||!i)&&(i=c,n=a)}for(let a=0;a<this.colorKeys.length;a++){let c=this.colorKeys[a];(c.time<e||!r)&&(r=c,s=a)}if(r)if(s+1<this.colorKeys.length){let c=this.colorKeys[s+1],d=H.remap(e,r.time,c.time,0,1);t.r=H.lerp(r.color.r,c.color.r,d),t.g=H.lerp(r.color.g,c.color.g,d),t.b=H.lerp(r.color.b,c.color.b,d)}else t.r=r.color.r,t.g=r.color.g,t.b=r.color.b;if(i)if(n+1<this.alphaKeys.length){let c=this.alphaKeys[n+1],d=H.remap(e,i.time,c.time,0,1);t.alpha=H.lerp(i.alpha,c.alpha,d)}else t.alpha=i.alpha;return t}};_([y()],Ei.prototype,"alphaKeys",2),_([y()],Ei.prototype,"colorKeys",2);var nm=(E=>(E[E.Sphere=0]="Sphere",E[E.SphereShell=1]="SphereShell",E[E.Hemisphere=2]="Hemisphere",E[E.HemisphereShell=3]="HemisphereShell",E[E.Cone=4]="Cone",E[E.Box=5]="Box",E[E.Mesh=6]="Mesh",E[E.ConeShell=7]="ConeShell",E[E.ConeVolume=8]="ConeVolume",E[E.ConeVolumeShell=9]="ConeVolumeShell",E[E.Circle=10]="Circle",E[E.CircleEdge=11]="CircleEdge",E[E.SingleSidedEdge=12]="SingleSidedEdge",E[E.MeshRenderer=13]="MeshRenderer",E[E.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",E[E.BoxShell=15]="BoxShell",E[E.BoxEdge=16]="BoxEdge",E[E.Donut=17]="Donut",E[E.Rectangle=18]="Rectangle",E[E.Sprite=19]="Sprite",E[E.SpriteRenderer=20]="SpriteRenderer",E))(nm||{});var U=class{mode;constant;constantMin;constantMax;curve;curveMin;curveMax;curveMultiplier;evaluate(e,t){let i=t===void 0?Math.random():t;switch(this.mode){case 0:return this.constant;case 1:return e=H.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:let n=e*this.curveMin.duration,r=e*this.curveMax.duration;return H.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(r),i%1)*this.curveMultiplier;case 3:return H.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(e)*this.curveMultiplier;break}return 0}};_([y()],U.prototype,"mode",2),_([y()],U.prototype,"constant",2),_([y()],U.prototype,"constantMin",2),_([y()],U.prototype,"constantMax",2),_([y(hi)],U.prototype,"curve",2),_([y(hi)],U.prototype,"curveMin",2),_([y(hi)],U.prototype,"curveMax",2),_([y()],U.prototype,"curveMultiplier",2);var Qt=class{mode;color;colorMin;colorMax;gradient;gradientMin;gradientMax;evaluate(e,t){let i=t===void 0?Math.random():t;switch(this.mode){case 0:return this.color;case 1:return this.gradient.evaluate(e,Qt._temp),Qt._temp;case 2:return Qt._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:return this.gradientMin.evaluate(e,Qt._temp),this.gradientMax.evaluate(e,Qt._temp2),Qt._temp.lerp(Qt._temp2,i)}return Qt._temp.set(16711935),Qt._temp.alpha=1,Qt._temp}},Oe=Qt;A(Oe,"_temp",new Z(0,0,0,1)),A(Oe,"_temp2",new Z(0,0,0,1)),_([y(Z)],Oe.prototype,"color",2),_([y(Z)],Oe.prototype,"colorMin",2),_([y(Z)],Oe.prototype,"colorMax",2),_([y(Ei)],Oe.prototype,"gradient",2),_([y(Ei)],Oe.prototype,"gradientMin",2),_([y(Ei)],Oe.prototype,"gradientMax",2);var ye=class{cullingMode;duration;emitterVelocityMode;flipRotation;gravityModifier;gravityModifierMultiplier;loop;maxParticles;playOnAwake;prewarm;ringBufferLoopRange;ringBufferMode;scalingMode;simulationSpace;simulationSpeed;startColor;startDelay;startDelayMultiplier;startLifetime;startLifetimeMultiplier;startRotation;startRotationMultiplier;startRotation3D;startRotationX;startRotationXMultiplier;startRotationY;startRotationYMultiplier;startRotationZ;startRotationZMultiplier;startSize;startSize3D;startSizeMultiplier;startSizeX;startSizeXMultiplier;startSizeY;startSizeYMultiplier;startSizeZ;startSizeZMultiplier;startSpeed;startSpeedMultiplier;stopAction;useUnscaledTime};_([y(U)],ye.prototype,"gravityModifier",2),_([y(Oe)],ye.prototype,"startColor",2),_([y(U)],ye.prototype,"startDelay",2),_([y(U)],ye.prototype,"startLifetime",2),_([y(U)],ye.prototype,"startRotation",2),_([y(U)],ye.prototype,"startRotationX",2),_([y(U)],ye.prototype,"startRotationY",2),_([y(U)],ye.prototype,"startRotationZ",2),_([y(U)],ye.prototype,"startSize",2),_([y(U)],ye.prototype,"startSizeX",2),_([y(U)],ye.prototype,"startSizeY",2),_([y(U)],ye.prototype,"startSizeZ",2),_([y(U)],ye.prototype,"startSpeed",2);var Rn=class{cycleCount;maxCount;minCount;probability;repeatInterval;time;count;_performed=0;reset(){this._performed=0}run(e){if(e<=this.time)return this.reset(),0;let t=0;if(this.cycleCount===0||this._performed<this.cycleCount){let i=this.time+this.repeatInterval*this._performed;if(e>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=H.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:let n=Math.random();t=H.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return t}},pt=class{enabled;get burstCount(){return this.bursts?.length??0}bursts;rateOverTime;rateOverTimeMultiplier;rateOverDistance;rateOverDistanceMultiplier;system;reset(){this.bursts?.forEach(e=>e.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){let i=this.bursts[t];i.time>=this.system.time&&i.reset(),e+=Math.round(i.run(this.system.time))}return e}};_([y()],pt.prototype,"enabled",2),_([y()],pt.prototype,"bursts",2),_([y(U)],pt.prototype,"rateOverTime",2),_([y()],pt.prototype,"rateOverTimeMultiplier",2),_([y(U)],pt.prototype,"rateOverDistance",2),_([y()],pt.prototype,"rateOverDistanceMultiplier",2);var Tn=class{enabled;color};_([y(Oe)],Tn.prototype,"color",2);var qt=class{enabled;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_time=0;_temp=new qe;evaluate(e,t,i){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,i)*this.xMultiplier,t.y=this.y.evaluate(e,i)*this.yMultiplier,t.z=this.z.evaluate(e,i)*this.zMultiplier;else{let n=this.size.evaluate(e,i)*this.sizeMultiplier;t.x=n}return t}};_([y(U)],qt.prototype,"size",2),_([y(U)],qt.prototype,"x",2),_([y(U)],qt.prototype,"y",2),_([y(U)],qt.prototype,"z",2);var Xo=class{get type(){return nm[this.shapeType]}initialize(e){this.getPosition(),e.position.copy(this._vector)}toJSON(){return this}clone(){return new Xo}shapeType=5;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcSpread;arcSpeedMultiplier;arcMode;boxThickness;position;rotation;_rotation=new l_;scale;radius;radiusThickness;sphericalDirectionAmount;randomDirectionAmount;randomPositionAmount;system;_space;_worldSpaceMatrix=new tm;_worldSpaceMatrixInverse=new tm;constructor(){}update(e,t,i,n){this.system=e,this._space=i,i===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}_vector=new qe(0,0,0);_temp=new qe(0,0,0);get vector(){return this._vector}getPosition(){if(!this.enabled){this._vector.set(0,0,0);return}let e=this._temp.copy(this.position),t=this._space===1;t&&e.applyQuaternion(this.system.worldQuaternion);let i=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;i&&(this._rotation.x=H.toRadians(this.rotation.x),this._rotation.y=-H.toRadians(this.rotation.y),this._rotation.z=-H.toRadians(this.rotation.z));let n=this.radius;switch(t&&(n*=this.system.worldScale.x),this.shapeType){case 5:this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(e);break;case 4:this.randomConePoint(this.position,this.angle,n,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector),this._vector.x*=this.scale.x,this._vector.y*=this.scale.y,this._vector.z*=this.scale.z;break;case 10:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector),this._vector.x*=this.scale.x,this._vector.y*=this.scale.y,this._vector.z*=0;break;default:this._vector.set(0,0,0);break}this.randomizePosition(this._vector,this.randomPositionAmount),i&&this._vector.applyEuler(this._rotation),this._space===1&&this._vector.add(this.system.worldPos)}_dir=new qe;getDirection(e){if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:let t=e.x,i=e.y,n=e.z;this._dir.set(t,i,n).sub(this.position);break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyMatrix4(this._worldSpaceMatrixInverse),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),this._dir}randomizePosition(e,t){if(t<=0)return;let i=Xo._tempVec;i.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),i.x*=t*this.scale.x,i.y*=t*this.scale.y,i.z*=t*this.scale.z,e.add(i)}randomizeDirection(e,t){if(t===0)return;console.log("randomizeDirection",t);let i=Xo._randomQuat,n=Xo._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),e.applyQuaternion(i)}spherizeDirection(e,t){if(t===0)return;let i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),r=Math.sin(n)*Math.cos(i),s=Math.sin(n)*Math.sin(i),a=Math.cos(n),c=new qe(r,s,a);e.lerp(c,t)}randomSpherePoint(e,t,i,n,r){let s=Math.random(),a=Math.random(),c=2*Math.PI*s*(n/360),d=Math.acos(2*a-1),l=H.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,u=e.x+-l*Math.sin(d)*Math.cos(c),h=e.y+l*Math.sin(d)*Math.sin(c),b=e.z+l*Math.cos(d);r.x=u,r.y=h,r.z=b}_loopTime=0;_loopDirection=1;randomConePoint(e,t,i,n,r,s,a){let c=0,d=0;switch(s){case 0:c=Math.random(),d=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:c=.5,d=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let l=2*Math.PI*c*(r/360);switch(s){case 2:case 1:l+=Math.PI+.5,l+=this._loopTime*Math.PI*2,l%=H.toRadians(r);break}let u=Math.acos(2*d-1),h=H.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,b=e.x+-h*Math.sin(u)*Math.cos(l),w=e.y+h*Math.sin(u)*Math.sin(l),v=e.z;a.x=b*this.scale.x,a.y=w*this.scale.y,a.z=v*this.scale.z}},ie=Xo;A(ie,"_randomQuat",new a_),A(ie,"_tempVec",new qe),_([y()],ie.prototype,"shapeType",2),_([y()],ie.prototype,"enabled",2),_([y()],ie.prototype,"alignToDirection",2),_([y()],ie.prototype,"angle",2),_([y()],ie.prototype,"arc",2),_([y()],ie.prototype,"arcSpread",2),_([y()],ie.prototype,"arcSpeedMultiplier",2),_([y()],ie.prototype,"arcMode",2),_([y(qe)],ie.prototype,"boxThickness",2),_([y(qe)],ie.prototype,"position",2),_([y(qe)],ie.prototype,"rotation",2),_([y(qe)],ie.prototype,"scale",2),_([y()],ie.prototype,"radius",2),_([y()],ie.prototype,"radiusThickness",2),_([y()],ie.prototype,"sphericalDirectionAmount",2),_([y()],ie.prototype,"randomDirectionAmount",2),_([y()],ie.prototype,"randomPositionAmount",2);var Y=class{damping;enabled;frequency;octaveCount;octaveMultiplier;octaveScale;positionAmount;quality;remap;remapEnabled;remapMultiplier;remapX;remapXMultiplier;remapY;remapYMultiplier;remapZ;remapZMultiplier;scrollSpeedMultiplier;separateAxes;strengthMultiplier;strengthX;strengthXMultiplier;strengthY;strengthYMultiplier;strengthZ;strengthZMultiplier;_noise;_time=0;update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}_temp=new qe;apply(e,t,i,n,r,s){if(!this.enabled)return;this._noise||(this._noise=c_(()=>0));let a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),c=this._noise(a.x,a.y,a.z,this._time),d=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),l=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(c,d,l).normalize();let u=r/s,h=this.positionAmount.evaluate(u);this.separateAxes?(this._temp.x*=h*this.strengthXMultiplier,this._temp.y*=h*this.strengthYMultiplier,this._temp.z*=h*this.strengthZMultiplier):(this.strengthX&&(h*=this.strengthX.evaluate(u)*1.5),this._temp.multiplyScalar(h)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}};_([y()],Y.prototype,"damping",2),_([y()],Y.prototype,"enabled",2),_([y()],Y.prototype,"frequency",2),_([y()],Y.prototype,"octaveCount",2),_([y()],Y.prototype,"octaveMultiplier",2),_([y()],Y.prototype,"octaveScale",2),_([y(U)],Y.prototype,"positionAmount",2),_([y()],Y.prototype,"quality",2),_([y(U)],Y.prototype,"remap",2),_([y()],Y.prototype,"remapEnabled",2),_([y()],Y.prototype,"remapMultiplier",2),_([y(U)],Y.prototype,"remapX",2),_([y()],Y.prototype,"remapXMultiplier",2),_([y(U)],Y.prototype,"remapY",2),_([y()],Y.prototype,"remapYMultiplier",2),_([y(U)],Y.prototype,"remapZ",2),_([y()],Y.prototype,"remapZMultiplier",2),_([y()],Y.prototype,"scrollSpeedMultiplier",2),_([y()],Y.prototype,"separateAxes",2),_([y()],Y.prototype,"strengthMultiplier",2),_([y(U)],Y.prototype,"strengthX",2),_([y()],Y.prototype,"strengthXMultiplier",2),_([y(U)],Y.prototype,"strengthY",2),_([y()],Y.prototype,"strengthYMultiplier",2),_([y(U)],Y.prototype,"strengthZ",2),_([y()],Y.prototype,"strengthZMultiplier",2);var ee=class{enabled;attachRibbonToTransform=!1;colorOverLifetime;colorOverTrail;dieWithParticles=!0;inheritParticleColor=!0;lifetime;lifetimeMultiplier;minVertexDistance=.2;mode=0;ratio=1;ribbonCount=1;shadowBias=0;sizeAffectsLifetime=!1;sizeAffectsWidth=!1;splitSubEmitterRibbons=!1;textureMode=0;widthOverTrail;widthOverTrailMultiplier;worldSpace=!1;getWidth(e,t,i){let n=this.widthOverTrail.evaluate(i);return i===0&&(n=e),e*=n,e}getColor(e,t,i){let n=this.colorOverTrail.evaluate(i),r=this.colorOverLifetime.evaluate(t);e.x*=n.r*r.r,e.y*=n.g*r.g,e.z*=n.b*r.b,e.w*=n.alpha*r.alpha}};_([y()],ee.prototype,"enabled",2),_([y()],ee.prototype,"attachRibbonToTransform",2),_([y(Oe)],ee.prototype,"colorOverLifetime",2),_([y(Oe)],ee.prototype,"colorOverTrail",2),_([y()],ee.prototype,"dieWithParticles",2),_([y()],ee.prototype,"inheritParticleColor",2),_([y(U)],ee.prototype,"lifetime",2),_([y()],ee.prototype,"lifetimeMultiplier",2),_([y()],ee.prototype,"minVertexDistance",2),_([y()],ee.prototype,"mode",2),_([y()],ee.prototype,"ratio",2),_([y()],ee.prototype,"ribbonCount",2),_([y()],ee.prototype,"shadowBias",2),_([y()],ee.prototype,"sizeAffectsLifetime",2),_([y()],ee.prototype,"sizeAffectsWidth",2),_([y()],ee.prototype,"splitSubEmitterRibbons",2),_([y()],ee.prototype,"textureMode",2),_([y(U)],ee.prototype,"widthOverTrail",2),_([y()],ee.prototype,"widthOverTrailMultiplier",2),_([y()],ee.prototype,"worldSpace",2);var je=class{enabled;space=0;speedModifier;speedModifierMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_system;update(e){this._system=e}_temp=new qe;apply(e,t,i,n,r,s){if(!this.enabled)return;let a=r/s,c=this.speedModifier.evaluate(a)*this.speedModifierMultiplier,d=this.x.evaluate(a),l=this.y.evaluate(a),u=this.z.evaluate(a);this._temp.set(-d,l,u),this._system&&(this.space===1&&this._temp.applyQuaternion(this._system.worldQuaternionInverted),this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z,i.x*=c,i.y*=c,i.z*=c}};_([y()],je.prototype,"enabled",2),_([y()],je.prototype,"space",2),_([y(U)],je.prototype,"speedModifier",2),_([y()],je.prototype,"speedModifierMultiplier",2),_([y(U)],je.prototype,"x",2),_([y()],je.prototype,"xMultiplier",2),_([y(U)],je.prototype,"y",2),_([y()],je.prototype,"yMultiplier",2),_([y(U)],je.prototype,"z",2),_([y()],je.prototype,"zMultiplier",2);var _e=class{animation;enabled;cycleCount;frameOverTime;frameOverTimeMultiplier;numTilesX;numTilesY;startFrame;startFrameMultiplier;rowMode;rowIndex;spriteCount;timeMode;sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?this.frameOverTime.evaluate(Math.random()):0}evaluate(e){if(!this.sampleOnceAtStart())return this.getIndex(e)}getIndex(e){let t=this.numTilesX*this.numTilesY,i=this.frameOverTime.evaluate(e%1);return i*=this.frameOverTimeMultiplier,i*=t,i=i%t,i=Math.floor(i),i}};_([y()],_e.prototype,"animation",2),_([y()],_e.prototype,"enabled",2),_([y()],_e.prototype,"cycleCount",2),_([y(U)],_e.prototype,"frameOverTime",2),_([y()],_e.prototype,"frameOverTimeMultiplier",2),_([y()],_e.prototype,"numTilesX",2),_([y()],_e.prototype,"numTilesY",2),_([y(U)],_e.prototype,"startFrame",2),_([y()],_e.prototype,"startFrameMultiplier",2),_([y()],_e.prototype,"rowMode",2),_([y()],_e.prototype,"rowIndex",2),_([y()],_e.prototype,"spriteCount",2),_([y()],_e.prototype,"timeMode",2);var Qe=class{enabled;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e){return this.enabled?this.separateAxes?0:this.z.evaluate(e)*-1:0}};_([y()],Qe.prototype,"enabled",2),_([y()],Qe.prototype,"separateAxes",2),_([y(U)],Qe.prototype,"x",2),_([y()],Qe.prototype,"xMultiplier",2),_([y(U)],Qe.prototype,"y",2),_([y()],Qe.prototype,"yMultiplier",2),_([y(U)],Qe.prototype,"z",2),_([y()],Qe.prototype,"zMultiplier",2);var Ve=class{enabled;range;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){let i=H.lerp(this.range.x,this.range.y,t);return this.z.evaluate(i)*-1}return 0}};_([y()],Ve.prototype,"enabled",2),_([y()],Ve.prototype,"range",2),_([y()],Ve.prototype,"separateAxes",2),_([y(U)],Ve.prototype,"x",2),_([y()],Ve.prototype,"xMultiplier",2),_([y(U)],Ve.prototype,"y",2),_([y()],Ve.prototype,"yMultiplier",2),_([y(U)],Ve.prototype,"z",2),_([y()],Ve.prototype,"zMultiplier",2);var de=class{enabled;dampen;drag;dragMultiplier;limit;limitMultiplier;separateAxes;limitX;limitXMultiplier;limitY;limitYMultiplier;limitZ;limitZMultiplier;multiplyDragByParticleSize=!1;multiplyDragByParticleVelocity=!1;space;_temp=new qe;_temp2=new qe;apply(e,t,i,n,r,s,a){if(!!this.enabled){let c=this.limit.evaluate(r)*this.limitMultiplier;if(t.length()>c){this._temp.copy(t).normalize().multiplyScalar(c);let l=this.dampen*.5;t.x=H.lerp(t.x,this._temp.x,l),t.y=H.lerp(t.y,this._temp.y,l),t.z=H.lerp(t.z,this._temp.z,l),i.x=H.lerp(i.x,this._temp.x,l),i.y=H.lerp(i.y,this._temp.y,l),i.z=H.lerp(i.z,this._temp.z,l)}}}};_([y()],de.prototype,"enabled",2),_([y()],de.prototype,"dampen",2),_([y(U)],de.prototype,"drag",2),_([y()],de.prototype,"dragMultiplier",2),_([y(U)],de.prototype,"limit",2),_([y()],de.prototype,"limitMultiplier",2),_([y()],de.prototype,"separateAxes",2),_([y(U)],de.prototype,"limitX",2),_([y()],de.prototype,"limitXMultiplier",2),_([y(U)],de.prototype,"limitY",2),_([y()],de.prototype,"limitYMultiplier",2),_([y(U)],de.prototype,"limitZ",2),_([y()],de.prototype,"limitZMultiplier",2),_([y()],de.prototype,"multiplyDragByParticleSize",2),_([y()],de.prototype,"multiplyDragByParticleVelocity",2),_([y()],de.prototype,"space",2);var Yt=class{enabled;curve;curveMultiplier;mode;system;_lastWorldPosition;_velocity=new qe;_temp=new qe;update(e){!this.enabled||this.system.worldspace!==!1&&(this._lastWorldPosition?(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)):(this._velocity.set(0,0,0),this._lastWorldPosition=this.system.worldPos.clone()))}applyInitial(e){if(!!this.enabled&&this.system.worldspace!==!1&&this.mode===0){let t=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(t),e.add(this._temp)}}applyCurrent(e,t,i){if(!!this.enabled&&this.system.worldspace!==!1&&this.mode===1){let n=this.curve.evaluate(t,i);this._temp.copy(this._velocity).multiplyScalar(n),e.add(this._temp)}}};_([y()],Yt.prototype,"enabled",2),_([y(U)],Yt.prototype,"curve",2),_([y()],Yt.prototype,"curveMultiplier",2),_([y()],Yt.prototype,"mode",2);var Pe=class{enabled;range;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t,i,n){let r=e.length(),s=H.remap(r,this.range.x,this.range.y,0,1),a=this.size.evaluate(s,i);return n*a}};_([y()],Pe.prototype,"enabled",2),_([y(im)],Pe.prototype,"range",2),_([y()],Pe.prototype,"separateAxes",2),_([y(U)],Pe.prototype,"size",2),_([y()],Pe.prototype,"sizeMultiplier",2),_([y(U)],Pe.prototype,"x",2),_([y()],Pe.prototype,"xMultiplier",2),_([y(U)],Pe.prototype,"y",2),_([y()],Pe.prototype,"yMultiplier",2),_([y(U)],Pe.prototype,"z",2),_([y()],Pe.prototype,"zMultiplier",2);var wi=class{enabled;range;color;evaluate(e,t,i){let n=e.length(),r=H.remap(n,this.range.x,this.range.y,0,1),s=this.color.evaluate(r,t);i.x*=s.r,i.y*=s.g,i.z*=s.b,i.w*=s.alpha}};_([y()],wi.prototype,"enabled",2),_([y(im)],wi.prototype,"range",2),_([y(Oe)],wi.prototype,"color",2);import{AxesHelper as u_,Material as rm,Mesh as om,Object3D as h_,Quaternion as Ru,Vector3 as ta,Vector4 as p_}from"three";import{BatchedParticleRenderer as f_,ConstantColor as m_,ConstantValue as g_,ParticleSystem as b_,RenderMode as Wl,TrailParticle as sm}from"three.quarks";import{Vector3 as zl,Quaternion as d_,Matrix4 as Tu}from"three";var h1=new zl(1,1,1),p1=new zl(0,0,1),f1=Symbol("emitterMatrix"),sr=class{constructor(e,t,i,n){this.system=e;this.particleSystem=t;this.subSystem=i;this.subParticleSystem=n;this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);let r=1e3;this._circularBuffer=new Ti(()=>new Tu,r)}type="NeedleParticleSubEmitter";q_=new d_;v_=new zl;v2_=new zl;_emitterMatrix=new Tu;_circularBuffer;clone(){throw new Error("Method not implemented.")}initialize(e){e.emissionState={burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0},this._emitterMatrix.copy(this.subSystem.matrixWorld).invert().premultiply(this.system.matrixWorld)}update(e,t){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!e.emissionState)return;let i=new Tu;i.set(1,0,0,e.position.x,0,1,0,e.position.y,0,0,1,e.position.z,0,0,0,1),this.particleSystem.worldSpace||i.multiplyMatrices(this._emitterMatrix,i),this.subParticleSystem.emit(t,e.emissionState,i)}frameUpdate(e){}toJSON(){}};var hm=M("debugparticles"),ar=class{particleSystem;_deserialize(e){let t=this.particleSystem;t&&!(t instanceof ge)&&typeof t.guid=="string"&&(hm&&console.log("DESERIALIZE SUBEMITTER",t),this.particleSystem=void 0,this.particleSystem=R.findByGuid(t.guid,e.scene))}},Ni=class extends k{renderMode;particleMaterial;trailMaterial;particleMesh;get transparent(){return this.particleMaterial?.transparent??!1}getMaterial(e=!1){return e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial}getMesh(){let e=null;return this.particleMesh instanceof om&&(e=this.particleMesh.geometry),e===null&&(e=new qo.BoxGeometry(1,1,1)),new om(e,this.getMaterial())}};_([y()],Ni.prototype,"renderMode",2),_([y(rm)],Ni.prototype,"particleMaterial",2),_([y(rm)],Ni.prototype,"trailMaterial",2);var Qo=class{_curve;constructor(e){this._curve=e}type="function";genValue(e){return this._curve.evaluate(e,Math.random())}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}};var ia=class{type="value";toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}system;constructor(e){this.system=e}},Su=class extends ia{genValue(){return this.system.textureSheetAnimation.getStartIndex()}},Pu=class extends ia{_lastPosition=new ta;_lastDistance=0;update(){let e=B(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){let n=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random()),s=this._lastDistance/this.system.deltaTime*n;Number.isFinite(s)||(s=0),e+=s}let t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);let i=this.system.maxParticles-this.system.currentParticles;return H.clamp(e,0,i/this.system.deltaTime)}},Ou=class extends ia{genValue(){return 0}},lr=class{system;get scaleFactorDiff(){return this.system.worldScale.x-this.system.scale}constructor(e){this.system=e}initialize(e){}update(e,t){}frameUpdate(e){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}},ku=class extends lr{type="NeedleTextureSheet";update(e,t){let i=this.system.textureSheetAnimation;if(i.enabled){let n=e.age/e.life,r=i.evaluate(n);r!==void 0&&(e.uvTile=r)}}},Mu=class extends lr{type="NeedleRotation";update(e,t){if(e.rotation===void 0)return;let i=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(i)*t:this.system.renderer.renderMode===0&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){let n=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(i,n)*t}}},am=Symbol("sizeLerpFactor"),Iu=class extends lr{type="NeedleSize";initialize(e){e[am]=Math.random()}update(e,t){if(this.system.renderer.renderMode!==4){let i=e.age/e.life,n=1;this.system.sizeOverLifetime.enabled&&(n*=this.system.sizeOverLifetime.evaluate(i,void 0,e[am]).x);let r=this.system.worldScale.x/this.system.cameraScale;e.size=e.startSize*n*r}}},Nl=Symbol("particleLife"),Xl=Symbol("trailLifetime"),lm=Symbol("trailStartLength"),Au=class extends lr{type="NeedleTrail";initialize(e){e instanceof sm&&(e[Nl]=e.life,e[Xl]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[Xl]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[Xl]),e[lm]=e.length)}update(e){if(this.system.trails?.enabled&&e instanceof sm){let t=e,i=e.age/e[Nl],n=e.previous.values(),r=e.previous.length;for(let s=0;s<r;s++){let c=n.next().value,d=1-s/(r-1);c.size=this.system.trails.getWidth(e.size,i,d),c.color.copy(e.color),this.system.trails.getColor(c.color,i,d)}if(e.age>e[Nl]){e.velocity.set(0,0,0);let s=(e.age-e[Nl])/e[Xl];t.length=H.lerp(e[lm],0,s)}}}},Ql=Symbol("startVelocity"),cm=Symbol("gravityModifier"),ql=Symbol("velocity lerp factor"),dm=new ta,dL=new Ru,Du=class extends lr{type="NeedleVelocity";_gravityDirection=new ta;initialize(e){let t=1+this.scaleFactorDiff;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random())*t,e.velocity.copy(this.system.shape.getDirection(e.position)).multiplyScalar(e.startSpeed),this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[Ql]?e[Ql].copy(e.velocity):e[Ql]=e.velocity.clone();let i=this.system.main.gravityModifier.evaluate(Math.random(),Math.random())/(9.81*2);e[cm]=i,e[ql]=Math.random(),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===0&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted)}update(e,t){let i=e[Ql],n=e[cm];n!==0&&(dm.copy(this._gravityDirection).multiplyScalar(n),i.add(dm)),e.velocity.copy(i);let r=e.age/e.life;this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,r,e[ql]);let s=this.system.noise;s.enabled&&s.apply(0,e.position,e.velocity,t,e.age,e.life);let a=this.system.sizeBySpeed;a?.enabled&&(e.size=a.evaluate(e.velocity,r,e[ql],e.size));let c=this.system.colorBySpeed;c?.enabled&&c.evaluate(e.velocity,e[ql],e.color);let d=this.system.velocityOverLifetime;d.enabled&&d.apply(0,e.position,e.velocity,t,e.age,e.life);let l=this.system.limitVelocityOverLifetime;l.enabled&&l.apply(e.position,i,e.velocity,e.size,r,t,1)}},um=Symbol("colorLerpFactor"),Lu=class extends lr{type="NeedleColor";initialize(e){let t=this.system.main.startColor.evaluate(e.age/e.life,Math.random());e.startColor.set(t.r,t.g,t.b,t.alpha),e.color.copy(e.startColor),e[um]=Math.random()}update(e,t){if(this.system.colorOverLifetime.enabled){let i=e.age/e.life,n=this.system.colorOverLifetime.color.evaluate(i,e[um]);e.color.set(n.r,n.g,n.b,n.alpha).multiply(e.startColor)}else e.color.copy(e.startColor)}},ju=class{system;emission;get anim(){return this.system.textureSheetAnimation}constructor(e){this.system=e,this.emission=new Pu(this.system)}update(){this.emission.update()}autoDestroy;get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new Qo(this.system.main.startLifetime)}get startSpeed(){return new Qo(this.system.main.startSpeed)}get startRotation(){return new Qo(this.system.main.startRotation)}get startSize(){return new Qo(this.system.main.startSize)}startLength;get startColor(){return new m_(new p_(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new Ou(this.system)}emissionBursts;onlyUsedByOther;behaviors=[];get instancingGeometry(){return this.system.renderer.getMesh().geometry}get renderMode(){if(this.system.trails.enabled===!0)return Wl.Trail;switch(this.system.renderer.renderMode){case 0:return Wl.BillBoard;case 4:return Wl.LocalSpace}return Wl.BillBoard}rendererEmitterSettings={startLength:new g_(220),followLocalOrigin:!1};get speedFactor(){return this.system.main.simulationSpeed}get texture(){let e=this.system.renderer.getMaterial(this.system.trails.enabled);if(e&&e.map){let t=e.map;return t.premultiplyAlpha=!1,t.encoding=qo.LinearEncoding,t}return ol(new Z(1,1,1,1),1)}get startTileIndex(){return new Su(this.system)}get uTileCount(){return this.anim.enabled?this.anim?.numTilesX:void 0}get vTileCount(){return this.anim.enabled?this.anim?.numTilesY:void 0}get renderOrder(){return 1}get blending(){return this.system.renderer.particleMaterial?.blending??qo.NormalBlending}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===1}},Hu=class{burstIndex=0;burstWaveIndex=0;time=0;waitEmiting=0},Fu=class extends k{play(e=!1){e&&R.foreachComponent(this.gameObject,t=>{t instanceof Fu&&t!==this&&t.play(!1)},!0),this._isPlaying=!0,this._time=0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),this.emission?.reset()}pause(){this._isPlaying=!1}stop(){this._isPlaying=!1,this._time=0}_state;emit(e){if(this._particleSystem){e=Math.min(e,this.maxParticles-this.currentParticles),this._state||(this._state=new Hu),this._state.waitEmiting=e,this._state.time=0;let t=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=t}}colorOverLifetime;main;emission;sizeOverLifetime;shape;noise;trails;velocityOverLifetime;limitVelocityOverLifetime;inheritVelocity;colorBySpeed;textureSheetAnimation;rotationOverLifetime;rotationBySpeed;sizeBySpeed;get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){return this._particleSystem?.particleNum??0}get maxParticles(){return this.main.maxParticles}get time(){return this._time}get duration(){return this.main.duration}get deltaTime(){return this.context.time.deltaTime*this.main.simulationSpeed}get scale(){return this.gameObject.scale.x}get cameraScale(){return this._cameraScale}_cameraScale=1;get container(){return this._container}get worldspace(){return this.main.simulationSpace===1}__worldQuaternion=new Ru;get worldQuaternion(){return this.__worldQuaternion}_worldQuaternionInverted=new Ru;get worldQuaternionInverted(){return this._worldQuaternionInverted}_worldScale=new ta;get worldScale(){return this._worldScale}_worldPositionFrame=-1;_worldPos=new ta;get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,B(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}_renderer;_batchSystem;_particleSystem;_interface;_container;_time=0;_isPlaying=!0;_isUsedAsSubsystem=!1;set bursts(e){for(let t=0;t<e.length;t++){let i=e[t];if(!(i instanceof Rn)){let n=new Rn;Mt(n,i),e[t]=n}}this._bursts=e}_bursts;set subEmitterSystems(e){for(let t=0;t<e.length;t++){let i=e[t];if(!(i instanceof ar)){let n=new ar;Mt(n,i),e[t]=n}}this._subEmitterSystems=e}_subEmitterSystems;awake(){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(let t of this._subEmitterSystems)t._deserialize(this.context);this._renderer=this.gameObject.getComponent(Ni),this._container=new h_,this._container.matrixAutoUpdate=!1,this.main.simulationSpace==0?this.gameObject.add(this._container):this.context.scene.add(this._container),this._batchSystem=new f_,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new ju(this),this._particleSystem=new b_(this._batchSystem,this._interface),this._particleSystem.addBehavior(new Iu(this)),this._particleSystem.addBehavior(new Lu(this)),this._particleSystem.addBehavior(new ku(this)),this._particleSystem.addBehavior(new Mu(this)),this._particleSystem.addBehavior(new Du(this)),this._particleSystem.addBehavior(new Au(this));let e=this._particleSystem.emitter;this.context.scene.add(e),hm&&(console.log(this),this.gameObject.add(new u_(1)))}start(){this.addSubParticleSystems()}onEnable(){this.inheritVelocity&&(this.inheritVelocity.system=this),this.play()}onDisable(){}onBeforeRender(){if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;let e=this.context.mainCamera;if(e){let n=Me(e);this._cameraScale=n.x}let t=this._container;if(this.worldspace&&(t=this.gameObject),pe(t,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Me(this.gameObject,this._worldScale),!this.worldspace&&this._container&&this.gameObject?.parent){let n=Me(this.gameObject.parent);n.x=1/n.x,n.y=1/n.y,n.z=1/n.z,this._container.matrix.identity(),this._container.matrix.scale(n)}this.emission.system=this;let i=this.deltaTime;this._interface.update(),this.shape.update(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),this.inheritVelocity?.update(this.context),this.velocityOverLifetime.update(this),this._batchSystem?.update(i),this._time+=i,this._time>this.duration&&(this._time=0)}addSubParticleSystems(){if(this._subEmitterSystems&&this._particleSystem)for(let e of this._subEmitterSystems){let t=e.particleSystem?._particleSystem;if(t){e.particleSystem._isUsedAsSubsystem=!0;let i=new sr(this,this._particleSystem,e.particleSystem,t);this._particleSystem.addBehavior(i)}}}},ge=Fu;_([y(Tn)],ge.prototype,"colorOverLifetime",2),_([y(ye)],ge.prototype,"main",2),_([y(pt)],ge.prototype,"emission",2),_([y(qt)],ge.prototype,"sizeOverLifetime",2),_([y(ie)],ge.prototype,"shape",2),_([y(Y)],ge.prototype,"noise",2),_([y(ee)],ge.prototype,"trails",2),_([y(je)],ge.prototype,"velocityOverLifetime",2),_([y(de)],ge.prototype,"limitVelocityOverLifetime",2),_([y(Yt)],ge.prototype,"inheritVelocity",2),_([y(wi)],ge.prototype,"colorBySpeed",2),_([y(_e)],ge.prototype,"textureSheetAnimation",2),_([y(Qe)],ge.prototype,"rotationOverLifetime",2),_([y(Ve)],ge.prototype,"rotationBySpeed",2),_([y(Pe)],ge.prototype,"sizeBySpeed",2);import*as fm from"three";function*pm(o,e=null){let t=e?e.time:G.Current.time,i=t.time;for(;t.time-i<o;)yield}var ft=class extends k{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 pm(.2),!this.tryAssignColor()););}tryAssignColor(){let e=R.getComponentInParent(this.gameObject,le);return e&&e.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(e.connectionId),!0):!1}assignUserColor(e){let t=ft.hashCode(e),i=ft.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 fm.Color(t/255,i/255,n/255)}};import{EquirectangularReflectionMapping as v_,sRGBEncoding as y_,Vector3 as mm}from"three";var Yo=M("debugreflectionprobe"),gm=M("noreflectionprobe"),__=Symbol("reflectionProbeKey"),x_=Symbol("original material"),Xi=class extends k{static get(e,t,i){if(!e||e.isObject3D!==!0||gm)return null;let n=Xi._probes.get(t);if(n){for(let r of n)if(r.__didAwake||r.__internalAwake(),r.enabled&&r.isInBox(e,i?1e-8:void 0))return Yo&&console.log("Found reflection probe",e.name,r.name),r}return Yo&&console.debug("Did not find reflection probe",e.name,i,e),null}_texture;set texture(e){this._texture=e}get texture(){return this._texture}center;size;_boxHelper;isInBox(e,t){return this._boxHelper?.isInBox(e,t)}constructor(){super(),Xi._probes.has(this.context)||Xi._probes.set(this.context,[]),Xi._probes.get(this.context)?.push(this)}awake(){this._boxHelper=this.gameObject.addNewComponent(Be),this._boxHelper.updateBox(!0),Yo&&this._boxHelper.showHelper(5592320,!0),this.texture&&(this.texture.mapping=v_,this.texture.encoding=y_,this.texture.needsUpdate=!0)}onDestroy(){let e=Xi._probes.get(this.context);if(e){let t=e.indexOf(this);t>=0&&e.splice(t,1)}}onSet(e){if(gm||e.sharedMaterials?.length<=0||!this.texture)return;let t=Xi._rendererMaterialsCache.get(e);t||(t=[],Xi._rendererMaterialsCache.set(e,t));for(let i=0;i<e.sharedMaterials.length;i++){let n=e.sharedMaterials[i];if(!n||n.envMap===void 0||n.envMap===this.texture)continue;let r=t[i];if(!r||r.material!==n||r.material.version!==n.version){let a=n.clone();r?(r.copy=a,r.material=n):(r={material:n,copy:a},t.push(r)),a[__]=this,a[x_]=n,a.envMap=this.texture,Yo&&console.log("Set reflection",e.name,e.guid)}let s=r?.copy;e.sharedMaterials[i]=s}}onUnset(e){let t=Xi._rendererMaterialsCache.get(e);if(t)for(let i=0;i<t.length;i++){let n=t[i];e.sharedMaterials[i]=n.material}}},Kt=Xi;A(Kt,"_probes",new Map),A(Kt,"_rendererMaterialsCache",new Map),_([y(mm)],Kt.prototype,"center",2),_([y(mm)],Kt.prototype,"size",2);import*as Qi from"three";import*as na from"three";var Sn=class{get lightmap(){return this.lightmapTexture}set lightmap(e){e!==this.lightmapTexture&&(this.lightmapTexture=e,this.setupLightmap())}lightmapIndex=-1;lightmapScaleOffset=new na.Vector4(1,1,0,0);context;gameObject;lightmapTexture=null;lightmapScaleOffsetUniform={value:new na.Vector4(1,1,0,0)};lightmapUniform={value:null};beforeRenderCallback;constructor(e,t){this.gameObject=e,this.context=t}init(e,t,i,n=!1){if(console.assert(this.gameObject!==void 0&&this.gameObject!==null,"Missing gameobject",this),this.lightmapIndex=e,this.lightmapIndex<0)return;this.lightmapScaleOffset=t,this.lightmapTexture=i,n&&this.setLightmapDebugMaterial(),this.setupLightmap()}bindOnBeforeRender(){this.beforeRenderCallback=this.onBeforeRenderThreeComplete.bind(this),this.context.addBeforeRenderListener(this.gameObject,this.beforeRenderCallback)}onBeforeRenderThreeComplete(e,t,i,n,r,s){this.onBeforeRenderThree(r)}setupLightmap(){if(this.gameObject.type==="Object3D")return;if(this.gameObject.type==="Group"){console.warn("Lightmap on multimaterial object is not supported yet... please ask kindly for implementation.");return}console.assert(this.gameObject.type==="Mesh","Lightmap only works on meshes",this);let e=this.gameObject;e.geometry.getAttribute("uv2")||e.geometry.setAttribute("uv2",e.geometry.getAttribute("uv"));let t=this.gameObject.material.clone();if(this.gameObject.material=t,this.gameObject.material.onBeforeCompile=(i,n)=>{i.uniforms.lightmap=this.lightmapUniform,i.uniforms.lightmapScaleOffset=this.lightmapScaleOffsetUniform},this.lightmapIndex>=0){let i=this.lightmapTexture,n=this.gameObject.material;n&&i&&(n.uniforms||(n.uniforms={}),n.lightMap=i,n.uniforms.lightmap={value:i})}}onBeforeRenderThree(e){let t=e.uniforms;t&&t.lightmap&&(this.lightmapScaleOffsetUniform.value=this.lightmapScaleOffset,this.lightmapUniform.value=this.lightmapTexture,t.lightmap=this.lightmapUniform,t.lightmapScaleOffset=this.lightmapScaleOffsetUniform)}setLightmapDebugMaterial(){this.gameObject.material=new na.ShaderMaterial({vertexShader:`
213
+ `;function yv(o){if(Dd.has(o))return Dd.get(o);{let e=document.createElement("div");e.classList.add(ji),e.classList.add("desktop"),e.classList.add("debug-container"),e.style.position="absolute",e.style.top="0",e.style.right="5px",e.style.paddingTop="0px",e.style.maxWidth="70%",e.style.maxHeight="calc(100% - 5px)",e.style.zIndex="1000",e.style.pointerEvents="scroll",e.style.display="flex",e.style.alignItems="end",e.style.flexDirection="column",e.style.color="white",e.style.overflow="auto",o.appendChild(e),Dd.set(o,e);let t=document.createElement("style");return t.innerHTML=vv,e.appendChild(t),e}}var kf=Symbol("logtype"),xl=new Map;function _v(o){o.remove();let e=o[kf],t=xl.get(e)??[];t.push(o),xl.set(e,t)}function xv(o,e){if(xl.has(o)){let i=xl.get(o);if(i.length>0)return i.pop()}let t=document.createElement("div");switch(t.style.marginRight="5px",t.style.padding=".5em",t.style.backgroundColor="rgba(0,0,0,.9)",t.style.marginTop="5px",t.style.marginBottom="3px",t.style.borderRadius="8px",t.style.pointerEvents="all",t.style.userSelect="text",t.style.maxWidth="250px",t.style.whiteSpace="pre-wrap",t.style["backdrop-filter"]="blur(10px)",t.style.backgroundColor="rgba(20,20,20,.8)",t.style.boxShadow="inset 0 0 80px rgba(0,0,0,.2), 0 0 5px rgba(0,0,0,.2)",t.style.border="1px solid rgba(160,160,160,.2)",t[kf]=o,o){case 0:t.classList.add("log"),t.style.color="rgba(200,200,200,.7)",t.style.backgroundColor="rgba(40,40,40,.7)";break;case 1:t.classList.add("warn"),t.style.color="rgb(255, 255, 150)",t.style.backgroundColor="rgba(50,50,20,.8)";break;case 2:t.classList.add("error"),t.style.color="rgb(255, 50, 50",t.style.backgroundColor="rgba(50,20,20,.8)";break}return t.title="Open the browser console (F12) for more information",t.innerHTML=e,t}var jd={};Gh(jd,{Behaviour:()=>M,Component:()=>xt,GameObject:()=>R});import*as et from"three";var R=class extends et.Object3D{guid;static setActive(e,t,i=!0,n=!0){!e||(wo(e,t,n),go(e),t&&i&&Fa(G.Current,e))}static isActiveSelf(e){return pn(e)}static isActiveInHierarchy(e){return Up(e)}static markAsInstancedRendered(e,t){Gp(e,t)}static isUsingInstancing(e){return qa(e)}static foreachComponent(e,t,i=!0){return oi(e,t,i)}static instantiateSynced(e,t){return e?Va(e,t):null}static instantiate(e,t=null){return Pr(e,t)}static destroySynced(e,t,i=!0){if(!e)return;let n=e;t=t??G.Current,bo(n,t.connection,i)}static destroy(e,t=!0,i=!0){return ri(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=G.Current),t.add(e),wo(e,!0),go(e),i?R.foreachComponent(e,n=>{$c(n,i),!n.__internalDidAwakeAndStart&&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),wo(e,!1),go(e),R.foreachComponent(e,t=>{mp(t)},!0))}static invokeOnChildren(e,t,...i){this.invoke(e,t,!0,i)}static invoke(e,t,i=!1,...n){!e||this.foreachComponent(e,r=>{let s=r[t];s&&typeof s=="function"&&s.bind(r)(...n)},i)}static addNewComponent(e,t,i=!0){let n=new t;return Vn(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");Ap(e,t)}static removeComponent(e){return Wa(e.gameObject,e),e}static getOrAddComponent(e,t){return Na(e,t)}static getComponent(e,t){return e===null?null:Or(e,t)}static getComponents(e,t,i=null){return e===null?i??[]:yo(e,t,i)}static findByGuid(e,t){return Sr(e,t)}static findObjectOfType(e,t,i=!0){return Hp(e,t??G.Current,i)}static findObjectsOfType(e,t){let i=[];return Fp(e,i,t),i}static getComponentInChildren(e,t){return kr(e,t)}static getComponentsInChildren(e,t,i=null){return _o(e,t,i??void 0)}static getComponentInParent(e,t){return vo(e,t)}static getComponentsInParent(e,t,i=null){return Hs(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]}},ai=class{get isComponent(){return!0}__context;get context(){return this.__context??G.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[Ii];return e===void 0?!0:e}set __isActiveInHierarchy(e){!this.gameObject||(this.gameObject[Ii]=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;get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}constructor(){this.__internalNewInstanceCreated()}__internalNewInstanceCreated(){this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(){return this.__didEnable?!1:(this.__didEnable=!0,this.onEnable(),this.__isEnabled=!0,!0)}__internalDisable(){!this.__didEnable||(this.__didEnable=!1,this.onDisable(),this.__isEnabled=!1)}__internalDestroy(){this.__destroyed||(this.__destroyed=!0,this.destroy?.call(this),Lp(this))}get enabled(){return this.__isEnabled??!0}set enabled(e){if(typeof e=="number"&&(e>=.5?e=!0:e=!1),!this.__didAwake){this.__isEnabled=e;return}e?this.__internalEnable():this.__internalDisable()}_worldPosition=void 0;_worldQuaternion=void 0;_worldEuler=void 0;_worldRotation=void 0;get worldPosition(){return this._worldPosition||(this._worldPosition=new et.Vector3),B(this.gameObject,this._worldPosition),this._worldPosition}set worldPosition(e){ie(this.gameObject,e)}setWorldPosition(e,t,i){ai._worldPositionBuffer.set(e,t,i),this.worldPosition=ai._worldPositionBuffer}get worldQuaternion(){return this._worldQuaternion||(this._worldQuaternion=new et.Quaternion),fe(this.gameObject,this._worldQuaternion)}set worldQuaternion(e){Je(this.gameObject,e)}setWorldQuaternion(e,t,i,n){ai._worldQuaternionBuffer.set(e,t,i,n),this.worldQuaternion=ai._worldQuaternionBuffer}get worldEuler(){return this._worldEuler||(this._worldEuler=new et.Euler),this._worldEuler.setFromQuaternion(this.worldQuaternion),this._worldEuler}set worldEuler(e){this._worldQuaternion||(this._worldQuaternion=new et.Quaternion),this._worldQuaternion?.setFromEuler(e),this.worldQuaternion=this._worldQuaternion}get worldRotation(){let e=this.worldEuler;this._worldRotation||(this._worldRotation=new et.Vector3);let t=this._worldRotation;return t.set(e.x,e.y,e.z),t.x=H.toDegrees(t.x),t.y=H.toDegrees(t.y),t.z=H.toDegrees(t.z),t}set worldRotation(e){this.setWorldRotation(e.x,e.y,e.z,!0)}setWorldRotation(e,t,i,n=!0){n&&(e=H.toRadians(e),t=H.toRadians(t),i=H.toRadians(i)),ai._worldEulerBuffer.set(e,t,i),ai._worldQuaternionBuffer.setFromEuler(ai._worldEulerBuffer),this.worldQuaternion=ai._worldQuaternionBuffer}get forward(){return ai._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}},xt=ai;D(xt,"_worldPositionBuffer",new et.Vector3),D(xt,"_worldQuaternionBuffer",new et.Quaternion),D(xt,"_worldEulerBuffer",new et.Euler),D(xt,"_tempQuaternionBuffer2",new et.Quaternion),D(xt,"_forward",new et.Vector3);var M=class extends xt{};var li=function(o,e){return function(t,i,n){wv(t,i,n,o,e)}};function wv(o,e,t,i,n){if(!(!n&&!i&&!o.onValidate)){if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",o,e,t),Ke("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,2);return}if(o.__internalAwake){let r=Symbol(e),s=o.__internalAwake;o.__internalAwake=function(){this[r]===void 0&&(this[r]=this[e],Object.defineProperty(this,e,{set:function(a){if(this[Ia]===!0)this[r]=a;else{i?.call(this,a);let c=this[r];this[r]=a,this.onValidate?.call(this,e,c)}},get:function(){return n?.call(this),this[r]}})),s.call(this)}}}}var Mf=O("debugloadingbar");var Ws=0,If;function Hd(o){Mf&&console.log(o.progress.loaded.toFixed(0)+"/"+o.progress.total.toFixed(0),o);let e=o.count,t=o.progress.total;t===0||t===void 0?(If!==o.name&&(Ws=0),If=o.name,Ws+=(1-Ws)*.001,Mf&&Ta("Loading "+o.name+" did not report total size")):Ws=o.progress.loaded/t;let i=o.index/e+Ws/e;return H.clamp01(i)}var wl=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){console.warn("Custom loading container is not allowed"),this.container.removeChild(i);continue}this._loadingElement=this.createLoadingElement(i);return}}this._loadingElement=this.createLoadingElement()}this._progress=0,this.loadingProgress=0,this._loadingElement.style.display="flex",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=Hd(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,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=H.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"),e||(this._loadingElement.style.position="fixed",this._loadingElement.style.width="100%",this._loadingElement.style.height="100%",this._loadingElement.style.left="0",this._loadingElement.style.top="0",this._loadingElement.style.backgroundColor="#000000",this._loadingElement.style.display="flex",this._loadingElement.style.alignItems="center",this._loadingElement.style.justifyContent="center",this._loadingElement.style.zIndex="1000",this._loadingElement.style.flexDirection="column",this._loadingElement.style.pointerEvents="none",this._loadingElement.style.color="white");let t=this._loadingElementOptions?.className??"loading";if(this._loadingElement.classList.add(t),this._loadingElementOptions?.additionalClasses)for(let a of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(a);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(a){return H.lerp(n*.5,100-n*.5,a)+"%"};this._loadingBar.style.background=`linear-gradient(90deg, #02022B ${r(0)}, #0BA398 ${r(.4)}, #99CC33 ${r(.5)}, #D7DB0A ${r(1)})`,this._loadingBar.style.backgroundAttachment="fixed",this._loadingBar.style.width="0%",this._loadingBar.style.height="100%",this._loadingTextContainer=document.createElement("div"),this._loadingTextContainer.style.display="flex",this._loadingTextContainer.style.justifyContent="center",this._loadingTextContainer.style.marginTop=".9em",this._loadingElement.appendChild(this._loadingTextContainer);let s=document.createElement("div");return this._messageContainer=s,s.style.display="flex",s.style.fontSize=".8em",s.style.paddingTop=".5em",s.style.color="rgba(255,255,255,.5)",s.style.justifyContent="center",this._loadingElement.appendChild(s),this._loadingElement}};import{DRACOLoader as Fd}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as Df}from"three/examples/jsm/loaders/KTX2Loader.js";var Ns=O("debugdecoders"),ci,qn;function Bd(o){o!==void 0&&typeof o=="string"&&(ci||(ci=new Fd),Ns&&console.log("Setting draco decoder path to",o),ci.setDecoderPath(o))}function Ud(o){o!==void 0&&typeof o=="string"&&(ci||(ci=new Fd),Ns&&console.log("Setting draco decoder type to",o),ci.setDecoderConfig({type:o}))}function Gd(o){o!==void 0&&typeof o=="string"&&(qn||(qn=new Df),Ns&&console.log("Setting ktx2 transcoder path to",o),qn.setTranscoderPath(o))}function gn(o,e){ci||(ci=new Fd,ci.setDecoderPath("./include/draco/"),ci.setDecoderConfig({type:"js"}),Ns&&console.log("Setting draco decoder path to","./include/draco/")),qn||(qn=new Df,qn.setTranscoderPath("./include/ktx2/"),Ns&&console.log("Setting ktx2 transcoder path to","./include/ktx2/"),e.renderer&&qn.detectSupport(e.renderer)),o.setDRACOLoader(ci),o.setKTX2Loader(qn)}import{AnimationClip as Ev,MathUtils as Cv}from"three";var Oo=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 Lf(o,e){return{name:"",isLooping:!1,guid:e?.generateUUID()??Cv.generateUUID(),index:-1,clip:new Ev(o,1,[])}}import{AnimationClip as Tv,AnimationMixer as Rv,AxesHelper as Sv,Euler as jf,LoopOnce as Pv,Quaternion as di,Vector3 as Xs}from"three";import*as Cl from"three";var Hi=O("debuganimatorcontroller"),Vd=O("debugrootmotion"),hi=class{Play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}let s=this.model.layers[t].stateMachine;for(let a of s.states)if(a.name===e||a.hash===e){Hi&&console.log("transition to ",a),this.transitionTo(a,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){Hi&&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 Rv(this.animator.gameObject),this.createActions(this.animator)}clone(){let e=Ss(this.model,(i,n,r)=>r==null?!0:!(r.type==="Object3D"||r.isObject3D===!0||pp(r)||r.tracks!==void 0));return console.assert(e!==this.model),new hi(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,Hi&&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()&&(Hi&&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;t.defaultState===void 0&&(Hi&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",e),t.defaultState=0);let i=t.states[t.defaultState];this.transitionTo(i,0,this.normalizedStartOffset)}}evaluateTransitions(){let t=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;t=!0}let i=this._activeState,n=i.motion.action,r=0;for(let a of i.transitions){if(++r,!a.hasExitTime&&a.conditions.length<=0)continue;let c=!0;for(let d of a.conditions)if(!this.evaluateCondition(d)){c=!1;break}if(!!c){for(let d of a.conditions){let l=this.model.parameters.find(u=>u.name===d.parameter);l?.type===9&&(l.value=!1)}if(n){let d=i.motion.clip.duration,l=d<=0?1:n.time/d;if(a.hasExitTime?l>=a.exitTime:!0){n.clampWhenFinished=!0,Hi&&console.log("transition to "+a.destinationState,a,l,a.exitTime,a.hasExitTime),this.transitionTo(a.destinationState,a.duration,a.offset);return}}else{this.transitionTo(a.destinationState,a.duration,a.offset);return}}}let s=!1;if(i.motion.isLooping&&n&&n.time>=n.getClip().duration&&(s=!0,n.reset(),n.time=0,n.play()),!s&&i&&!t&&n&&this.animator&&i.behaviours){let a=n?.getClip().duration,c=n.time/a,d=new Oo(this._activeState,c,a,this._speed);for(let l of i.behaviours)l.instance&&l.instance.onStateUpdate?.call(l.instance,this.animator,d,0)}}getState(e,t){return typeof e=="number"&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState,e===void 0&&(Hi&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+t),e=0)),e=this.model.layers[t].stateMachine.states[e]),e}transitionTo(e,t,i){if(!this.animator)return;let n=0;if(e=this.getState(e,n),!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,l=this._activeState.motion.action.time/d,u=new Oo(this._activeState,l,d,this._speed);for(let h of this._activeState.behaviours)h.instance?.onStateExit?.call(h.instance,this.animator,u,n)}let s=this._activeState?.motion.action;s&&s.fadeOut(t),r&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=s);let a=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(Pv,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 l=new Oo(e,i,d,this._speed);for(let u of this._activeState.behaviours)u.instance?.onStateEnter?.call(u.instance,this.animator,l,n)}}else console.warn("No action",e.motion,this);Hi&&console.log("TRANSITION FROM "+a?.name+" TO "+e.name,t,s,c,c?.getEffectiveTimeScale(),c?.getEffectiveWeight(),c?.isRunning(),c?.isScheduled(),c?.paused)}createAction(e){if(this._mixer.existingAction(e)&&this._mixer.uncacheAction(e,this.animator?.gameObject),this.animator?.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new zd(this));let i=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,i,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];r.transitions||(r.transitions=[]);for(let s of r.transitions)s.conditions||(s.conditions=[]);if(r.motion||(r.motion=Lf(r.name)),this.animator&&r.motion.clips){let s=r.motion.clips?.find(a=>a.node.name===this.animator?.gameObject?.name);r.motion.clip=s?.clip}if(!r.motion.clip){let s=new Tv(void 0,void 0,[]);r.motion.clip=s}if(r.motion?.clip){let s=r.motion.clip,a=this.createAction(s);r.motion.action=a}if(r.behaviours&&Array.isArray(r.behaviours))for(let s of r.behaviours){if(!s?.typeName)continue;let a=P.get(s.typeName),c=new a;c.isStateMachineBehaviour&&(c._context=this.context??void 0,It(c,s.properties),s.instance=c),Hi&&console.log("Created animator controller behaviour",r.name,s.typeName,s.properties,c)}}}}*enumerateActions(){for(let e of this.model.layers){let t=e.stateMachine;for(let i=0;i<t.states.length;i++){let n=t.states[i];n?.motion&&(n.motion.action&&(yield n.motion.action),n.motion.action_loopback&&(yield n.motion.action_loopback))}}}rootMotionHandler},El=class{track;createdInterpolant;originalEvaluate;customEvaluate;constructor(e,t){this.track=e;let i=e,n=i.createInterpolant.bind(e);i.createInterpolant=()=>(i.createInterpolant=n,this.createdInterpolant=n(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=r=>{if(!this.originalEvaluate)return;let s=this.originalEvaluate(r);return t(r,s)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}evaluate(e){this.customEvaluate&&this.customEvaluate(e)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}},xe=class{set action(e){this._action=e}get action(){return this._action}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new Xs;rotationChange=new di;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 Cl.Quaternion),r){let s=r.values;xe.firstKeyframeRotation[i.uuid].set(s[0],s[1],s[2],s[3])}xe.spaceRotation[i.uuid]||(xe.spaceRotation[i.uuid]=new di),xe.effectiveSpaceRotation[i.uuid]||(xe.effectiveSpaceRotation[i.uuid]=new di),xe.clipOffsetRotation[i.uuid]=new di,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 Cl.Euler().setFromQuaternion(t);console.log("START",this.clip.name,H.toDegrees(i.y))}}getClipRotationOffset(){return xe.clipOffsetRotation[this.clip.uuid]}handlePosition(e,t){if(t){let i=this.root;Vd&&i.add(new Sv),xe.lastObjPosition[i.uuid]||(xe.lastObjPosition[i.uuid]=new Xs);let n=new Xs,r=new Xs,s=0;this.positionWrapper=new El(t,(a,c)=>{let d=this.action.getEffectiveWeight();if(Vd&&i.position.length()>8&&i.position.set(0,i.position.y,0),a>s){n.set(c[0],c[1],c[2]),n.sub(r),n.multiplyScalar(d),n.applyQuaternion(this.getClipRotationOffset());let l=this.clip.uuid;n.applyQuaternion(xe.spaceRotation[l]),this.positionChange.copy(n)}return r.fromArray(c),s=a,c[0]=0,c[1]=0,c[2]=0,c})}}handleRotation(e,t){if(t){if(Vd){let a=t.values,c=new jf().setFromQuaternion(new di(a[0],a[1],a[2],a[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",H.toDegrees(c.y));let d=t.values.length-4,l=new di().set(a[d],a[d+1],a[d+2],a[d+3]),u=new jf().setFromQuaternion(l);console.log(e.name,t.name,"LAST ROTATION IN TRACK",H.toDegrees(u.y))}let i=this.root;xe.lastObjRotation[i.uuid]||(xe.lastObjRotation[i.uuid]=new di);let n=0,r=new di,s=new di;this.rotationWrapper=new El(t,(a,c)=>(a>n&&(s.set(c[0],c[1],c[2],c[3]),r.invert(),s.multiply(r),this.rotationChange.copy(s)),r.fromArray(c),n=a,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(xe.identityQuaternion,1-e)}},ui=xe;D(ui,"lastObjPosition",{}),D(ui,"lastObjRotation",{}),D(ui,"firstKeyframeRotation",{}),D(ui,"spaceRotation",{}),D(ui,"effectiveSpaceRotation",{}),D(ui,"clipOffsetRotation",{}),D(ui,"identityQuaternion",new di);var zd=class{controller;handler=[];root;constructor(e){this.controller=e}createClip(e,t,i){this.root=t;let n="";t&&"name"in t&&(n=t.name);let r=this.findRootTrack(i,".position"),s=this.findRootTrack(i,".quaternion"),a=new ui(this.controller.context,t,i,r,s);this.handler.push(a);let c=e.clipAction(i);return a.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 Xs;summedRotation=new di;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),ui.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 ko=function(o){return _(o)},_=function(o){if(o===void 0&&(o=null),!Array.isArray(o))o=Hf(o);else for(let e=0;e<o.length;e++){let t=o[e];o[e]=Hf(t)}return function(e,t){Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});let i=e.$serializedTypes=e.$serializedTypes||{};i[t]=o}};function Hf(o){switch(o?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return o}var Ff=O("debuganimator"),Be=class extends M{applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof hi?this._animatorController=e:(Ff&&console.log("Assign animator controller",e,this),this._animatorController=new hi(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=H.lerp(e.x,e.y,Math.random())}set minMaxOffsetNormalized(e){this.normalizedStartOffset=H.lerp(e.x,e.y,Math.random()),this.runtimeAnimatorController&&(this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset)}speed=1;normalizedStartOffset=0;_animatorController=null;awake(){if(Ff&&console.log("ANIMATOR",this.name,this),!!this.gameObject&&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}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.Reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}};y([_()],Be.prototype,"applyRootMotion",2),y([_()],Be.prototype,"hasRootMotion",2),y([_()],Be.prototype,"keepAnimatorControllerStateOnDisable",2),y([_()],Be.prototype,"runtimeAnimatorController",1);import*as jr from"three";import{AnimationClip as Ov}from"three";var Tl=O("debuganimation"),Lt=class extends M{playAutomatically=!0;randomStartTime=!0;minMaxSpeed;minMaxOffsetNormalized;loop=!0;clampWhenFinished=!1;_tempAnimationClipBeforeGameObjectExisted=null;get clip(){return this.animations?.length?this.animations[0]:null}set clip(e){if(!this.__didAwake){Tl&&console.log("Assign clip during serialization",e),this._tempAnimationClipBeforeGameObjectExisted=e;return}!e||(Tl&&console.log("Assign clip",e,Boolean(this.gameObject)),this.gameObject.animations||(this.gameObject.animations=[]),!this.animations.includes(e)&&(this.animations.length>0?this.animations.splice(0,0,e):this.animations.push(e)))}set clips(e){this.animations=e}set animations(e){Tl&&console.log("assign 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(){Tl&&console.log(this),this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.playAutomatically&&this.init()}onEnable(){if(this.playAutomatically&&this.animations?.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&&oe.markDirty(this.gameObject)}}getAction(e){return this.actions?.find(t=>t.getClip().name===e)}get isPlaying(){for(let e=0;e<this._currentActions.length;e++)if(this._currentActions[e].isRunning())return!0;return!1}play(e,t){if(this.init(),!this.mixer)return;e===void 0&&(e=0);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}t||(t={}),t.minMaxOffsetNormalized||(t.minMaxOffsetNormalized=this.minMaxOffsetNormalized),t.minMaxSpeed||(t.minMaxSpeed=this.minMaxSpeed),t.loop||(t.loop=this.loop),t.clampWhenFinished||(t.clampWhenFinished=this.clampWhenFinished);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 a=this.tryFindHandle(e);if(a)return a.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;let r=e.getClip();t?.minMaxOffsetNormalized&&(e.time=H.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*r.duration),t?.minMaxSpeed&&(e.timeScale=H.lerp(t.minMaxSpeed.x,t.minMaxSpeed.y,Math.random())),t?.clampWhenFinished&&(e.clampWhenFinished=!0),t?.startTime!==void 0&&(e.time=t.startTime),t?.loop!==void 0?e.loop=t.loop?jr.LoopRepeat:jr.LoopOnce:e.loop=jr.LoopOnce,e.play();let s=new Wd(e,this.mixer,t,a=>{this._handles.splice(this._handles.indexOf(s),1)});return this._handles.push(s),s.getPromise()}tryFindHandle(e){for(let t of this._handles)if(t.action===e)return t}_didInit=!1;init(){this._didInit||(this._didInit=!0,this.gameObject&&(this.actions=[],this.mixer=new jr.AnimationMixer(this.gameObject)))}};y([_()],Lt.prototype,"playAutomatically",2),y([_()],Lt.prototype,"randomStartTime",2),y([_()],Lt.prototype,"loop",2),y([_()],Lt.prototype,"clampWhenFinished",2),y([_(Ov)],Lt.prototype,"clips",1);var Wd=class{mixer;action;promise=null;resolve=null;reject=null;_options;_resolveCallback=null;_rejectCallback=null;_loopCallback;_finishedCallback;_resolvedOrRejectedCallback;constructor(e,t,i,n){this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=n,this._options=i}getPromise(){return this.promise?this.promise:(this.promise=new Promise((e,t)=>{this._resolveCallback=e,this._rejectCallback=t,this.resolve=this.onResolve.bind(this),this.reject=this.onReject.bind(this)}),this._loopCallback=this.onLoop.bind(this),this._finishedCallback=this.onFinished.bind(this),this.mixer.addEventListener("loop",this._loopCallback),this.mixer.addEventListener("finished",this._finishedCallback),this.promise)}_update(){!this._options||this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._resolveCallback?.call(this,this.action)}onReject(e){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._rejectCallback?.call(this,e)}onLoop(e){}onFinished(e){e.action===this.action&&this.onResolve()}dispose(){this._loopCallback&&this.mixer.removeEventListener("loop",this._loopCallback),this._finishedCallback&&this.mixer.removeEventListener("finished",this._finishedCallback),this._loopCallback=void 0,this._finishedCallback=void 0}};import{GLTFLoader as ag}from"three/examples/jsm/loaders/GLTFLoader.js";import*as X from"three";import{RawShaderMaterial as Mv}from"three";var bn=O("debugshaders"),Mo="NEEDLE_techniques_webgl";var Nd=class{objectToWorldMatrix=new X.Matrix4;worldToObjectMatrix=new X.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),Vs(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),Vs(this.worldToObjectMatrix,this.worldToObject)}};var ce=class extends Mv{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){let e=super.clone();return Bf(e),e}constructor(e,...t){super(...t),this.identifier=e,bn&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName]&&this.waitForLighting(),(this.depthTextureUniform||this.opaqueTextureUniform)&&G.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();let e=G.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&G.Current.pre_render_callbacks.splice(e,1)}async waitForLighting(){let e=G.Current;if(!e){console.error("Missing context");return}let t=await e.rendererData.getSceneLightingData(this.identifier);if(!t||!t.array){console.warn("Missing lighting data for custom shader, getSceneLightingData did not return anything");return}bn&&console.log(t);let i=t.array,n=t.texture;this.uniforms.unity_SpecCube0={value:n},Sd(this.uniforms,i);let r=Math.sqrt(Math.PI*.5);this.uniforms.unity_SpecCube0_HDR={value:new X.Vector4(r,r,r,r)},bn&&console.log("Set environment lighting",this.uniforms)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";_rendererData=new Nd;get depthTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&G.Current.setRequireColor(!0),this.depthTextureUniform&&G.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,r,s){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,r)}onUpdateUniforms(e,t){let i=G.Current;e&&(ce.viewProjection&&this.uniforms[this._viewProjectionName]&&(ce.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),Vs(ce.viewProjection,ce._viewProjectionValues)),ce.viewMatrix&&this.uniforms[this._viewMatrixName]&&(ce.viewMatrix.copy(e.matrixWorldInverse),Vs(ce.viewMatrix,ce._viewMatrixValues)),this.uniforms[ce._worldSpaceCameraPosName]&&ce._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters?this.uniforms._TimeParameters.value=i.rendererData.timeVec4:this.uniforms._Time&&(this.uniforms._Time.value=i.rendererData.timeVec4);let n=i.mainLight;if(n){let a=B(n.gameObject,ce._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},ce._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:ce._mainLightColor};let c=n.intensity;ce._lightData.z=c,this.uniforms.unity_LightData={value:ce._lightData}}if(e&&(ce.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=ce._viewProjectionValues),ce.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=ce._viewMatrixValues),this.uniforms[ce._worldSpaceCameraPosName]&&(this.uniforms[ce._worldSpaceCameraPosName]={value:ce._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){let a=this.uniforms._ProjectionParams.value;a.x=1,a.y=i.mainCameraComponent.nearClipPlane,a.z=i.mainCameraComponent.farClipPlane,a.w=1/a.z,this.uniforms._ProjectionParams.value=a}if(this.uniforms._ZBufferParams){let a=this.uniforms._ZBufferParams.value,c=i.mainCameraComponent;a.x=1-c.farClipPlane/c.nearClipPlane,a.y=c.farClipPlane/c.nearClipPlane,a.z=a.x/c.farClipPlane,a.w=a.y/c.farClipPlane,this.uniforms._ZBufferParams.value=a}if(this.uniforms._ScreenParams){let a=this.uniforms._ScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScreenParams.value=a}}let r=this.depthTextureUniform;r&&(r.value=i.depthTexture);let s=this.opaqueTextureUniform;if(s&&(s.value=i.opaqueColorTexture),t){let a=this._rendererData;a.updateFrom(t),this.uniforms[this._worldToObjectName].value=a.worldToObject,this.uniforms[this._objToWorldName].value=a.objectToWorld}this.uniformsNeedUpdate=!0}},jt=ce;D(jt,"viewProjection",new X.Matrix4),D(jt,"_viewProjectionValues",[]),D(jt,"viewMatrix",new X.Matrix4),D(jt,"_viewMatrixValues",[]),D(jt,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),D(jt,"_worldSpaceCameraPos",new X.Vector3),D(jt,"_mainLightColor",new X.Vector4),D(jt,"_mainLightPosition",new X.Vector3),D(jt,"_lightData",new X.Vector4);var Rl=class{get name(){return Mo}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){let t=this.parser.json.materials[e];if(!t)return bn&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Mo])return bn&&console.log("material "+e+" does not use NEEDLE_techniques_webgl"),null;let i=t.extensions[Mo].technique;if(i<0)return null;let n=this.parser.json.extensions[Mo];if(!n)return null;bn&&console.log(n);let r=n.techniques[i];return r?new Promise(async(s,a)=>{let c=await wf(n,r.program),d=c?.fragmentShader,l=c?.vertexShader;if(!d||!l)return a();bn&&console.log("loadMaterial",t,c);let u={},h=r.uniforms;l.includes("_Time")&&(u._Time={value:new X.Vector4(0,0,0,0)});for(let m in h){let f=m;switch(f){case"_TimeParameters":let p=new X.Vector4;u[f]={value:p};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":u[f]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":u[f]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":u[f]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":u[f]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":u[f]={value:null};break}}let b=!1;if(t.extensions&&t.extensions[Mo]){let m=t.extensions[Mo];if(m.technique===i){bn&&console.log(t.name,"Material Properties",m);for(let f in m.values){let p=m.values[f];if(typeof p=="string"){if(p.startsWith("/textures/")){let g=p.substring(10),E=Number.parseInt(g);if(E>=0){let C=await this.parser.getDependency("texture",E);C&&(C.encoding=X.LinearEncoding,C.needsUpdate=!0),u[f]={value:C};continue}}switch(f){case"alphaMode":p==="BLEND"&&(b=!0);continue}}if(Array.isArray(p)&&p.length===4){u[f]={value:new X.Vector4(p[0],p[1],p[2],p[3])};continue}u[f]={value:p}}}}let w=new jt(this.identifier,{name:t.name??"",uniforms:u,vertexShader:l,fragmentShader:d,lights:!1});switch(u._Cull?.value){case 0:w.side=X.DoubleSide;break;case 1:w.side=X.BackSide;break;case 2:w.side=X.FrontSide;break;default:w.side=X.FrontSide;break}switch(u._ZTest?.value){case 3:w.depthTest=!0,w.depthFunc=X.EqualDepth;break;case 6:w.depthTest=!0,w.depthFunc=X.NotEqualDepth;break;case 2:w.depthTest=!0,w.depthFunc=X.LessDepth;break;case 4:w.depthTest=!0,w.depthFunc=X.LessEqualDepth;break;case 5:w.depthTest=!0,w.depthFunc=X.GreaterDepth;break;case 7:w.depthTest=!0,w.depthFunc=X.GreaterEqualDepth;break;case 8:w.depthTest=!1,w.depthFunc=X.AlwaysDepth;break}w.transparent=b,b&&(w.depthWrite=!1),Sd(u),w.onUpdateUniforms();for(let m in h){let f=m,p=h[m].type;if(u[f]?.value===void 0)switch(p){case 35678:u[f]={value:_f},console.warn("Missing/unassigned texture, fallback to white: "+f);break;default:console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+f,h[m]);break}}bn&&console.log(w.uuid,u),Bf(w),s(w)}):null}};function Bf(o){if(o.uniforms)for(let e in o.uniforms)Object.getOwnPropertyDescriptor(o,e)||Object.defineProperty(o,e,{get:()=>o.uniforms[e].value,set:t=>{o.uniforms[e].value=t,o.needsUpdate=!0}})}var Yn=Te,Sl="$___Export_Components",Iv="NEEDLE_components",Xd=class{[Rr]},Qd=class{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}},Io=class{get name(){return Iv}parser;nodeToObjectMap={};exportContext;objectToNodeMap={};context;writer;registerExport(e){e.register(t=>{if("serializeUserData"in t){let i=t.serializeUserData.bind(t);this.writer=t,t.serializeUserData=(n,r)=>{try{this.serializeUserData(n,r),i(n,r)}finally{this.afterSerializeUserData(n,r)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){let i=e.userData?.components;!i||i.length<=0||(delete e.userData.components,e[Sl]=i)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Yn&&console.log("DONE",JSON.stringify(t)),e[Sl]===void 0)return;let i=e[Sl];delete e[Sl],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 Qd(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){Yn&&console.log("AFTER",e);for(let t in this.exportContext){let i=this.exportContext[t],n=i.node,r=i.nodeDef,s=i.nodeIndex,a=n.userData?.components;if(!a||a.length<=0)continue;let c=new Xd;r.extensions=r.extensions||{},r.extensions[this.name]=c,this.context.object=n,this.context.nodeId=s,this.context.objectToNode=this.objectToNodeMap;let d=[];for(let l of a){this.context.target=l;let u=Xe().writeBuiltinComponentData(l,this.context);u!==null&&d.push(u)}d.length>0&&(c[Rr]=d,Yn&&console.log("DID WRITE",n,"nodeIndex",s,d))}}beforeRoot(){return Yn&&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];Yn&&console.log("After root",e,this.parser,i);let r=[];if(n===!0){let s=t.json.nodes;for(let a=0;a<s.length;a++){let c=await t.getDependency("node",a);this.nodeToObjectMap[a]=c}for(let a=0;a<s.length;a++){let c=s[a],d=a,l=c.extensions;if(!l)continue;let u=l[this.name];if(!u)continue;Yn&&console.log("NODE",c);let h=this.nodeToObjectMap[d];if(!h){console.error("Could not find object for node index: "+d,c,t);continue}xo(h),r.push(this.createComponents(h,u))}}await Promise.all(r)}async createComponents(e,t){if(!t)return;let i=t[Rr];if(i){let n=new Array;Yn&&console.log(e.name,i);for(let r in i){let s=i[r];Yn&&console.log("Serialized data",JSON.parse(JSON.stringify(s))),s&&this.parser&&n.push(po(this.parser,s)),e.userData=e.userData||{},e.userData[Rr]=e.userData[Rr]||[],e.userData[Rr].push(s)}await Promise.all(n)}}};import{EXRLoader as Dv}from"three/examples/jsm/loaders/EXRLoader";var qd=O("debugexr"),Pl=class{parser;name;constructor(e){this.parser=e,this.name="EXT_texture_exr",qd&&console.log(e)}loadTexture(e){let t=this.name,i=this.parser,r=i.json.textures[e];if(qd&&console.log("EXT_texture_exr.loadTexture",e,r),!r.extensions||!r.extensions[t])return null;let s=r.extensions[t],a=new Dv(i.options.manager);return qd&&console.log("EXT_texture_exr.loadTexture",s,a),i.loadTextureImage(e,s.source,a)}};window.addEventListener("unhandledrejection",o=>{});var Uf="NEEDLE_gameobject_data",Ol=class{get name(){return Uf}parser;constructor(e){this.parser=e}afterRoot(e){let t=[];for(let i=0;i<this.parser.json.nodes.length;i++){let n=this.parser.json.nodes[i];if(n&&n.extensions){let r=n.extensions[Uf];if(r){let s=this.findAndApplyExtensionData(i,r);t.push(s)}}}return Promise.all(t).then(()=>{})}async findAndApplyExtensionData(e,t){let i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(t.layers),e.userData.tag=t.tag,e.userData.hideFlags=t.hideFlags,e.userData.static=t.static,e.visible=t.activeSelf,e.guid=t.guid}};import{AmbientLight as Av,Color as Gf,HemisphereLight as Lv}from"three";var Vf="NEEDLE_lighting_settings",Do=O("debugenvlight"),kl=class{get name(){return Vf}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}afterRoot(e){let t=this.parser.json.extensions;if(t){let i=t[Vf];if(i){Do&&console.log(i);let n=R.addNewComponent(e.scene,Yd,!1);n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new Gf().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(r=>new Gf().fromArray(r))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource,this.context&&this.context.rendererData.registerSceneLightSettings(n)}}return null}},Yd=class extends M{ambientMode=0;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=0;_hasReflection=!1;_ambientLightObj;_lightProbeObj;awake(){if(this.sourceId){let e=this.environmentReflectionSource===0?1:2,t=this.context.lightmaps.tryGet(this.sourceId,e,0);this._hasReflection=t!=null,t&&this.context.rendererData.registerReflection(this.sourceId,t)}Do&&window.addEventListener("keydown",e=>{switch(e.key){case"l":this.enabled=!this.enabled;break}})}onEnable(){let e=this.context.mainCameraComponent?.sourceId===this.sourceId;if(Do&&console.log("Enable scene lighting",this.sourceId,e,this,this.context.mainCameraComponent?.sourceId),e||Do&&console.warn("This is no active?!",this.context.mainCameraComponent?.sourceId),this.ambientMode==3)this.ambientLight&&!this._ambientLightObj&&(this._ambientLightObj=new Av(this.ambientLight,Math.PI*this.ambientIntensity)),this._ambientLightObj&&this.gameObject.add(this._ambientLightObj),this._lightProbeObj&&this._lightProbeObj.removeFromParent();else if(this.ambientMode===1){if(this.ambientTrilight){let t=this.ambientTrilight[0],i=this.ambientTrilight[this.ambientTrilight.length-1],n=new Lv(i,t,this.ambientIntensity);this.gameObject.add(n)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._lightProbeObj?this.enabled&&this.destroyed&&this._lightProbeObj&&this.scene.add(this._lightProbeObj):this.sourceId&&this.context.rendererData.getSceneLightingData(this.sourceId).then(t=>{Do&&console.log(t),t&&(this._lightProbeObj=t.lightProbe,this.enabled&&!this.destroyed&&this._lightProbeObj&&this.scene.add(this._lightProbeObj))});this.sourceId&&this.context.rendererData.enableReflection(this.sourceId)}onDisable(){Do&&console.log("disable",this.sourceId,this),this._lightProbeObj&&this._lightProbeObj.removeFromParent(),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this.sourceId&&this.context.rendererData.disableReflection()}};import{NeverStencilFunc as jv,LessStencilFunc as Hv,EqualStencilFunc as Fv,LessEqualStencilFunc as Bv,GreaterStencilFunc as Uv,NotEqualStencilFunc as Gv,GreaterEqualStencilFunc as Vv,AlwaysStencilFunc as zv,ZeroStencilOp as Wv,KeepStencilOp as Nv,ReplaceStencilOp as Xv,IncrementStencilOp as Qv,DecrementStencilOp as qv,IncrementWrapStencilOp as Yv,DecrementWrapStencilOp as Kv,InvertStencilOp as Jv}from"three";var Kd=O("debugstencil");function Zv(o,e){return(o&1<<e.layer)!=0}var Hr=class{static applyStencil(e){if(!e)return;let t=e.sourceId;if(Kd&&console.log(t,Hr.stencils),!t)return;let i=Hr.stencils[t];if(!!i)for(let n=i.length-1;n>=0;n--){let r=i[n];if(Zv(r.layer,e)){Kd&&console.log(r);let s=e.sharedMaterial?.clone();s&&(e.sharedMaterial=s,e.gameObject.renderOrder=r.event*1e3+r.index*50,s.stencilWrite=!0,s.stencilWriteMask=255,s.stencilFuncMask=255,s.stencilRef=r.value,s.stencilFunc=r.compareFunc,s.stencilZPass=r.passOp,s.stencilFail=r.failOp,s.stencilZFail=r.zFailOp);break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){let t=this.parser.json.extensions;if(t){let i=t[ey];if(i){Kd&&console.log(i);let n=i.stencil;if(n&&Array.isArray(n))for(let r of n){let s={...r};s.compareFunc=$v(s.compareFunc),s.passOp=Jd(s.passOp),s.failOp=Jd(s.failOp),s.zFailOp=Jd(s.zFailOp),Hr.stencils[this.source]||(Hr.stencils[this.source]=[]),Hr.stencils[this.source].push(s)}}}return null}},Fr=Hr;D(Fr,"stencils",{});function Jd(o){switch(o){case 0:return Nv;case 1:return Wv;case 2:return Xv;case 3:return Qv;case 4:return qv;case 6:return Yv;case 7:return Kv;case 5:return Jv}return 0}function $v(o){switch(o){case 1:return jv;case 2:return Hv;case 3:return Fv;case 4:return Bv;case 5:return Uv;case 6:return Gv;case 7:return Vv;case 8:return zv}return 0}var ey="NEEDLE_render_objects";import{TextureLoader as ty}from"three";import{GLTFLoader as iy}from"three/examples/jsm/loaders/GLTFLoader";var Zd="NEEDLE_deferred_texture",dt=O("debugprogressive"),eu=new Map,$d=!1;dt&&window.addEventListener("keyup",o=>{o.key==="p"&&(eu.forEach((e,t)=>{Object.entries(e).forEach(([i,n])=>{$d?t[i]=n.lod0:t[i]=n.original,t.needsUpdate=!0})}),$d=!$d)});var Qs=class{static assignTextureLOD(e,t,i,n=0){if(!!i)for(let r of Object.keys(i)){let s=i[r];s?.isTexture===!0&&(dt&&console.log(`-----------
214
+ `,"FIND",i.name,r,s?.name,s?.userData,s,i),Qs.getOrLoadTexture(e,t,i,r,s,n).then(a=>{if(a?.isTexture===!0&&(dt&&console.log("Assign LOD",i.name,r,a.name,a.guid,i,"Prev:",s,"Now:",a,`
215
+ --------------`),i[r]=a,a.needsUpdate=!0,i.needsUpdate=!0,dt)){let c=eu.get(i);c||(c={},eu.set(i,c));let d=c[r];d||(d=c[r]={original:s,lod0:a}),d.lod0=a}}))}}get name(){return Zd}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}_loading=[];afterRoot(e){return dt&&console.log("AFTER",this.sourceId,e),this.parser.json.textures?.forEach((t,i)=>{if(t?.extensions){let n=t?.extensions[Zd];if(n){let r=this.parser.getDependency("texture",i);this._loading.splice(this._loading.indexOf(i),1),r.then(s=>{dt&&console.log("register texture",s.name,s.uuid,n),s.userData.deferred=n,Qs.cache.set(s.uuid,n)})}}}),null}static async getOrLoadTexture(e,t,i,n,r,s){let a=r.uuid,c=Qs.cache.get(a);if(c){dt&&console.log(a,c.uri,c.guid);let d=Oi(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 l=d+"_"+c.guid;if(this.resolved[l])return dt&&console.log("Texture has already been loaded: "+l,i.name,n,r.name),this.resolved[l];let u=new iy;gn(u,e),dt&&console.log("Load "+d,i.name,n,c.guid);let h=await u.loadAsync(d),b=h.parser;dt&&console.log("Loading finished "+d,i.name,n,c.guid);let w=-1,v=!1;for(let m of h.parser.json.textures)if(w++,m?.extensions){let f=m?.extensions[Zd];if(f?.guid&&f.guid===c.guid){v=!0;break}}if(!v)return null;let x=await b.getDependency("texture",w);return x.encoding=r.encoding,x&&(x.guid=c.guid),this.resolved[l]=x,dt&&console.log(i.name,n,'change "'+r.name+'" \u2192 "'+x.name+'"',d,w,x,i,l),x}else{dt&&console.log("Load texture from uri: "+d);let u=await new ty().loadAsync(d);return u&&dt?console.log(c,u):console.warn("failed loading",d),u}}else dt&&console.warn("unknown uuid",r.name,r.uuid,r);return null}},vn=Qs;D(vn,"cache",new Map),D(vn,"resolved",{});function iu(o){let e=new Io;return o.register(t=>(e.parser=t,e)),e}var tu=class{resolvePath(e){return e.includes("/extensions/builtin_components/")?e.replace("/extensions/builtin_components/","/userData/components/"):e.includes("extensions/builtin_components/")?e.replace("extensions/builtin_components/","/userData/components/"):e}};function nu(o,e,t){o.register(n=>new Ol(n)),o.register(n=>new Pa(n)),o.register(n=>new gl(n,e.lightmaps,t)),o.register(n=>new kl(n,t,e)),o.register(n=>new Rl(n,t)),o.register(n=>new Fr(n,t)),o.register(n=>new vn(n,t,e)),o.register(n=>new Pl(n));let i=o.setAnimationPointerResolver;typeof i=="function"&&i.bind(o)(new tu)}import{Vector3 as ny}from"three";var Kn=class extends M{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new ny}update(){if(!this.from||!this.to)return;let e=B(this.from).clone(),t=B(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),ie(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(B(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}};y([_(R)],Kn.prototype,"from",2),y([_(R)],Kn.prototype,"to",2);var Fi=class{time;value;inTangent;inWeight;outTangent;outWeight;weightedMode};y([_()],Fi.prototype,"time",2),y([_()],Fi.prototype,"value",2),y([_()],Fi.prototype,"inTangent",2),y([_()],Fi.prototype,"inWeight",2),y([_()],Fi.prototype,"outTangent",2),y([_()],Fi.prototype,"outWeight",2),y([_()],Fi.prototype,"weightedMode",2);var pi=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;if(this.keys[0].time>=e)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){let i=this.keys[t];if(i.time<=e)if(t+1<this.keys.length){let r=this.keys[t+1];if(r.time<e)continue;let s=H.remap(e,i.time,r.time,0,1);return H.lerp(i.value,r.value,s)}else return i.value}return this.keys[this.keys.length-1].value}};y([_(Fi)],pi.prototype,"keys",2);import*as zf from"three";import*as qs from"three";import{PositionalAudioHelper as ry}from"three/examples/jsm/helpers/PositionalAudioHelper.js";var ut=O("debugaudio");var De=class extends M{static get userInteractionRegistered(){return De._didCallBeginWaitForUserInteraction||(De._didCallBeginWaitForUserInteraction=!0,De._beginWaitForUserInteraction()),De._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),De._didCallBeginWaitForUserInteraction||(De._didCallBeginWaitForUserInteraction=!0,De._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);let i=(()=>{if(i!=null&&!De._userInteractionRegistered){De._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&&(ut&&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&&De._userInteractionRegistered){let e=R.getComponent(this.context.mainCamera,fi)??R.findObjectOfType(fi,this.context);e?.listener&&(this.sound=new qs.PositionalAudio(e.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}_focusCallback;awake(){this.audioLoader=new qs.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&&De._userInteractionRegistered&&this.play()},this.context.application.addEventListener("application-visible",this._focusCallback)}onDestroy(){this.context.application.removeEventListener("application-visible",this._focusCallback)}onEnable(){De._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():De._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){ut&&console.log("audio buffer loaded"),De.registerWaitForAllowAudio(()=>{ut&&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(),ut&&console.log(this.name,this.shouldPlay,De.userInteractionRegistered,this),this.shouldPlay&&De._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(ut&&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?ut&&!this.helper&&(this.helper=new ry(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&(ut&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new qs.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){ut&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,ut&&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,ut&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying&&this.sound.play()}pause(){ut&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause())}stop(){ut&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,ut&&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,ut&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},se=De;D(se,"_didCallBeginWaitForUserInteraction",!1),D(se,"callbacks",[]),D(se,"_userInteractionRegistered",!1),y([_()],se.prototype,"clip",2),y([_()],se.prototype,"playOnAwake",2),y([_()],se.prototype,"loop",1),y([_()],se.prototype,"spatialBlend",1),y([_()],se.prototype,"minDistance",1),y([_()],se.prototype,"maxDistance",1),y([_()],se.prototype,"volume",1),y([_()],se.prototype,"rollOffMode",2);import*as Ht from"three";import{Color as oy}from"three";var Z=class extends oy{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=H.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}lerpColors(e,t,i){let n=e,r=t;return n.alpha&&r.alpha&&(this.alpha=H.lerp(n.alpha,r.alpha,i)),super.lerpColors(e,t,i)}multiply(e){let t=e;return t.alpha&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}};import{PerspectiveCamera as ay,Ray as ly}from"three";var Ml=O("debugcam"),Il=class extends M{get isCamera(){return!0}get aspect(){return this._cam instanceof ay?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 Ht.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())}_nearClipPlane=.1;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())}_farClipPlane=1e3;get clearFlags(){return this._clearFlags}set clearFlags(e){e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}orthographic=!1;orthographicSize=5;ARBackgroundAlpha=0;set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}_cullingMask=4294967295;set backgroundBlurriness(e){e!==this._backgroundBlurriness&&(e===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(e,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}_backgroundBlurriness;set backgroundIntensity(e){e!==this._backgroundIntensity&&(e===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(e,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}_backgroundIntensity;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()}e.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}_backgroundColor;_fov=60;_cam=null;_clearFlags=2;_skybox;get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(e,t,i){let n=Il._origin;n.set(e,t,-1),this.context.input.convertScreenspaceToRaycastSpace(n),n.z=-1,n.unproject(this.cam);let r=Il._direction.set(n.x,n.y,n.z),s=B(this.cam);return r.sub(s),r.normalize(),i?(i.set(s,r),i):new ly(s.clone(),r.clone())}awake(){this.sourceId||console.warn("Camera has no source - the camera should be exported inside a gltf",this.name)}onEnable(){Ml&&console.log(this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&this.context.setCurrentCamera(this),this.applyClearFlagsIfIsActiveCamera()}onDisable(){this.context.removeCamera(this)}buildCamera(){if(this._cam)return;let e=this.gameObject.isCamera,t=null;if(e?(t=this.gameObject,t?.layers.enableAll()):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 Ht.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),t.fov=this.fieldOfView;else{let i=this.orthographicSize*100;t=new Ht.OrthographicCamera(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,this._nearClipPlane,this._farClipPlane)}this._cam=t,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){if(Ml&&Ke("apply Camera clear flags"),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(),this._backgroundBlurriness!==void 0&&(this.context.scene.backgroundBlurriness=this._backgroundBlurriness),this._backgroundIntensity!==void 0&&(this.context.scene.backgroundIntensity=this._backgroundIntensity);break;case 2:if(this._backgroundColor){let 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;Ml&&Ke("Environment blend mode: "+t+" on "+navigator.userAgent);let i=t==="additive"||t==="alpha-blend";if(this.context.xrSessionMode==="immersive-ar"&&t==="opaque"){if(navigator.userAgent?.includes("OculusBrowser"))return!0;if(navigator.userAgent?.includes("Mozilla")&&navigator.userAgent?.includes("Mobile WebXRViewer/v2"))return!0}return i}enableSkybox(){this._skybox||(this._skybox=new ru(this)),this._skybox.enable()}},ee=Il;D(ee,"_origin",new Ht.Vector3),D(ee,"_direction",new Ht.Vector3),y([_()],ee.prototype,"fieldOfView",1),y([_()],ee.prototype,"nearClipPlane",1),y([_()],ee.prototype,"farClipPlane",1),y([_()],ee.prototype,"clearFlags",1),y([_()],ee.prototype,"orthographic",2),y([_()],ee.prototype,"orthographicSize",2),y([_()],ee.prototype,"ARBackgroundAlpha",2),y([_()],ee.prototype,"cullingMask",1),y([_()],ee.prototype,"backgroundBlurriness",1),y([_()],ee.prototype,"backgroundIntensity",1),y([_(Z)],ee.prototype,"backgroundColor",1);var ru=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?this.context.scene.background!==this._skybox&&(Ml&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=Ht.sRGBEncoding,this._skybox.mapping=Ht.EquirectangularReflectionMapping,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this)}};var fi=class extends M{get listener(){return this._listener==null&&(this._listener=new zf.AudioListener),this._listener}_listener=null;awake(){se.registerWaitForAllowAudio(()=>{let e=this.listener;if(e==null||e.parent)return;let t=R.getComponentInParent(this.gameObject,ee);t?t.cam.add(e):this.gameObject.add(e)})}};import{GLTFLoader as cy}from"three/examples/jsm/loaders/GLTFLoader";import*as Dl from"three";var Ys=O("debugavatar"),Br=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))}},Jn=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 Fe;i=R.instantiate(Un(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 a=await n.blob();a&&(r=await a.arrayBuffer())}return!r&&(r=await sl(t,t,0,"no url here go away",!0),!r)?null:(await Xe().parseSync(e,r,null,0))?.scene??null}let i=new cy;return gn(i,e),new Promise((n,r)=>{let s=this.avatarRegistryUrl+"/"+t;i.load(s,async a=>{await Xe().createBuiltinComponents(e,s,a,null,void 0),n(a.scene)},a=>{Ys&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),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"]),s=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;let c=new Dl.Vector3;new Dl.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 Br(t,n,r,s)}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 s=this.findAvatarPart(r,t);if(s)return s}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}};import{AxesHelper as dy}from"three";var yn=class extends M{length=1;depthTest=!0;isGizmo=!0;_axes=null;onEnable(){if(this.isGizmo&&!Mi)return;this._axes||(this._axes=new dy(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)}};y([_()],yn.prototype,"length",2),y([_()],yn.prototype,"depthTest",2),y([_()],yn.prototype,"isGizmo",2);import*as Wf from"three";var Ao=class extends M{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=B(this.to).clone(),t=B(this.from).clone(),i=e.distanceTo(t),n=e.clone();n.sub(t);let r=t.clone();r.add(e),r.multiplyScalar(.5);let s=B(this.hint).clone();s.sub(r);let a=new Wf.Vector3;a.crossVectors(s,n),a.crossVectors(n,a),a.normalize();let c=i*.5,d=Math.max(this.desiredDistance,c),l=Math.sqrt(d*d-c*c),u=a.clone();u.multiplyScalar(l),u.add(r),ie(this.gameObject,u);let h=r.clone();h.sub(a),this.gameObject.lookAt(h)}};import*as Ur from"three";var uy=O("gizmos"),hy=O("debugboxhelper"),Ft=class extends M{box=null;_lastMatrixUpdateFrame=-1;isInBox(e,t){if(!e)return;if(this.box||(this.box=new Ur.Box3),e.type==="Mesh")Ft.testBox.setFromObject(e);else if(e.type==="Group"){if(Ft.testBox.makeEmpty(),e.children.length>0)for(let n=0;n<e.children.length;n++)e.children[n].type==="Mesh"&&Ft.testBox.expandByObject(e)}else{let n=B(e,Ft._position),r=Me(e,Ft._size);t!==void 0&&r.multiplyScalar(t),Ft.testBox.setFromCenterAndSize(n,r)}this.updateBox();let i=this.box?.intersectsBox(Ft.testBox);return i&&hy&&Dr.DrawBox3(Ft.testBox,16711680,5),i}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new Ur.Box3),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){let t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;let i=t,n=B(this.gameObject,Ft._position,i),r=Me(this.gameObject,Ft._size);this.box.setFromCenterAndSize(n,r)}return this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!uy&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=Ya(e),this.gameObject.add(this._helper)}}},Ue=Ft;D(Ue,"testBox",new Ur.Box3),D(Ue,"_position",new Ur.Vector3),D(Ue,"_size",new Ur.Vector3(.01,.01,.01));import{Quaternion as _y,Ray as xy,Vector3 as zr}from"three";import*as Nf from"three";var mi=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)}}},py=o=>/^[A-Z]*$/.test(o),Gr=class extends Event{args},ue=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&&py(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 mi(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}};import{Color as fy,Object3D as my}from"three";var su=class extends ln{constructor(){super([fy,Z])}onDeserialize(e){if(e!=null)return e.a!==void 0?new Z(e.r,e.g,e.b,e.a):e.alpha!==void 0?new Z(e.r,e.g,e.b,e.alpha):new Nf.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}}},lO=new su,au=class extends ln{constructor(){super(my)}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){let i=t.objectToNode[e.uuid];return Te&&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 Te&&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=R.findByGuid(e.guid,n)),i||(i=R.findByGuid(e.guid,t.context.scene)),i?Te&&console.log("Deserialized object reference?",e,i,t?.nodeToObject):console.warn("could not resolve reference",e,t.target,t.path,t.context.scene),i}}}},gy=new au,lu=class extends ln{constructor(){super([xt,M])}onSerialize(e,t){if(e?.guid)return{guid:e.guid}}onDeserialize(e,t){if(e?.guid){Te&&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=R.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],s=this.findObjectForGuid(e,r);if(s)return s}}},ou=new lu,cu=class extends ln{constructor(){super([ue])}onSerialize(e,t){console.log("TODO: SERIALIZE EVENT")}onDeserialize(e,t){if(typeof e=="function")return new ue([new mi(e,!0)]);if(e&&e.type==="EventList"){Te&&console.log("DESERIALIZE EVENT",e);let i=new Array;if(e.calls&&Array.isArray(e.calls))for(let s of e.calls){Te&&console.log(s);let a=ou.findObjectForGuid(s.target,t.root);!a&&t.context?.scene&&(a=ou.findObjectForGuid(s.target,t.context?.scene));let c=s.method?.length>0;if(a&&c){let h=()=>console.warn(`Could not find method ${s.method} on object ${a.name}`,a,typeof a[s.method]);if(typeof a[s.method]!="function"){let b=!1;s.method.startsWith("set_")&&s.method.length>4&&(s.method=s.method.substring(4),a[s.method]!==void 0&&(b=!0)),b||h()}}let d,l=s.argument;s.argument!==void 0?(typeof l=="object"&&(l=gy.onDeserialize(s.argument,t),l||(l=ou.onDeserialize(s.argument,t))),d=new mi(c?(...h)=>u(...h):void 0,s.enabled)):d=new mi(c?(...h)=>u(...h):void 0,s.enabled);let u=(...h)=>{let b=a[s.method];typeof b=="function"?l!==void 0?b?.call(a,l):b?.call(a,...h):a[s.method]=l};if(d.method||(d.__debuginfo=t.object?.name),!a||!d.method){let h=t.object?"Current object: "+t.object.name+", "+t.object.guid:null;a?console.warn('EventList method not found: "'+s.method+'" on',a):console.warn("EventList is missing target - will be ignored",s.target,h,e)}else i.push(d)}let n=new ue(i);Te&&console.log(n);let r=t.target;return r!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,r),n}}},cO=new cu;import*as Lo from"three";import{Matrix4 as vy,Vector3 as Xf}from"three";var du=class{get isDirty(){return this.positionChanged||this.rotationChanged}positionChanged=!1;rotationChanged=!1;position;quaternion;_positionKeys=["x","y","z"];_quaternionKeys=["_x","_y","_z","_w"];reset(e=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,e){if(this.position)for(let t of this._positionKeys)delete this.position[t];if(this.quaternion)for(let t of this._quaternionKeys)delete this.quaternion[t]}}syncValues(){for(let e of this._positionKeys)this.position[e]=this.obj.position[e];for(let e of this._quaternionKeys)this.quaternion[e]=this.obj.quaternion[e]}mute=!1;applyValues(){if(this.positionChanged&&this.position)for(let e of this._positionKeys){let t=this.position[e];t!==void 0&&(this.obj.position[e]=t)}if(this.rotationChanged&&this.quaternion)for(let e of this._quaternionKeys){let t=this.quaternion[e];t!==void 0&&(this.obj.quaternion[e]=t)}}context;obj;_positionWatch;_rotationWatch;constructor(e,t){this.context=t,this.obj=e}start(e,t){this.reset(),e&&(this._positionWatch||(this._positionWatch=new sn(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((r,s)=>{if(this.context.physics.isUpdating||this.mute)return;let a=this.position[s];Math.abs(a-r)<1e-5||(this.position[s]=r,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new sn(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((r,s)=>{if(this.context.physics.isUpdating||this.mute)return;let a=this.quaternion[s];Math.abs(a-r)<1e-5||(this.quaternion[s]=r,this.rotationChanged=!0)}));let i=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),n=new vy;this.obj.matrixWorld.multiplyMatrices=(r,s)=>(n.equals(r)||(this.positionChanged=!0,this.rotationChanged=!0,n.copy(r)),i(r,s))}stop(){this._positionWatch?.revoke(),this._rotationWatch?.revoke()}},Al=class extends M{mass=1;useGravity=!0;constraints=0;isKinematic=!1;drag=0;angularDrag=1;detectCollisions=!0;sleepThreshold=.01;collisionDetectionMode=0;get lockPositionX(){return(this.constraints&2)!==0}get lockPositionY(){return(this.constraints&4)!==0}get lockPositionZ(){return(this.constraints&8)!==0}get lockRotationX(){return(this.constraints&16)!==0}get lockRotationY(){return(this.constraints&32)!==0}get lockRotationZ(){return(this.constraints&64)!==0}set lockPositionX(e){e?this.constraints|=2:this.constraints&=-3}set lockPositionY(e){e?this.constraints|=4:this.constraints&=-5}set lockPositionZ(e){e?this.constraints|=8:this.constraints&=-9}set lockRotationX(e){e?this.constraints|=16:this.constraints&=-17}set lockRotationY(e){e?this.constraints|=32:this.constraints&=-33}set lockRotationZ(e){e?this.constraints|=64:this.constraints&=-65}_propertiesChanged=!1;_currentVelocity=new Lo.Vector3;_smoothedVelocity=new Lo.Vector3;_smoothedVelocityGetter=new Lo.Vector3;_lastPosition=new Lo.Vector3;_watch;awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new du(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),2)}onDisable(){this._watch?.stop(),this.context.physics.removeBody(this)}onDestroy(){this.context.physics.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,this.context.physics.updateProperties(this)),this._watch?.isDirty?(this._watch.mute=!0,this._watch.applyValues(),this.context.physics.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):this._watch?.syncValues(),this.captureVelocity(),yield}get body(){return this.context.physics.internal_getRigidbody(this)}teleport(e,t=!0){this._watch?.reset(!0),t?this.gameObject.position.set(e.x,e.y,e.z):this.setWorldPosition(e.x,e.y,e.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(){this.body?.resetForces(!0)}resetTorques(){this.body?.resetTorques(!0)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){this.body?.wakeUp()}applyForce(e,t){this.body?.addForce(e,!0)}applyImpulse(e){this.body?.applyImpulse(e,!0)}setForce(e,t,i){this.body?.resetForces(!0),this.body?.addForce({x:e,y:t,z:i},!0)}getVelocity(){let e=this.body?.linvel();return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(e,t,i){if(e instanceof Xf){let n=e;this.body?.setLinvel(n,!0);return}t===void 0||i===void 0||this.body?.setLinvel({x:e,y:t,z:i},!0)}setAngularVelocity(e,t,i){if(e instanceof Xf){let n=e;this.body?.setAngvel(n,!0);return}t===void 0||i===void 0||this.body?.setAngvel({x:e,y:t,z:i},!0)}setTorque(e,t,i){this.setAngularVelocity(e,t,i)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(e=null){this.gameObject&&this.destroyed}captureVelocity(){if(this.body){let e=B(this.gameObject);Al.tempPosition.copy(e);let t=e.sub(this._lastPosition);this._lastPosition.copy(Al.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}}},K=Al;D(K,"tempPosition",new Lo.Vector3),y([li(),_()],K.prototype,"mass",2),y([li(),_()],K.prototype,"useGravity",2),y([li(),_()],K.prototype,"constraints",2),y([li(),_()],K.prototype,"isKinematic",2),y([li(),_()],K.prototype,"drag",2),y([li(),_()],K.prototype,"angularDrag",2),y([li(),_()],K.prototype,"detectCollisions",2),y([li(),_()],K.prototype,"sleepThreshold",2),y([li(),_()],K.prototype,"collisionDetectionMode",2);import{Mesh as yy,Vector3 as Zn}from"three";var Ut=class extends M{get isCollider(){return!0}attachedRigidbody=null;isTrigger=!1;awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(K))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(K))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(K))}onDisable(){this.context.physics.removeBody(this)}};y([_(K)],Ut.prototype,"attachedRigidbody",2),y([_()],Ut.prototype,"isTrigger",2);var $n=class extends Ut{radius=.5;center=new Zn(0,0,0);onEnable(){super.onEnable(),this.context.physics.addSphereCollider(this,this.center,this.radius)}};y([_()],$n.prototype,"radius",2),y([_(Zn)],$n.prototype,"center",2);var er=class extends Ut{size=new Zn(1,1,1);center=new Zn(0,0,0);onEnable(){super.onEnable(),this.context.physics.addBoxCollider(this,this.center,this.size)}};y([_(Zn)],er.prototype,"size",2),y([_(Zn)],er.prototype,"center",2);var Vr=class extends Ut{sharedMesh;convex=!1;onEnable(){super.onEnable(),this.sharedMesh?.isMesh||this.gameObject instanceof yy&&(this.sharedMesh=this.gameObject),this.sharedMesh?.isMesh&&this.context.physics.addMeshCollider(this,this.sharedMesh,this.convex,Me(this.gameObject))}};y([_()],Vr.prototype,"convex",2);var Bt=class extends Ut{center=new Zn(0,0,0);radius=.5;height=2;onEnable(){super.onEnable(),this.context.physics.addCapsuleCollider(this,this.center,this.height,this.radius)}};y([_(Zn)],Bt.prototype,"center",2),y([_()],Bt.prototype,"radius",2),y([_()],Bt.prototype,"height",2);var Bi=class extends M{center=new zr(0,0,0);radius=.5;height=2;_rigidbody=null;get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(K),this._rigidbody||(this._rigidbody=this.gameObject.addNewComponent(K)),this.rigidbody)}onEnable(){let e=this.rigidbody,t=this.gameObject.getComponent(Bt);t||(t=this.gameObject.addNewComponent(Bt)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height,this.gameObject.rotation.x=0,this.gameObject.rotation.z=0,e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}_activeGroundCollisions=new Set;onCollisionEnter(e){for(let t of e.contacts)if(t.normal.y>.1){this._activeGroundCollisions.add(e);break}}onCollisionExit(e){this._activeGroundCollisions.delete(e)}get isGrounded(){return this._activeGroundCollisions.size>0}};y([_(zr)],Bi.prototype,"center",2),y([_()],Bi.prototype,"radius",2),y([_()],Bi.prototype,"height",2);var gi=class extends M{controller;movementSpeed=2;rotationSpeed=2;jumpForce=1;animator;lookForward=!0;_currentSpeed=new zr(0,0,0);_currentAngularSpeed=new zr(0,0,0);_temp=new zr(0,0,0);_jumpCount=0;_currentRotation;awake(){this._currentRotation=new _y}update(){this.controller?.isGrounded&&(this._jumpCount=0,this.animator?.SetBool("doubleJump",!1));let e=this.context.input.isKeyPressed("w"),t=this.context.input.isKeyPressed("s"),i=this.context.input.isKeyPressed("a"),n=this.context.input.isKeyPressed("d"),r=this.context.input.isKeyDown(" "),s=e?1:0+t?-1:0;this._currentSpeed.z+=s*this.movementSpeed*this.context.time.deltaTime,this.animator?.SetBool("running",s!=0),this.animator?.SetBool("jumping",this.controller?.isGrounded===!0&&r),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp);let a=i?1:0+n?-1:0;if(this._currentAngularSpeed.y+=H.toRadians(a*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){let c=this.context.mainCameraComponent.forward;c.y=0,c.normalize(),this._currentRotation.setFromUnitVectors(new zr(0,0,1),c),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&r&&this.jumpForce>0){let c=this.controller?.isGrounded;if(!this.controller?.isGrounded&&this._jumpCount===1&&(c=!0,this.animator?.SetBool("doubleJump",!0)),c){this._jumpCount+=1;let d=this.controller.rigidbody,l=this._jumpCount===2?2:1;d.applyImpulse(new zr(0,1,0).multiplyScalar(this.jumpForce*l))}}if(this.controller){let c=this.controller?.rigidbody.getVelocity().y;if(c<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new xy),this._raycastOptions.ray.origin.copy(B(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);let d=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);let l=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(d),(l.length&&l[0].distance>2||c<-10)&&this.animator?.SetBool("falling",!0)}else this.animator?.SetBool("falling",!1)}}_raycastOptions=new ge};y([_(Bi)],gi.prototype,"controller",2),y([_()],gi.prototype,"movementSpeed",2),y([_()],gi.prototype,"rotationSpeed",2),y([_()],gi.prototype,"jumpForce",2),y([_(Be)],gi.prototype,"animator",2);var Gt=class extends M{canGrab=!0;onPointerClick(e){}},Vt=class extends M{isUsed=!0;usedBy=null};var Wr=class extends Ue{},jo=class extends M{deleteBoxes=[];awake(){this.deleteBoxes=R.findObjectsOfType(Wr,this.context)}update(){for(let e of this.deleteBoxes){let t=this.gameObject;e.isInBox(t)===!0&&(R.getComponentInParent(this.gameObject,Vt)||bo(this.gameObject,this.context.connection))}}};var Nr=class extends M{visibleOn;onEnable(){this.apply()}apply(){this.test()||R.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:wy()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}};y([_()],Nr.prototype,"visibleOn",2);var Ll;function wy(){if(Ll===!0||Ll===!1)return Ll;let o=!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)))&&(o=!0)}(navigator.userAgent||navigator.vendor||window.opera),Ll=o,o}import*as _n from"three";var we=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 Ho=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new we).__init(this.bb_pos,this.bb)}rotation(e){return(e||new we).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new we).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,n,r,s,a,c,d,l){return e.prep(4,36),e.prep(4,12),e.writeFloat32(l),e.writeFloat32(d),e.writeFloat32(c),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(s),e.writeFloat32(r),e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var zt=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 zt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+4),(t||new zt).__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 Ho).__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 tr=O("debugsync"),Fo="STRS";So(Fo,zt.getRootAsSyncedTransformModel);var Ui=new yt;function uu(o,e,t=!0){Ui.clear();let i=Ui.createString(o);zt.startSyncedTransformModel(Ui),zt.addGuid(Ui,i),zt.addFast(Ui,t);let n=e.worldPosition,r=e.worldEuler,s=e.gameObject.scale;zt.addTransform(Ui,Ho.createTransform(Ui,n.x,n.y,n.z,r.x,r.y,r.z,s.x,s.y,s.z));let a=zt.endSyncedTransformModel(Ui);return Ui.finish(a,Fo),Ui.asUint8Array()}var wt=class extends M{overridePhysics=!0;interpolatePosition=!0;interpolateRotation=!0;fastMode=!1;syncDestroy=!1;_model=null;_needsUpdate=!0;rb=null;_wasKinematic=!1;_receivedDataBefore=!1;_targetPosition;_targetRotation;_receivedFastUpdate=!1;_shouldRequestOwnership=!1;requestOwnership(){tr&&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(){tr&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new _n.Vector3,this._targetRotation=new _n.Quaternion,this.lastWorldPos=new _n.Vector3,this.lastWorldRotation=new _n.Quaternion,this.rb=R.getComponentInChildren(this.gameObject,K),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Nn(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(Fo,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Cp(this.guid,this.context.connection),this._model=null,this.context.connection.stopListening("joined-room",this.joinedRoomCallback),this.context.connection.stopListenBinary(Fo,this.receivedDataCallback)}tryGetLastState(){let e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new _n.Euler;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){tr&&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){oe.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)&&hp(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){tr&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());let e=this.worldPosition,t=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){let r=e.distanceTo(this.lastWorldPos),s=t.angleTo(this.lastWorldRotation),a=this._model.hasOwnership||this.fastMode?1e-4:.001;(r>a||s>a)&&(this._model.hasOwnership?this._needsUpdate=!0:(tr&&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),oe.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){let s=this._receivedFastUpdate||this.fastMode?.5:.3,a=!1;if(this.interpolatePosition&&this._targetPosition){let c=this.worldPosition;c.lerp(this._targetPosition,s),this.worldPosition=c,a=!0}if(this.interpolateRotation&&this._targetRotation){let c=this.worldQuaternion;c.slerp(this._targetRotation,s),this.worldQuaternion=c,a=!0}a&&oe.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&&(tr&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new _n.Vector3(0,0,0))>1e3&&(tr&&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)){tr&&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=uu(this.guid,this,!!n);this.context.connection.sendBinary(r)}}};import*as q from"three";import{Euler as Jy,EventDispatcher as Zy,Group as $y,Matrix4 as nm,Mesh as e_,MeshBasicMaterial as t_,Object3D as im,Quaternion as Wl,RingGeometry as i_,Vector3 as xu}from"three";var jl=class{static createButton(e,t={}){let i=document.createElement("button"),n=!1;function r(){if(t.domOverlay===void 0){var d=document.createElement("div");d.style.display="none",document.body.appendChild(d);var l=document.createElementNS("http://www.w3.org/2000/svg","svg");l.setAttribute("width",38),l.setAttribute("height",38),l.style.position="absolute",l.style.right="20px",l.style.top="20px",l.addEventListener("click",function(){h.end()}),d.appendChild(l);var u=document.createElementNS("http://www.w3.org/2000/svg","path");u.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),u.setAttribute("stroke","#fff"),u.setAttribute("stroke-width",2),l.appendChild(u),t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("dom-overlay"),t.domOverlay={root:d},n=!0}t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("local-floor"),t.optionalFeatures.push("hand-tracking"),t.optionalFeatures.push("layers");let h=null,b=null;async function w(x){if(/WebXRViewer\//i.test(navigator.userAgent))if(t.domOverlay?.root){let f=t.domOverlay.root;b=f.parentElement,b&&(console.log("Reparent DOM Overlay to body",f,f.style.display),f.style.display="",f.style.visibility="",document.body.appendChild(f))}else console.warn("WebXRViewer: No DOM Overlay found");x.addEventListener("end",v),await e.xr.setSession(x),i.textContent="STOP AR",n&&(t.domOverlay.root.style.display=""),h=x}function v(){h.removeEventListener("end",v),i.textContent="START AR",b&&b.appendChild(t.domOverlay.root),n&&(t.domOverlay.root.style.display="none"),h=null}i.style.display="",i.style.cursor="pointer",i.style.left="calc(50% - 50px)",i.style.width="100px",i.textContent="START AR",i.onmouseenter=function(){i.style.opacity="1.0"},i.onmouseleave=function(){i.style.opacity="0.5"},i.onclick=function(){h===null?navigator.xr.requestSession("immersive-ar",t).then(w):h.end()}}function s(){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 a(){s(),i.textContent="AR NOT SUPPORTED"}function c(d){d.style.position="absolute",d.style.bottom="20px",d.style.padding="12px 6px",d.style.border="1px solid #fff",d.style.borderRadius="4px",d.style.background="rgba(0,0,0,0.1)",d.style.color="#fff",d.style.font="normal 13px sans-serif",d.style.textAlign="center",d.style.opacity="0.5",d.style.outline="none",d.style.zIndex="999"}if("xr"in navigator)return i.id="ARButton",i.style.display="none",c(i),navigator.xr.isSessionSupported("immersive-ar").then(function(d){d?r():a()}).catch(a),i;{let d=document.createElement("a");return window.isSecureContext===!1?(d.href=document.location.href.replace(/^http:/,"https:"),d.innerHTML="WEBXR NEEDS HTTPS"):(d.href="https://immersiveweb.dev/",d.innerHTML="WEBXR NOT AVAILABLE"),d.style.left="calc(50% - 90px)",d.style.width="180px",d.style.textDecoration="none",c(d),d}}};var Hl=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",l),await e.xr.setSession(u),i.textContent="EXIT VR",c=u}function l(){c.removeEventListener("end",l),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 s(){r(),i.textContent="VR NOT SUPPORTED"}function a(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",a(i),navigator.xr.isSessionSupported("immersive-vr").then(function(c){c?n():s(),Hl.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",a(c),c}}static registerSessionGrantedListener(){if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent))return;navigator.xr.addEventListener("sessiongranted",()=>{Hl.xrSessionIsGranted=!0})}}},Uo=Hl;D(Uo,"xrSessionIsGranted",!1);Uo.registerSessionGrantedListener();import*as Fl from"three";var Qf=wa(el(),1);import{AudioAnalyser as Ey}from"three";var Go="noVoip",ht=O("debugvoip"),Cy=O("voip");var hu=class{id;constructor(e){this.id=e}};var pu=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(){ht&&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 tt.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}ht&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),ht&&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=>{ht&&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){ht&&console.log("call closed",e)}},fu=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,se.userInteractionRegistered||ht&&console.log("Incoming call, waiting for user interaction before opening audio"),se.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){ht&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);let t=new Fl.AudioListener;this.audio=new Fl.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}}}),ht&&console.log("call is setup, you should hear something now"),this.analyzer=new Ey(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()}},tt=class extends M{requireParam=!1;set muteInput(e){if(e===this._inputMuted||(this._inputMuted=e,!this.currentIncomingCalls))return;let t=this._inputMuted?0:1;for(let i in this.currentIncomingCalls)this.currentIncomingCalls[i]?.currentAudio?.setVolume(t)}get muteInput(){return this._inputMuted}set muteOutput(e){if(e!==this._outputMuted&&(this._outputMuted=e,!!this.connections))for(let t in this.connections)this.connections[t]?.updateMute(e)}get muteOutput(){return this._outputMuted}getFrequency(e){if(e===null){for(let i in this.currentIncomingCalls){let n=this.currentIncomingCalls[i];if(n&&n.currentAnalyzer)return n.currentAnalyzer.getAverageFrequency()}return null}let t=this.currentIncomingCalls[e];return t&&t.currentAnalyzer?t.currentAnalyzer.getAverageFrequency():null}peer=null;model=null;connections={};currentIncomingCalls={};_inputMuted=!1;_outputMuted=!1;awake(){if(O(Go)){console.log("VOIP is disabled by url parameter: "+Go);return}if(this.requireParam&&!Cy){console.debug("VOIP must be enabled explicitly by url parameter");return}this.peer=new Qf.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 pu(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];ht&&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){ht&&console.log("Peer connection established and received id"),this.model=new hu(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){ht&&console.log("CONNECTION",t),t.on("data",function(i){ht&&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(),ht&&console.log("received call"),await tt.HasMicrophonePermissions()){let s=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(s)}else e.answer(null);this.currentIncomingCalls[i]=new fu(this,this.gameObject,e),e.on("stream",s=>{ht&&console.log("receive caller stream, will setup audio now"),this.currentIncomingCalls[i]?.openAudioStream(s)}),e.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}};import{Matrix4 as Ks}from"three";var Wt=class extends M{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 Ks;_selectStartFn=this.onSelectStart.bind(this);_selectEndFn=this.onSelectEnd.bind(this);start(){let e=R.findObjectOfType(V);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 Ks().fromArray(i.transform.matrix).invert()),!0):!1}placeAt(e,t){if(this._placementPose||(this._placementPose=new Ks),this._placementPose.copy(t),e){if(this.invertForward){let i=new Ks().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)),oe.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 Ks().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld(),console.log("Place",t.position))}};y([_()],Wt.prototype,"invertForward",2),y([_()],Wt.prototype,"arScale",1);import{BoxHelper as Iy,BufferGeometry as Dy,Color as Zf,Euler as Ay,Layers as Ly,Line as jy,Mesh as Hy,MeshBasicMaterial as Fy,Quaternion as Vl,Ray as By,SphereGeometry as Uy,Vector2 as Gy,Vector3 as xi}from"three";import{OculusHandModel as Vy}from"three/examples/jsm/webxr/OculusHandModel.js";import{OculusHandPointerModel as zy}from"three/examples/jsm/webxr/OculusHandPointerModel.js";import{XRControllerModelFactory as Wy}from"three/examples/jsm/webxr/XRControllerModelFactory.js";import{GLTFLoader as Ny}from"three/examples/jsm/loaders/GLTFLoader.js";import*as Kf from"three";import{Quaternion as Ty,Vector3 as Bl}from"three";var Vo=O("debugflags");var mu=class{Mask=17;Has(e){return(this.Mask&e)!==0}Set(e){Vo&&console.warn("Set XR flag state to",e),this.Mask=e,Ee.Apply()}Enable(e){this.Mask|=e,Ee.Apply()}Disable(e){this.Mask&=~e,Ee.Apply()}Toggle(e){this.Mask^=e,Ee.Apply()}EnableAll(){this.Mask=-1,Ee.Apply()}DisableAll(){this.Mask=0,Ee.Apply()}},Et=mu;D(Et,"Global",new mu);var Gi=class extends M{static Apply(){for(let e of this.registry)e.UpdateVisible(Et.Global)}awake(){Gi.registry.push(this)}onEnable(){Gi.firstApply||(Gi.firstApply=!0,Gi.Apply())}onDestroy(){let e=Gi.registry.indexOf(this);e>=0&&Gi.registry.splice(e,1)}visibleIn;get isOn(){return this.gameObject.visible}UpdateVisible(e=null){let t,i=e;i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),Vo&&console.log(i),Gi.buffer.Mask=i,e=Gi.buffer);let n=e;if(n?(Vo&&console.warn(this.name,"use passed in mask",n.Mask,this.visibleIn),t=n.Has(this.visibleIn)):(Vo&&console.log(this.name,"use global mask"),Et.Global.Has(this.visibleIn)),t!==void 0)if(t)Vo&&console.log(this.name,"is visible",this.gameObject.uuid),R.setActive(this.gameObject,!0);else{if(Vo&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},Ee=Gi;D(Ee,"registry",[]),D(Ee,"firstApply"),D(Ee,"buffer",new Et);import{Object3D as gu}from"three";var ir=O("debugavatar"),bi=class extends M{static getAvatar(e){return e>=0&&e<bi.instances.length?bi.instances[e]:null}static onAvatarMarkerCreated(e){return bi._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return bi._onAvatarMarkerDestroyed.push(e),e}connectionId;avatar;awake(){bi.instances.push(this),ir&&console.log(this);for(let e of bi._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){bi.instances.splice(bi.instances.indexOf(this),1);for(let e of bi._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):R.setActive(this.avatar,e))}},le=bi;D(le,"instances",[]),D(le,"_onNewAvatarMarkerAdded",[]),D(le,"_onAvatarMarkerDestroyed",[]);var Js=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 Bl(1,1,1);handLeftScale=new Bl(1,1,1);handRightScale=new Bl(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;this.context.isInVR?e|=4:this.context.isInAR?e|=2:e|=1;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 gu;_handLeftTarget=new gu;_handRightTarget=new gu;_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),oe.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 s=this.isLocalAvatar?this.handLeft:this._handLeftTarget;s.position.set(e.posLeftHand.x,e.posLeftHand.y,e.posLeftHand.z),s.quaternion.set(e.rotLeftHand._x,e.rotLeftHand._y,e.rotLeftHand._z,e.rotLeftHand._w),s.quaternion.multiply(Js.invertRotation),s.scale.set(e.scale,e.scale,e.scale),s.scale.multiply(this.handLeftScale),oe.markDirty(this.handLeft)}if(this.handRight){let s=this.isLocalAvatar?this.handRight:this._handRightTarget;s.position.set(e.posRightHand.x,e.posRightHand.y,e.posRightHand.z),s.quaternion.set(e.rotRightHand._x,e.rotRightHand._y,e.rotRightHand._z,e.rotRightHand._w),s.quaternion.multiply(Js.invertRotation),s.scale.set(e.scale,e.scale,e.scale),s.scale.multiply(this.handRightScale),oe.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(){ir&&console.log("Destroy avatar",this.guid),this.root?.removeFromParent(),this.avatarMarker?.destroy(),this.lastAvatarId=null,this.head&&ve.Remove(this.context,this.head)}updateVisibility(){let e=this.root;e&&R.setActive(e,this._isVisible)}async setupCustomAvatar(e){if(ir&&console.log("LOAD",e,this),!e||typeof e=="string"&&e.length<=0)return!1;this.head&&ve.Remove(this.context,this.head);let t=e;if(t?.loadAssetAsync!==void 0){await t.loadAssetAsync();let n=t.asset;R.setActive(n,!1),e=R.instantiate(n),R.setActive(e,!0)}ir&&console.log(e);let i=await Js.loader.getOrCreateNewAvatarInstance(this.context,e);if(ir&&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=R.addNewComponent(this.root,le),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&&ve.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(...R.getComponentsInChildren(this.root,Ee)),this.flags.length<=0&&this.head){let n=R.addNewComponent(this.head,Ee);n.visibleIn=20,this.flags.push(n),ir&&console.log("Added flag to head: "+n.visibleIn,this.head.name)}return ir&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return ir&&console.warn("build avatar failed"),!1}},Nt=Js;D(Nt,"loader",new Jn),D(Nt,"invertRotation",new Ty().setFromAxisAngle(new Bl(0,1,0),Math.PI));var ve=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??G.Current?.time.time;return}}}};D(ve,"Pois",[]),D(ve,"LastChangeTime",0);var bu=class{guid;position=new Kf.Vector3},xn=class extends M{set controlledTarget(e){this.target=e;let t=P.get("MoveRandom");if(t&&this.target){let i=R.getComponent(this.target,t);i&&i.destroy()}}target=null;avatar=null;_model=null;_targetModel=new bu;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=R.getComponentInParent(this.gameObject,le),this.avatar){let e=R.getComponentInParent(this.gameObject,le);this._model=new Nn(this.context.connection,this.guid),e?.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{this.target&&e&&e.guid===this.avatar?.guid&&ie(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(ve.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=ve.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){let t=B(this._currentTargetObject);ie(this.target,t),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(t))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;let t=ve.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 Gl from"three-mesh-ui";import{OrbitControls as Sy}from"three/examples/jsm/controls/OrbitControls";import{Object3D as Ry}from"three";var wn=class extends M{constraintActive=!0;locked=!1;sources=[]};y([_(Ry)],wn.prototype,"sources",2);import*as Zs from"three";var Ul=O("freecam"),it=class extends M{get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){this.controls?.addEventListener("start",e)}autoRotate=!1;autoRotateSpeed=1;enableKeys=!0;enableDamping=!0;dampingFactor=.1;enableZoom=!0;minZoom=0;maxZoom=1/0;enablePan=!0;lookAtConstraint=null;lookAtConstraint01=1;middleClickToFocus=!0;doubleClickToFocus=!0;useSlerp=!0;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 Zs.Vector3,this._startedListeningToKeyEvents=!1}onEnable(){this._enableTime=this.context.time.time;let t=R.getComponent(this.gameObject,ee)?.cam;this._controls||(console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t),this._controls=new Sy(t,this.context.renderer.domElement)),this._controls&&(Ul&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,Ea()&&(this.doubleClickToFocus=!0)),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"?Ul||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):Ul||(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=R.getComponent(this.gameObject,ee);if(e&&!this.setFromTargetPosition()){this.debugLog&&console.log("NO TARGET");let t=new Zs.Vector3(0,0,-1).applyMatrix4(e.cam.matrixWorld);this.setTarget(t,!0)}}this.startCoroutine(this.startRaycastDelayed())}*startRaycastDelayed(){if(yield,!this.setFromTargetPosition()){let e=new ge;e.screenPoint=new Zs.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;if(this._lerpCameraToTarget&&this._cameraTargetPosition&&this._cameraObject){if(this.useSlerp){let i=this._cameraObject?.position;dp(i,this._cameraTargetPosition,t)}else this._cameraObject?.position.lerp(this._cameraTargetPosition,t);this._cameraObject.position.distanceTo(this._cameraTargetPosition)<1e-4&&(this._lerpCameraToTarget=!1)}this._lerpToTargetPosition&&(this.lerpTarget(this._lookTargetPosition,t),this._lookTargetPosition.distanceTo(this._controls.target)<1e-5&&(this._lerpToTargetPosition=!1))}!Ul&&this.lookAtConstraint?.locked&&this.setFromTargetPosition(0,this.lookAtConstraint01),this._controls&&!this.context.isInXR&&(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&&R.isActiveInHierarchy(t.object)){if(this._lookTargetPosition.copy(t.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;let i=B(this.context.mainCamera);this._cameraTargetPosition=i.clone().sub(this.controls.target).add(this._lookTargetPosition),this._cameraObject?.parent?.worldToLocal(this._cameraTargetPosition)}break}}};y([_(wn)],it.prototype,"lookAtConstraint",2);var vi=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 Oy}from"three";var ky=O("debugeventsystem"),Vi=class extends M{static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Vi.systems.length<=0&&Vi.systems.push(...R.findObjectsOfType(Vi,e)));for(let i of Vi.systems)if(i.context===e)return;let t=new Oy;R.addNewComponent(t,Vi),e.scene.add(t)}static get systems(){let e=G.Current;return this._eventSystemMap.has(e)||this._eventSystemMap.set(e,[]),this._eventSystemMap.get(e)}static ensureUpdateMeshUI(e,t){yi.update(e,t)}static markUIDirty(e){yi.markDirty()}static get instance(){return this.systems[0]}orbitControl=null;orbitControlWasEnabled=!1;raycaster=[];constructor(){super(),Vi.systems.push(this)}onDestroy(){Vi.systems.splice(Vi.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(){let e=new Map;this._selectStartFn??=(i,n)=>{if(!n.grab)return;yi.resetLastSelected();let r=new vi;r.inputSource=i,r.isDown=i.selectionDown,r.isUp=i.selectionUp,r.isPressed=i.selectionPressed,r.isClicked=!1,e.set(i,n.grab),n.grab&&!this.handleEvents(n.grab,r)&&(n.grab=null)},this._selectEndFn??=(i,n)=>{if(!n.grab)return;let r=new vi;r.inputSource=i,r.isDown=i.selectionDown,r.isUp=i.selectionUp,r.isPressed=i.selectionPressed,r.isClicked=i.selectionClick,this.handleEvents(n.grab,r);let s=e.get(i);if(e.set(i,null),s)for(let a=0;a<this.raisedPointerDownEvents.length;a++){let c=this.raisedPointerDownEvents[a];this.raisedPointerDownObjects[a]===s&&c&&(c.onPointerUp?.call(c,r),this.raisedPointerDownEvents.splice(a,1),this.raisedPointerDownObjects.splice(a,1),a--)}};let t=new ge;this._selectUpdateFn??=i=>{t.ray=i.getRay();let n=this.performRaycast(t);if(!n)return;let r=new vi;r.inputSource=i,this.handleIntersections(n,r)},J.addEventListener("select-start",this._selectStartFn),J.addEventListener("select-end",this._selectEndFn),J.addEventListener("update",this._selectUpdateFn),this.context.pre_update_callbacks.push(this.onBeforeUpdate.bind(this)),this.context.input.addEventListener("pointerdown",this.onPointerDown.bind(this))}onDisable(){J.removeEventListener("select-start",this._selectStartFn),J.removeEventListener("select-end",this._selectEndFn),J.removeEventListener("update",this._selectUpdateFn)}onPointerDown(){this.onBeforeUpdate()}lastPointerEvent=null;objectsHoveredThisFrame=[];objectsHoveredLastFrame=[];raisedPointerDownEvents=[];raisedPointerDownObjects=[];_didMove=!1;onBeforeUpdate(){if(this.objectsHoveredThisFrame.length=0,this.resetMeshUIStates(),V.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 vi(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=R.getComponent(this.context.mainCameraComponent.gameObject,it)??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,this.raisedPointerDownObjects.length=0}for(let t of this.objectsHoveredLastFrame)if(this.objectsHoveredThisFrame.indexOf(t)<0){this._tempComponentsArray.length=0;let i=R.getComponentsInParent(t,M,this._tempComponentsArray);this.lastPointerEvent.object=t;for(let n=0;n<i.length;n++){let r=i[n];if(!r.gameObject||r.destroyed)continue;let s=r;s.onPointerExit&&s.onPointerExit(this.lastPointerEvent)}}let e=this.objectsHoveredLastFrame;this.objectsHoveredLastFrame=this.objectsHoveredThisFrame,this.objectsHoveredThisFrame=e}_sortedHits=[];performRaycast(e){if(!this.raycaster)return null;this._sortedHits.length=0;for(let t of this.raycaster){if(!t.activeAndEnabled)continue;let i=t.performRaycast(e);i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}handleIntersections(e,t){if(!e||e.length<=0)return!1;e=this.sortCandidates(e);for(let i of e){let{object:n}=i;if(this.handleEvents(n,t))return!0}return!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){let i=e[t],n=i.object;if(n.material&&n.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(let t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventsArray=[];out={};handleEvents(e,t){if(!this.testIsVisible(e))return t.isClicked&&ky&&console.log("not allowed",e),!1;let i=e;t.object=e,this.lastPointerEvent=t;let n=e.parent,r=!1,s=t.isClicked??!1,a=null;if(n&&n.isUI){let c=(t.isPressed||t.isClicked)??!1;if(n[Ct]){let d=n[Ct].gameObject;if(d){if(!_i.isInteractable(d,this.out))return this.out.canvasGroup?.interactable??!1;a=this.out.canvasGroup??null;let u=this.handleMeshUIIntersection(e,c);e=d,r=!0}}if(!r&&this.handleMeshUiObjectWithoutShadowDom(n,c))return!0}if(this.objectsHoveredThisFrame.push(e),a===null||a.interactable){let c=this.objectsHoveredLastFrame.indexOf(e)>=0;this.handleEventsArray.length=0;let d=R.getComponentsInParent(e,M,this.handleEventsArray);for(let l=0;l<d.length;l++){if(t.used)return!0;if(d[l].destroyed)continue;let u=d[l];u.interactable!==!1&&(u.onPointerEnter&&(c||u.onPointerEnter(t)),t.isDown&&u.onPointerDown&&!this.raisedPointerDownEvents.includes(u)&&(u.onPointerDown(t),this.raisedPointerDownEvents.push(u),this.raisedPointerDownObjects.push(i)),t.isUp&&u.onPointerUp&&u.onPointerUp(t),t.isClicked&&u.onPointerClick&&u.onPointerClick(t))}}return!0}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){let i=yi.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&yi.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){let t=this.currentActiveMeshUIComponents[e];yi.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?R.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}},Qe=Vi;D(Qe,"_eventSystemMap",new Map),D(Qe,"didSearchEventSystem",!1);var yi=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}};D(yi,"lastSelected",null),D(yi,"lastUpdateFrame",[]),D(yi,"needsUpdate",!1);import{AxesHelper as My}from"three";var zo="./include";Gl.Block.prototype.interactable={get(){return this.interactive},set(o){this.interactable=o}};var Ct=Symbol("shadowDomOwner"),Ge=class extends M{isRoot(){return this.Root?.gameObject===this.gameObject}markDirty(){Qe.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=R.getComponentInParent(this.gameObject,En)),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=R.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[Ct]=this,e.traverse(r=>{r[Ct]===void 0&&(r[Ct]=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),Mi&&e.add(new My(.5)),this.onAfterAddedToScene(),n&&Gl.update()}set(e){}traverseOwnedShadowComponents(e,t,i){if(!!e&&e[Ct]===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)}},En=class extends Ge{awake(){super.awake()}};var _i=class{static getObject(e){let t=e[Ct];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=oi(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=oi(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 $s=O("debugwebxrcontroller");var Xr=class extends M{},Ae=class extends M{static CreateRaycastLine(){let e=new jy(this.geometry),t=e.material;return t.color=this.raycastColor,e.layers.set(2),e.name="line",e.scale.z=1,e}static CreateRaycastHitPoint(){let e=new Uy(.5,22,22),t=new Fy({color:this.raycastColor}),i=new Hy(e,t);return i.visible=!1,i.layers.set(2),i}static Create(e,t,i,n){let r=i?R.addNewComponent(i,Ae,!1):new Ae;r.webXR=e,r.index=t,r.type=n;let s=e.context;r.controller=s.renderer.xr.getController(t),r.controllerGrip=s.renderer.xr.getControllerGrip(t),r.controllerModel=this.Factory.createControllerModel(r.controller),r.controllerGrip.add(r.controllerModel),r.hand=s.renderer.xr.getHand(t);let a=new Ny;gn(a,s),r.webXR.handModelPath&&r.webXR.handModelPath!==""?a.setPath(Oi(e.sourceId,r.webXR.handModelPath)):a.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/");let c=new Vy(r.hand,a);return r.hand.add(c),r.hand.traverse(d=>d.layers.set(2)),r.handPointerModel=new zy(r.hand,r.controller),r.controller.addEventListener("connected",d=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),r.setControllerLayers(r.hand,2),setTimeout(()=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),r.setControllerLayers(r.hand,2)},1e3)}),r.hand.addEventListener("connected",d=>{if(d.data.hand){e.Rig&&e.Rig.add(r.hand),r.type=0,r.handPointerModel.traverse(h=>h.layers.set(2)),r.handPointerModel.pointerObject?.traverse(h=>h.layers.set(2));let u=r.hand.joints;if(u)for(let h of Object.keys(u)){let b=u[h];b.parent||r.hand.add(b)}}}),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;showRaycastLine=!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 Vl),fe(e).multiply(this._wristQuaternion.setFromEuler(new Ay(-Math.PI/4,0,0)))):null}movementVector=new xi;worldRot=new Vl;joystick=new Gy;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=Ae.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=Ae.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),$s&&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({clientX:0,clientY:0,button:this.index,pointerType:"touch"});break;case"move":break;case"up":this.context.input.createPointerUp({clientX:0,clientY:0,button:this.index,pointerType:"touch"});break}}rayRotation=new Vl;update(){this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));let e=Ae.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(fe(this.controller),this.useSmoothing?t:1);let i=B(this.controller);if(this.isUsingHands&&this.handPointerModel.cursorObject&&(this.handPointerModel.cursorObject.visible=!1),this.raycastLine){let n=this.showRaycastLine&&this.context.isInVR;if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed&&n,ie(this.raycastLine,i);let r=this.hand.joints;if(r&&r.wrist&&this.grabbed&&this.grabbed.isCloseGrab){let a=this.getWristQuaternion();a&&this.rayRotation.copy(a)}Je(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=n,Je(this.raycastLine,this.rayRotation),ie(this.raycastLine,i)}this.lastHit=this.updateLastHit(),this.grabbed&&this.grabbed.update(),this._selectionPressedLastFrame=this._selectionPressed,this.selectStartCallback&&this.selectStartCallback()}_pinchStartTime=void 0;onUpdate(e){if(this.lastHit=null,!e||e.inputSources.length<=this.index){this.input=null;return}if(this.type===0&&(this.input=e.inputSources[this.index]),!this.input)return;let t=this.webXR.Rig;if(!t)return;this._didNotEndSelection&&!this.handPointerModel.pinched&&(this._didNotEndSelection=!1,this.onSelectEnd()),this.updateStick(this.input);let i=this.input?.gamepad?.buttons;switch(this.input.handedness){case"left":let n=3*Ae.MovementSpeedFactor,r=2,s=H.clamp01(this.joystick.length()*2),a=this.joystick.x>0?1:-1,c=Math.pow(this.joystick.x,r);c*=a,c*=s;let d=this.joystick.y>0?1:-1,l=Math.pow(this.joystick.y,r);l*=d,c*=s,t.getWorldQuaternion(this.worldRot),this.movementVector.set(c,0,l),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 b=u>0?-1:1;t.rotateY(H.toRadians(30*b)),this.didRotate=!0}this.runTeleport(t,i);break}}runTeleport(e,t){let i=-this.joystick.y;if(this.hand?.visible&&!this.grabbed){let a=this.handPointerModel.isPinched();a&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),a&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(i=this.handPointerModel.isPinched()?1:0),a||(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,s=null;if(t&&this.input&&!this.input.hand)for(let a=0;a<t.length;a++){let c=t[a];if(a===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),s=1,Ae.MovementSpeedFactor=1;let l=this.context.mainCamera;Ae.PreviousCameraFarDistance&&(l.far=Ae.PreviousCameraFarDistance)}else{r=!0,n=!0,s=.1,Ae.MovementSpeedFactor=s*2;let l=this.context.mainCamera;Ae.PreviousCameraFarDistance=l.far,l.far/=s}}else c.pressed||(this.didChangeScale=!1)}if(n){if(!this.didTeleport){let a=this.raycast();if(this.didTeleport=!0,a&&a.length>0){let c=a[0];if(r||this.isValidTeleportTarget(c.object)){let d=c.point;ie(e,d)}}}}else i<.1&&(this.didTeleport=!1);s!==null&&(e.scale.set(s,s,s),e.updateMatrixWorld())}isValidTeleportTarget(e){return R.getComponentInParent(e,Xr)!=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=Ae.raycastColor:n.color=Ae.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;let n=H.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(),$s&&console.log("onHandleSelectStart","close grab? "+t,"intersections",e),e&&e.length>0)for(let i of e){let n=i.object;this.lastSelectStartObject=n;let r={selected:n,grab:n},s=Ae.eventSubs["select-start"];if(s&&s.length>0)for(let a of s)a(this,r);r.grab!==n&&$s&&console.log("Grabbed object changed","original",n,"new",r.grab),r.grab&&(this.grabbed=pt.TryTake(this,r.grab,i,t));break}else{let i=Ae.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=Ae.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||R.isActiveInHierarchy(e)===!1||_i.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 By;return e.origin.copy(B(this.controller)),e.direction.set(0,0,-1).applyQuaternion(this.rayRotation),e}closeGrabBoundingBoxHelper;overlap(){let e=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if($s&&(!this.closeGrabBoundingBoxHelper&&e&&(this.closeGrabBoundingBoxHelper=new Iy(e,16776960),this.scene.add(this.closeGrabBoundingBoxHelper)),this.closeGrabBoundingBoxHelper&&e&&this.closeGrabBoundingBoxHelper.setFromObject(e)),!e)return new Array;let t=B(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){let e=new ge;e.layerMask=new Ly,e.layerMask.set(0),e.layerMask.disable(2),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=_i.getObject(r);break}return t}},J=Ae;D(J,"Factory",new Wy),D(J,"raycastColor",new Zf(.9,.3,.3)),D(J,"raycastNoHitColor",new Zf(.6,.6,.6)),D(J,"geometry",new Dy().setFromPoints([new xi(0,0,0),new xi(0,0,-1)])),D(J,"handModels",{}),D(J,"eventSubs",{}),D(J,"PreviousCameraFarDistance"),D(J,"MovementSpeedFactor",1);var nt=class{static AddEventListener(e,t){return nt.Events[e]||(nt.Events[e]=[]),nt.Events[e].push(t),t}static RemoveEventListener(e,t){if(!t||!nt.Events[e])return;let i=nt.Events[e].indexOf(t);i>=0&&nt.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=R.getComponentInParent(t,Gt);if(r)t=r.gameObject;else return $s&&console.warn("Prevented taking object that is not interactable",t),null;let s=t,a=R.getComponentInParent(t,wt);a&&(a.requestOwnership(),s=a.gameObject);for(let d of this.Current)if(d.selected===s)return d.controller===e||(d.free(),d.Take(e,s,t,a,r,i,n)),d;let c=new nt;return c.Take(e,s,t,a,r,i,n),c}sync=null;selected=null;selectedParent=null;selectedMesh=null;controller=null;grabTime=0;grabUUID="";isCloseGrab=!1;originalMaterial=null;usageMarker=null;rigidbodies=null;didReparent=!1;grabDistance=0;interactable=null;positionSource=null;Take(e,t,i,n,r,s,a){if(console.assert(t!==null,"Expected object to be taken but was",t),e.isUsingHands?this.positionSource=a?e.wrist:e.controller:this.positionSource=e.controller,!this.positionSource)return console.warn("No position source"),this;let c={controller:e,take:t,hit:i,sync:n,interactable:r};nt.Events.WillTake?.forEach(b=>b(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=a,this.didReparent=!1,this.sync=n,this.grabTime=e.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=R.addNewComponent(this.selected,Vt),this.rigidbodies=R.getComponentsInChildren(this.selected,K),B(this.positionSource,this.lastControllerWorldPos);let l=()=>a?this.lastControllerWorldPos.clone():s.point.clone();this.grabDistance=l().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(l());let u=e.isUsingHands&&a?this.controller.getWristQuaternion().clone():e.rayRotation.clone();fe(this.selected,this.localQuaternionToGrab).premultiply(u.invert());let h=this.controller.webXR.Rig;return h&&this.rigPositionLastFrame.copy(B(h)),ve.Add(e.context,this.selected),nt.Register(this),this.sync&&(this.sync.fastMode=!0),nt.Events.DidTake?.forEach(b=>b(this,c)),this}free(){if(!this.selected)return;let e={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};nt.Events.WillFree?.forEach(n=>n(this,e)),ve.Remove(this.controller.context,this.selected),nt.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.setVelocity(n.smoothedVelocity);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,nt.Events.DidFree?.forEach(n=>n(this,e))}grabPoint=new xi;localPositionOffsetToGrab=null;localPositionOffsetToGrab_worldSpace=new xi;localQuaternionToGrab=new Vl(0,0,0,1);targetDir=null;quaternionLerp=null;controllerDir=new xi;controllerWorldPos=new xi;lastControllerWorldPos=new xi;controllerPosDelta=new xi;totalChangeAlongDirection=0;rigPositionLastFrame=new xi;controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),B(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=B(e),n=this.rigPositionLastFrame.sub(i);this.controllerPosDelta.add(n),this.rigPositionLastFrame.copy(i)}return this.controllerDir.dot(this.controllerPosDelta)}update(){if(this.rigidbodies)for(let e of this.rigidbodies)e.resetVelocities();if(this.sync&&this.controller&&this.controller.context.connection.isInRoom&&this.controller.context.time.time-this.grabTime>3&&this.sync.hasOwnership()===!1&&(console.log("no ownership, will leave",this.sync.guid),this.free()),!(this.interactable&&!this.interactable.canGrab)){if(!this.didReparent&&this.selected&&this.controller){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 xi),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),Je(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(B(this.selected)),i.sub(this.localPositionOffsetToGrab_worldSpace)),ie(this.selected,i)}if(this.rigidbodies!=null)for(let e of this.rigidbodies)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0});oe.markDirty(this.selected,!0)}}},pt=nt;D(pt,"Events",{}),D(pt,"Current",[]);import{Object3D as Qy}from"three";import*as $f from"three";import{Color as Xy}from"three";var wi=class extends M{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!Mi||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new $f.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=Ya(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}};y([_()],wi.prototype,"objectBounds",2),y([_(Xy)],wi.prototype,"color",2),y([_()],wi.prototype,"isGizmo",2);var qy=O("debugrig"),nr=class extends M{awake(){if(qy){let e=new Qy;e.position.y+=.5,this.gameObject.add(e);let t=e.addNewComponent(wi);t&&(t.isGizmo=!1)}}};import{Quaternion as ea,Vector3 as zl,Vector4 as Yy}from"three";var zi=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 Se=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 Se).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+4),(t||new Se).__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 we).__init(this.bb_pos+t,this.bb):null}rotation(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new zi).__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 we).__init(this.bb_pos+t,this.bb):null}posRightHand(e){let t=this.bb.__offset(this.bb_pos,18);return t?(e||new we).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){let t=this.bb.__offset(this.bb_pos,20);return t?(e||new zi).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){let t=this.bb.__offset(this.bb_pos,22);return t?(e||new zi).__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 em=O("debugxr"),ta=O("debugavatar");var _u="VRUS";So(_u,Se.getRootAsVrUserStateBuffer);function yu(){return new Date().getTime()}function Ky(o){let e=o&4294967295,t=o/Math.pow(2,32)&1048575;return Ne.create(e,t)}var ia=class{guid;time;avatarId;position=new zl;rotation=new Yy;scale=1;posLeftHand=new zl;posRightHand=new zl;rotLeftHand=new ea;rotRightHand=new ea;constructor(e){this.guid=e}update(e,t,i,n,r){this.time=yu(),this.avatarId=r,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let s=ia.quat0,a=ia.quat1;s.set(i.x,i.y,i.z,i.w),s=s.multiplyQuaternions(s,ia.invertRotation),e&&(e.getWorldQuaternion(a),s.multiplyQuaternions(a,s)),this.rotation.set(s.x,s.y,s.z,s.w),this.scale=e.scale.x;let c=n.LeftController?.controllerGrip;c&&(c.getWorldPosition(this.posLeftHand),c.getWorldQuaternion(this.rotLeftHand));let d=n.RightController?.controllerGrip;if(d&&(d.getWorldPosition(this.posRightHand),d.getWorldQuaternion(this.rotRightHand)),n.LeftController?.hand?.visible){let l=n.LeftController.wrist;l&&(l.getWorldPosition(this.posLeftHand),l.getWorldQuaternion(this.rotLeftHand))}if(n.RightController?.hand?.visible){let l=n.RightController.wrist;l&&(l.getWorldPosition(this.posRightHand),l.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(e,t){e.clear();let i=e.createString(this.guid),n=e.createString(this.avatarId);Se.startVrUserStateBuffer(e),Se.addGuid(e,i),Se.addTime(e,Ky(this.time)),Se.addAvatarId(e,n),Se.addPosition(e,we.createVec3(e,this.position.x,this.position.y,this.position.z)),Se.addRotation(e,zi.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),Se.addScale(e,this.scale),Se.addPosLeftHand(e,we.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),Se.addPosRightHand(e,we.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),Se.addRotLeftHand(e,zi.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),Se.addRotRightHand(e,zi.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));let r=Se.endVrUserStateBuffer(e);e.finish(r,_u);let s=e.asUint8Array();t.sendBinary(s)}setFromBuffer(e,t){if(!e)return;this.guid=e,this.time=t.time().toFloat64();let i=t.avatarId();i&&(this.avatarId=i);let n=t.position();n&&this.position.set(n.x(),n.y(),n.z());let r=t.rotation();r&&this.rotation.set(r.x(),r.y(),r.z(),r.w());let s=t.posLeftHand();s&&this.posLeftHand.set(s.x(),s.y(),s.z());let a=t.posRightHand();a&&this.posRightHand.set(a.x(),a.y(),a.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()}},Xt=ia;D(Xt,"invertRotation",new ea().setFromAxisAngle(new zl(0,1,0),Math.PI)),D(Xt,"quat0",new ea),D(Xt,"quat1",new ea);var Cn=class extends M{webXR=null;debugAvatarUser=null;voip=null;async awake(){if(this.webXR||(this.webXR=R.getComponent(this.gameObject,V)),this.webXR||(this.webXR=R.findObjectOfType(V,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=R.findObjectOfType(V,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=R.findObjectOfType(tt,this.context)),ta){let e="debug-avatar-"+ta,t=new Nt(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof ta=="string"&&ta.length>0)if(await t.setAvatarOverride(ta)){let i=new Xt(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=R.getComponent(this.gameObject,V),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),V.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),V.addEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),V.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(_u,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 Xt("");onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;let i=new Date().getTime()-t;if(i>5e3)return em&&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 Nt(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),V.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),V.removeEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),V.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}update(){let e=yu();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=yu();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 Nt(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(){em&&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"}),this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null)}ownership=null;xrState=null;builder=new yt(1024);onXRSessionUpdate(e){this.xrState??=new Xt(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership??=new Nn(this.context.connection,this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership.guid=this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid,this.buildLocalAvatar();let{frame:t,xr:i,rig:n}=e,r=t.getViewerPose(i.getReferenceSpace());if(!r)return;let s=r?.transform,a=s.position,c=s.orientation;this.xrState.update(n,a,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 O("avatar")??null}};async function n_(){return Ca()?!0:"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function r_(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}var wu=!1,Eu=!1;n_().then(o=>wu=o);r_().then(o=>Eu=o);var Le=class extends M{enableVR=!0;enableAR=!0;defaultAvatar;handModelPath="";createVRButton=!0;createARButton=!0;static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(wu||Eu)}static get IsARSupported(){return wu}static get IsVRSupported(){return Eu}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?e.__internalAwake():console.warn("WebXR is not supported on this device");let i=Uo.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){e.__internalAwake();let i=e.webAR?.getAROverlayContainer(),n={};i?(n.domOverlay={root:i},n.optionalFeatures=["hit-test","dom-overlay"]):console.warn("No dom overlay root found, HTML overlays on top of screen-based AR will not work."),n.optionalFeatures.push("plane-detection"),n.optionalFeatures.push("anchors");let r=jl.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=$e.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!R.findObjectOfType(Cn,this.context)){let e=R.addNewComponent(this.gameObject,Cn,!1);e.webXR=this}this.webAR=new rr(this)}onEnable(){if(this.isInit||!this.enableAR&&!this.enableVR)return;this.isInit=!0,this.context.renderer.xr.enabled=!0;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&&(i=Le.createVRButton(this),this._vrButton=i,n.appendChild(i)),setTimeout(()=>{Le.resetButtonStyles(i),Le.resetButtonStyles(t)},1e3)}_transformOrientation=new Wl;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.captureStateBeforeXR())}onClickedVRButton(){if(!this._isInVR){if(this._requestedVR){this.onExitXR(null);return}this._requestedAR=!1,this._requestedVR=!0,this.captureStateBeforeXR(),this.ensureRig();for(let e=0;e<2;e++)J.Create(this,e,this.gameObject,0);Le.events.dispatchEvent({type:"requestVRSession"})}}captureStateBeforeXR(){this.context.mainCamera&&(this._originalCameraPosition.copy(B(this.context.mainCamera)),this._originalCameraRotation.copy(fe(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent),this.Rig&&(this._originalXRRigParent=this.Rig.parent,this._originalXRRigPosition.copy(this.Rig.position),this._originalXRRigRotation.copy(this.Rig.quaternion))}ensureRig(){if(!this.rig){let e=R.findObjectOfType(nr,this.context);e?(this.rig=e.gameObject,this.rig.rotateY(Math.PI)):(this.rig=new $y,this.rig.rotateY(Math.PI),this.rig.name="XRRig",this.context.scene.add(this.rig))}}_originalCameraParent=null;_originalCameraPosition=new xu;_originalCameraRotation=new Wl;_originalXRRigParent=null;_originalXRRigPosition=new xu;_originalXRRigRotation=new Wl;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 a=t.getViewerPose(i)?.transform.orientation;if(a){let c=new Wl(a.x,a.y,a.z,a.w),d=new Jy().setFromQuaternion(c);this.rig.rotateY(d.y)}}let n=this.context.renderer.xr;if(this.context.mainCamera){let s=n.getCamera(this.context.mainCamera);for(let a of s.cameras)a.layers.enableAll();this.rig.add(this.context.mainCamera),this._requestedAR&&this.context.scene.add(this.rig)}let r=this._requestedAR?2:4;switch(Et.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){let t=this._isInAR;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),ie(this.context.mainCamera,this._originalCameraPosition),Je(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),t&&(this._originalXRRigParent?.add(this.rig),this.rig.position.copy(this._originalXRRigPosition),this.rig.quaternion.copy(this._originalXRRigRotation)),Et.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){!O("mirror")||setTimeout(()=>{if(!Le.IsInWebXR)return;let t=new URL(window.location.href);ho(t.searchParams,Go,1),ho(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)}},V=Le;D(V,"_isInXr",!1),D(V,"events",new Zy),y([_()],V.prototype,"enableVR",2),y([_()],V.prototype,"enableAR",2),y([_($e)],V.prototype,"defaultAvatar",2),y([_()],V.prototype,"handModelPath",2),y([_()],V.prototype,"createVRButton",2),y([_()],V.prototype,"createARButton",2);var Wo=class{get webxr(){return this._webxr}_webxr;reticle=null;reticleParent=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(){this.arDomOverlay=this.webxr.context.domElement;let e=this.arDomOverlay;return e.getAROverlayContainer?this.arOverlayElement=e.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,this.getAROverlayContainer();let i=navigator.userAgent?.includes("OculusBrowser")?0:1,n=i===1?4:2;for(let s=0;s<n;s++)J.Create(this.webxr,s,this.webxr.gameObject,i);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=R.findObjectOfType(Wt,t)),this.previousBackground=t.scene.background,this.previousEnvironment=t.scene.environment,t.scene.background=null,e.requestReferenceSpace("viewer").then(s=>{e.requestHitTestSource?.call(e,{space:s})?.then(a=>{this.hitTestSource=a}).catch(a=>{this.noHitTestAvailable=!0,console.warn("WebXR: Hit test not supported",a)})}),!this.reticle&&this.sessionRoot&&(this.reticle=new e_(new i_(.07,.09,32).rotateX(-Math.PI/2),new t_),this.reticle.name="AR Placement reticle",this.reticle.matrixAutoUpdate=!1,this.reticle.visible=!1,this.reticleParent=new im,this.reticleParent.name="AR Reticle Parent",this.reticleParent.matrixAutoUpdate=!1,this.reticleParent.add(this.reticle),this.reticleParent.matrix.copy(this.sessionRoot.gameObject.matrixWorld),this.webxr.scene?(this.context.scene.add(this.reticleParent),this.context.scene.visible=!0):console.warn("Could not found WebXR Rig")),this._previousParent=this.webxr.gameObject,Wo.tempWebXRObject||(Wo.tempWebXRObject=new im),this.context.scene.add(Wo.tempWebXRObject),R.addComponent(Wo.tempWebXRObject,this.webxr),this.sessionRoot?(this.sessionRoot.webAR=this,this.sessionRoot?.onBegin(e)):console.warn("No WebARSessionRoot found in scene");let r=this.context.domElement;r?.onEnterAR?.call(r,e,this.arOverlayElement),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onEnd(e){this._previousParent&&(R.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);let i=this.context.domElement;i.onExitAR?.call(i,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=o_.clone();if(n){let s=new xu(0,0,0).add(n.position).divideScalar(this.sessionRoot?.arScale??1);r.multiply(new nm().makeTranslation(s.x,s.y,s.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 s=n.getPose(r);if(this.sessionRoot){let a=this.sessionRoot.onUpdate(this.webxr.Rig,e,s);this.didPlaceARSessionRoot=a}if(this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&s)){let a=s.transform.matrix;this.reticle.matrix.fromArray(a),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)}},rr=Wo;D(rr,"tempWebXRObject");var o_=new nm().identity().makeTranslation(0,-.5,0);var Cu=!1;var Tn=class extends Gt{static get HasAnySelected(){return this._active>0}transformSelf=!0;orbit=null;selectStartEventListener=[];selectEndEventListener=[];constructor(){super(),this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new q.Vector2}addDragEventListener(e,t){switch(e){case"selectstart":this.selectStartEventListener.push(t);break;case"selectend":this.selectEndEventListener.push(t);break}}_dragHelper=null;start(){this.orbit=R.findObjectOfType(it,this.context)}_draggingRigidbodies=[];allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||V.IsInWebXR)return;let t=R.getComponentInParent(e.object,Tn);!t||t!==this||(Tn.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){!this.allowEdit(this.gameObject)||V.IsInWebXR||Tn.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}_waitingForDragStart=null;onPointerDown(e){!this.allowEdit(this.gameObject)||V.IsInWebXR||(Tn._active+=1,this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation(),this.orbit&&(this.orbit.enabled=!1))}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&(Tn._active>0&&(Tn._active-=1),!V.IsInWebXR&&(this.onDragEnd(e),e.StopPropagation(),this.orbit&&(this.orbit.enabled=!0)))}update(){if(!V.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===!1&&this.onDragEnd(null)}}_isDragging=!1;_marker=null;_dragDelta;_didDrag=!1;onDragStart(e){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new Nl(this.context.mainCamera);else return;if(!e||!e.object)return;let t=R.getComponentInParent(e.object,Tn);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),this.orbit&&(this.orbit.enabled=!1);let r=R.getComponentInChildren(i,wt);Cu&&console.log("DRAG START",r,i),r&&(r.fastMode=!0,r?.requestOwnership()),this._marker=R.addNewComponent(i,Vt),this._draggingRigidbodies.length=0;let s=R.getComponentsInChildren(i,K);s&&this._draggingRigidbodies.push(...s);let a=Dc();R.invokeOnChildren(this._dragHelper.selected,a("onDragStart"))}onUpdateDrag(){if(!!this._dragHelper){this._dragHelper.onUpdate(this.context);for(let e of this._draggingRigidbodies)e.wakeUp(),e.resetVelocities()}}onDragEnd(e){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;for(let n of this._draggingRigidbodies)n.setVelocity(n.smoothedVelocity);this._draggingRigidbodies.length=0;let t=this._dragHelper.selected;if(Cu&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context),this.orbit&&(this.orbit.enabled=!0),e?.object){let n=R.getComponentInChildren(e.object,wt);n&&(n.fastMode=!1),this._marker&&this._marker.destroy()}for(let n of this.selectEndEventListener)n(this);let i=Dc();R.invokeOnChildren(t,i("onDragEnd"))}},Wi=Tn;D(Wi,"_active",0),D(Wi,"lastHovered");var Tu=class{get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}_selected=null;_context=null;_camera;_cameraPlane=new q.Plane;_hasGroundPlane=!1;_groundPlane=new q.Plane;_groundOffset=new q.Vector3;_groundOffsetFactor=0;_groundDistance=0;_groundPlanePoint=new q.Vector3;_raycaster=new q.Raycaster;_cameraPlaneOffset=new q.Vector3;_intersection=new q.Vector3;_worldPosition=new q.Vector3;_inverseMatrix=new q.Matrix4;_rbs=[];_groundLine;_groundMarker;constructor(e){this._camera=e;let t=new q.Line(Tu.geometry),i=t.material;i.color=new q.Color(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;let n=new q.SphereGeometry(.5,22,22),r=new q.MeshBasicMaterial({color:i.color}),s=new q.Mesh(n,r);s.visible=!1,s.layers.set(2),this._groundMarker=s}setSelected(e,t){if(this._selected&&t)for(let i of this._rbs)i.wakeUp(),i.setVelocity(0,0,0);if(this._selected&&ve.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}ve.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this.onUpdateScreenSpacePlane()}}_groundOffsetVector=new q.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),s=this._context.input.getTouchesPressedCount()>=2||r;if(s){let c=this._context.input.getPointerPositionDelta(0);c&&(this._groundOffsetVector.set(0,1,0),this._selected?.rotateOnWorldAxis(this._groundOffsetVector,c.x*this._context.time.deltaTime))}let a=this._context.input.getPointerPositionRC(0);if(!!a&&(this._raycaster.setFromCamera(a,this._camera),this._selected)){Cu&&console.log("UPDATE DRAG",this._selected),this._groundOffsetVector.set(0,1,0);let c=B(this._camera).clone().sub(B(this._selected)).normalize(),d=Math.abs(c.dot(this._groundOffsetVector)),l=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(i),u=!s&&d>.2&&!l&&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 b=this._intersection.y;if(this._groundPlanePoint.copy(this._intersection).sub(this._groundOffset),this._groundPlanePoint.y=b,u){this._groundOffsetVector.set(0,1,0);let w=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(w,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=B(this._selected);n.y=e.y,e=n}if(ie(this._selected,e),ie(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=t!==null,t){let n=B(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(n,n,n),ie(this._groundMarker,t)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;let e=this._context.input.getPointerPositionRC(0);!e||(this._raycaster.setFromCamera(e,this._camera),this._cameraPlane.setFromNormalAndCoplanarPoint(this._camera.getWorldDirection(this._cameraPlane.normal),this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld)),this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&this._selected.parent&&(this._inverseMatrix.copy(this._selected.parent.matrixWorld).invert(),this._cameraPlaneOffset.copy(this._intersection).sub(this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld))))}onUpdateGroundPlane(){if(!this._selected||!this._context)return;let e=B(this._selected),t=new q.Ray(new q.Vector3(0,.1,0).add(e),new q.Vector3(0,-1,0)),i=new ge;i.ignore=[this._selected];let n=this._context.physics.raycastFromRay(t,i);for(let r=0;r<n.length;r++){let s=n[r];if(!s.face||this.contains(this._selected,s.object))continue;let a=new q.Vector3(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(a,s.point);break}this._hasGroundPlane=!0,this._groundPlane.setFromNormalAndCoplanarPoint(t.direction.multiplyScalar(-1),t.origin),this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection),this._groundDistance=this._intersection.distanceTo(e),this._groundOffset.copy(this._intersection).sub(e)}onDidUpdate(){oe.markDirty(this._selected);for(let e of this._rbs)e.wakeUp(),e.resetForcesAndTorques(),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}},Nl=Tu;D(Nl,"geometry",new q.BufferGeometry().setFromPoints([new q.Vector3(0,0,0),new q.Vector3(0,-1,0)]));var Ei=class extends M{url=null;urlParameterName=null;localhost=null;awake(){this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?Ei.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){let r=O(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=Ei.IsLocalNetwork()&&t;return n&&(i=t),e?.startsWith("/")&&(i=(n?i:window.location.origin)+e),i}static IsLocalNetwork(e=window.location.hostname){return ti(e)}};var or=class extends M{filesBackendUrl;localhost;_dragOver;_drop;onEnable(){this.filesBackendUrl=this.filesBackendUrl?Ei.GetUrl(this.filesBackendUrl,this.localhost):void 0,this._dragOver=this.onDrag.bind(this),this._drop=this.onDrop.bind(this),this.context.domElement.addEventListener("dragover",this._dragOver),this.context.domElement.addEventListener("drop",this._drop)}onDisable(){this.context.domElement.removeEventListener("dragover",this._dragOver),this.context.domElement.removeEventListener("drop",this._drop)}onDrag(e){e.preventDefault()}async onDrop(e){if(console.log(e),!e.dataTransfer)return;e.preventDefault();let t=e.dataTransfer.items;if(!!t)for(let i in t){let n=t[i];if(n.kind==="file"){let r=n.getAsFile();if(!r)continue;console.log("Register file "+r.name+" to",this.filesBackendUrl,r);let s=await pf(r,this.context,this.filesBackendUrl);s&&this.addObject(e,s)}else n.kind==="string"&&n.type=="text/plain"&&n.getAsString(async r=>{console.log("dropped url",r);try{let s=new URL(r);if(!s)return;let a=await ff(s,this.context);a&&this.addObject(e,a)}catch{console.log("dropped string is not a valid URL!",r)}})}}async addObject(e,t){console.log("Dropped",t);let i=new ge;i.setMask(16777215),i.screenPointFromOffset(e.offsetX,e.offsetY);let n=this.context.physics.raycast(i),r=t.scene;if(n&&n.length>0)for(let s of n){r.position.copy(s.point);break}this.gameObject.add(r),this.dispatchEvent(new CustomEvent("object-added",{detail:t}))}};y([_()],or.prototype,"filesBackendUrl",2),y([_()],or.prototype,"localhost",2);import{Vector3 as s_,Quaternion as a_,Object3D as rm}from"three";var Ni=class extends Gt{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 s_(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new a_(0,0,0,1)}let e=R.getComponentInParent(this.gameObject,Wi);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),J.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 Fe;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=R.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}};y([_(rm)],Ni.prototype,"parent",2),y([_(rm)],Ni.prototype,"object",2),y([_()],Ni.prototype,"limitCount",2),y([_()],Ni.prototype,"limitInterval",2);var na=class{eventID;callback};y([_()],na.prototype,"eventID",2),y([_(ue)],na.prototype,"callback",2);var Qr=class extends M{triggers;invoke(e){if(!!this.triggers)for(let t of this.triggers)t.eventID===e&&t.callback.invoke()}onPointerClick(e){this.invoke(4)}onPointerEnter(e){this.invoke(0)}onPointerExit(e){this.invoke(1)}onPointerDown(e){this.invoke(2)}onPointerUp(e){this.invoke(3)}};y([_(na)],Qr.prototype,"triggers",2);import{FlyControls as l_}from"three/examples/jsm/controls/FlyControls";var No=class extends M{_controls=null;onEnable(){let e=R.getComponent(this.gameObject,ee)?.cam;this._controls=new l_(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{Color as Xl,GridHelper as c_}from"three";var Rn=class extends M{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!Mi)return;let e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new c_(e,t,this.color0??new Xl(.4,.4,.4),this.color1??new Xl(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset),this.gameObject.add(this.gridHelper))}};y([_()],Rn.prototype,"isGizmo",2),y([_(Xl)],Rn.prototype,"color0",2),y([_(Xl)],Rn.prototype,"color1",2);import{GroundProjectedEnv as d_}from"three/examples/jsm/objects/GroundProjectedEnv.js";var Sn=class extends M{set scale(e){this._scale=e,this.env?.scale.setScalar(e)}get scale(){return this._scale}_scale=20;set radius(e){this._radius=e,this.env&&(this.env.height=e)}get radius(){return this._radius}_radius=100;set height(e){this._height=e,this.env&&(this.env.height=e)}get height(){return this._height}_height=100;_lastEnvironment;env;_watcher;onEnable(){this.context.time.frameCount>0&&this.updateAndCreate()}start(){this.updateAndCreate()}onDisable(){this._watcher?.revoke(),this.env?.removeFromParent()}updateAndCreate(){this.updateProjection(),this._watcher||(this._watcher=new sn(this.context.scene,"environment"),this._watcher.subscribeWrite(e=>{this.updateProjection()})),this._watcher.apply()}updateProjection(){if(!this.context.scene.environment){this.env?.removeFromParent();return}(!this.env||this.context.scene.environment!==this._lastEnvironment)&&(console.log("Create/Update Ground Projection",this.context.scene.environment.name),this.env=new d_(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)}};y([_()],Sn.prototype,"scale",1),y([_()],Sn.prototype,"radius",1),y([_()],Sn.prototype,"height",1);import{Vector3 as om}from"three";var ra=class extends M{connectedBody;get rigidBody(){return this._rigidBody}_rigidBody=null;onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(K)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.createJoint(this.rigidBody,this.connectedBody)}};y([_(K)],ra.prototype,"connectedBody",2);var Xo=class extends ra{createJoint(e,t){this.context.physics.addFixedJoint(e,t)}},sr=class extends ra{anchor;axis;createJoint(e,t){this.axis&&this.anchor&&this.context.physics.addHingeJoint(e,t,this.anchor,this.axis)}};y([_(om)],sr.prototype,"anchor",2),y([_(om)],sr.prototype,"axis",2);import*as rt from"three";import{Color as u_}from"three";function Ru(o){return o*Math.PI/180}var sm=300,Su=O("debuglights");var Ve=class extends M{type=0;range=1;spotAngle=1;innerSpotAngle=1;color=new rt.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;_overrideShadowBiasSettings=!1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}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 rt.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=V.addEventListener("xrStarted",this.onWebXRStarted.bind(this)),this._webXREndedListener=V.addEventListener("xrStopped",this.onWebXREnded.bind(this)))}onDisable(){V.removeEventListener("xrStarted",this._webXRStartedListener),V.removeEventListener("xrStopped",this._webXREndedListener)}_webXRStartedListener;_webXREndedListener;_webARRoot;onWebXRStarted(){this._webARRoot=R.getComponentInParent(this.gameObject,Wt)??void 0,this.startCoroutine(this._updateLightIntensityInARRoutine())}*_updateLightIntensityInARRoutine(){for(;this.context.isInAR;){yield,this.updateIntensity();for(let e=0;e<30;e++)yield}}onWebXREnded(){this.updateIntensity()}createLight(){let e=this.selfIsLight;if(e&&!this.light)switch(this.light=this.gameObject,this.type){case 1:this.setDirectionalLight(this.light);break}else if(!this.light)switch(this.type){case 1:let t=new rt.DirectionalLight(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-sm*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),dn(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Su){let s=new rt.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(s)}break;case 0:let i=new rt.SpotLight(this.color,this.intensity*Math.PI,this.range,Ru(this.spotAngle/2),1-Ru(this.innerSpotAngle/2)/Ru(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 rt.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=r;break}if(this.light){this._intensity>=0?this.light.intensity=this._intensity: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),Su&&console.log("Override shadow bias?",this._overrideShadowBiasSettings,this.shadowBias,this.shadowNormalBias),this._overrideShadowBiasSettings===!0?(this.light.shadow.bias=this.shadowBias,this.light.shadow.normalBias=this.shadowNormalBias):(this.light.shadow.bias=this.shadowBias*1e-5,this.light.shadow.normalBias=this.shadowNormalBias*1e-4),this.updateShadowSoftHard();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=sm*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,Su&&this.context.scene.add(new rt.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}}updateShadowSoftHard(){!this.light||this.shadows===2||(this.light.shadow.radius=1,this.light.shadow.blurSamples=1)}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}};D(Ve,"allowChangingRendererShadowMapType",!0),y([_()],Ve.prototype,"type",2),y([_(u_)],Ve.prototype,"color",2),y([_()],Ve.prototype,"shadowNearPlane",1),y([_()],Ve.prototype,"shadowBias",1),y([_()],Ve.prototype,"shadowNormalBias",1),y([_()],Ve.prototype,"shadows",1),y([_()],Ve.prototype,"lightmapBakeType",2),y([_()],Ve.prototype,"intensity",1),y([_()],Ve.prototype,"shadowDistance",1),y([_()],Ve.prototype,"shadowResolution",1);var QA=new rt.Vector3(0,0,0);import*as Ql from"three";import{Vector3 as h_}from"three";var Qo=O("debugLODs"),p_=O("noLODs");var Xi=class{screenRelativeTransitionHeight;distance;renderers};y([_()],Xi.prototype,"screenRelativeTransitionHeight",2),y([_()],Xi.prototype,"distance",2),y([_()],Xi.prototype,"renderers",2);var Pu=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):Qo&&console.warn("Renderer not found: "+i,e.gameObject)}}findRenderer(e,t){let i=R.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 M{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(!p_&&!this._lodsHandler&&!!this.gameObject&&(Qo&&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 Pu(this,n);this._lods.push(r);for(let s of r.renderers)t.includes(s)||t.push(s)}this._lodsHandler=new Array;for(let n=0;n<t.length;n++){let r=new Ql.LOD;this._lodsHandler.push(r),this.gameObject.add(r)}let i=new Ql.Object3D;Qo&&console.log(t);for(let n=0;n<t.length;n++){let r=t[n],s=this._lodsHandler[n],a=r.gameObject,c=0,d=0;Qo&&console.log(n,a.name);for(let u of this._lods){let h=null;u.renderers.includes(r)?h=a:h=i,Qo&&console.log("add",u.model.distance,h.name);let b=u.model.distance;d=b-c,c=Math.max(b,c),this.onAddLodLevel(s,h,b)}let l=c+d;Qo&&console.log("cull",l),this.onAddLodLevel(s,i,l)}}}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}}}};y([_(h_)],ar.prototype,"localReferencePoint",2),y([_(Xi)],ar.prototype,"lodModels",2);var Ou=O("debugnestedgltf"),qr=class extends M{filePath;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){this.filePath?.preload()}async start(){if(this._isLoadingOrDoneLoading)return;Ou&&console.log(this,this.guid);let e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;let t=new Fe;t.idProvider=new Ie(this.hash(this.guid)),t.parent=e,this.gameObject.updateMatrix();let i=this.gameObject.matrix;Ou&&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,n.layers.disableAll(),n.layers.set(this.layer)),this.destroy(),Ou&&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}};y([_($e)],qr.prototype,"filePath",2);import{Quaternion as f_,Euler as m_,Vector3 as Yr,Plane as g_}from"three";var Qi=class extends M{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new Yr(0,0,0);rotationOffset=new Yr(0,0,0);offset=new Yr(0,0,0);update(){if(!this.from)return;var e=B(this.from),t=fe(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 a=new g_(this.gameObject.up,0),c=B(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,c);let d=new Yr(0,0,0);a.projectPoint(e,d),e.copy(d)}this.affectPosition&&ie(this.gameObject,e);let n=new m_(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),r=new f_().setFromEuler(n);this.affectRotation&&Je(this.gameObject,t.multiply(r));let s=new Yr;this.from.getWorldDirection(s).multiplyScalar(50),this.levelLookDirection&&(s.y=0),this.alignLookDirection&&this.gameObject.lookAt(s)}};y([_(R)],Qi.prototype,"referenceSpace",2),y([_(R)],Qi.prototype,"from",2),y([_(Yr)],Qi.prototype,"positionOffset",2),y([_(Yr)],Qi.prototype,"rotationOffset",2);import*as Ko from"three";import{Matrix4 as am,Quaternion as b_,Vector3 as Ye,Vector2 as lm,Euler as v_}from"three";import{createNoise4D as y_}from"simplex-noise";var Ti=class{alphaKeys;colorKeys;get duration(){return 1}evaluate(e,t){let i,n=0,r=null,s=0;for(let a=0;a<this.alphaKeys.length;a++){let c=this.alphaKeys[a];(c.time<e||!i)&&(i=c,n=a)}for(let a=0;a<this.colorKeys.length;a++){let c=this.colorKeys[a];(c.time<e||!r)&&(r=c,s=a)}if(r)if(s+1<this.colorKeys.length){let c=this.colorKeys[s+1],d=H.remap(e,r.time,c.time,0,1);t.r=H.lerp(r.color.r,c.color.r,d),t.g=H.lerp(r.color.g,c.color.g,d),t.b=H.lerp(r.color.b,c.color.b,d)}else t.r=r.color.r,t.g=r.color.g,t.b=r.color.b;if(i)if(n+1<this.alphaKeys.length){let c=this.alphaKeys[n+1],d=H.remap(e,i.time,c.time,0,1);t.alpha=H.lerp(i.alpha,c.alpha,d)}else t.alpha=i.alpha;return t}};y([_()],Ti.prototype,"alphaKeys",2),y([_()],Ti.prototype,"colorKeys",2);var cm=(E=>(E[E.Sphere=0]="Sphere",E[E.SphereShell=1]="SphereShell",E[E.Hemisphere=2]="Hemisphere",E[E.HemisphereShell=3]="HemisphereShell",E[E.Cone=4]="Cone",E[E.Box=5]="Box",E[E.Mesh=6]="Mesh",E[E.ConeShell=7]="ConeShell",E[E.ConeVolume=8]="ConeVolume",E[E.ConeVolumeShell=9]="ConeVolumeShell",E[E.Circle=10]="Circle",E[E.CircleEdge=11]="CircleEdge",E[E.SingleSidedEdge=12]="SingleSidedEdge",E[E.MeshRenderer=13]="MeshRenderer",E[E.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",E[E.BoxShell=15]="BoxShell",E[E.BoxEdge=16]="BoxEdge",E[E.Donut=17]="Donut",E[E.Rectangle=18]="Rectangle",E[E.Sprite=19]="Sprite",E[E.SpriteRenderer=20]="SpriteRenderer",E))(cm||{});var U=class{mode;constant;constantMin;constantMax;curve;curveMin;curveMax;curveMultiplier;evaluate(e,t){let i=t===void 0?Math.random():t;switch(this.mode){case 0:return this.constant;case 1:return e=H.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:let n=e*this.curveMin.duration,r=e*this.curveMax.duration;return H.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(r),i%1)*this.curveMultiplier;case 3:return H.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(e)*this.curveMultiplier;break}return 0}};y([_()],U.prototype,"mode",2),y([_()],U.prototype,"constant",2),y([_()],U.prototype,"constantMin",2),y([_()],U.prototype,"constantMax",2),y([_(pi)],U.prototype,"curve",2),y([_(pi)],U.prototype,"curveMin",2),y([_(pi)],U.prototype,"curveMax",2),y([_()],U.prototype,"curveMultiplier",2);var Qt=class{mode;color;colorMin;colorMax;gradient;gradientMin;gradientMax;evaluate(e,t){let i=t===void 0?Math.random():t;switch(this.mode){case 0:return this.color;case 1:return this.gradient.evaluate(e,Qt._temp),Qt._temp;case 2:return Qt._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:return this.gradientMin.evaluate(e,Qt._temp),this.gradientMax.evaluate(e,Qt._temp2),Qt._temp.lerp(Qt._temp2,i)}return Qt._temp.set(16711935),Qt._temp.alpha=1,Qt._temp}},Oe=Qt;D(Oe,"_temp",new Z(0,0,0,1)),D(Oe,"_temp2",new Z(0,0,0,1)),y([_(Z)],Oe.prototype,"color",2),y([_(Z)],Oe.prototype,"colorMin",2),y([_(Z)],Oe.prototype,"colorMax",2),y([_(Ti)],Oe.prototype,"gradient",2),y([_(Ti)],Oe.prototype,"gradientMin",2),y([_(Ti)],Oe.prototype,"gradientMax",2);var ye=class{cullingMode;duration;emitterVelocityMode;flipRotation;gravityModifier;gravityModifierMultiplier;loop;maxParticles;playOnAwake;prewarm;ringBufferLoopRange;ringBufferMode;scalingMode;simulationSpace;simulationSpeed;startColor;startDelay;startDelayMultiplier;startLifetime;startLifetimeMultiplier;startRotation;startRotationMultiplier;startRotation3D;startRotationX;startRotationXMultiplier;startRotationY;startRotationYMultiplier;startRotationZ;startRotationZMultiplier;startSize;startSize3D;startSizeMultiplier;startSizeX;startSizeXMultiplier;startSizeY;startSizeYMultiplier;startSizeZ;startSizeZMultiplier;startSpeed;startSpeedMultiplier;stopAction;useUnscaledTime};y([_(U)],ye.prototype,"gravityModifier",2),y([_(Oe)],ye.prototype,"startColor",2),y([_(U)],ye.prototype,"startDelay",2),y([_(U)],ye.prototype,"startLifetime",2),y([_(U)],ye.prototype,"startRotation",2),y([_(U)],ye.prototype,"startRotationX",2),y([_(U)],ye.prototype,"startRotationY",2),y([_(U)],ye.prototype,"startRotationZ",2),y([_(U)],ye.prototype,"startSize",2),y([_(U)],ye.prototype,"startSizeX",2),y([_(U)],ye.prototype,"startSizeY",2),y([_(U)],ye.prototype,"startSizeZ",2),y([_(U)],ye.prototype,"startSpeed",2);var On=class{cycleCount;maxCount;minCount;probability;repeatInterval;time;count;_performed=0;reset(){this._performed=0}run(e){if(e<=this.time)return this.reset(),0;let t=0;if(this.cycleCount===0||this._performed<this.cycleCount){let i=this.time+this.repeatInterval*this._performed;if(e>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=H.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:let n=Math.random();t=H.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return t}},ft=class{enabled;get burstCount(){return this.bursts?.length??0}bursts;rateOverTime;rateOverTimeMultiplier;rateOverDistance;rateOverDistanceMultiplier;system;reset(){this.bursts?.forEach(e=>e.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){let i=this.bursts[t];i.time>=this.system.time&&i.reset(),e+=Math.round(i.run(this.system.time))}return e}};y([_()],ft.prototype,"enabled",2),y([_()],ft.prototype,"bursts",2),y([_(U)],ft.prototype,"rateOverTime",2),y([_()],ft.prototype,"rateOverTimeMultiplier",2),y([_(U)],ft.prototype,"rateOverDistance",2),y([_()],ft.prototype,"rateOverDistanceMultiplier",2);var Pn=class{enabled;color};y([_(Oe)],Pn.prototype,"color",2);var qt=class{enabled;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_time=0;_temp=new Ye;evaluate(e,t,i){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,i)*this.xMultiplier,t.y=this.y.evaluate(e,i)*this.yMultiplier,t.z=this.z.evaluate(e,i)*this.zMultiplier;else{let n=this.size.evaluate(e,i)*this.sizeMultiplier;t.x=n}return t}};y([_(U)],qt.prototype,"size",2),y([_(U)],qt.prototype,"x",2),y([_(U)],qt.prototype,"y",2),y([_(U)],qt.prototype,"z",2);var qo=class{get type(){return cm[this.shapeType]}initialize(e){this.getPosition(),e.position.copy(this._vector)}toJSON(){return this}clone(){return new qo}shapeType=5;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcSpread;arcSpeedMultiplier;arcMode;boxThickness;position;rotation;_rotation=new v_;scale;radius;radiusThickness;sphericalDirectionAmount;randomDirectionAmount;randomPositionAmount;system;_space;_worldSpaceMatrix=new am;_worldSpaceMatrixInverse=new am;constructor(){}update(e,t,i,n){this.system=e,this._space=i,i===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}_vector=new Ye(0,0,0);_temp=new Ye(0,0,0);get vector(){return this._vector}getPosition(){if(!this.enabled){this._vector.set(0,0,0);return}let e=this._temp.copy(this.position),t=this._space===1;t&&e.applyQuaternion(this.system.worldQuaternion);let i=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;i&&(this._rotation.x=H.toRadians(this.rotation.x),this._rotation.y=-H.toRadians(this.rotation.y),this._rotation.z=-H.toRadians(this.rotation.z));let n=this.radius;switch(t&&(n*=this.system.worldScale.x),this.shapeType){case 5:this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(e);break;case 4:this.randomConePoint(this.position,this.angle,n,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector),this._vector.x*=this.scale.x,this._vector.y*=this.scale.y,this._vector.z*=this.scale.z;break;case 10:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector),this._vector.x*=this.scale.x,this._vector.y*=this.scale.y,this._vector.z*=0;break;default:this._vector.set(0,0,0);break}this.randomizePosition(this._vector,this.randomPositionAmount),i&&this._vector.applyEuler(this._rotation),this._space===1&&this._vector.add(this.system.worldPos)}_dir=new Ye;getDirection(e){if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:let t=e.x,i=e.y,n=e.z;this._dir.set(t,i,n).sub(this.position);break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyMatrix4(this._worldSpaceMatrixInverse),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),this._dir}randomizePosition(e,t){if(t<=0)return;let i=qo._tempVec;i.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),i.x*=t*this.scale.x,i.y*=t*this.scale.y,i.z*=t*this.scale.z,e.add(i)}randomizeDirection(e,t){if(t===0)return;let i=qo._randomQuat,n=qo._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),e.applyQuaternion(i)}spherizeDirection(e,t){if(t===0)return;let i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),r=Math.sin(n)*Math.cos(i),s=Math.sin(n)*Math.sin(i),a=Math.cos(n),c=new Ye(r,s,a);e.lerp(c,t)}randomSpherePoint(e,t,i,n,r){let s=Math.random(),a=Math.random(),c=2*Math.PI*s*(n/360),d=Math.acos(2*a-1),l=H.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,u=e.x+-l*Math.sin(d)*Math.cos(c),h=e.y+l*Math.sin(d)*Math.sin(c),b=e.z+l*Math.cos(d);r.x=u,r.y=h,r.z=b}_loopTime=0;_loopDirection=1;randomConePoint(e,t,i,n,r,s,a){let c=0,d=0;switch(s){case 0:c=Math.random(),d=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:c=.5,d=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let l=2*Math.PI*c*(r/360);switch(s){case 2:case 1:l+=Math.PI+.5,l+=this._loopTime*Math.PI*2,l%=H.toRadians(r);break}let u=Math.acos(2*d-1),h=H.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,b=e.x+-h*Math.sin(u)*Math.cos(l),w=e.y+h*Math.sin(u)*Math.sin(l),v=e.z;a.x=b*this.scale.x,a.y=w*this.scale.y,a.z=v*this.scale.z}},ne=qo;D(ne,"_randomQuat",new b_),D(ne,"_tempVec",new Ye),y([_()],ne.prototype,"shapeType",2),y([_()],ne.prototype,"enabled",2),y([_()],ne.prototype,"alignToDirection",2),y([_()],ne.prototype,"angle",2),y([_()],ne.prototype,"arc",2),y([_()],ne.prototype,"arcSpread",2),y([_()],ne.prototype,"arcSpeedMultiplier",2),y([_()],ne.prototype,"arcMode",2),y([_(Ye)],ne.prototype,"boxThickness",2),y([_(Ye)],ne.prototype,"position",2),y([_(Ye)],ne.prototype,"rotation",2),y([_(Ye)],ne.prototype,"scale",2),y([_()],ne.prototype,"radius",2),y([_()],ne.prototype,"radiusThickness",2),y([_()],ne.prototype,"sphericalDirectionAmount",2),y([_()],ne.prototype,"randomDirectionAmount",2),y([_()],ne.prototype,"randomPositionAmount",2);var Y=class{damping;enabled;frequency;octaveCount;octaveMultiplier;octaveScale;positionAmount;quality;remap;remapEnabled;remapMultiplier;remapX;remapXMultiplier;remapY;remapYMultiplier;remapZ;remapZMultiplier;scrollSpeedMultiplier;separateAxes;strengthMultiplier;strengthX;strengthXMultiplier;strengthY;strengthYMultiplier;strengthZ;strengthZMultiplier;_noise;_time=0;update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}_temp=new Ye;apply(e,t,i,n,r,s){if(!this.enabled)return;this._noise||(this._noise=y_(()=>0));let a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),c=this._noise(a.x,a.y,a.z,this._time),d=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),l=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(c,d,l).normalize();let u=r/s,h=this.positionAmount.evaluate(u);this.separateAxes?(this._temp.x*=h*this.strengthXMultiplier,this._temp.y*=h*this.strengthYMultiplier,this._temp.z*=h*this.strengthZMultiplier):(this.strengthX&&(h*=this.strengthX.evaluate(u)*1.5),this._temp.multiplyScalar(h)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}};y([_()],Y.prototype,"damping",2),y([_()],Y.prototype,"enabled",2),y([_()],Y.prototype,"frequency",2),y([_()],Y.prototype,"octaveCount",2),y([_()],Y.prototype,"octaveMultiplier",2),y([_()],Y.prototype,"octaveScale",2),y([_(U)],Y.prototype,"positionAmount",2),y([_()],Y.prototype,"quality",2),y([_(U)],Y.prototype,"remap",2),y([_()],Y.prototype,"remapEnabled",2),y([_()],Y.prototype,"remapMultiplier",2),y([_(U)],Y.prototype,"remapX",2),y([_()],Y.prototype,"remapXMultiplier",2),y([_(U)],Y.prototype,"remapY",2),y([_()],Y.prototype,"remapYMultiplier",2),y([_(U)],Y.prototype,"remapZ",2),y([_()],Y.prototype,"remapZMultiplier",2),y([_()],Y.prototype,"scrollSpeedMultiplier",2),y([_()],Y.prototype,"separateAxes",2),y([_()],Y.prototype,"strengthMultiplier",2),y([_(U)],Y.prototype,"strengthX",2),y([_()],Y.prototype,"strengthXMultiplier",2),y([_(U)],Y.prototype,"strengthY",2),y([_()],Y.prototype,"strengthYMultiplier",2),y([_(U)],Y.prototype,"strengthZ",2),y([_()],Y.prototype,"strengthZMultiplier",2);var te=class{enabled;attachRibbonToTransform=!1;colorOverLifetime;colorOverTrail;dieWithParticles=!0;inheritParticleColor=!0;lifetime;lifetimeMultiplier;minVertexDistance=.2;mode=0;ratio=1;ribbonCount=1;shadowBias=0;sizeAffectsLifetime=!1;sizeAffectsWidth=!1;splitSubEmitterRibbons=!1;textureMode=0;widthOverTrail;widthOverTrailMultiplier;worldSpace=!1;getWidth(e,t,i){let n=this.widthOverTrail.evaluate(i);return i===0&&(n=e),e*=n,e}getColor(e,t,i){let n=this.colorOverTrail.evaluate(i),r=this.colorOverLifetime.evaluate(t);e.x*=n.r*r.r,e.y*=n.g*r.g,e.z*=n.b*r.b,e.w*=n.alpha*r.alpha}};y([_()],te.prototype,"enabled",2),y([_()],te.prototype,"attachRibbonToTransform",2),y([_(Oe)],te.prototype,"colorOverLifetime",2),y([_(Oe)],te.prototype,"colorOverTrail",2),y([_()],te.prototype,"dieWithParticles",2),y([_()],te.prototype,"inheritParticleColor",2),y([_(U)],te.prototype,"lifetime",2),y([_()],te.prototype,"lifetimeMultiplier",2),y([_()],te.prototype,"minVertexDistance",2),y([_()],te.prototype,"mode",2),y([_()],te.prototype,"ratio",2),y([_()],te.prototype,"ribbonCount",2),y([_()],te.prototype,"shadowBias",2),y([_()],te.prototype,"sizeAffectsLifetime",2),y([_()],te.prototype,"sizeAffectsWidth",2),y([_()],te.prototype,"splitSubEmitterRibbons",2),y([_()],te.prototype,"textureMode",2),y([_(U)],te.prototype,"widthOverTrail",2),y([_()],te.prototype,"widthOverTrailMultiplier",2),y([_()],te.prototype,"worldSpace",2);var je=class{enabled;space=0;speedModifier;speedModifierMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_system;update(e){this._system=e}_temp=new Ye;apply(e,t,i,n,r,s){if(!this.enabled)return;let a=r/s,c=this.speedModifier.evaluate(a)*this.speedModifierMultiplier,d=this.x.evaluate(a),l=this.y.evaluate(a),u=this.z.evaluate(a);this._temp.set(-d,l,u),this._system&&(this.space===1&&this._temp.applyQuaternion(this._system.worldQuaternionInverted),this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z,i.x*=c,i.y*=c,i.z*=c}};y([_()],je.prototype,"enabled",2),y([_()],je.prototype,"space",2),y([_(U)],je.prototype,"speedModifier",2),y([_()],je.prototype,"speedModifierMultiplier",2),y([_(U)],je.prototype,"x",2),y([_()],je.prototype,"xMultiplier",2),y([_(U)],je.prototype,"y",2),y([_()],je.prototype,"yMultiplier",2),y([_(U)],je.prototype,"z",2),y([_()],je.prototype,"zMultiplier",2);var _e=class{animation;enabled;cycleCount;frameOverTime;frameOverTimeMultiplier;numTilesX;numTilesY;startFrame;startFrameMultiplier;rowMode;rowIndex;spriteCount;timeMode;sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?this.frameOverTime.evaluate(Math.random()):0}evaluate(e){if(!this.sampleOnceAtStart())return this.getIndex(e)}getIndex(e){let t=this.numTilesX*this.numTilesY,i=this.frameOverTime.evaluate(e%1);return i*=this.frameOverTimeMultiplier,i*=t,i=i%t,i=Math.floor(i),i}};y([_()],_e.prototype,"animation",2),y([_()],_e.prototype,"enabled",2),y([_()],_e.prototype,"cycleCount",2),y([_(U)],_e.prototype,"frameOverTime",2),y([_()],_e.prototype,"frameOverTimeMultiplier",2),y([_()],_e.prototype,"numTilesX",2),y([_()],_e.prototype,"numTilesY",2),y([_(U)],_e.prototype,"startFrame",2),y([_()],_e.prototype,"startFrameMultiplier",2),y([_()],_e.prototype,"rowMode",2),y([_()],_e.prototype,"rowIndex",2),y([_()],_e.prototype,"spriteCount",2),y([_()],_e.prototype,"timeMode",2);var qe=class{enabled;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e){return this.enabled?this.separateAxes?0:this.z.evaluate(e)*-1:0}};y([_()],qe.prototype,"enabled",2),y([_()],qe.prototype,"separateAxes",2),y([_(U)],qe.prototype,"x",2),y([_()],qe.prototype,"xMultiplier",2),y([_(U)],qe.prototype,"y",2),y([_()],qe.prototype,"yMultiplier",2),y([_(U)],qe.prototype,"z",2),y([_()],qe.prototype,"zMultiplier",2);var ze=class{enabled;range;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){let i=H.lerp(this.range.x,this.range.y,t);return this.z.evaluate(i)*-1}return 0}};y([_()],ze.prototype,"enabled",2),y([_()],ze.prototype,"range",2),y([_()],ze.prototype,"separateAxes",2),y([_(U)],ze.prototype,"x",2),y([_()],ze.prototype,"xMultiplier",2),y([_(U)],ze.prototype,"y",2),y([_()],ze.prototype,"yMultiplier",2),y([_(U)],ze.prototype,"z",2),y([_()],ze.prototype,"zMultiplier",2);var de=class{enabled;dampen;drag;dragMultiplier;limit;limitMultiplier;separateAxes;limitX;limitXMultiplier;limitY;limitYMultiplier;limitZ;limitZMultiplier;multiplyDragByParticleSize=!1;multiplyDragByParticleVelocity=!1;space;_temp=new Ye;_temp2=new Ye;apply(e,t,i,n,r,s,a){if(!!this.enabled){let c=this.limit.evaluate(r)*this.limitMultiplier;if(t.length()>c){this._temp.copy(t).normalize().multiplyScalar(c);let l=this.dampen*.5;t.x=H.lerp(t.x,this._temp.x,l),t.y=H.lerp(t.y,this._temp.y,l),t.z=H.lerp(t.z,this._temp.z,l),i.x=H.lerp(i.x,this._temp.x,l),i.y=H.lerp(i.y,this._temp.y,l),i.z=H.lerp(i.z,this._temp.z,l)}}}};y([_()],de.prototype,"enabled",2),y([_()],de.prototype,"dampen",2),y([_(U)],de.prototype,"drag",2),y([_()],de.prototype,"dragMultiplier",2),y([_(U)],de.prototype,"limit",2),y([_()],de.prototype,"limitMultiplier",2),y([_()],de.prototype,"separateAxes",2),y([_(U)],de.prototype,"limitX",2),y([_()],de.prototype,"limitXMultiplier",2),y([_(U)],de.prototype,"limitY",2),y([_()],de.prototype,"limitYMultiplier",2),y([_(U)],de.prototype,"limitZ",2),y([_()],de.prototype,"limitZMultiplier",2),y([_()],de.prototype,"multiplyDragByParticleSize",2),y([_()],de.prototype,"multiplyDragByParticleVelocity",2),y([_()],de.prototype,"space",2);var Yt=class{enabled;curve;curveMultiplier;mode;system;_lastWorldPosition;_velocity=new Ye;_temp=new Ye;update(e){!this.enabled||this.system.worldspace!==!1&&(this._lastWorldPosition?(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)):(this._velocity.set(0,0,0),this._lastWorldPosition=this.system.worldPos.clone()))}applyInitial(e){if(!!this.enabled&&this.system.worldspace!==!1&&this.mode===0){let t=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(t),e.add(this._temp)}}applyCurrent(e,t,i){if(!!this.enabled&&this.system.worldspace!==!1&&this.mode===1){let n=this.curve.evaluate(t,i);this._temp.copy(this._velocity).multiplyScalar(n),e.add(this._temp)}}};y([_()],Yt.prototype,"enabled",2),y([_(U)],Yt.prototype,"curve",2),y([_()],Yt.prototype,"curveMultiplier",2),y([_()],Yt.prototype,"mode",2);var Pe=class{enabled;range;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t,i,n){let r=e.length(),s=H.remap(r,this.range.x,this.range.y,0,1),a=this.size.evaluate(s,i);return n*a}};y([_()],Pe.prototype,"enabled",2),y([_(lm)],Pe.prototype,"range",2),y([_()],Pe.prototype,"separateAxes",2),y([_(U)],Pe.prototype,"size",2),y([_()],Pe.prototype,"sizeMultiplier",2),y([_(U)],Pe.prototype,"x",2),y([_()],Pe.prototype,"xMultiplier",2),y([_(U)],Pe.prototype,"y",2),y([_()],Pe.prototype,"yMultiplier",2),y([_(U)],Pe.prototype,"z",2),y([_()],Pe.prototype,"zMultiplier",2);var Ci=class{enabled;range;color;evaluate(e,t,i){let n=e.length(),r=H.remap(n,this.range.x,this.range.y,0,1),s=this.color.evaluate(r,t);i.x*=s.r,i.y*=s.g,i.z*=s.b,i.w*=s.alpha}};y([_()],Ci.prototype,"enabled",2),y([_(lm)],Ci.prototype,"range",2),y([_(Oe)],Ci.prototype,"color",2);import{AxesHelper as x_,Material as dm,Mesh as um,Object3D as w_,Quaternion as Mu,Vector3 as oa,Vector4 as E_}from"three";import{BatchedParticleRenderer as C_,ConstantColor as T_,ConstantValue as R_,ParticleSystem as S_,RenderMode as Yl,TrailParticle as hm}from"three.quarks";import{Vector3 as ql,Quaternion as __,Matrix4 as ku}from"three";var I1=new ql(1,1,1),D1=new ql(0,0,1),A1=Symbol("emitterMatrix"),lr=class{constructor(e,t,i,n){this.system=e;this.particleSystem=t;this.subSystem=i;this.subParticleSystem=n;this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);let r=1e3;this._circularBuffer=new Pi(()=>new ku,r)}type="NeedleParticleSubEmitter";q_=new __;v_=new ql;v2_=new ql;_emitterMatrix=new ku;_circularBuffer;clone(){throw new Error("Method not implemented.")}initialize(e){e.emissionState={burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0},this._emitterMatrix.copy(this.subSystem.matrixWorld).invert().premultiply(this.system.matrixWorld)}update(e,t){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!e.emissionState)return;let i=new ku;i.set(1,0,0,e.position.x,0,1,0,e.position.y,0,0,1,e.position.z,0,0,0,1),this.particleSystem.worldSpace||i.multiplyMatrices(this._emitterMatrix,i),this.subParticleSystem.emit(t,e.emissionState,i)}frameUpdate(e){}toJSON(){}};var vm=O("debugparticles"),cr=class{particleSystem;_deserialize(e){let t=this.particleSystem;t&&!(t instanceof be)&&typeof t.guid=="string"&&(vm&&console.log("DESERIALIZE SUBEMITTER",t),this.particleSystem=void 0,this.particleSystem=R.findByGuid(t.guid,e.scene))}},qi=class extends M{renderMode;particleMaterial;trailMaterial;particleMesh;get transparent(){return this.particleMaterial?.transparent??!1}getMaterial(e=!1){return e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial}getMesh(){let e=null;return this.particleMesh instanceof um&&(e=this.particleMesh.geometry),e===null&&(e=new Ko.BoxGeometry(1,1,1)),new um(e,this.getMaterial())}};y([_()],qi.prototype,"renderMode",2),y([_(dm)],qi.prototype,"particleMaterial",2),y([_(dm)],qi.prototype,"trailMaterial",2);var Yo=class{_curve;constructor(e){this._curve=e}type="function";genValue(e){return this._curve.evaluate(e,Math.random())}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}};var sa=class{type="value";toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}system;constructor(e){this.system=e}},Iu=class extends sa{genValue(){return this.system.textureSheetAnimation.getStartIndex()}},Du=class extends sa{_lastPosition=new oa;_lastDistance=0;update(){let e=B(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){let n=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random()),s=this._lastDistance/this.system.deltaTime*n;Number.isFinite(s)||(s=0),e+=s}let t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);let i=this.system.maxParticles-this.system.currentParticles;return H.clamp(e,0,i/this.system.deltaTime)}},Au=class extends sa{genValue(){return 0}},dr=class{system;get scaleFactorDiff(){return this.system.worldScale.x-this.system.scale}constructor(e){this.system=e}initialize(e){}update(e,t){}frameUpdate(e){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}},Lu=class extends dr{type="NeedleTextureSheet";update(e,t){let i=this.system.textureSheetAnimation;if(i.enabled){let n=e.age/e.life,r=i.evaluate(n);r!==void 0&&(e.uvTile=r)}}},ju=class extends dr{type="NeedleRotation";update(e,t){if(e.rotation===void 0)return;let i=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(i)*t:this.system.renderer.renderMode===0&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){let n=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(i,n)*t}}},pm=Symbol("sizeLerpFactor"),Hu=class extends dr{type="NeedleSize";initialize(e){e[pm]=Math.random()}update(e,t){if(this.system.renderer.renderMode!==4){let i=e.age/e.life,n=1;this.system.sizeOverLifetime.enabled&&(n*=this.system.sizeOverLifetime.evaluate(i,void 0,e[pm]).x);let r=this.system.worldScale.x/this.system.cameraScale;e.size=e.startSize*n*r}}},Kl=Symbol("particleLife"),Jl=Symbol("trailLifetime"),fm=Symbol("trailStartLength"),Fu=class extends dr{type="NeedleTrail";initialize(e){e instanceof hm&&(e[Kl]=e.life,e[Jl]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[Jl]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[Jl]),e[fm]=e.length)}update(e){if(this.system.trails?.enabled&&e instanceof hm){let t=e,i=e.age/e[Kl],n=e.previous.values(),r=e.previous.length;for(let s=0;s<r;s++){let c=n.next().value,d=1-s/(r-1);c.size=this.system.trails.getWidth(e.size,i,d),c.color.copy(e.color),this.system.trails.getColor(c.color,i,d)}if(e.age>e[Kl]){e.velocity.set(0,0,0);let s=(e.age-e[Kl])/e[Jl];t.length=H.lerp(e[fm],0,s)}}}},Zl=Symbol("startVelocity"),mm=Symbol("gravityModifier"),$l=Symbol("velocity lerp factor"),gm=new oa,kL=new Mu,Bu=class extends dr{type="NeedleVelocity";_gravityDirection=new oa;initialize(e){let t=1+this.scaleFactorDiff;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random())*t,e.velocity.copy(this.system.shape.getDirection(e.position)).multiplyScalar(e.startSpeed),this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[Zl]?e[Zl].copy(e.velocity):e[Zl]=e.velocity.clone();let i=this.system.main.gravityModifier.evaluate(Math.random(),Math.random())/(9.81*2);e[mm]=i,e[$l]=Math.random(),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===0&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted)}update(e,t){let i=e[Zl],n=e[mm];n!==0&&(gm.copy(this._gravityDirection).multiplyScalar(n),i.add(gm)),e.velocity.copy(i);let r=e.age/e.life;this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,r,e[$l]);let s=this.system.noise;s.enabled&&s.apply(0,e.position,e.velocity,t,e.age,e.life);let a=this.system.sizeBySpeed;a?.enabled&&(e.size=a.evaluate(e.velocity,r,e[$l],e.size));let c=this.system.colorBySpeed;c?.enabled&&c.evaluate(e.velocity,e[$l],e.color);let d=this.system.velocityOverLifetime;d.enabled&&d.apply(0,e.position,e.velocity,t,e.age,e.life);let l=this.system.limitVelocityOverLifetime;l.enabled&&l.apply(e.position,i,e.velocity,e.size,r,t,1)}},bm=Symbol("colorLerpFactor"),Uu=class extends dr{type="NeedleColor";initialize(e){let t=this.system.main.startColor.evaluate(e.age/e.life,Math.random());e.startColor.set(t.r,t.g,t.b,t.alpha),e.color.copy(e.startColor),e[bm]=Math.random()}update(e,t){if(this.system.colorOverLifetime.enabled){let i=e.age/e.life,n=this.system.colorOverLifetime.color.evaluate(i,e[bm]);e.color.set(n.r,n.g,n.b,n.alpha).multiply(e.startColor)}else e.color.copy(e.startColor)}},Gu=class{system;emission;get anim(){return this.system.textureSheetAnimation}constructor(e){this.system=e,this.emission=new Du(this.system)}update(){this.emission.update()}autoDestroy;get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new Yo(this.system.main.startLifetime)}get startSpeed(){return new Yo(this.system.main.startSpeed)}get startRotation(){return new Yo(this.system.main.startRotation)}get startSize(){return new Yo(this.system.main.startSize)}startLength;get startColor(){return new T_(new E_(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new Au(this.system)}emissionBursts;onlyUsedByOther;behaviors=[];get instancingGeometry(){return this.system.renderer.getMesh().geometry}get renderMode(){if(this.system.trails.enabled===!0)return Yl.Trail;switch(this.system.renderer.renderMode){case 0:return Yl.BillBoard;case 4:return Yl.LocalSpace}return Yl.BillBoard}rendererEmitterSettings={startLength:new R_(220),followLocalOrigin:!1};get speedFactor(){return this.system.main.simulationSpeed}get texture(){let e=this.system.renderer.getMaterial(this.system.trails.enabled);if(e&&e.map){let t=e.map;return t.premultiplyAlpha=!1,t.encoding=Ko.LinearEncoding,t}return dl(new Z(1,1,1,1),1)}get startTileIndex(){return new Iu(this.system)}get uTileCount(){return this.anim.enabled?this.anim?.numTilesX:void 0}get vTileCount(){return this.anim.enabled?this.anim?.numTilesY:void 0}get renderOrder(){return 1}get blending(){return this.system.renderer.particleMaterial?.blending??Ko.NormalBlending}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===1}},Vu=class{burstIndex=0;burstWaveIndex=0;time=0;waitEmiting=0},zu=class extends M{play(e=!1){e&&R.foreachComponent(this.gameObject,t=>{t instanceof zu&&t!==this&&t.play(!1)},!0),this._isPlaying=!0,this._time=0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),this.emission?.reset()}pause(){this._isPlaying=!1}stop(){this._isPlaying=!1,this._time=0}_state;emit(e){if(this._particleSystem){e=Math.min(e,this.maxParticles-this.currentParticles),this._state||(this._state=new Vu),this._state.waitEmiting=e,this._state.time=0;let t=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=t}}colorOverLifetime;main;emission;sizeOverLifetime;shape;noise;trails;velocityOverLifetime;limitVelocityOverLifetime;inheritVelocity;colorBySpeed;textureSheetAnimation;rotationOverLifetime;rotationBySpeed;sizeBySpeed;get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){return this._particleSystem?.particleNum??0}get maxParticles(){return this.main.maxParticles}get time(){return this._time}get duration(){return this.main.duration}get deltaTime(){return this.context.time.deltaTime*this.main.simulationSpeed}get scale(){return this.gameObject.scale.x}get cameraScale(){return this._cameraScale}_cameraScale=1;get container(){return this._container}get worldspace(){return this.main.simulationSpace===1}__worldQuaternion=new Mu;get worldQuaternion(){return this.__worldQuaternion}_worldQuaternionInverted=new Mu;get worldQuaternionInverted(){return this._worldQuaternionInverted}_worldScale=new oa;get worldScale(){return this._worldScale}_worldPositionFrame=-1;_worldPos=new oa;get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,B(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}_renderer;_batchSystem;_particleSystem;_interface;_container;_time=0;_isPlaying=!0;_isUsedAsSubsystem=!1;set bursts(e){for(let t=0;t<e.length;t++){let i=e[t];if(!(i instanceof On)){let n=new On;It(n,i),e[t]=n}}this._bursts=e}_bursts;set subEmitterSystems(e){for(let t=0;t<e.length;t++){let i=e[t];if(!(i instanceof cr)){let n=new cr;It(n,i),e[t]=n}}this._subEmitterSystems=e}_subEmitterSystems;awake(){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(let t of this._subEmitterSystems)t._deserialize(this.context);this._renderer=this.gameObject.getComponent(qi),this._container=new w_,this._container.matrixAutoUpdate=!1,this.main.simulationSpace==0?this.gameObject.add(this._container):this.context.scene.add(this._container),this._batchSystem=new C_,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new Gu(this),this._particleSystem=new S_(this._batchSystem,this._interface),this._particleSystem.addBehavior(new Hu(this)),this._particleSystem.addBehavior(new Uu(this)),this._particleSystem.addBehavior(new Lu(this)),this._particleSystem.addBehavior(new ju(this)),this._particleSystem.addBehavior(new Bu(this)),this._particleSystem.addBehavior(new Fu(this));let e=this._particleSystem.emitter;this.context.scene.add(e),vm&&(console.log(this),this.gameObject.add(new x_(1)))}start(){this.addSubParticleSystems()}onEnable(){this.inheritVelocity&&(this.inheritVelocity.system=this),this.play()}onDisable(){}onBeforeRender(){if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;let e=this.context.mainCamera;if(e){let n=Me(e);this._cameraScale=n.x}let t=this._container;if(this.worldspace&&(t=this.gameObject),fe(t,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Me(this.gameObject,this._worldScale),!this.worldspace&&this._container&&this.gameObject?.parent){let n=Me(this.gameObject.parent);n.x=1/n.x,n.y=1/n.y,n.z=1/n.z,this._container.matrix.identity(),this._container.matrix.scale(n)}this.emission.system=this;let i=this.deltaTime;this._interface.update(),this.shape.update(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),this.inheritVelocity?.update(this.context),this.velocityOverLifetime.update(this),this._batchSystem?.update(i),this._time+=i,this._time>this.duration&&(this._time=0)}addSubParticleSystems(){if(this._subEmitterSystems&&this._particleSystem)for(let e of this._subEmitterSystems){let t=e.particleSystem?._particleSystem;if(t){e.particleSystem._isUsedAsSubsystem=!0;let i=new lr(this,this._particleSystem,e.particleSystem,t);this._particleSystem.addBehavior(i)}}}},be=zu;y([_(Pn)],be.prototype,"colorOverLifetime",2),y([_(ye)],be.prototype,"main",2),y([_(ft)],be.prototype,"emission",2),y([_(qt)],be.prototype,"sizeOverLifetime",2),y([_(ne)],be.prototype,"shape",2),y([_(Y)],be.prototype,"noise",2),y([_(te)],be.prototype,"trails",2),y([_(je)],be.prototype,"velocityOverLifetime",2),y([_(de)],be.prototype,"limitVelocityOverLifetime",2),y([_(Yt)],be.prototype,"inheritVelocity",2),y([_(Ci)],be.prototype,"colorBySpeed",2),y([_(_e)],be.prototype,"textureSheetAnimation",2),y([_(qe)],be.prototype,"rotationOverLifetime",2),y([_(ze)],be.prototype,"rotationBySpeed",2),y([_(Pe)],be.prototype,"sizeBySpeed",2);import*as _m from"three";function*ym(o,e=null){let t=e?e.time:G.Current.time,i=t.time;for(;t.time-i<o;)yield}var mt=class extends M{awake(){this.context.connection.beginListen("joined-room",this.tryAssignColor.bind(this))}_didAssignPlayerColor=!1;onEnable(){this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}*waitForConnection(){for(;!this.destroyed&&this.enabled&&(yield ym(.2),!this.tryAssignColor()););}tryAssignColor(){let e=R.getComponentInParent(this.gameObject,le);return e&&e.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(e.connectionId),!0):!1}assignUserColor(e){let t=mt.hashCode(e),i=mt.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 _m.Color(t/255,i/255,n/255)}};import{EquirectangularReflectionMapping as P_,sRGBEncoding as O_,Vector3 as xm}from"three";var Jo=O("debugreflectionprobe"),wm=O("noreflectionprobe"),k_=Symbol("reflectionProbeKey"),M_=Symbol("original material"),Yi=class extends M{static get(e,t,i){if(!e||e.isObject3D!==!0||wm)return null;let n=Yi._probes.get(t);if(n){for(let r of n)if(r.__didAwake||r.__internalAwake(),r.enabled&&r.isInBox(e,i?1e-8:void 0))return Jo&&console.log("Found reflection probe",e.name,r.name),r}return Jo&&console.debug("Did not find reflection probe",e.name,i,e),null}_texture;set texture(e){this._texture=e}get texture(){return this._texture}center;size;_boxHelper;isInBox(e,t){return this._boxHelper?.isInBox(e,t)}constructor(){super(),Yi._probes.has(this.context)||Yi._probes.set(this.context,[]),Yi._probes.get(this.context)?.push(this)}awake(){this._boxHelper=this.gameObject.addNewComponent(Ue),this._boxHelper.updateBox(!0),Jo&&this._boxHelper.showHelper(5592320,!0),this.texture&&(this.texture.mapping=P_,this.texture.encoding=O_,this.texture.needsUpdate=!0)}onDestroy(){let e=Yi._probes.get(this.context);if(e){let t=e.indexOf(this);t>=0&&e.splice(t,1)}}onSet(e){if(wm||e.sharedMaterials?.length<=0||!this.texture)return;let t=Yi._rendererMaterialsCache.get(e);t||(t=[],Yi._rendererMaterialsCache.set(e,t));for(let i=0;i<e.sharedMaterials.length;i++){let n=e.sharedMaterials[i];if(!n||n.envMap===void 0||n.envMap===this.texture)continue;let r=t[i];if(!r||r.material!==n||r.material.version!==n.version){let a=n.clone();r?(r.copy=a,r.material=n):(r={material:n,copy:a},t.push(r)),a[k_]=this,a[M_]=n,a.envMap=this.texture,Jo&&console.log("Set reflection",e.name,e.guid)}let s=r?.copy;e.sharedMaterials[i]=s}}onUnset(e){let t=Yi._rendererMaterialsCache.get(e);if(t)for(let i=0;i<t.length;i++){let n=t[i];e.sharedMaterials[i]=n.material}}},Kt=Yi;D(Kt,"_probes",new Map),D(Kt,"_rendererMaterialsCache",new Map),y([_(xm)],Kt.prototype,"center",2),y([_(xm)],Kt.prototype,"size",2);import*as Ki from"three";import*as aa from"three";var kn=class{get lightmap(){return this.lightmapTexture}set lightmap(e){e!==this.lightmapTexture&&(this.lightmapTexture=e,this.setupLightmap())}lightmapIndex=-1;lightmapScaleOffset=new aa.Vector4(1,1,0,0);context;gameObject;lightmapTexture=null;lightmapScaleOffsetUniform={value:new aa.Vector4(1,1,0,0)};lightmapUniform={value:null};beforeRenderCallback;constructor(e,t){this.gameObject=e,this.context=t}init(e,t,i,n=!1){if(console.assert(this.gameObject!==void 0&&this.gameObject!==null,"Missing gameobject",this),this.lightmapIndex=e,this.lightmapIndex<0)return;this.lightmapScaleOffset=t,this.lightmapTexture=i,n&&this.setLightmapDebugMaterial(),this.setupLightmap()}bindOnBeforeRender(){this.beforeRenderCallback=this.onBeforeRenderThreeComplete.bind(this),this.context.addBeforeRenderListener(this.gameObject,this.beforeRenderCallback)}onBeforeRenderThreeComplete(e,t,i,n,r,s){this.onBeforeRenderThree(r)}setupLightmap(){if(this.gameObject.type==="Object3D")return;if(this.gameObject.type==="Group"){console.warn("Lightmap on multimaterial object is not supported yet... please ask kindly for implementation.");return}console.assert(this.gameObject.type==="Mesh","Lightmap only works on meshes",this);let e=this.gameObject;e.geometry.getAttribute("uv2")||e.geometry.setAttribute("uv2",e.geometry.getAttribute("uv"));let t=this.gameObject.material.clone();if(this.gameObject.material=t,this.gameObject.material.onBeforeCompile=(i,n)=>{i.uniforms.lightmap=this.lightmapUniform,i.uniforms.lightmapScaleOffset=this.lightmapScaleOffsetUniform},this.lightmapIndex>=0){let i=this.lightmapTexture,n=this.gameObject.material;n&&i&&(n.uniforms||(n.uniforms={}),n.lightMap=i,n.uniforms.lightmap={value:i})}}onBeforeRenderThree(e){let t=e.uniforms;t&&t.lightmap&&(this.lightmapScaleOffsetUniform.value=this.lightmapScaleOffset,this.lightmapUniform.value=this.lightmapTexture,t.lightmap=this.lightmapUniform,t.lightmapScaleOffset=this.lightmapScaleOffsetUniform)}setLightmapDebugMaterial(){this.gameObject.material=new aa.ShaderMaterial({vertexShader:`
216
216
  attribute vec2 uv2;
217
217
  varying vec2 vUv2;
218
218
  void main()
@@ -244,7 +244,7 @@ a:hover {
244
244
  // gl_FragColor = vec4(vUv2.xy, 0, 1);
245
245
  gl_FragColor = lightMapTexel;
246
246
  }
247
- `,defines:{USE_LIGHTMAP:""}})}};import{AxesHelper as E_,Object3D as C_,Vector4 as T_}from"three";import{Layers as FL}from"three";var w_=Symbol("customVisibilityFlag");function Yl(o,e){o.layers[w_]=e}var UL=Symbol("DidPatchLayers");var bm=M("noInstancing"),vm=!!M("debuglightmaps"),R_=M("debuginstancing"),S_=M("debugprogressive"),P_=M("noprogressive");var Ko=class{path=null;asset=null;default};var Bu=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"SkinnedMesh":case"Mesh":this._targets.push(n);break}return new Proxy(this,{get(r,s){if(typeof s=="string"){let a=parseInt(s);if(!isNaN(a))return i(a)}return r[s]},set(r,s,a){return typeof s=="string"&&t(a,Number.parseInt(s)),Reflect.set(r,s,a)}})}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===void 0||(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}},Jl=class extends k{static setVisible(e,t){Yl(e,t)}receiveShadows=!1;shadowCastingMode=Uu.Off;lightmapIndex=-1;lightmapScaleOffset=new Qi.Vector4(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;probeAnchor;reflectionProbeUsage=0;_lightmaps;get sharedMesh(){if(this.gameObject.type==="Mesh")return this.gameObject;if(this.gameObject.type==="SkinnesMesh")return this.gameObject;if(this.gameObject.type==="Group")return this.gameObject.children[0]}get sharedMaterial(){return this.sharedMaterials[0]}set sharedMaterial(e){this.sharedMaterials[0]=e}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 Bu(this)),this._sharedMaterials}static get shouldSuppressInstancing(){return bm}_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}allowProgressiveLoading=!0;awake(){this.clearInstancingState(),this.probeAnchor&&Yo&&this.probeAnchor.add(new E_(.2)),this._reflectionProbe=null;let e=this.gameObject.type;if(this.isMultiMaterialObject(this.gameObject)){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"||R.getComponent(n,Jl))){if(this.renderOrder.length<=t){console.error("Incorrect element count",this);break}n.renderOrder=this.renderOrder[t],t+=1}}}}else this.isMeshOrSkinnedMesh(this.gameObject)&&(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 Sn(this.gameObject,this.context);this._lightmaps.push(i),i.init(this.lightmapIndex,this.lightmapScaleOffset,t,vm)}}else if(this.isMultiMaterialObject(this.gameObject)){for(let i of this.gameObject.children)if(!i.material?.isMeshBasicMaterial){let n=new Sn(i,this.context);this._lightmaps.push(n),n.init(this.lightmapIndex,this.lightmapScaleOffset,t,vm),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=O_.setup(this.gameObject,this.context,null,{rend:this,foundMeshes:0}),this.handles)return R.markAsInstancedRendered(this.gameObject,!0),!0}else if(this.handles!==null){for(let t of this.handles)t.updateInstanceMatrix(!0),t.add();return R.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&&!bm&&this.setInstancingEnabled(!0),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.isMultiMaterialObject(this.gameObject))for(let e=0;e<this.gameObject.children.length;e++){let t=this.gameObject.children[e];t.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this.setVisibility(!0),this._isInstancingEnabled?this.setInstancingEnabled(!0):this.enabled&&this.applyStencil(),this.updateReflectionProbe()}onDisable(){this.setVisibility(!1),this.handles&&this.handles.length>0&&this.setInstancingEnabled(!1)}onDestroy(){this.handles=null}applyStencil(){jr.applyStencil(this)}onBeforeRender(){if(!this.gameObject)return;Jl.envmap=this.scene.environment;let e=this.gameObject[Va]===!0||this.gameObject.matrixWorldNeedsUpdate;if(this.isMultiMaterialObject(this.gameObject)&&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[Va],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&&R.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()}this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onSet(this)}onBeforeRenderThree(e,t,i,n,r,s){if(!P_&&r._didRequestTextureLOD===void 0&&this.allowProgressiveLoading&&(r._didRequestTextureLOD=0,S_?(console.log("Load material LOD (with delay)",r.name),setTimeout(()=>{fn.assignTextureLOD(this.context,this.sourceId,r)},2e3)):fn.assignTextureLOD(this.context,this.sourceId,r)),r.envMapIntensity!==void 0){let a=this.hasLightmap?Math.PI:1;r.envMapIntensity=Math.max(0,this.context.rendererData.environmentIntensity/a)}if(this._lightmaps)for(let a of this._lightmaps)a.onBeforeRenderThree(r)}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]}this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onUnset(this)}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==Uu.On?e.castShadow=!0:e.castShadow=!1}_reflectionProbe=null;updateReflectionProbe(){if(this._reflectionProbe=null,this.reflectionProbeUsage!==0){if(!this.probeAnchor)return;let e=this.probeAnchor||this.gameObject,t=!!this.probeAnchor;this._reflectionProbe=Kt.get(e,this.context,t)}}setVisibility(e){if(!this.isMultiMaterialObject(this.gameObject))Yl(this.gameObject,e);else for(let t of this.gameObject.children)this.isMeshOrSkinnedMesh(t)&&Yl(t,e)}isMultiMaterialObject(e){return e.type==="Group"}isMeshOrSkinnedMesh(e){return e.type==="Mesh"||e.type==="SkinnedMesh"}},ae=Jl;A(ae,"envmap",null),_([y()],ae.prototype,"receiveShadows",2),_([y()],ae.prototype,"shadowCastingMode",2),_([y()],ae.prototype,"lightmapIndex",2),_([y(T_)],ae.prototype,"lightmapScaleOffset",2),_([y()],ae.prototype,"enableInstancing",2),_([y()],ae.prototype,"renderOrder",2),_([y()],ae.prototype,"allowOcclusionWhenDynamic",2),_([y(C_)],ae.prototype,"probeAnchor",2),_([y()],ae.prototype,"reflectionProbeUsage",2);var Qr=class extends ae{},Jo=class extends Qr{awake(){super.awake(),this.allowOcclusionWhenDynamic=!1}},Uu=(n=>(n[n.Off=0]="Off",n[n.On=1]="On",n[n.TwoSided=2]="TwoSided",n[n.ShadowsOnly=3]="ShadowsOnly",n))(Uu||{}),Gu=class{objs=[];setup(e,t,i,n,r=0){let s=this.tryCreateOrAddInstance(e,t,n);if(s)return i===null&&(i=[]),i.push(s),i;if(r<=0&&e.type!=="Mesh"){let a=r+1;for(let c of e.children)i=this.setup(c,t,i,n,a)}return i}tryCreateOrAddInstance(e,t,i){if(e.type==="Mesh"){let n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing||n>=i.rend.enableInstancing.length||!i.rend.enableInstancing[n])return null;let r=e,s=r.geometry,a=r.material;for(let d of this.objs)if(!d.isFull()&&d.geo===s&&d.material===a)return d.addInstance(r);let c=new Kl(e.name,s,a,200,t);return this.objs.push(c),c.addInstance(r)}return null}},O_=new Gu,Vu=class{get name(){return this.object.name}instanceIndex=-1;object;instancer;constructor(e,t,i){this.instanceIndex=e,this.object=t,this.instancer=i,R.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)}},zu=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,R_&&(i=new Qi.MeshBasicMaterial({color:this.randomColor()})),this.inst=new Qi.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 Qi.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 Vu(-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,zu.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}},Kl=zu;A(Kl,"nullMatrix",new Qi.Matrix4);import*as ec from"three";import{Object3D as D_,ShaderMaterial as L_,Texture as j_,Vector2 as Wu,Vector4 as H_}from"three";function k_(){return new Promise((o,e)=>{let i=()=>{i!=null&&(document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i),o())};document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)})}async function ym(o){await k_(),o()}import{PlaneGeometry as M_,MeshBasicMaterial as I_,Mesh as A_}from"three";var Zl=class{static createPrimitive(e,t){let i;switch(e){case 0:let n=new M_(1,1,1,1),r=t?.material??new I_({color:16777215});i=new A_(n,r)}return t?.name&&(i.name=t.name),i}};var $l=M("debugvideo");var _m=(n=>(n[n.CameraFarPlane=0]="CameraFarPlane",n[n.CameraNearPlane=1]="CameraNearPlane",n[n.RenderTexture=2]="RenderTexture",n[n.MaterialOverride=3]="MaterialOverride",n))(_m||{}),Ce=class extends k{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,$l&&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(),ym(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],M("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)}),$l&&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 ec.VideoTexture(this.videoElement)),this._videoTexture.flipY=!1,this._videoTexture.encoding=ec.sRGBEncoding,this.handleBeginPlaying(e),$l&&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 Nu(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),$l&&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=R.getComponent(this.gameObject,ae)?.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,_m[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 s=r.getSettings();if(s&&s.width&&s.height){n=s.width/s.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 s=1;if(r.parent){let a=Me(r.parent);s=a.x/a.y}switch(this.aspectMode){case 1:r.scale.y=1/n*r.scale.x*s;break;case 2:r.scale.x=n*r.scale.y*s;break}}for(let r=0;r<3;r++)yield}}};_([y(D_)],Ce.prototype,"renderer",2),_([y()],Ce.prototype,"playOnAwake",2),_([y()],Ce.prototype,"playOnEnable",2),_([y()],Ce.prototype,"aspectMode",2),_([y()],Ce.prototype,"renderMode",2),_([y()],Ce.prototype,"targetMaterialProperty",2),_([y(ae)],Ce.prototype,"targetMaterialRenderer",2),_([y(j_)],Ce.prototype,"targetTexture",2),_([y()],Ce.prototype,"time",2),_([y()],Ce.prototype,"playbackSpeed",1),_([y()],Ce.prototype,"isLooping",1);var Nu=class{context;constructor(e){this.context=e,this._input=new Xu(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=Zl.createPrimitive(0,{material:new Qu(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},Xu=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 Wu;window.addEventListener("mousemove",n=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){let r=new Wu(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],s=n.touches[1],a=r.clientX-s.clientX,c=r.clientY-s.clientY,d=Math.sqrt(a*a+c*c);if(this._lastPinch!==0){let l=d-this._lastPinch;this._material.zoom-=l*.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)}},Qu=class extends L_{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 Wu;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 H_(0,0,1,1)}},this.vertexShader=`
247
+ `,defines:{USE_LIGHTMAP:""}})}};import{AxesHelper as D_,Object3D as A_,Vector4 as L_}from"three";import{Layers as rj}from"three";var I_=Symbol("customVisibilityFlag");function ec(o,e){o.layers[I_]=e}var sj=Symbol("DidPatchLayers");var Em=O("noInstancing"),Cm=!!O("debuglightmaps"),j_=O("debuginstancing"),H_=O("debugprogressive"),F_=O("noprogressive");var Zo=class{path=null;asset=null;default};var Wu=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"SkinnedMesh":case"Mesh":this._targets.push(n);break}return new Proxy(this,{get(r,s){if(typeof s=="string"){let a=parseInt(s);if(!isNaN(a))return i(a)}return r[s]},set(r,s,a){return typeof s=="string"&&t(a,Number.parseInt(s)),Reflect.set(r,s,a)}})}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===void 0||(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}},ic=class extends M{static setVisible(e,t){ec(e,t)}receiveShadows=!1;shadowCastingMode=Nu.Off;lightmapIndex=-1;lightmapScaleOffset=new Ki.Vector4(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;probeAnchor;reflectionProbeUsage=0;_lightmaps;get sharedMesh(){if(this.gameObject.type==="Mesh")return this.gameObject;if(this.gameObject.type==="SkinnesMesh")return this.gameObject;if(this.gameObject.type==="Group")return this.gameObject.children[0]}get sharedMaterial(){return this.sharedMaterials[0]}set sharedMaterial(e){this.sharedMaterials[0]=e}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 Wu(this)),this._sharedMaterials}static get shouldSuppressInstancing(){return Em}_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}allowProgressiveLoading=!0;awake(){this.clearInstancingState(),this.probeAnchor&&Jo&&this.probeAnchor.add(new D_(.2)),this._reflectionProbe=null;let e=this.gameObject.type;if(this.isMultiMaterialObject(this.gameObject)){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"||R.getComponent(n,ic))){if(this.renderOrder.length<=t){console.error("Incorrect element count",this);break}n.renderOrder=this.renderOrder[t],t+=1}}}}else this.isMeshOrSkinnedMesh(this.gameObject)&&(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 kn(this.gameObject,this.context);this._lightmaps.push(i),i.init(this.lightmapIndex,this.lightmapScaleOffset,t,Cm)}}else if(this.isMultiMaterialObject(this.gameObject)){for(let i of this.gameObject.children)if(!i.material?.isMeshBasicMaterial){let n=new kn(i,this.context);this._lightmaps.push(n),n.init(this.lightmapIndex,this.lightmapScaleOffset,t,Cm),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=B_.setup(this.gameObject,this.context,null,{rend:this,foundMeshes:0}),this.handles)return R.markAsInstancedRendered(this.gameObject,!0),!0}else if(this.handles!==null){for(let t of this.handles)t.updateInstanceMatrix(!0),t.add();return R.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&&!Em&&this.setInstancingEnabled(!0),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.isMultiMaterialObject(this.gameObject))for(let e=0;e<this.gameObject.children.length;e++){let t=this.gameObject.children[e];t.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this.setVisibility(!0),this._isInstancingEnabled?this.setInstancingEnabled(!0):this.enabled&&this.applyStencil(),this.updateReflectionProbe()}onDisable(){this.setVisibility(!1),this.handles&&this.handles.length>0&&this.setInstancingEnabled(!1)}onDestroy(){this.handles=null}applyStencil(){Fr.applyStencil(this)}onBeforeRender(){if(!this.gameObject)return;ic.envmap=this.scene.environment;let e=this.gameObject[Qa]===!0||this.gameObject.matrixWorldNeedsUpdate;if(this.isMultiMaterialObject(this.gameObject)&&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[Qa],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&&R.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()}this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onSet(this)}onBeforeRenderThree(e,t,i,n,r,s){if(!F_&&r._didRequestTextureLOD===void 0&&this.allowProgressiveLoading&&(r._didRequestTextureLOD=0,H_?(console.log("Load material LOD (with delay)",r.name),setTimeout(()=>{vn.assignTextureLOD(this.context,this.sourceId,r)},2e3)):vn.assignTextureLOD(this.context,this.sourceId,r)),r.envMapIntensity!==void 0){let a=this.hasLightmap?Math.PI:1;r.envMapIntensity=Math.max(0,this.context.rendererData.environmentIntensity/a)}if(this._lightmaps)for(let a of this._lightmaps)a.onBeforeRenderThree(r)}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]}this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onUnset(this)}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==Nu.On?e.castShadow=!0:e.castShadow=!1}_reflectionProbe=null;updateReflectionProbe(){if(this._reflectionProbe=null,this.reflectionProbeUsage!==0){if(!this.probeAnchor)return;this.startCoroutine(this._updateReflectionProbe(),3)}}*_updateReflectionProbe(){let e=this.probeAnchor||this.gameObject,t=!!this.probeAnchor;this._reflectionProbe=Kt.get(e,this.context,t)}setVisibility(e){if(!this.isMultiMaterialObject(this.gameObject))ec(this.gameObject,e);else for(let t of this.gameObject.children)this.isMeshOrSkinnedMesh(t)&&ec(t,e)}isMultiMaterialObject(e){return e.type==="Group"}isMeshOrSkinnedMesh(e){return e.type==="Mesh"||e.type==="SkinnedMesh"}},ae=ic;D(ae,"envmap",null),y([_()],ae.prototype,"receiveShadows",2),y([_()],ae.prototype,"shadowCastingMode",2),y([_()],ae.prototype,"lightmapIndex",2),y([_(L_)],ae.prototype,"lightmapScaleOffset",2),y([_()],ae.prototype,"enableInstancing",2),y([_()],ae.prototype,"renderOrder",2),y([_()],ae.prototype,"allowOcclusionWhenDynamic",2),y([_(A_)],ae.prototype,"probeAnchor",2),y([_()],ae.prototype,"reflectionProbeUsage",2);var Kr=class extends ae{},$o=class extends Kr{awake(){super.awake(),this.allowOcclusionWhenDynamic=!1}},Nu=(n=>(n[n.Off=0]="Off",n[n.On=1]="On",n[n.TwoSided=2]="TwoSided",n[n.ShadowsOnly=3]="ShadowsOnly",n))(Nu||{}),Xu=class{objs=[];setup(e,t,i,n,r=0){let s=this.tryCreateOrAddInstance(e,t,n);if(s)return i===null&&(i=[]),i.push(s),i;if(r<=0&&e.type!=="Mesh"){let a=r+1;for(let c of e.children)i=this.setup(c,t,i,n,a)}return i}tryCreateOrAddInstance(e,t,i){if(e.type==="Mesh"){let n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing||n>=i.rend.enableInstancing.length||!i.rend.enableInstancing[n])return null;let r=e,s=r.geometry,a=r.material;for(let d of this.objs)if(!d.isFull()&&d.geo===s&&d.material===a)return d.addInstance(r);let c=new tc(e.name,s,a,200,t);return this.objs.push(c),c.addInstance(r)}return null}},B_=new Xu,Qu=class{get name(){return this.object.name}instanceIndex=-1;object;instancer;constructor(e,t,i){this.instanceIndex=e,this.object=t,this.instancer=i,R.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)}},qu=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,j_&&(i=new Ki.MeshBasicMaterial({color:this.randomColor()})),this.inst=new Ki.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 Ki.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 Qu(-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,qu.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}},tc=qu;D(tc,"nullMatrix",new Ki.Matrix4);import*as oc from"three";import{Object3D as W_,ShaderMaterial as N_,Texture as X_,Vector2 as Yu,Vector4 as Q_}from"three";function U_(){return new Promise((o,e)=>{let i=()=>{i!=null&&(document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i),o())};document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)})}async function Tm(o){await U_(),o()}import{PlaneGeometry as G_,MeshBasicMaterial as V_,Mesh as z_}from"three";var nc=class{static createPrimitive(e,t){let i;switch(e){case 0:let n=new G_(1,1,1,1),r=t?.material??new V_({color:16777215});i=new z_(n,r)}return t?.name&&(i.name=t.name),i}};var rc=O("debugvideo");var Rm=(n=>(n[n.CameraFarPlane=0]="CameraFarPlane",n[n.CameraNearPlane=1]="CameraNearPlane",n[n.RenderTexture=2]="RenderTexture",n[n.MaterialOverride=3]="MaterialOverride",n))(Rm||{}),Ce=class extends M{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,rc&&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(),Tm(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],O("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)}),rc&&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 oc.VideoTexture(this.videoElement)),this._videoTexture.flipY=!1,this._videoTexture.encoding=oc.sRGBEncoding,this.handleBeginPlaying(e),rc&&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 Ku(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),rc&&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=R.getComponent(this.gameObject,ae)?.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,Rm[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 s=r.getSettings();if(s&&s.width&&s.height){n=s.width/s.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 s=1;if(r.parent){let a=Me(r.parent);s=a.x/a.y}switch(this.aspectMode){case 1:r.scale.y=1/n*r.scale.x*s;break;case 2:r.scale.x=n*r.scale.y*s;break}}for(let r=0;r<3;r++)yield}}};y([_(W_)],Ce.prototype,"renderer",2),y([_()],Ce.prototype,"playOnAwake",2),y([_()],Ce.prototype,"playOnEnable",2),y([_()],Ce.prototype,"aspectMode",2),y([_()],Ce.prototype,"renderMode",2),y([_()],Ce.prototype,"targetMaterialProperty",2),y([_(ae)],Ce.prototype,"targetMaterialRenderer",2),y([_(X_)],Ce.prototype,"targetTexture",2),y([_()],Ce.prototype,"time",2),y([_()],Ce.prototype,"playbackSpeed",1),y([_()],Ce.prototype,"isLooping",1);var Ku=class{context;constructor(e){this.context=e,this._input=new Ju(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=nc.createPrimitive(0,{material:new Zu(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},Ju=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 Yu;window.addEventListener("mousemove",n=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){let r=new Yu(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],s=n.touches[1],a=r.clientX-s.clientX,c=r.clientY-s.clientY,d=Math.sqrt(a*a+c*c);if(this._lastPinch!==0){let l=d-this._lastPinch;this._material.zoom-=l*.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)}},Zu=class extends N_{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 Yu;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 Q_(0,0,1,1)}},this.vertexShader=`
248
248
  uniform sampler2D map;
249
249
  uniform float screenAspect;
250
250
  uniform vec4 offsetScale;
@@ -294,8 +294,7 @@ a:hover {
294
294
  else
295
295
  gl_FragColor = texture2D(map, vUv);
296
296
  }
297
- `}};var xm=ba(Ya(),1);import{EventDispatcher as Zu}from"three";var wm=M("debugscreenshare");function tc(o){if(!!o)for(let e of o.getTracks())e.stop()}var cr=class extends k{onPointerClick(){if(this.context.connection.isInRoom!==!1){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(){wm&&console.log(this),oe.registerWaitForAllowAudio(()=>{this.videoPlayer&&this._currentStream&&this._currentMode===2&&this.videoPlayer.setVideo(this._currentStream)})}start(){if(this.videoPlayer||(this.videoPlayer=R.getComponent(this.gameObject,Ce)??void 0),!this.videoPlayer){console.error("Screencapture did not find a VideoPlayer component");return}let e=ic.getOrCreate(this.context,this.guid);this._net=new Ju(this.context,e),this._net.enable(),this._net.addEventListener(Em.ReceiveVideo,this.onReceiveVideo.bind(this))}async share(e){e?.device&&(this.device=e.device),this._requestOpen=!0;try{if(this.videoPlayer){let t=e?.constraints??{echoCancellation:!0,autoGainControl:!1},i={video:t,audio:t};switch(this.device){case 1:this.tryShareUserCamera(i,e);break;case 0:if(!navigator.mediaDevices.getDisplayMedia){console.error("No getDisplayMedia support");return}let n=await navigator.mediaDevices.getDisplayMedia(i);this._requestOpen?this.setVideo(n,1):tc(n);break;case 2:let r=0,s=this.context.renderer.domElement.captureStream(r);this.setVideo(s,1);break}}}catch(t){if(t.name==="NotAllowedError"){console.log("Selection cancelled"),this._requestOpen=!1;return}console.error("Error opening video",t)}}close(){this._requestOpen=!1,this._currentStream&&(console.warn("Close current stream / disposing resources"),this._net?.stopSendingVideo(this._currentStream),tc(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,t){let i=(await navigator.mediaDevices.enumerateDevices()).filter(n=>n.kind==="videoinput");console.log("Request camera",i);for(let n of i)try{if(!this._requestOpen)break;if(n.kind!=="videoinput")continue;let r=n.deviceId;if(t?.deviceId!==void 0&&r!==t.deviceId)continue;e.video!==!1&&((typeof e.video>"u"||typeof e.video=="boolean")&&(e.video={}),e.video.deviceId=r);let s=await navigator.mediaDevices.getUserMedia(e);this._requestOpen?this.setVideo(s,1):tc(s),console.log("Selected camera",n);break}catch(r){console.warn(r)}}};_([y(Ce)],cr.prototype,"videoPlayer",2),_([y()],cr.prototype,"device",2);var Em=(i=>(i.Connected="peer-user-connected",i.ReceiveVideo="receive-video",i.Disconnected="peer-user-disconnected",i))(Em||{}),qu=class{type="receive-video";stream;target;constructor(e,t){this.stream=e,this.target=t}},Yu=class{guid;peerId;dontSave=!0;constructor(e,t){this.guid=e.id,this.peerId=t}};var Ku=class extends Zu{userId;direction;call;get stream(){return this._stream}_stream=null;_isDisposed=!1;close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),tc(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 qu(n,this);this.dispatchEvent(r)}})}},Zo=class extends Zu{static getOrCreate(e,t){if(Zo.instances.has(t))return Zo.instances.get(t);let i=new Zo(e,t);return Zo.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 xm.default(e)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){!this._peer||(this._peer.on("open",this.onPeerConnectFn),this._peer.on("call",this.onPeerReceiveCallFn))}unsubscribePeerEvents(){}onPeerConnect(e){wm&&console.log("Peer connected as",e),this.context.connection.send("peer-user-connected",new Yu(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,s=new Ku(n,e,t);return r.push(s),e.on("error",a=>{console.error("Call error",a)}),e.on("close",()=>{console.log("Call ended",e.metadata),e.close();let a=r.indexOf(s);a!==-1&&r.splice(a,1)}),t==="incoming"&&(s.addEventListener("receive-video",a=>{this.dispatchEvent(a)}),e.on("stream",()=>{let a=setInterval(()=>{s.isOpen||(clearInterval(a),s.close())},2e3)})),s}},ic=Zo;A(ic,"instances",new Map);var Ju=class extends Zu{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(s=>s.userId===n)){let s=this.peer.makeCall(this.peer.getPeerIdFromUserId(n),t);s&&(e=!0,i.push(s))}}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 F_,AdditiveBlending as B_}from"three";var dr=class extends k{mode=0;shadowColor=new Z(0,0,0,1);awake(){switch(this.mode){case 0:this.applyShadowMaterial();break;case 1:this.applyLightBlendMaterial();break}}applyLightBlendMaterial(){let e=R.getComponent(this.gameObject,ae);if(e){let t=e.material;t.blending=B_,this.applyMaterialOptions(t),t.onBeforeCompile=i=>{i.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
298
-
297
+ `}};var Sm=wa(el(),1);import{EventDispatcher as nh}from"three";var Pm=O("debugscreenshare");function sc(o){if(!!o)for(let e of o.getTracks())e.stop()}var ur=class extends M{onPointerClick(){if(this.context.connection.isInRoom!==!1){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(){Pm&&console.log(this),se.registerWaitForAllowAudio(()=>{this.videoPlayer&&this._currentStream&&this._currentMode===2&&this.videoPlayer.setVideo(this._currentStream)})}start(){if(this.videoPlayer||(this.videoPlayer=R.getComponent(this.gameObject,Ce)??void 0),!this.videoPlayer){console.error("Screencapture did not find a VideoPlayer component");return}let e=ac.getOrCreate(this.context,this.guid);this._net=new ih(this.context,e),this._net.enable(),this._net.addEventListener(Om.ReceiveVideo,this.onReceiveVideo.bind(this))}async share(e){e?.device&&(this.device=e.device),this._requestOpen=!0;try{if(this.videoPlayer){let t=e?.constraints??{echoCancellation:!0,autoGainControl:!1},i={video:t,audio:t};switch(this.device){case 1:this.tryShareUserCamera(i,e);break;case 0:if(!navigator.mediaDevices.getDisplayMedia){console.error("No getDisplayMedia support");return}let n=await navigator.mediaDevices.getDisplayMedia(i);this._requestOpen?this.setVideo(n,1):sc(n);break;case 2:let r=0,s=this.context.renderer.domElement.captureStream(r);this.setVideo(s,1);break}}}catch(t){if(t.name==="NotAllowedError"){console.log("Selection cancelled"),this._requestOpen=!1;return}console.error("Error opening video",t)}}close(){this._requestOpen=!1,this._currentStream&&(console.warn("Close current stream / disposing resources"),this._net?.stopSendingVideo(this._currentStream),sc(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,t){let i=(await navigator.mediaDevices.enumerateDevices()).filter(n=>n.kind==="videoinput");console.log("Request camera",i);for(let n of i)try{if(!this._requestOpen)break;if(n.kind!=="videoinput")continue;let r=n.deviceId;if(t?.deviceId!==void 0&&r!==t.deviceId)continue;e.video!==!1&&((typeof e.video>"u"||typeof e.video=="boolean")&&(e.video={}),e.video.deviceId=r);let s=await navigator.mediaDevices.getUserMedia(e);this._requestOpen?this.setVideo(s,1):sc(s),console.log("Selected camera",n);break}catch(r){console.warn(r)}}};y([_(Ce)],ur.prototype,"videoPlayer",2),y([_()],ur.prototype,"device",2);var Om=(i=>(i.Connected="peer-user-connected",i.ReceiveVideo="receive-video",i.Disconnected="peer-user-disconnected",i))(Om||{}),$u=class{type="receive-video";stream;target;constructor(e,t){this.stream=e,this.target=t}},eh=class{guid;peerId;dontSave=!0;constructor(e,t){this.guid=e.id,this.peerId=t}};var th=class extends nh{userId;direction;call;get stream(){return this._stream}_stream=null;_isDisposed=!1;close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),sc(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 $u(n,this);this.dispatchEvent(r)}})}},es=class extends nh{static getOrCreate(e,t){if(es.instances.has(t))return es.instances.get(t);let i=new es(e,t);return es.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 Sm.default(e)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){!this._peer||(this._peer.on("open",this.onPeerConnectFn),this._peer.on("call",this.onPeerReceiveCallFn))}unsubscribePeerEvents(){}onPeerConnect(e){Pm&&console.log("Peer connected as",e),this.context.connection.send("peer-user-connected",new eh(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,s=new th(n,e,t);return r.push(s),e.on("error",a=>{console.error("Call error",a)}),e.on("close",()=>{console.log("Call ended",e.metadata),e.close();let a=r.indexOf(s);a!==-1&&r.splice(a,1)}),t==="incoming"&&(s.addEventListener("receive-video",a=>{this.dispatchEvent(a)}),e.on("stream",()=>{let a=setInterval(()=>{s.isOpen||(clearInterval(a),s.close())},2e3)})),s}},ac=es;D(ac,"instances",new Map);var ih=class extends nh{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(s=>s.userId===n)){let s=this.peer.makeCall(this.peer.getPeerIdFromUserId(n),t);s&&(e=!0,i.push(s))}}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 q_,AdditiveBlending as Y_}from"three";var hr=class extends M{mode=0;shadowColor=new Z(0,0,0,1);awake(){switch(this.mode){case 0:this.applyShadowMaterial();break;case 1:this.applyLightBlendMaterial();break}}applyLightBlendMaterial(){let e=R.getComponent(this.gameObject,ae);if(e){let t=e.sharedMaterial;t.blending=Y_,this.applyMaterialOptions(t),t.onBeforeCompile=i=>{i.fragmentShader=i.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
299
298
  // diffuse-only lighting with overdrive to somewhat compensate
300
299
  // for the loss of indirect lighting and to make it more visible.
301
300
  vec3 direct = reflectedLight.directDiffuse * 3.;
@@ -305,13 +304,13 @@ a:hover {
305
304
  // be blended onto the scene.
306
305
  gl_FragColor = vec4(direct, max);
307
306
  return;
308
- `)}}}applyShadowMaterial(){let e=R.getComponent(this.gameObject,ae);if(e)if(e.material?.type!=="ShadowMaterial"){let t=new F_;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)}};_([y()],dr.prototype,"mode",2),_([y(Z)],dr.prototype,"shadowColor",2);import{RGBELoader as V_}from"three/examples/jsm/loaders/RGBELoader.js";import{EXRLoader as z_}from"three/examples/jsm/loaders/EXRLoader";import{EquirectangularRefractionMapping as W_,sRGBEncoding as N_,TextureLoader as Rm}from"three";var Cm=M("debugautosync"),$u=class{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];let t=new eh(e);return this._syncers[e.guid]=t,t}},Tm=new $u,eh=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)){Cm&&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 U_(o,e){let t=e!==o;if(!t&&o&&e){if(Array.isArray(o)&&Array.isArray(e))t=!0;else if(typeof o=="object"&&typeof e=="object"){for(let i of Object.keys(o))if(o[i]!==e[i]){t=!0;break}}}return t}function G_(o){if(o.__autoPropertySyncHandler)return o.__autoPropertySyncHandler;let e=Tm.getOrCreateSyncer(o);return e?.init(o),o.__autoPropertySyncHandler=e,e}var nc=function(o){return function(e,t){let i=null,n=o?e[o]:void 0,r=e,s=r.__internalAwake;Cm&&console.log(t);let a=t+"k__BackingField";r.__internalAwake=function(){if(this[a]!==void 0)return;this[a]=this[t],s.call(this),i=Tm.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,t)?.set===void 0&&Object.defineProperty(this,t,{set:function(d){let l=this[a];this[a]=d,U_(d,l)&&n?.call(this,d,l)!==!1&&G_(this)?.notifyChanged(t,d)},get:function(){return this[a]},configurable:!0,enumerable:!0}),i?.init(this)}}};var qi=class extends k{url;allowDrop=!0;background=!0;environment=!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"),r=e.endsWith(".hdr");n?this._loader=new z_:r?this._loader=new V_:this._loader=new Rm}let t=await this._loader.loadAsync(e);if(!t||!this.enabled)return;this.url=e,t.mapping=W_,this._loader instanceof Rm&&(t.encoding=N_),this._prevBackground=this.context.scene.background,this._prevEnvironment=this.context.scene.environment,console.log("Set skybox",this.url),this.environment&&(this.context.scene.environment=t),this.background&&(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))}};_([nc("setSkybox"),y()],qi.prototype,"url",2),_([y()],qi.prototype,"allowDrop",2),_([y()],qi.prototype,"background",2),_([y()],qi.prototype,"environment",2);import*as rc from"three";import{Object3D as X_}from"three";var th=class extends k{target=null;followFactor=.1;rotateFactor=.1;positionAxes=-1;flipForward=!1;_firstUpdate=!0;onBeforeRender(){this.updateNow(!1)}updateNow(e){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){let t=B(this.target),i=this._firstUpdate||e?1:H.clamp01(this.context.time.deltaTime*this.followFactor),n=this.worldPosition;this.positionAxes&2&&(n.x=H.lerp(n.x,t.x,i)),this.positionAxes&4&&(n.y=H.lerp(n.y,t.y,i)),this.positionAxes&8&&(n.z=H.lerp(n.z,t.z,i)),this.worldPosition=n}if(this.rotateFactor>0){let t=pe(this.target);this.flipForward&&t.premultiply(th._invertForward);let i=this._firstUpdate||e?1:H.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(t,i)}this._firstUpdate=!1}}},Et=th;A(Et,"_invertForward",new rc.Quaternion().setFromAxisAngle(new rc.Vector3(0,1,0),Math.PI)),_([y(X_)],Et.prototype,"target",2),_([y()],Et.prototype,"followFactor",2),_([y()],Et.prototype,"rotateFactor",2),_([y()],Et.prototype,"positionAxes",2);import{Layers as Om}from"three";var ra=M("debugspatialtrigger"),Sm=new Om,Pm=new Om;function Q_(o,e){return Sm.mask=o,Pm.mask=e,Sm.test(Pm)}var Ct=class extends k{triggerMask=0;onEnter;onStay;onExit;start(){ra&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(let e of Pn.triggers)Q_(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){ra&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),this.onEnter?.invoke(this,e)}onExitTrigger(e){ra&&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)}};_([y()],Ct.prototype,"triggerMask",2),_([y(be)],Ct.prototype,"onEnter",2),_([y(be)],Ct.prototype,"onStay",2),_([y(be)],Ct.prototype,"onExit",2);var oa=class extends k{triggerMask;boxHelper;start(){ra&&console.log(this.name,this.triggerMask,this)}onEnable(){oa.triggers.push(this),this.boxHelper||(this.boxHelper=R.addNewComponent(this.gameObject,Be),this.boxHelper?.showHelper(null,ra))}onDisable(){oa.triggers.splice(oa.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){R.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof Ct&&t.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){R.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof Ct&&t.onStayTrigger(this)},!1)}raiseOnExitEvent(e){R.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof Ct&&t.onExitTrigger(this)},!1)}},Pn=oa;A(Pn,"triggers",[]),_([y()],Pn.prototype,"triggerMask",2);import*as ur from"three";var Tt=M("debugspectator"),$o=class extends k{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}get localId(){return this.context.connection.connectionId??"local"}set target(e){if(this._handler){let t=this._handler.currentTarget?.userId,i=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&i?.currentObject===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),R.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,t)):this._handler.currentTarget!==e&&(this._handler.set(e),R.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.localId)?.currentObject}orbit=null;_handler;eventSub_WebXRRequestStartEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;_debug;_networking;awake(){if(this._debug=new nh(this.context,this),this._networking=new sh(this.context,this),this._networking.awake(),R.setActive(this.gameObject,!1),this.cam=R.getComponent(this.gameObject,se),!this.cam){console.error("Spectator camera needs camera component",this);return}!this._handler&&this.cam&&(this._handler=new ih(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),V.addEventListener("requestVRSession",this.eventSub_WebXRRequestStartEvent),V.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),V.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.orbit=R.getComponent(this.context.mainCamera,it)}onDestroy(){this.stopSpectating(),V.removeEventListener("requestVRSession",this.eventSub_WebXRStartEvent),V.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),V.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()||R.setActive(this.gameObject,!0)}onXRSessionStart(e){!this.isSupportedPlatform()||(Tt&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onXRSessionEnded(e){this.context.removeCamera(this.cam),R.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),this.target||(this.context.players.setPlayerView(this.localId,this.context.mainCamera,"headset"),this.target=this.context.players.getPlayerView(this.localId)),Tt&&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 ur.Color(1,1,1));e.setRenderTarget(null),e.xr.enabled=!1;let s=this.cam?.cam;this.context.updateAspect(s);let a=e.xr.isPresenting;e.xr.isPresenting=!1,e.setSize(this.context.domWidth,this.context.domHeight),e.render(this.context.scene,s),e.xr.isPresenting=a,e.xr.enabled=t,i?e.setRenderTarget(i):e.state.bindXRFramebuffer(n),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){let e=this._mode===0;for(let t of le.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 le.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)}}},ih=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=R.addNewComponent(this.cam.gameObject,Et)),this.target||(this.target=new ur.Object3D),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Tt&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Tt&&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&&R.destroy(this.follow)}update(e){if(this.currentTarget?.isConnected===!1||this.currentTarget?.removed===!0){Tt&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&this.currentTarget?.currentObject!==this.currentObject&&(Tt&&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(q_):i.quaternion.identity()}}},q_=new ur.Quaternion().setFromAxisAngle(new ur.Vector3(0,1,0),Math.PI),nh=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 me;e.setMask(16777215);let t=this.context.physics.raycast(e);if(Tt&&console.log(...t),t?.length)for(let i of t){if(i.distance<.2)continue;let n=i.object,r=R.getComponentInParent(n,le),s=r?.connectionId;if(s){let a=this.context.players.getPlayerView(s);this.spectator.target=a,Tt&&console.log("spectate",s,r);break}}}},rh=class{guid;dontSave=!0;targetUserId;stoppedFollowing;constructor(e,t,i){this.guid=e,this.targetUserId=t,this.stoppedFollowing=i}},oh=class{guid;userId;constructor(e,t){this.guid=e.guid,this.userId=t}},sh=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(Tt&&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 rh(this.context.connection.connectionId,n,i);this.context.connection.send("spectator-follower-changed",r)}}onRequestFollowMe(e=!1){if(Tt&&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 oh(this.spectator,t);this.context.connection.send("spectator-request-follow",i)}}onUserJoinedRoom(){M("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){let t=e.targetUserId,i=e.guid;if(Tt&&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 Tt&&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):(Tt&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}};import*as Rt from"three";import{Material as Y_,Texture as K_}from"three";var qr=class{texture;triangles;uv;vertices;_geometry};_([y(K_)],qr.prototype,"texture",2);var oc=class{static getOrCreateGeometry(e){if(e._geometry)return e._geometry;let t=new Rt.BufferGeometry;e._geometry=t;let i=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let r=0;r<e.triangles.length;r+=1){let s=e.triangles[r];i[r*3]=-e.vertices[s].x,i[r*3+1]=e.vertices[s].y,i[r*3+2]=0;let a=e.uv[s];n[r*2]=a.x,n[r*2+1]=1-a.y}return t.setAttribute("position",new Rt.BufferAttribute(i,3)),t.setAttribute("uv",new Rt.BufferAttribute(n,2)),t}},On=class extends k{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=oc.getOrCreateGeometry(this.sprite),this._currentSprite.material.map=this.sprite.texture;else{let e=new Rt.MeshBasicMaterial({color:16777215,side:Rt.DoubleSide});if(!e)return;if(this.color&&(e.color||(e.color=new Rt.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 Rt.Mesh(oc.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))}}};_([y()],On.prototype,"drawMode",2),_([y(Z)],On.prototype,"color",2),_([y(Y_)],On.prototype,"sharedMaterial",2);var St=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 St).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+4),(t||new St).__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 we).__init(this.bb_pos+t,this.bb):null}rot(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new we).__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 J_}from"three";var sc="SCAM";To(sc,St.getRootAsSyncedCameraModel);var Pt=new vt,ah=class{userId;guid;constructor(e,t){this.guid=t,this.userId=e}send(e,t){if(e){Pt.clear();let i=Pt.createString(this.guid),n=Pt.createString(this.userId);St.startSyncedCameraModel(Pt),St.addGuid(Pt,i),St.addUserId(Pt,n);let r=B(e),s=ka(e);St.addPos(Pt,we.createVec3(Pt,r.x,r.y,r.z)),St.addRot(Pt,we.createVec3(Pt,s.x,s.y,s.z));let a=St.endSyncedCameraModel(Pt);Pt.finish(a,sc),t.sendBinary(Pt.asUint8Array())}}},ac=class extends k{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(sc,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(sc,this._receiveCallback)}update(){for(let n in this.remoteCams){let r=this.remoteCams[n],s=this.context.time.realtimeSinceStartup-r.lastUpdate;if(!r||s>this._camTimeoutInSeconds){console.log("Remote cam timeout",r,s),r?.obj&&R.destroy(r.obj),delete this.remoteCams[n],r&&delete this.userToCamMap[r.userId],ac.instances.push(r),this.context.players.removePlayerView(r.userId,"browser");continue}}if(V.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 ah(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));let t=B(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 c=new Fe;c.context=this.context;let d=R.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,ac.instances.push(n);let l=R.getOrAddComponent(d,le);l.connectionId=i,l.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 s=e.pos();s&&sn(r,s.x(),s.y(),s.z());let a=e.rot();a&&Ma(r,a.x(),a.y(),a.z())}},hr=ac;A(hr,"instances",[]),_([y([J_,Ze])],hr.prototype,"cameraPrefab",2);var lh="view",lc=M("debugsyncedroom"),Ci=class extends k{roomName;urlParameterName="room";joinRandomRoom=!0;requireRoomParameter=!1;autoRejoin=!0;_roomPrefix;awake(){lc&&console.log("Room",this.roomName,this.urlParameterName,this.joinRandomRoom,this.requireRoomParameter,this.autoRejoin),this._roomPrefix===void 0&&(this._roomPrefix=this.roomName,this.roomName="")}onEnable(){let e=M(lh);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=M(this.urlParameterName);if(i&&typeof i=="string"){t=!0;let n=Uh(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?(lc&&console.log('No required room parameter "'+this.urlParameterName+'" in url - will not connect to networking backend.'),!1):!this.roomName||this.roomName.length<=0?(lc&&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(),lc&&console.log("Join "+this.roomName),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=M(lh);return e||M(this.urlParameterName)}setRandomRoomUrlParameter(){let e=kc(),t=this.generateRoomName();M(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),Hh(t,e)}generateRoomName(){return Bh()+"_"+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(lh,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}};_([y()],Ci.prototype,"roomName",2),_([y()],Ci.prototype,"urlParameterName",2),_([y()],Ci.prototype,"joinRandomRoom",2),_([y()],Ci.prototype,"requireRoomParameter",2),_([y()],Ci.prototype,"autoRejoin",2);function km(){let o=M("testwindowcount")||0;o&&o>0&&Z_(o)}function Z_(o){if(M("testwindow"))return null;let e=new URL(window.location.href);co(e.searchParams,Fo,1),co(e.searchParams,"testwindow",1);let t=e.toString(),i=[];window.onbeforeunload=()=>{for(let c of i)c.close()};let n=.05,r=128,s=0,a=0;for(let c=0;c<o;c++){s*r+r*.01>=window.innerWidth&&(a+=1,s=0);let d=s*(r*(1+n))+window.screenLeft,l=a*(r*(1+n))+window.screenTop+90+60*a;s+=1;let u=window.open(t,"test window "+c,`popup=yes width=${r} height=${r} top=${l} 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 b=i[h];b!==u&&b.close()}i.length=0}}}return i}import{Vector3 as ex}from"three";var es=class extends k{awake(){km()}},ts=class extends k{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinrary(Lo,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new cc(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 vt(1024));let e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();let i=su(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)}}}},cc=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}}};A(cc,"temp",new ex);import{MathUtils as tx}from"three";import{TransformControls as ix}from"three/examples/jsm/controls/TransformControls";import{OrbitControls as nx}from"three/examples/jsm/controls/OrbitControls";var Yr=class extends k{isGizmo=!0;control;orbit;awake(){this.isGizmo&&!Pi||!this.context.mainCamera||(this.control=new ix(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=R.getComponentInParent(this.context.mainCamera,nx)??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=R.getComponentInParent(this.gameObject,_t);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(tx.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))}};_([y()],Yr.prototype,"isGizmo",2);import{LinearToneMapping as ch,ACESFilmicToneMapping as rx,ReinhardToneMapping as ox}from"three";var dc=M("debugvolume"),Im=(i=>(i[i.None=0]="None",i[i.Neutral=1]="Neutral",i[i.ACES=2]="ACES",i))(Im||{}),is=class{overrideState=!1;value=0},Yi=class{active=!1;parameters},fr=class extends Yi{mode;get isToneMapping(){return!0}},mr=class extends Yi{postExposure};function sx(o){return"mode"in o?fr:"postExposure"in o?mr:Yi}var Mm=Symbol("volumeprofile"),pr=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[Mm]!==void 0;if(t){if(!r)return}else i[Mm]=this;for(let s of this.components)if(s instanceof fr){let a=s;if(!s.active||t){e.renderer.toneMapping=ch;continue}dc&&console.log("VOLUME:",Im[a.mode?.value??0]);let c=a.mode;switch((c?.overrideState?c?.value:0)??0){case 0:e.renderer.toneMapping=ch;break;case 1:e.renderer.toneMapping=ox;break;case 2:e.renderer.toneMapping=rx;break}}else if(s instanceof mr){let a=s;dc&&console.log(a.postExposure);let c=Math.pow(2,a.postExposure?.value??0),d=a.postExposure?.overrideState&&!t;e.renderer.toneMappingExposure=d?c:1,e.renderer.toneMapping||(e.renderer.toneMapping=ch)}}};_([y([o=>sx(o),Yi])],pr.prototype,"components",2);var Kr=class extends k{sharedProfile;awake(){dc&&(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(){dc&&console.log("APPLY VOLUME",this),this.sharedProfile?.apply(this.context)}onDisable(){this.sharedProfile?.unapply(this.context)}};_([y(pr)],Kr.prototype,"sharedProfile",2);import{Vector3 as ax}from"three";var Jr=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}},ns=class extends k{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=ht.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),ht.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=R.instantiate(this.prefab);if(i.visible=!0,this._instances[e.guid]={instance:i,model:e},e.userId){let n=R.getComponentsInChildren(i,ft);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]&&(R.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<ht.Current.length;e++){let t=ht.Current[e];if(!t.controller||!t.selected)continue;this._grabModels.length<=e&&(this._grabModels.push(new Jr),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 ax;updateRendering(){let e=this.context.time.deltaTime/.5;for(let t in this._instances){let{instance:i,model:n}=this._instances[t];if(!i||!n)continue;let{point:r}=n,s=B(i);this.temp.set(r.x,r.y,r.z),s.lerp(this.temp,e),te(i,s)}}};import{Object3D as lx}from"three";var Ki=class extends k{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=R.getComponentInParent(this.gameObject,Ee)}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)}}};_([y(lx)],Ki.prototype,"eyes",2),_([y()],Ki.prototype,"lastBlinkTime",2),_([y()],Ki.prototype,"blinkLength",2),_([y()],Ki.prototype,"eyesOpen",2);import*as uc from"three";import{Object3D as dh}from"three";var uh=class extends k{head=null;eyes=null;target=null;brain=null;awake(){this.brain||(this.brain=R.getComponentInParent(this.gameObject,bn)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=R.addNewComponent(this.gameObject,bn)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new uc.Vector3;currentTargetPoint=new uc.Vector3;update(){let e=this.target;if(e&&this.head){let t=this.eyes;if(t){let i=B(e);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);let n=B(this.head),r=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(r.length()<.1)return;let s=uh.forward;if(s.set(0,0,1),s.applyQuaternion(pe(this.head)),s.dot(r)>.45)for(let c=0;c<t.length;c++)t[c].lookAt(this.currentTargetPoint)}}}},Ji=uh;A(Ji,"forward",new uc.Vector3(0,0,1)),_([y(dh)],Ji.prototype,"head",2),_([y(dh)],Ji.prototype,"eyes",2),_([y(dh)],Ji.prototype,"target",2);import{Object3D as Am}from"three";var cx=M("debugmouth"),gr=class extends k{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){setTimeout(()=>{this.voip=R.findObjectOfType(tt,this.context),this.marker||(this.marker=R.getComponentInParent(this.gameObject,le))},3e3)}update(){if(!this.voip||this.context.time.frameCount%10!==0)return;let e=this.marker?.connectionId??null;if(!e){cx&&(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)}}}};_([y(Am)],gr.prototype,"idle",2),_([y(Am)],gr.prototype,"talking",2);var rs=class extends k{voip=null;marker=null;_startPosition=null;awake(){this.voip=R.findObjectOfType(tt,this.context),this.marker=R.getComponentInParent(this.gameObject,le)}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 bh={};Dh(bh,{AlignmentConstraint:()=>qn,Animation:()=>Lt,AnimationCurve:()=>hi,AnimationTrackHandler:()=>br,Animator:()=>et,AnimatorController:()=>ui,AttachedObject:()=>ht,AudioListener:()=>pi,AudioSource:()=>oe,AudioTrackHandler:()=>vr,AvatarBlink_Simple:()=>Ki,AvatarEyeLook_Rotation:()=>Ji,AvatarLoader:()=>Yn,AvatarMarker:()=>le,AvatarModel:()=>Hr,Avatar_Brain_LookAt:()=>bn,Avatar_MouthShapes:()=>gr,Avatar_MustacheShake:()=>rs,Avatar_POI:()=>ve,AxesHelper:()=>mn,BaseUIComponent:()=>Ue,BasicIKConstraint:()=>Mo,BoxCollider:()=>Zn,BoxGizmo:()=>wn,BoxHelperComponent:()=>Be,Button:()=>Zt,CallInfo:()=>fi,Camera:()=>se,Canvas:()=>ze,CanvasGroup:()=>jn,CapsuleCollider:()=>Bt,CharacterController:()=>ji,CharacterControllerInput:()=>mi,Collider:()=>Ut,ColorAdjustments:()=>mr,ColorBySpeedModule:()=>wi,ColorOverLifetimeModule:()=>Tn,ControlTrackHandler:()=>Mn,Deletable:()=>Ao,DeleteBox:()=>Vr,DeviceFlag:()=>zr,DragControls:()=>Gi,DropListener:()=>nr,Duplicatable:()=>Vi,EmissionModule:()=>pt,EventList:()=>be,EventListEvent:()=>Br,EventSystem:()=>Xe,EventTrigger:()=>Vo,FieldWithDefault:()=>Ko,FixedJoint:()=>Wo,FlyControls:()=>zo,GltfExport:()=>Jt,GltfExportBox:()=>ss,Gradient:()=>Ei,Graphic:()=>Ot,GraphicRaycaster:()=>gs,GridHelper:()=>En,GridLayoutGroup:()=>ms,GroundProjectedEnv:()=>Cn,HingeJoint:()=>rr,HorizontalLayoutGroup:()=>fs,Image:()=>Ln,InheritVelocityModule:()=>Yt,InputField:()=>kt,Interactable:()=>Gt,Keyboard:()=>hs,LODGroup:()=>or,LODModel:()=>zi,LayoutGroup:()=>Hn,Light:()=>Ge,LimitVelocityOverLifetimeModule:()=>de,LogStats:()=>os,LookAtConstraint:()=>vn,MainModule:()=>ye,MaskableGraphic:()=>Dn,MeshCollider:()=>Ur,MeshRenderer:()=>Qr,MinMaxCurve:()=>U,MinMaxGradient:()=>Oe,NestedGltf:()=>Nr,Networking:()=>xi,NoiseModule:()=>Y,ObjectRaycaster:()=>ro,OffsetConstraint:()=>Wi,OrbitControls:()=>it,ParticleBurst:()=>Rn,ParticleSubEmitter:()=>sr,ParticleSystem:()=>ge,ParticleSystemRenderer:()=>Ni,PlayableDirector:()=>An,PlayerColor:()=>ft,PointerEventData:()=>bi,RGBAColor:()=>Z,RawImage:()=>to,Raycaster:()=>no,Rect:()=>eo,RectTransform:()=>mt,ReflectionProbe:()=>Kt,RemoteSkybox:()=>qi,Renderer:()=>ae,RendererLightmap:()=>Sn,Rigidbody:()=>K,RotationBySpeedModule:()=>Ve,RotationOverLifetimeModule:()=>Qe,ScreenCapture:()=>cr,ShadowCatcher:()=>dr,ShapeModule:()=>ie,SignalAsset:()=>Zr,SignalReceiver:()=>kn,SignalReceiverEvent:()=>$r,SignalTrackHandler:()=>In,Size:()=>ds,SizeBySpeedModule:()=>Pe,SizeOverLifetimeModule:()=>qt,SkinnedMeshRenderer:()=>Jo,SmoothFollow:()=>Et,SpatialHtml:()=>bs,SpatialTrigger:()=>Pn,SpatialTriggerReceiver:()=>Ct,SpectatorCamera:()=>$o,SphereCollider:()=>Jn,Sprite:()=>qr,SpriteRenderer:()=>On,SubEmitterSystem:()=>ar,SyncedCamera:()=>hr,SyncedRoom:()=>Ci,SyncedTransform:()=>_t,TeleportTarget:()=>Wr,TestRunner:()=>es,TestSimulateUserData:()=>ts,Text:()=>ke,TextureSheetAnimationModule:()=>_e,ToneMapping:()=>fr,TrailModule:()=>ee,TransformGizmo:()=>Yr,UIRaycastUtils:()=>yi,UIRootComponent:()=>yn,UsageMarker:()=>Vt,VRUserState:()=>Xt,VelocityOverLifetimeModule:()=>je,VerticalLayoutGroup:()=>ps,VideoPlayer:()=>Ce,Voip:()=>tt,Volume:()=>Kr,VolumeComponent:()=>Yi,VolumeParameter:()=>is,VolumeProfile:()=>pr,WebAR:()=>ir,WebARSessionRoot:()=>Wt,WebXR:()=>V,WebXRAvatar:()=>Nt,WebXRController:()=>J,WebXRSync:()=>_n,XRFlag:()=>Ee,XRGrabModel:()=>Jr,XRGrabRendering:()=>ns,XRRig:()=>tr,XRState:()=>xt,__Ignore:()=>da});var dx=M("logstats"),os=class extends k{onEnable(){console.log(this),dx&&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{GLTFExporter as px}from"three/examples/jsm/exporters/GLTFExporter.js";import{BufferAttribute as hh,Matrix4 as ux,Vector3 as Dm,Quaternion as hx}from"three";var sa=class{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;let i=this.writer,n=i.extensionsUsed,r={};t.extensions=t.extensions||{},t.extensions[this.name]=r;let s=new ux,a=new Array,c=new Array,d=new Array;for(let b=0;b<e.count;b++){e.getMatrixAt(b,s);let w=new Dm,v=new hx,x=new Dm;s.decompose(w,v,x),a.push(w.x,w.y,w.z),c.push(v.x,v.y,v.z,v.w),d.push(x.x,x.y,x.z)}let l=new Float32Array(a),u=new Float32Array(c),h=new Float32Array(d);r.attributes={TRANSLATION:i.processAccessor(new hh(l,3)),ROTATION:i.processAccessor(new hh(u,4)),SCALE:i.processAccessor(new hh(h,3))},n[this.name]=!0}};import{Object3D as fx,Vector3 as mx}from"three";var ss=class extends Be{sceneRoot;start(){this.startCoroutine(this.updateGltfBox())}*updateGltfBox(){for(;;)for(let e=0;e<10;e++)yield}},Jt=class extends k{binary=!0;objects=[];exporter;ext;async exportNow(e){console.log("DO EXPORT",this.objects);let t={binary:this.binary,pivot:Jt.calculateCenter(this.objects)},i=await this.export(this.objects,t);this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?Jt.saveArrayBuffer(i,e):Jt.saveJson(i,e)}async export(e,t){if(e===null||e.length<=0){console.log("no objects set to export");return}this.exporter||(this.exporter=new px,this.exporter.register(a=>new sa(a)),this.ext=new Oo,this.ext.registerExport(this.exporter)),Jt.filterTopmostParent(e);let i={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:t?.binary??!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:Jt.collectAnimations(e)},n=new fx;t?.pivot&&n.position.sub(t.pivot),console.log("EXPORT",e),e.forEach(a=>{a&&(n.children.push(a),a.matrixAutoUpdate=!1,a.matrix.copy(a.matrixWorld),R.getComponentsInChildren(a,ae).forEach(c=>{R.isActiveInHierarchy(c.gameObject)&&c.setInstancingEnabled(!1)}))});let r=new ho(n);return this.ext.context=r,new Promise((a,c)=>{try{this.exporter?.parse(n,d=>{s(),a(d)},d=>{s(),c(d)},i)}catch(d){console.error(d),c(d)}finally{console.log("FINALLY")}});function s(){e.forEach(a=>{!a||(a.matrixAutoUpdate=!0,R.getComponentsInChildren(a,ae).forEach(c=>{R.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 mx;return i.set(0,0,0),e.forEach(n=>{i.add(B(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*as Hm from"three";var Zr=class{guid},$r=class{signal;reaction;$serializedTypes={signal:Zr,reaction:be}},kn=class extends k{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)}}};_([y($r)],kn.prototype,"events",2);import*as $ from"three";import{Quaternion as gx,Vector3 as bx}from"three";var as=M("debugtimeline"),ls=class{director;track;get muted(){return this.track.muted}set muted(e){e!==this.track.muted&&(this.track.muted=e,this.onMuteChanged?.call(this))}*forEachClip(e=!1){if(!!this.track?.clips)if(e)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(let t of this.track.clips)yield t}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,i,n=!0){if(t<0||t>=i.length)return 0;let r=i[t];if(n||e>=r.start&&e<=r.end){let s=1,a=!1;if(r.easeInDuration>0){let c=Math.min((e-r.start)/r.easeInDuration,1);s*=c}if(r.easeOutDuration>0&&!a){let c=Math.min((r.end-e)/r.easeOutDuration,1);s*=c}return s}return 0}},ph=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";as&&console.log(t.name,t.tracks,n);for(let s of t.tracks)if(!(s.times.length<=0)){if(s.name.endsWith(n))this.rootStartPosition=new $.Vector3().fromArray(s.values,0),this.rootEndPosition=new $.Vector3().fromArray(s.values,s.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),as&&console.log(this.rootPositionOffset);else if(s.name.endsWith(r)&&(this.rootStartQuaternion=new $.Quaternion().fromArray(s.values,0),this.rootEndQuaternion=new $.Quaternion().fromArray(s.values,s.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),as)){let a=new $.Euler().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",a)}}}},br=class extends ls{models=[];trackOffset;target;mixer;clips=[];actions=[];_actionOffsets=[];_didBind=!1;createHooks(e,t){if(t.tracks?.length<=0){console.warn("No tracks in AnimationClip",t);return}let i=t.tracks[0].name.split("."),n=i[i.length-2],r=n+".position",s=n+".quaternion",a=!1,c=!1;for(let d of t.tracks)d.name.endsWith(r)?(a=!0,this.createPositionInterpolant(t,e,d)):d.name.endsWith(s)&&(c=!0,this.createRotationInterpolant(t,e,d));if(!a||!c){let d=this.mixer?.getRoot(),l=t.tracks[0],u=l.name.lastIndexOf("."),h=l.name.substring(0,u),b=h.substring(h.lastIndexOf(".")+1),w=d.getObjectByName(b);if(w)if(a){if(!c){let v=t.tracks[0].name.substring(0,u)+".quaternion";as&&console.warn("Create quaternion track",b,w);let x=w.quaternion,m=new $.QuaternionKeyframeTrack(v,[0,t.duration],[x.x,x.y,x.z,x.w,x.x,x.y,x.z,x.w]);t.tracks.push(m),this.createRotationInterpolant(t,e,m)}}else{let v=h+".position";as&&console.warn("Create position track",b,w);let x=w.position,m=new $.VectorKeyframeTrack(v,[0,t.duration],[x.x,x.y,x.z,x.x,x.y,x.z]);t.tracks.push(m),this.createPositionInterpolant(t,e,m)}}}bind(){if(!this._didBind){this._didBind=!0,as&&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 ph(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 bx(i.x,i.y,i.z)),n.isQuaternion||(t.rotation=new gx(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 $.Vector3(e.x,e.y,e.z)));let t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new $.Quaternion(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new $.Vector3;_totalOffsetRotation=new $.Quaternion;_totalOffsetPosition2=new $.Vector3;_totalOffsetRotation2=new $.Quaternion;_summedPos=new $.Vector3;_tempPos=new $.Vector3;_summedRot=new $.Quaternion;_tempRot=new $.Quaternion;evaluate(e){if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let t=0,i=0,n=!1;for(let r=0;r<this.clips.length;r++){let s=this.models[r],a=this.actions[r],c=s.asset;a.weight=0;let d=e>=s.start&&e<=s.end,l=s.postExtrapolationMode,u=d;if(!u&&!n&&s.end<e&&s.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 b=this.getClipTime(e,s),w=0,v=c.duration;if(d){if(c.loop)for(w+=Math.floor(b/(v+1e-6));b>v;)b-=v}else if(!d)switch(l){case 2:b%=v;break;case 3:let f=Math.floor(b/v)%2!==0;b%=v,f&&(b=v-b);break}a.time=b,a.timeScale=0;let x=h*this.director.weight;if(a.weight=x,a.clampWhenFinished=!0,a.isRunning()||a.play(),this._useclipOffsets){let m=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,f=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-h),t+=1;let p=this._summedPos.set(0,0,0),g=this._tempPos.set(0,0,0),E=this._summedRot.identity(),C=this._tempRot.identity(),T=c.rotation,S=new $.Quaternion;S.slerp(T,h);let I=this._actionOffsets[r];if(I.hasOffsets)for(let D=0;D<w;D++)I.rootPositionOffset?g.copy(I.rootPositionOffset):g.set(0,0,0),g.applyQuaternion(E).applyQuaternion(S),I.rootQuaternionOffset&&(C.copy(I.rootQuaternionOffset),E.multiply(C)),p.add(g);f.multiply(S),f.multiply(E),p.add(c.position),m.add(p)}}}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 $.Quaternion;this.ensureTrackOffsets();let s=this.trackOffset?.rotation;i.createInterpolant=()=>{let a=n(),c=a.evaluate.bind(a);return a.evaluate=d=>{let l=c(d);return r.set(l[0],l[1],l[2],l[3]),r.premultiply(this._totalOffsetRotation),s&&r.premultiply(s),l[0]=r.x,l[1]=r.y,l[2]=r.z,l[3]=r.w,l},a}}createPositionInterpolant(e,t,i){let n=i.createInterpolant.bind(i),r=new $.Vector3;this.ensureTrackOffsets();let s=this.trackOffset?.rotation,a=this.trackOffset?.position,c;i.createInterpolant=()=>{let d=n(),l=d.evaluate.bind(d);return d.evaluate=u=>{let h=l(u);return r.set(h[0],h[1],h[2]),t.removeStartOffset&&(c===void 0?(c=null,c=this._actionOffsets.find(b=>b.clip===e)?.rootStartPosition?.clone()):c?.isVector3&&r.sub(c)),r.applyQuaternion(this._totalOffsetRotation),r.add(this._totalOffsetPosition),s&&r.applyQuaternion(s),a&&(r.x-=a.x,r.y+=a.y,r.z+=a.z),h[0]=r.x,h[1]=r.y,h[2]=r.z,h},d}}},vr=class extends ls{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;getAudioFilePath(e){let t=this.director.sourceId;return Ri(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 $.Audio(this.listener);i.setVolume(e.asset.volume);let n=new $.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;if(i.easeInDuration>0){let s=Math.min((e-i.start)/i.easeInDuration,1);r*=s}if(i.easeOutDuration>0){let s=Math.min((i.end-e)/i.easeOutDuration,1);r*=s}n.setVolume(r*this.director.weight)}else n.isPlaying&&n.stop()}this.lastTime=e}}},In=class extends ls{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 a of this.receivers)!a||a.invoke(i.asset)}}else i.emitOnce||(this.didTrigger[t]=!1)}}},aa=class extends ls{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;aa.resolved[r]?n.sourceObject=aa.resolved[r]:(n.sourceObject=R.findByGuid(r,e.scene),aa.resolved[r]=n.sourceObject)}if(n.sourceObject){let r=R.getComponent(n.sourceObject,An);this.timelines.push(r),r&&n.updateDirector&&(r.playOnAwake=!1)}else{this.models.splice(t,1);continue}}}_previousActiveModel=null;evaluate(e){this._previousActiveModel=null;for(let t=0;t<this.models.length;t++){let i=this.models[t],n=i.asset;if(e>=i.start&&e<=i.end){this._previousActiveModel=i;let r=this.getClipTime(e,i);if(n.controlActivation){let s=n.sourceObject;s.visible=!0}if(n.updateDirector){let s=this.timelines[t];s&&(s.isPlaying&&s.pause(),s.time=r,s.evaluate())}}else{let r=this._previousActiveModel?.asset;if(n.controlActivation){let s=n.sourceObject;r?.sourceObject!==s&&(s.visible=!1)}}}}},Mn=aa;A(Mn,"resolved",{});var jm=M("debugtimeline");var hc=class extends k{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(){jm&&console.log(this,this.playableAsset?.tracks),this.rebuildGraph(),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.activeAndEnabled;)!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 a of t.clips)a.start<=e&&e<=a.end&&(r=!0);let s=n;s.visible!==void 0&&(s.visible=r)}}break}for(let t of this._animationTracks)t.evaluate(e);for(let t of this._audioTracks)t.evaluate(e);for(let t of this._signalTracks)t.evaluate(e);for(let t of this._controlTracks)t.evaluate(e);for(let t of this._customTracks)t.evaluate(e)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Cs(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=R.findByGuid(n,e);r===null||typeof r!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(jm&&console.log("Resolved binding",n,"to",r),t.outputs[i]=r)}else if(n===null){if(t.outputs.splice(i,1),hc.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=hc.createTrackFunctions[i];if(n!=null){let r=n(this,t);if(typeof r.evaluate=="function"){r.director=this,r.track=t,this._customTracks.push(r);continue}}if(t.type==="AnimationTrack"){if(t.clips.length<=0)continue;for(let r=t.outputs.length-1;r>=0;r--){let s=t.outputs[r];typeof s.enabled=="boolean"&&(s.enabled=!1);let a=s?.gameObject?.animations;if(a){let c=new br;c.trackOffset=t.trackOffset,c.director=this,c.track=t;for(let d=0;d<t.clips.length;d++){let l=t.clips[d],u=l.asset;if(!u){console.error("MISSING anim model?","clip#"+d,l,t,this.playableAsset,this.name);continue}let h=u.clip,b=h;if((typeof b=="string"||typeof b=="number")&&(b=a.find(v=>v.name===h)),!b){console.warn("Could not find animationClip for model",l,t.name,this.name,this.playableAsset?.name);continue}c.mixer||(c.mixer=new Hm.AnimationMixer(s.gameObject)),c.clips.push(b),c.mixer.uncacheAction(b),c.createHooks(l.asset,b);let w=c.mixer.clipAction(b);c.actions.push(w),c.models.push(l)}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 In;r.director=this,r.track=t;for(let s of t.markers)switch(s.type){case"SignalEmitter":r.models.push(s),r.didTrigger.push(!1);break}if(r!==null&&r.models.length>0){let s=R.getComponent(this.gameObject,kn);s&&(r.receivers.push(s),this._signalTracks.push(r))}}else if(t.type==="SignalTrack"){let r=new In;r.director=this,r.track=t;for(let s of t.markers)r.models.push(s),r.didTrigger.push(!1);for(let s of t.outputs)r.receivers.push(s);this._signalTracks.push(r)}else if(t.type==="ControlTrack"){let r=new Mn;r.director=this,r.track=t;for(let s of t.clips)r.models.push(s);r.resolveSourceObjects(this.context),this._controlTracks.push(r)}}oe.registerWaitForAllowAudio(()=>{let t=R.findObjectOfType(pi,this.context);if(!!t)for(let i of e){let n=new vr;n.director=this,n.track=i,n.listener=t.listener;for(let r=0;r<i.clips.length;r++){let s=i.clips[r];n.addModel(s)}this._audioTracks.push(n)}})}setAudioTracksAllowPlaying(e){for(let t of this._audioTracks)t.onAllowAudioChanged(e)}},An=hc;A(An,"createTrackFunctions",{});import{Color as xx,Texture as zm}from"three";import*as mh from"three-mesh-ui";import{Matrix4 as yx,Object3D as _x,Vector2 as Gm,Vector3 as fh}from"three";import{FrontSide as Fm,DoubleSide as Bm}from"three";function cs(o,e){if(!o)return;let t=o.material;t?.isMaterial===!0&&(t.depthTest=!e.renderOnTop,t.side=e.doubleSided??!0?Bm:Fm,t.depthWrite=e.depthWrite??!1,t.shadowSide=e.doubleSided?Bm:Fm,o.castShadow=e.castShadows?e.castShadows:!1,o.receiveShadow=e.receiveShadows?e.receiveShadows:!1);for(let i of o.children)cs(i,e)}function pc(o,e,t){o[e]===void 0&&console.warn("Field",e,"is undefined on",o);let i=Proxy.revocable(o[e],{set(s,a,c,d){let l=s[a],u=Reflect.set(s,a,c,d);return t(c,l),u}}),n=i.revoke,r=o[e];return i.revoke=()=>{o[e]=r,n()},o[e]=i.proxy,i}function Um(o,e,t=3){let i=o.__scheduledActions;i||(i=o.__scheduledActions={});let n=e.name;i[t]||(i[t]={});let r=i[t];if(r[n])return;function*a(){e?.call(o),r[n]=null}let c=o.startCoroutine(a(),t);r[n]=c}var Vm=M("debugui"),ds=class{width;height},eo=class{x;y;width;height},mt=class extends Ue{offset=.01;get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}_anchoredPosition;get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new fh),this._anchoredPosition}rect;sizeDelta;anchoredPosition3D;pivot;lastMatrix;rectBlock;_transformNeedsUpdate=!1;awake(){super.awake(),this.lastMatrix=new yx,this.rectBlock=new _x,this.rectBlock.position.z=.1,this.rectBlock.name=this.name,this._anchoredPosition||(this._anchoredPosition=new fh),pc(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)&&(Vm&&console.log("updating",this.name),this.applyTransform()),Xe.ensureUpdateMeshUI(mh,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},Vm&&console.log(this.name,e);let t=new mh.Block(e);return this._createdBlocks.push(t),t}};_([y(eo)],mt.prototype,"rect",2),_([y(Gm)],mt.prototype,"sizeDelta",2),_([y(fh)],mt.prototype,"anchoredPosition3D",2),_([y(Gm)],mt.prototype,"pivot",2);var Ot=class extends Ue{get isGraphic(){return!0}get color(){return this._color||(this._color=new Z(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 Z(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=R.getComponent(this.gameObject,mt)),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(),pc(this,"_color",()=>Um(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)}};_([y(Z)],Ot.prototype,"color",1),_([y()],Ot.prototype,"raycastTarget",2);var Dn=class extends Ot{onAfterCreated(){this.uiObject&&(this.uiObject.scale.y*=-1)}};var fc=class{texture;rect};_([y(zm)],fc.prototype,"texture",2);var Ln=class extends Dn{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 xx(.4,.4,.4),e.borderOpacity=this.color.alpha,e.borderWidth=.3)}onAfterCreated(){super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture)}};_([y(fc)],Ln.prototype,"sprite",2);var to=class extends Dn{mainTexture;onAfterCreated(){super.onAfterCreated(),this.setTexture(this.mainTexture)}};_([y(zm)],to.prototype,"mainTexture",2);var us=M("debugbutton");var Zt=class extends k{onClick;_isHovered=!1;onPointerEnter(e){us&&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"),this.context.input.setCursorPointer()}onPointerExit(){us&&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"),this.context.input.setCursorNormal()}onPointerDown(e){us&&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){us&&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){us&&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(),us&&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=R.getComponent(this.gameObject,Ln),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){e.setInteractable(this.interactable);let t=this.getFinalColor(e.color,this.colors?.normalColor),i={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(i);let n=this.getFinalColor(e.color,this.colors?.highlightedColor),r={state:"hovered",attributes:{backgroundColor:n,backgroundOpacity:n.alpha}};e.setupState(r);let s=this.getFinalColor(e.color,this.colors?.pressedColor),a={state:"pressed",attributes:{backgroundColor:s,backgroundOpacity:s.alpha}};e.setupState(a);let c=this.getFinalColor(e.color,this.colors?.selectedColor),d={state:"selected",attributes:{backgroundColor:c,backgroundOpacity:c.alpha}};e.setupState(d);let l=this.getFinalColor(e.color,this.colors?.disabledColor),u={state:"disabled",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(u)}getFinalColor(e,t){return t?e.clone().multiply(t):e.clone()}};_([y(be)],Zt.prototype,"onClick",2),_([y()],Zt.prototype,"colors",2),_([y()],Zt.prototype,"transition",2),_([y()],Zt.prototype,"animationTriggers",2),_([y(et)],Zt.prototype,"animator",2),_([y()],Zt.prototype,"interactable",1);var gh=class extends yn{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 gh||(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(),cs(this.shadowComponent,this);for(let e of R.getComponentsInChildren(this.gameObject,Ue))cs(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(H.toRadians(e.fieldOfView)*n)*(e.aspect*1.333333),s=r*(this.context.domHeight/this.context.domWidth);t.scale.x=-r,t.scale.y=s;break;case 2:break}}},ze=gh;_([y()],ze.prototype,"renderOnTop",1),_([y()],ze.prototype,"depthWrite",1),_([y()],ze.prototype,"doubleSided",1),_([y()],ze.prototype,"castShadows",1),_([y()],ze.prototype,"receiveShadows",1),_([y()],ze.prototype,"renderMode",1),_([y(ze)],ze.prototype,"rootCanvas",1),_([y()],ze.prototype,"scaleFactor",1);var jn=class extends k{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 R.getComponentsInChildren(this.gameObject,Ot,this._buffer)){let t=e.color;t.alpha=this._alpha,e.color=t}}};_([y()],jn.prototype,"alpha",1),_([y()],jn.prototype,"interactable",2),_([y()],jn.prototype,"blocksRaycasts",2);import*as Wm from"three-mesh-ui";import{Color as L}from"three";var wx=M("debugtext");var ke=class extends Ot{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){wx&&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 s=e.createNewBlock(r);return i&&(Array.isArray(i)?s.add(...i):s.add(i)),s}getAlignment(e,t=!1){switch(t||(e.contentDirection="row"),this.alignment){default:case 0:case 1:case 2:e.justifyContent="start";break;case 3:case 4:case 5:e.justifyContent="center";break;case 6:case 7:case 8:e.justifyContent="end";break}switch(this.alignment){case 0:case 3:case 6:e.alignContent=t?"left":"top";break;case 1:case 4:case 7:e.alignContent="center";break;case 2:case 5:case 8:e.alignContent=t?"right":"bottom";break}return e}updateWidth(){this.horizontalOverflow===1&&setTimeout(()=>{if(!this._textMeshUi)return;let e=this._textMeshUi[0].parent;if(!!e&&e.lines){let t=e.lines.reduce((i,n)=>i+n.width,0);t+=e.getFontSize()*5,t+=e.padding*2||0,t+=this.fontSize*1.5,e.set({width:t}),this.ensureShadowComponentOwner()}},1)}ensureShadowComponentOwner(){this.shadowComponent&&this.shadowComponent.traverse(e=>{e[wt]===void 0&&(e[wt]=this)})}createText(e,t,i){if(!(!e||e.length<=0))if(this._textMeshUi||(this._textMeshUi=[]),i){let n=this.getNextTag(e);if(n)n.startIndex>0&&this.createText(e.substring(0,n.startIndex),t,!1);else return this.createText(e,t,!1);let r=[];for(;n;){let s=this.getNextTag(e,n.endIndex);if(s){let a=this.getText(e,n,s);this.handleTag(n,t,r),this.createText(a,t,!1)}else{let a=e.substring(n.endIndex);this.handleTag(n,t,r),this.createText(a,t,!1)}n=s}}else{let n={...t};n.content=e;let r=new Wm.Text(n);this._textMeshUi.push(r),this._textContainer&&this._textContainer.add(r)}}_didHandleTextRenderOnTop=!1;handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;let e=[],t=this.canvas,i={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let n=!1;if(this._textMeshUi)for(let r=0;r<this._textMeshUi.length;r++){if(e[r]===!0)continue;n=!0;let s=this._textMeshUi[r];!s.textContent||(cs(s,i),e[r]=!0)}if(!n)break;yield}}handleTag(e,t,i){if(e.isEndTag){if(i.length>0){let n=i.pop();if(n)for(let r in n.previousValues){let s=n.previousValues[r];t[r]=s}}}else if(e.type.includes("color")){let n=new la(e,{fontColor:t.fontColor});if(i.push(n),e.type.length>6){let r=e.type.substring(6);t.fontColor=Ex(r)}else t.fontColor=new L(1,1,1)}else if(e.type=="b"){let n=new la(e,{fontFamily:t.fontFamily,fontTexture:t.fontTexture});i.push(n),this.setFont(t,1)}else if(e.type=="i"){let n=new la(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=Ri(this.sourceId,this.font),this.font):null}};_([y(ze)],ke.prototype,"canvas",2),_([y()],ke.prototype,"alignment",2),_([y()],ke.prototype,"verticalOverflow",2),_([y()],ke.prototype,"horizontalOverflow",2),_([y()],ke.prototype,"lineSpacing",2),_([y()],ke.prototype,"supportRichText",2),_([y()],ke.prototype,"font",2),_([y()],ke.prototype,"fontStyle",2),_([y()],ke.prototype,"text",1),_([y()],ke.prototype,"fontSize",1);var la=class{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}};function Ex(o){if(o.startsWith("#")){let t=o.substring(1);var e=parseInt(t,16);let i=e>>16&255,n=e>>8&255,r=e&255;return new L(i/255,n/255,r/255)}switch(o){case"black":return new L(0,0,0);case"white":return new L(1,1,1);case"red":return new L(1,0,0);case"lime":return new L(0,1,0);case"blue":return new L(0,0,1);case"yellow":return new L(1,1,0);case"cyan":return new L(0,1,1);case"magenta":return new L(1,0,1);case"silver":return new L(.75,.75,.75);case"gray":return new L(.5,.5,.5);case"maroon":return new L(.5,0,0);case"olive":return new L(.5,.5,0);case"green":return new L(0,.5,0);case"purple":return new L(.5,0,.5);case"teal":return new L(0,.5,.5);case"navy":return new L(0,0,.5);case"darkred":return new L(.54,0,0);case"brown":return new L(.55,.27,0);case"firebrick":return new L(.69,.13,.13);case"crimson":return new L(.86,.08,.24);case"tomato":return new L(1,.39,.28);case"coral":return new L(1,.49,.31);case"indianred":return new L(.6,.31,.51);case"lightcoral":return new L(.94,.5,.5);case"darkorange":return new L(1,.55,0);case"orange":return new L(1,.65,0);case"gold":return new L(1,.84,0);case"darkgoldenrod":return new L(.72,.53,.04);case"goldenrod":return new L(.85,.65,.13);case"palegoldenrod":return new L(.93,.87,.67);case"darkkhaki":return new L(.74,.7,.42);case"khaki":return new L(.94,.9,.55);case"yellowgreen":return new L(.6,.8,.19);case"darkolivegreen":return new L(.33,.42,.18);case"olivedrab":return new L(.42,.56,.14);case"lawngreen":return new L(.49,.99,0);case"chartreuse":return new L(.5,1,0);case"greenyellow":return new L(.68,1,.18);case"darkgreen":return new L(0,.39,0);case"forestgreen":return new L(.13,.55,.13);case"limegreen":return new L(.19,.8,.19);case"lightgreen":return new L(.56,.93,.56);case"palegreen":return new L(.59,.98,.59);case"darkseagreen":return new L(.56,.74,.56);case"mediumspringgreen":return new L(0,.98,.6);case"springgreen":return new L(0,1,.5);case"seagreen":return new L(.18,.31,.31);case"mediumaquamarine":return new L(.4,.8,.66);case"mediumseagreen":return new L(.24,.7,.44);case"lightseagreen":return new L(.13,.7,.67);case"darkslategray":return new L(.18,.31,.31);case"darkcyan":return new L(0,.55,.55);case"aqua":return new L(0,1,1);case"lightcyan":return new L(.8,1,1);case"darkturquoise":return new L(0,.81,.82);case"turquoise":return new L(0,.82,.82);case"mediumturquoise":return new L(.28,.82,.8);case"paleturquoise":return new L(.68,1,.93);case"aquamarine":return new L(.5,1,.83);case"powderblue":return new L(.69,.88,.9);case"cadetblue":return new L(.37,.62,.63);case"steelblue":return new L(.27,.51,.71);case"cornflowerblue":return new L(.39,.58,.93);case"deepskyblue":return new L(0,.7,1);case"dodgerblue":return new L(.12,.56,1);case"lightblue":return new L(.68,.85,.9);case"skyblue":return new L(.53,.81,.92);case"lightskyblue":return new L(.53,.81,.98);case"midnightblue":return new L(.18,.18,.31);case"darkblue":return new L(0,0,.55);case"mediumblue":return new L(0,0,.82);case"royalblue":return new L(.25,.41,.88);case"blueviolet":return new L(.54,.17,.89);case"indigo":return new L(.29,0,.51);case"darkslateblue":return new L(.28,.24,.55);case"slateblue":return new L(.42,.35,.8);case"mediumslateblue":return new L(.48,.41,.9);case"mediumpurple":return new L(.58,.44,.86);case"darkmagenta":return new L(.55,0,.55);case"darkviolet":return new L(.58,0,.83);case"darkorchid":return new L(.6,.2,.8);case"mediumorchid":return new L(.73,.33,.83);case"thistle":return new L(.84,.75,.85);case"plum":return new L(.87,.63,.87);case"violet":return new L(.93,.51,.93);case"fuchsia":return new L(1,0,1);case"orchid":return new L(.85,.44,.84);case"mediumvioletred":return new L(.78,.08,.52);case"palevioletred":return new L(.86,.44,.58);case"hotpink":return new L(1,.4,.71);case"deeppink":return new L(1,.08,.58);case"lightpink":return new L(1,.71,.76);case"pink":return new L(1,.75,.78);case"antiquewhite":return new L(.98,.92,.84);case"beige":return new L(.96,.96,.86);case"bisque":return new L(1,.89,.77);case"blanchedalmond":return new L(1,.92,.82);case"wheat":return new L(.96,.87,.87);case"cornsilk":return new L(1,.97,.86);case"lemonchiffon":return new L(1,.98,.8);case"lightgoldenrodyellow":return new L(.98,.98,.82);case"lightyellow":return new L(1,1,.8);case"saddlebrown":return new L(.55,.27,.07);case"sienna":return new L(.63,.32,.18);case"chocolate":return new L(.82,.41,.12);case"peru":return new L(.82,.52,.25);case"sandybrown":return new L(.96,.64,.38);case"burlywood":return new L(.87,.72,.53);case"tan":return new L(.82,.71,.55);case"rosybrown":return new L(.74,.56,.56);case"moccasin":return new L(1,.89,.71);case"navajowhite":return new L(1,.87,.68);case"peachpuff":return new L(1,.85,.73);case"mistyrose":return new L(1,.89,.88);case"lavenderblush":return new L(1,.94,.93);case"linen":return new L(.98,.94,.9);case"oldlace":return new L(.99,.96,.9);case"papayawhip":return new L(1,.94,.84);case"seashell":return new L(1,.96,.93);case"mintcream":return new L(.98,1,.98);case"slategray":return new L(.44,.5,.56);case"lightslategray":return new L(.47,.53,.6);case"lightsteelblue":return new L(.69,.77,.87);case"lavender":return new L(.9,.9,.98);case"floralwhite":return new L(1,.98,.98);case"aliceblue":return new L(.94,.97,1);case"ghostwhite":return new L(.97,.97,1);case"honeydew":return new L(.94,1,.94);case"ivory":return new L(1,1,.94);case"azure":return new L(.94,1,1);case"snow":return new L(1,.98,.98);case"dimgray":return new L(.4,.4,.4);case"darkgray":return new L(.66,.66,.66);case"lightgray":return new L(.83,.83,.83);case"gainsboro":return new L(.86,.86,.86);case"whitesmoke":return new L(.96,.96,.96)}return new L(1,1,1)}var io=M("debuginputfield"),N=class extends k{get text(){return this.textComponent?.text??""}get isFocused(){return N.active===this}textComponent;placeholder;onValueChanged;onEndEdit;inputEventFn;start(){io&&console.log(this.name,this)}onEnable(){N.htmlField||(N.htmlField=document.createElement("input"),N.htmlField.classList.add("ar"),document.body.appendChild(N.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),N.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&R.setActive(this.placeholder.gameObject,!1)}onDisable(){N.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected()}onPointerClick(e){io&&console.log("CLICK",e,N.active),N.activeTime=this.context.time.time,N.active!==this&&this.startCoroutine(this.activeLoop(),2),this.selectInputField()}*activeLoop(){for(this.onSelected();N.active===this&&!(this.context.input.getPointerUp(0)&&this.context.time.time-N.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(N.active!==this&&(io&&console.log("Select",this.name,this,N.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,N.htmlField?.value),N.active?.onDeselected(),N.active=this,this.placeholder&&R.setActive(this.placeholder.gameObject,!1),N.htmlField)){if(N.htmlField.value=this.textComponent?.text||"",io&&console.log("set input field value",N.htmlField.value),this.context.isInXR){let e=this.context.arOverlayElement;e&&(N.htmlField.style.width="0px",N.htmlField.style.height="0px",e.append(N.htmlField))}this.selectInputField()}}onDeselected(){N.active===this&&(N.active=null,io&&console.log("Deselect",this.name,this),N.htmlField&&(N.htmlField.blur(),document.body.append(N.htmlField),N.htmlField.style.width="",N.htmlField.style.height=""),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&R.setActive(this.placeholder.gameObject,!0),this.onEndEdit?.invoke())}onInput(e){if(N.active===this){if(io&&console.log(e.code,e,N.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}N.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&R.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&N.htmlField){if(this.textComponent.text!==N.htmlField.value){io&&console.log("VALUE CHANGED");let e=this.textComponent.text,t=N.htmlField.value;this.onValueChanged?.invoke(t,e)}this.textComponent.text=N.htmlField.value}}selectInputField(){N.htmlField&&(N.htmlField.setSelectionRange(N.htmlField.value.length,N.htmlField.value.length),N.htmlField.focus())}},kt=N;A(kt,"active",null),A(kt,"activeTime",-1),A(kt,"htmlField",null),_([y(ke)],kt.prototype,"textComponent",2),_([y(ke)],kt.prototype,"placeholder",2),_([y(be)],kt.prototype,"onValueChanged",2),_([y(be)],kt.prototype,"onEndEdit",2);import*as Nm from"three-mesh-ui";import*as ca from"three";var Xm=(a=>(a[a.fr=0]="fr",a[a.ru=1]="ru",a[a.de=2]="de",a[a.es=3]="es",a[a.el=4]="el",a[a.nord=5]="nord",a[a.eng=6]="eng",a))(Xm||{}),hs=class extends Ue{font;text;keymap;padding;margin;fontSize;borderRadius;colors={keyboardBack:8750469,panelBack:2500134,button:3552822,hovered:1842204,selected:1088605};awake(){super.awake();let e=Xm[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=R.getComponent(this.gameObject,mt);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 ca.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 Nm.Keyboard(n),this.gameObject.scale.set(1,1,1),this.keyboard.keys.forEach(s=>{s.setupState({state:"normal",attributes:{offset:.003,backgroundColor:new ca.Color(this.colors.button),backgroundOpacity:1}}),s.setState("normal"),s.setupState({state:"hovered",attributes:{offset:.3,backgroundColor:new ca.Color(this.colors.hovered),backgroundOpacity:1}}),s.setupState({state:"pressed",attributes:{offset:.1,backgroundColor:new ca.Color(this.colors.selected),backgroundOpacity:1},onSet:()=>{let a=s.info.input,c=s.info.command;if(this._lastKeyPressed!==a)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=a,c)switch(c){case"switch":this.keyboard.setNextPanel();break;case"switch-set":this.keyboard.setNextCharset();break;case"enter":this.tryAppend(`
309
- `);break;case"space":this.tryAppend(" ");break;case"backspace":if(!this.text?.text?.length)break;this.text?.text&&(this.text.text=this.text.text.substring(0,this.text.text.length-1)||"");break;case"shift":this.keyboard.toggleCase();break}else s.info.input!==void 0&&this.tryAppend(s.info.input)}})})}tryAppend(e){this.text&&(this.text.text+=e,this.markDirty())}};var Hn=class extends k{reverseArrangement=!1},ps=class extends Hn{},fs=class extends Hn{},ms=class extends Hn{};var no=class extends k{awake(){Xe.createIfNoneExists(this.context)}onEnable(){Xe.instance?.register(this)}onDisable(){Xe.instance?.unregister(this)}performRaycast(e=null){return null}},ro=class extends no{targets=null;raycastHits=[];start(){this.targets=[this.gameObject]}performRaycast(e=null){return this.targets?(e??=new me,e.targets=this.targets,e.results=this.raycastHits,this.context.physics.raycast(e)):null}},gs=class extends ro{};import*as Qm from"three";import{HTMLMesh as Cx}from"three/examples/jsm/interactive/HTMLMesh.js";import{InteractiveGroup as Tx}from"three/examples/jsm/interactive/InteractiveGroup.js";var bs=class extends k{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 Tx(this.context.renderer,this.context.mainCamera);this.gameObject.add(t);let i=new Cx(e);t.add(i),i.visible=!1,console.log(i);let n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;let r=ka(this.gameObject).clone();Ma(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();let s=new Qm.Box3;s.setFromObject(t),this.setWorldRotation(r.x,r.y,r.z);let a=s.max.x-s.min.x,c=s.max.y-s.min.y;if(this.keepAspect){let l=a/c;a>c?i.scale.set(1/a,1/c/l,1):i.scale.set(1/a*l,1/c,1)}else i.scale.set(1/a,1/c,1);let d=this.gameObject.scale;i.scale.multiply(d)},1)}};var da=class{};var mc=class extends k{toggleKey="p";update(){this.context.input.isKeyDown("p")&&this.context.domElement.classList.toggle("presentation-mode")}};import*as qm from"three";import{Raycaster as Px,Vector3 as Ox}from"three";import*as gc from"three";import{MeshLine as Rx,MeshLineMaterial as Sx}from"three.meshline";var vh=class{id=0;points=[];line=new Rx;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 gc.Mesh(this.line,this.material),e.add(this.mesh)}appendPoint(e){let t=vh.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 Sx({color:10066329,lineWidth:.01})},vs=vh;A(vs,"wp",new gc.Vector3);var oo=class extends k{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=R.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 vs(e??this.context.scene,n);r.id=t,this.inFlight[t]=r,i&&this.sendLineStart(r);let s;return this.freeBuffer.length<=0?s=new Array:s=this.freeBuffer.pop(),this.buffer[t]=s,{id:t}}sendLineStart(e){let t=e.mesh.parent;this.context.connection.send("line-start",{id:e.id,parentGuid:t?t.guid:void 0})}sendLineUpdate(e,t,i,n){if(e){let r={parentGuid:e.mesh.parent.guid,guid:e.id,points:n?[...n]:e.points,width:e.material.lineWidth,color:e.material.color.toArray(),startIndex:i!==void 0?i:e.points.length,finished:t};this.context.connection.send("line-update",r)}}};import{MeshLineMaterial as kx}from"three.meshline";var bc=class{isDrawing;lastHit;currentHandle;maxDistance;prevDistance;lastParent;constructor(){this.isDrawing=!1,this.lastHit=new Ox,this.currentHandle=null,this.maxDistance=0,this.prevDistance=0,this.lastParent=null}},vc=class extends k{lines;colliders;alignToSurface=!0;addToPaintedObject=!0;orbit;start(){this.lines||(this.lines=R.getComponent(this.gameObject,oo),this.lines||(this.lines=R.addNewComponent(this.gameObject,oo))),this.orbit=R.findObjectOfType(it,this.context)??void 0,this._states.mouse=new bc;let e={};J.addEventListener("select-start",(t,i)=>{e[t.controller.uuid]=!0}),J.addEventListener("update",(t,i)=>{if(e[t.controller.uuid]===!0){let n=t.getRay();this.updateLine(t.controller.uuid,n,!0,!1,!1)}}),J.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);vc._raycaster.setFromCamera(t,this.context.mainCamera);let i=vc._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 s=this._states[e];if(s||(this._states[e]=new bc,s=this._states[e]),n)s.isDrawing=!1,s.currentHandle&&(this.lines.endLine(s.currentHandle),s.currentHandle=null);else if(i){if(r)return s;let a=this.getHit(t),c=null,d=s.prevDistance;if(a)s.currentHandle||(s.maxDistance=a.distance),c=a.point,c.add(a.face.normal.multiplyScalar(.01)),s.prevDistance=a.distance;else if(s.maxDistance>0){let l=s.maxDistance;if(!s.currentHandle&&s.lastHit){let u=B(this.context.mainCamera);l=s.lastHit.distanceTo(u)}c=t.origin.add(t.direction.multiplyScalar(s.maxDistance)),s.prevDistance=s.maxDistance}if(c){if(!s.currentHandle){let l=s.lastParent??this.gameObject;this.addToPaintedObject&&a&&(l=a.object),s.lastParent=l,s.currentHandle=this.lines.startLine(l,{material:this.createRandomMaterial()})}if(this.alignToSurface&&(s.prevDistance>s.maxDistance||Math.abs(d-s.prevDistance)>.2)){let l=s.maxDistance;c=t.origin.add(t.direction.multiplyScalar(l)),s.prevDistance=l}if(s.lastHit&&s.lastHit.distanceTo(c)<s.prevDistance*.01)return s;this.lines.updateLine(s.currentHandle,{point:c}),s.lastHit.copy(c)}s.isDrawing=s.currentHandle!==null}return s}_raycastOptions=new me;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(!!R.isActiveInHierarchy(i.object))return i}return null}createRandomMaterial(){let e;return this.context.connection.connectionId?e=ft.colorFromHashCode(ft.hashCode(this.context.connection.connectionId)):e=new qm.Color("hsl("+(Math.random()*100).toFixed(0)+", 80%, 30%)"),new kx({color:e,lineWidth:H.lerp(.005,.01,Math.random())})}},ua=vc;A(ua,"_raycaster",new Px);import{Object3D as Mx}from"three";var ha=class extends k{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=R.getComponent(t,Zi);i&&(i.owner=this.context.connection.connectionId)}}watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=Zi.all.length-1;t>=0;t--){let i=Zi.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};_([y(Ze)],ha.prototype,"asset",2);var $t=class extends k{static get all(){return $t._all}static get local(){return $t._local}static isLocalPlayer(e){return e instanceof Mx?R.getComponentInParent(e,$t)?.isLocalPlayer??!1:e instanceof yt?R.getComponentInParent(e.gameObject,$t)?.isLocalPlayer??!1:!1}owner;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}awake(){this.isLocalPlayer&&$t.local.push(this),$t.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(){mo(this.gameObject,this.context.connection)}onDestroy(){if($t.all.splice($t.all.indexOf(this),1),this.isLocalPlayer){let e=$t._local.indexOf(this);e>=0&&$t._local.splice(e,1)}}},Zi=$t;A(Zi,"_all",[]),A(Zi,"_local",[]),_([nc(),y()],Zi.prototype,"owner",2);P.add("AlignmentConstraint",qn);P.add("Animation",Lt);P.add("AnimationCurve",hi);P.add("Animator",et);P.add("AnimatorController",ui);P.add("AudioListener",pi);P.add("AudioSource",oe);P.add("AvatarModel",Hr);P.add("AvatarLoader",Yn);P.add("AxesHelper",mn);P.add("BasicIKConstraint",Mo);P.add("BoxHelperComponent",Be);P.add("Camera",se);P.add("CharacterController",ji);P.add("CharacterControllerInput",mi);P.add("Collider",Ut);P.add("SphereCollider",Jn);P.add("BoxCollider",Zn);P.add("MeshCollider",Ur);P.add("CapsuleCollider",Bt);P.add("DeleteBox",Vr);P.add("Deletable",Ao);P.add("DeviceFlag",zr);P.add("DragControls",Gi);P.add("DropListener",nr);P.add("Duplicatable",Vi);P.add("CallInfo",fi);P.add("EventListEvent",Br);P.add("EventList",be);P.add("EventTrigger",Vo);P.add("FlyControls",zo);P.add("BoxGizmo",wn);P.add("GridHelper",En);P.add("GroundProjectedEnv",Cn);P.add("Interactable",Gt);P.add("UsageMarker",Vt);P.add("FixedJoint",Wo);P.add("HingeJoint",rr);P.add("Light",Ge);P.add("LODModel",zi);P.add("LODGroup",or);P.add("LookAtConstraint",vn);P.add("NestedGltf",Nr);P.add("Networking",xi);P.add("OffsetConstraint",Wi);P.add("OrbitControls",it);P.add("SubEmitterSystem",ar);P.add("ParticleSystemRenderer",Ni);P.add("ParticleSystem",ge);P.add("Gradient",Ei);P.add("MinMaxCurve",U);P.add("MinMaxGradient",Oe);P.add("MainModule",ye);P.add("ParticleBurst",Rn);P.add("EmissionModule",pt);P.add("ColorOverLifetimeModule",Tn);P.add("SizeOverLifetimeModule",qt);P.add("ShapeModule",ie);P.add("NoiseModule",Y);P.add("TrailModule",ee);P.add("VelocityOverLifetimeModule",je);P.add("TextureSheetAnimationModule",_e);P.add("RotationOverLifetimeModule",Qe);P.add("RotationBySpeedModule",Ve);P.add("LimitVelocityOverLifetimeModule",de);P.add("InheritVelocityModule",Yt);P.add("SizeBySpeedModule",Pe);P.add("ColorBySpeedModule",wi);P.add("ParticleSubEmitter",sr);P.add("PlayerColor",ft);P.add("ReflectionProbe",Kt);P.add("FieldWithDefault",Ko);P.add("Renderer",ae);P.add("MeshRenderer",Qr);P.add("SkinnedMeshRenderer",Jo);P.add("RendererLightmap",Sn);P.add("Rigidbody",K);P.add("ScreenCapture",cr);P.add("ShadowCatcher",dr);P.add("RemoteSkybox",qi);P.add("SmoothFollow",Et);P.add("SpatialTriggerReceiver",Ct);P.add("SpatialTrigger",Pn);P.add("SpectatorCamera",$o);P.add("Sprite",qr);P.add("SpriteRenderer",On);P.add("SyncedCamera",hr);P.add("SyncedRoom",Ci);P.add("SyncedTransform",_t);P.add("TestRunner",es);P.add("TestSimulateUserData",ts);P.add("TransformGizmo",Yr);P.add("VideoPlayer",Ce);P.add("Voip",tt);P.add("VolumeParameter",is);P.add("VolumeComponent",Yi);P.add("ToneMapping",fr);P.add("ColorAdjustments",mr);P.add("VolumeProfile",pr);P.add("Volume",Kr);P.add("WebARSessionRoot",Wt);P.add("WebXR",V);P.add("WebAR",ir);P.add("AvatarMarker",le);P.add("WebXRAvatar",Nt);P.add("TeleportTarget",Wr);P.add("WebXRController",J);P.add("AttachedObject",ht);P.add("XRGrabModel",Jr);P.add("XRGrabRendering",ns);P.add("XRRig",tr);P.add("VRUserState",Xt);P.add("WebXRSync",_n);P.add("XRState",xt);P.add("XRFlag",Ee);P.add("AvatarBlink_Simple",Ki);P.add("AvatarEyeLook_Rotation",Ji);P.add("Avatar_POI",ve);P.add("Avatar_Brain_LookAt",bn);P.add("Avatar_MouthShapes",gr);P.add("Avatar_MustacheShake",rs);P.add("__Ignore",da);P.add("LogStats",os);P.add("GltfExportBox",ss);P.add("GltfExport",Jt);P.add("RGBAColor",Z);P.add("PlayableDirector",An);P.add("SignalAsset",Zr);P.add("SignalReceiverEvent",$r);P.add("SignalReceiver",kn);P.add("AnimationTrackHandler",br);P.add("AudioTrackHandler",vr);P.add("SignalTrackHandler",In);P.add("ControlTrackHandler",Mn);P.add("BaseUIComponent",Ue);P.add("UIRootComponent",yn);P.add("Button",Zt);P.add("Canvas",ze);P.add("CanvasGroup",jn);P.add("EventSystem",Xe);P.add("Graphic",Ot);P.add("MaskableGraphic",Dn);P.add("Image",Ln);P.add("RawImage",to);P.add("InputField",kt);P.add("Keyboard",hs);P.add("LayoutGroup",Hn);P.add("VerticalLayoutGroup",ps);P.add("HorizontalLayoutGroup",fs);P.add("GridLayoutGroup",ms);P.add("PointerEventData",bi);P.add("Raycaster",no);P.add("ObjectRaycaster",ro);P.add("GraphicRaycaster",gs);P.add("UIRaycastUtils",yi);P.add("Size",ds);P.add("Rect",eo);P.add("RectTransform",mt);P.add("SpatialHtml",bs);P.add("Text",ke);P.add("PresentationMode",mc);P.add("LinesDrawer",ua);P.add("LineInstanceHandler",vs);P.add("LinesManager",oo);P.add("PlayerSync",ha);P.add("PlayerState",Zi);var Ym=Te,Ix=M("debugtypestore");Ix&&console.log(P);function Km(o,e){let i=zc(o,e);return i!==void 0?i:null}var Ax=new Ra;async function Jm(o,e,t,i=null,n){if(!t)return;let r=[],s=i;typeof s=="number"&&(s=new Ie(i));let a=new ho(t.scene);a.gltfId=e,a.context=o,a.gltf=t,a.nodeToObject=n?.nodeToObjectMap,a.implementationInformation=Ax;let c=[];if(t.scenes)for(let d of t.scenes)await _h(a,d,c,r);if(t.children)for(let d of t.children)await _h(a,d,c,r);o.new_scripts_pre_setup_callbacks.push(()=>{for(let d of c)Dx(d,a);if(s){yh(t,s);for(let d of t.scenes)yh(d,s)}})}function yh(o,e){if(e!==null&&!!o){if(o.guid=e.generateUUID(),o&&o.userData&&o.userData.components)for(let t of o.userData.components)t!==null&&(t.guid=e.generateUUID());if(o.children)for(let t of o.children)yh(t,e)}}var pa=[];async function _h(o,e,t,i){if(!e)return;let n=e.userData;if(n){let r=n.builtin_components;if(r&&r.length>0)for(let s of r)try{if(s===null)continue;let a=P.get(s.name);if(a!=null){let c=new a;c.sourceId=o.gltfId,Mt(c,s,o.implementationInformation),Un(e,c,!1),t.push({instance:c,compData:s,obj:e})}else Ym&&console.debug("unknown component: "+s.name),pa.includes(s.name)||pa.push(s.name)}catch(a){console.error(s.name+" - "+a.message,a)}if(pa.length>0){let s=pa.join(", ");console.warn("unknown components: "+s),pa.length=0,ei()&&Ye(`<strong>Unknown components in scene</strong>:
307
+ `)}}}applyShadowMaterial(){let e=R.getComponent(this.gameObject,ae);if(e)if(e.sharedMaterial?.type!=="ShadowMaterial"){let t=new q_;t.color=this.shadowColor,t.opacity=this.shadowColor.alpha,this.applyMaterialOptions(t),e.sharedMaterial=t}else{let t=e.sharedMaterial;t.color=this.shadowColor,t.opacity=this.shadowColor.alpha,this.applyMaterialOptions(t)}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}};y([_()],hr.prototype,"mode",2),y([_(Z)],hr.prototype,"shadowColor",2);import{RGBELoader as Z_}from"three/examples/jsm/loaders/RGBELoader.js";import{EXRLoader as $_}from"three/examples/jsm/loaders/EXRLoader";import{EquirectangularRefractionMapping as ex,sRGBEncoding as tx,TextureLoader as Im}from"three";var km=O("debugautosync"),rh=class{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];let t=new oh(e);return this._syncers[e.guid]=t,t}},Mm=new rh,oh=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)){km&&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 K_(o,e){let t=e!==o;if(!t&&o&&e){if(Array.isArray(o)&&Array.isArray(e))t=!0;else if(typeof o=="object"&&typeof e=="object"){for(let i of Object.keys(o))if(o[i]!==e[i]){t=!0;break}}}return t}function J_(o){if(o.__autoPropertySyncHandler)return o.__autoPropertySyncHandler;let e=Mm.getOrCreateSyncer(o);return e?.init(o),o.__autoPropertySyncHandler=e,e}var lc=function(o){return function(e,t){let i=null,n=o?e[o]:void 0,r=e,s=r.__internalAwake;km&&console.log(t);let a=t+"k__BackingField";r.__internalAwake=function(){if(this[a]!==void 0)return;this[a]=this[t],s.call(this),i=Mm.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,t)?.set===void 0&&Object.defineProperty(this,t,{set:function(d){let l=this[a];this[a]=d,K_(d,l)&&n?.call(this,d,l)!==!1&&J_(this)?.notifyChanged(t,d)},get:function(){return this[a]},configurable:!0,enumerable:!0}),i?.init(this)}}};var Ri=class extends M{url;allowDrop=!0;background=!0;backgroundBlurriness=0;environment=!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"),r=e.endsWith(".hdr");n?this._loader=new $_:r?this._loader=new Z_:this._loader=new Im}let t=await this._loader.loadAsync(e);if(!t||!this.enabled)return;this.url=e,t.mapping=ex,this._loader instanceof Im&&(t.encoding=tx),this._prevBackground=this.context.scene.background,this._prevEnvironment=this.context.scene.environment,console.log("Set skybox",this.url),this.environment&&(this.context.scene.environment=t),this.background&&(this.context.scene.background=t),this._prevLoadedEnvironment=t;let i=e.lastIndexOf("/");t.name=e.substring(i>=0?i+1:0),this.context.scene.backgroundBlurriness=this.backgroundBlurriness}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))}};y([lc("setSkybox"),_()],Ri.prototype,"url",2),y([_()],Ri.prototype,"allowDrop",2),y([_()],Ri.prototype,"background",2),y([_()],Ri.prototype,"backgroundBlurriness",2),y([_()],Ri.prototype,"environment",2);import*as cc from"three";import{Object3D as ix}from"three";var sh=class extends M{target=null;followFactor=.1;rotateFactor=.1;positionAxes=-1;flipForward=!1;_firstUpdate=!0;onBeforeRender(){this.updateNow(!1)}updateNow(e){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){let t=B(this.target),i=this._firstUpdate||e?1:H.clamp01(this.context.time.deltaTime*this.followFactor),n=this.worldPosition;this.positionAxes&2&&(n.x=H.lerp(n.x,t.x,i)),this.positionAxes&4&&(n.y=H.lerp(n.y,t.y,i)),this.positionAxes&8&&(n.z=H.lerp(n.z,t.z,i)),this.worldPosition=n}if(this.rotateFactor>0){let t=fe(this.target);this.flipForward&&t.premultiply(sh._invertForward);let i=this._firstUpdate||e?1:H.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(t,i)}this._firstUpdate=!1}}},Tt=sh;D(Tt,"_invertForward",new cc.Quaternion().setFromAxisAngle(new cc.Vector3(0,1,0),Math.PI)),y([_(ix)],Tt.prototype,"target",2),y([_()],Tt.prototype,"followFactor",2),y([_()],Tt.prototype,"rotateFactor",2),y([_()],Tt.prototype,"positionAxes",2);import{Layers as Lm}from"three";var la=O("debugspatialtrigger"),Dm=new Lm,Am=new Lm;function nx(o,e){return Dm.mask=o,Am.mask=e,Dm.test(Am)}var Rt=class extends M{triggerMask=0;onEnter;onStay;onExit;start(){la&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(let e of Mn.triggers)nx(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){la&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),this.onEnter?.invoke(this,e)}onExitTrigger(e){la&&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)}};y([_()],Rt.prototype,"triggerMask",2),y([_(ue)],Rt.prototype,"onEnter",2),y([_(ue)],Rt.prototype,"onStay",2),y([_(ue)],Rt.prototype,"onExit",2);var ca=class extends M{triggerMask;boxHelper;start(){la&&console.log(this.name,this.triggerMask,this)}onEnable(){ca.triggers.push(this),this.boxHelper||(this.boxHelper=R.addNewComponent(this.gameObject,Ue),this.boxHelper?.showHelper(null,la))}onDisable(){ca.triggers.splice(ca.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){R.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof Rt&&t.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){R.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof Rt&&t.onStayTrigger(this)},!1)}raiseOnExitEvent(e){R.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof Rt&&t.onExitTrigger(this)},!1)}},Mn=ca;D(Mn,"triggers",[]),y([_()],Mn.prototype,"triggerMask",2);import*as pr from"three";var St=O("debugspectator"),ts=class extends M{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}get localId(){return this.context.connection.connectionId??"local"}set target(e){if(this._handler){let t=this._handler.currentTarget?.userId,i=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&i?.currentObject===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),R.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,t)):this._handler.currentTarget!==e&&(this._handler.set(e),R.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.localId)?.currentObject}orbit=null;_handler;eventSub_WebXRRequestStartEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;_debug;_networking;awake(){if(this._debug=new lh(this.context,this),this._networking=new uh(this.context,this),this._networking.awake(),R.setActive(this.gameObject,!1),this.cam=R.getComponent(this.gameObject,ee),!this.cam){console.error("Spectator camera needs camera component",this);return}!this._handler&&this.cam&&(this._handler=new ah(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),V.addEventListener("requestVRSession",this.eventSub_WebXRRequestStartEvent),V.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),V.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.orbit=R.getComponent(this.context.mainCamera,it)}onDestroy(){this.stopSpectating(),V.removeEventListener("requestVRSession",this.eventSub_WebXRStartEvent),V.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),V.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()||R.setActive(this.gameObject,!0)}onXRSessionStart(e){!this.isSupportedPlatform()||(St&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onXRSessionEnded(e){this.context.removeCamera(this.cam),R.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),this.target||(this.context.players.setPlayerView(this.localId,this.context.mainCamera,"headset"),this.target=this.context.players.getPlayerView(this.localId)),St&&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 pr.Color(1,1,1));e.setRenderTarget(null),e.xr.enabled=!1;let s=this.cam?.cam;this.context.updateAspect(s);let a=e.xr.isPresenting;e.xr.isPresenting=!1,e.setSize(this.context.domWidth,this.context.domHeight),e.render(this.context.scene,s),e.xr.isPresenting=a,e.xr.enabled=t,i?e.setRenderTarget(i):e.state.bindXRFramebuffer(n),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){let e=this._mode===0;for(let t of le.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 le.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)}}},ah=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=R.addNewComponent(this.cam.gameObject,Tt)),this.target||(this.target=new pr.Object3D),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,St&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){St&&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&&R.destroy(this.follow)}update(e){if(this.currentTarget?.isConnected===!1||this.currentTarget?.removed===!0){St&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&this.currentTarget?.currentObject!==this.currentObject&&(St&&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(rx):i.quaternion.identity()}}},rx=new pr.Quaternion().setFromAxisAngle(new pr.Vector3(0,1,0),Math.PI),lh=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 ge;e.setMask(16777215);let t=this.context.physics.raycast(e);if(St&&console.log(...t),t?.length)for(let i of t){if(i.distance<.2)continue;let n=i.object,r=R.getComponentInParent(n,le),s=r?.connectionId;if(s){let a=this.context.players.getPlayerView(s);this.spectator.target=a,St&&console.log("spectate",s,r);break}}}},ch=class{guid;dontSave=!0;targetUserId;stoppedFollowing;constructor(e,t,i){this.guid=e,this.targetUserId=t,this.stoppedFollowing=i}},dh=class{guid;userId;constructor(e,t){this.guid=e.guid,this.userId=t}},uh=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(St&&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 ch(this.context.connection.connectionId,n,i);this.context.connection.send("spectator-follower-changed",r)}}onRequestFollowMe(e=!1){if(St&&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 dh(this.spectator,t);this.context.connection.send("spectator-request-follow",i)}}onUserJoinedRoom(){O("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){let t=e.targetUserId,i=e.guid;if(St&&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 St&&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):(St&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}};import*as ot from"three";import{Material as ox,NearestFilter as jm,Texture as sx,Vector2 as Hm}from"three";var ph=O("debugspriterenderer"),dc=class{static getOrCreateGeometry(e){if(e._geometry)return e._geometry;if(e.guid&&dc.cache[e.guid])return ph&&console.log("Take cached geometry for sprite",e.guid),dc.cache[e.guid];let t=new ot.BufferGeometry;e._geometry=t;let i=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let r=0;r<e.triangles.length;r+=1){let s=e.triangles[r];i[r*3]=-e.vertices[s].x,i[r*3+1]=e.vertices[s].y,i[r*3+2]=0;let a=e.uv[s];n[r*2]=a.x,n[r*2+1]=1-a.y}return t.setAttribute("position",new ot.BufferAttribute(i,3)),t.setAttribute("uv",new ot.BufferAttribute(n,2)),e.guid&&(this.cache[e.guid]=t),ph&&console.log("Built sprite geometry",e,t),t}},da=dc;D(da,"cache",{});var Jt=class{guid;texture;triangles;uv;vertices;_geometry};y([_()],Jt.prototype,"guid",2),y([_(sx)],Jt.prototype,"texture",2),y([ko()],Jt.prototype,"triangles",2),y([ko()],Jt.prototype,"uv",2),y([ko()],Jt.prototype,"vertices",2);var is=class{name;offset;size};y([_()],is.prototype,"name",2),y([_(Hm)],is.prototype,"offset",2),y([_(Hm)],is.prototype,"size",2);var hh=Symbol("spriteOwner"),Zi=class{sprite;index=0;slices;update(){let e=this.index;if(e<0||e>=this.slices.length)return;let t=this.slices[e],i=this.sprite?.texture;!i||(i.encoding=ot.sRGBEncoding,i.offset.set(t.offset.x,t.offset.y),i.minFilter==jm&&i.magFilter==jm&&(i.anisotropy=1),i.needsUpdate=!0)}};y([_(Jt)],Zi.prototype,"sprite",2),y([_()],Zi.prototype,"index",2),y([_(is)],Zi.prototype,"slices",2);var Ji=class extends M{drawMode=0;size={x:1,y:1};color;sharedMaterial;get sprite(){return this._spriteSheet}set sprite(e){if(e!==this._spriteSheet)if(typeof e=="number"){let t=Math.floor(e);t===e&&(this.spriteIndex=t);return}else this._spriteSheet=e,this.updateSprite()}set spriteIndex(e){!this._spriteSheet||(this._spriteSheet.index=e,this._spriteSheet.update())}get spriteIndex(){return this._spriteSheet?.index??0}get spriteFrames(){return this._spriteSheet?.slices.length??0}_spriteSheet;_currentSprite;awake(){this._currentSprite=void 0,ph&&(console.log("Awake",this.name,this,this.sprite?.sprite?.texture),this.sprite?.sprite?.texture&&console.log(this.sprite.sprite.texture.minFilter.toString(),this.sprite.sprite.texture.magFilter.toString()))}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(){if(!this.__didAwake||!this.sprite?.sprite)return;let e=this.sprite.sprite;if(this._currentSprite)this._currentSprite.geometry=da.getOrCreateGeometry(e),this._currentSprite.material.map=e.texture;else{let t=new ot.MeshBasicMaterial({color:16777215,side:ot.DoubleSide});if(!t)return;if(this.color&&(t.color||(t.color=new ot.Color),t.color.copy(this.color),t.opacity=this.color.alpha),t.alphaTest=.5,e.texture&&!t.wireframe){let i=e.texture;i[hh]!==void 0&&i[hh]!==this&&this.spriteFrames>1&&(i=e.texture=i.clone()),i[hh]=this,t.map=i}this.sharedMaterial=t,this._currentSprite=new ot.Mesh(da.getOrCreateGeometry(e),t)}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)),this._spriteSheet?.update()}};y([_()],Ji.prototype,"drawMode",2),y([_(Z)],Ji.prototype,"color",2),y([_(ox)],Ji.prototype,"sharedMaterial",2),y([_(Zi)],Ji.prototype,"sprite",1);var Pt=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 Pt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+4),(t||new Pt).__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 we).__init(this.bb_pos+t,this.bb):null}rot(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new we).__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 ax}from"three";var uc="SCAM";So(uc,Pt.getRootAsSyncedCameraModel);var Ot=new yt,fh=class{userId;guid;constructor(e,t){this.guid=t,this.userId=e}send(e,t){if(e){Ot.clear();let i=Ot.createString(this.guid),n=Ot.createString(this.userId);Pt.startSyncedCameraModel(Ot),Pt.addGuid(Ot,i),Pt.addUserId(Ot,n);let r=B(e),s=La(e);Pt.addPos(Ot,we.createVec3(Ot,r.x,r.y,r.z)),Pt.addRot(Ot,we.createVec3(Ot,s.x,s.y,s.z));let a=Pt.endSyncedCameraModel(Ot);Ot.finish(a,uc),t.sendBinary(Ot.asUint8Array())}}},hc=class extends M{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(uc,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(uc,this._receiveCallback)}update(){for(let n in this.remoteCams){let r=this.remoteCams[n],s=this.context.time.realtimeSinceStartup-r.lastUpdate;if(!r||s>this._camTimeoutInSeconds){console.log("Remote cam timeout",r,s),r?.obj&&R.destroy(r.obj),delete this.remoteCams[n],r&&delete this.userToCamMap[r.userId],hc.instances.push(r),this.context.players.removePlayerView(r.userId,"browser");continue}}if(V.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 fh(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));let t=B(e),i=fe(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 Fe;c.context=this.context;let d=R.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,hc.instances.push(n);let l=R.getOrAddComponent(d,le);l.connectionId=i,l.avatar=d}else return;let r=n.obj;this.context.players.setPlayerView(i,r,"browser"),n.lastUpdate=this.context.time.realtimeSinceStartup,oe.markDirty(r);let s=e.pos();s&&dn(r,s.x(),s.y(),s.z());let a=e.rot();a&&ja(r,a.x(),a.y(),a.z())}},fr=hc;D(fr,"instances",[]),y([_([ax,$e])],fr.prototype,"cameraPrefab",2);var mh="view",pc=O("debugsyncedroom"),Si=class extends M{roomName;urlParameterName="room";joinRandomRoom=!0;requireRoomParameter=!1;autoRejoin=!0;_roomPrefix;awake(){pc&&console.log("Room",this.roomName,this.urlParameterName,this.joinRandomRoom,this.requireRoomParameter,this.autoRejoin),this._roomPrefix===void 0&&(this._roomPrefix=this.roomName,this.roomName="")}onEnable(){let e=O(mh);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=O(this.urlParameterName);if(i&&typeof i=="string"){t=!0;let n=Qh(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?(pc&&console.log('No required room parameter "'+this.urlParameterName+'" in url - will not connect to networking backend.'),!1):!this.roomName||this.roomName.length<=0?(pc&&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(),pc&&console.log("Join "+this.roomName),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=O(mh);return e||O(this.urlParameterName)}setRandomRoomUrlParameter(){let e=Lc(),t=this.generateRoomName();O(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),Wh(t,e)}generateRoomName(){return Xh()+"_"+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(mh,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}};y([_()],Si.prototype,"roomName",2),y([_()],Si.prototype,"urlParameterName",2),y([_()],Si.prototype,"joinRandomRoom",2),y([_()],Si.prototype,"requireRoomParameter",2),y([_()],Si.prototype,"autoRejoin",2);function Fm(){let o=O("testwindowcount")||0;o&&o>0&&lx(o)}function lx(o){if(O("testwindow"))return null;let e=new URL(window.location.href);ho(e.searchParams,Go,1),ho(e.searchParams,"testwindow",1);let t=e.toString(),i=[];window.onbeforeunload=()=>{for(let c of i)c.close()};let n=.05,r=128,s=0,a=0;for(let c=0;c<o;c++){s*r+r*.01>=window.innerWidth&&(a+=1,s=0);let d=s*(r*(1+n))+window.screenLeft,l=a*(r*(1+n))+window.screenTop+90+60*a;s+=1;let u=window.open(t,"test window "+c,`popup=yes width=${r} height=${r} top=${l} 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 b=i[h];b!==u&&b.close()}i.length=0}}}return i}import{Vector3 as dx}from"three";var ns=class extends M{awake(){Fm()}},rs=class extends M{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinrary(Fo,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new fc(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 yt(1024));let e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();let i=uu(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)}}}},fc=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}}};D(fc,"temp",new dx);import{MathUtils as ux}from"three";import{TransformControls as hx}from"three/examples/jsm/controls/TransformControls";import{OrbitControls as px}from"three/examples/jsm/controls/OrbitControls";var Jr=class extends M{isGizmo=!0;control;orbit;awake(){this.isGizmo&&!Mi||!this.context.mainCamera||(this.control=new hx(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=R.getComponentInParent(this.context.mainCamera,px)??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=R.getComponentInParent(this.gameObject,wt);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(ux.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))}};y([_()],Jr.prototype,"isGizmo",2);import{LinearToneMapping as gh,ACESFilmicToneMapping as fx,ReinhardToneMapping as mx}from"three";var mc=O("debugvolume"),Um=(i=>(i[i.None=0]="None",i[i.Neutral=1]="Neutral",i[i.ACES=2]="ACES",i))(Um||{}),os=class{overrideState=!1;value=0},$i=class{active=!1;parameters},gr=class extends $i{mode;get isToneMapping(){return!0}},br=class extends $i{postExposure};function gx(o){return"mode"in o?gr:"postExposure"in o?br:$i}var Bm=Symbol("volumeprofile"),mr=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[Bm]!==void 0;if(t){if(!r)return}else i[Bm]=this;for(let s of this.components)if(s instanceof gr){let a=s;if(!s.active||t){e.renderer.toneMapping=gh;continue}mc&&console.log("VOLUME:",Um[a.mode?.value??0]);let c=a.mode;switch((c?.overrideState?c?.value:0)??0){case 0:e.renderer.toneMapping=gh;break;case 1:e.renderer.toneMapping=mx;break;case 2:e.renderer.toneMapping=fx;break}}else if(s instanceof br){let a=s;mc&&console.log(a.postExposure);let c=Math.pow(2,a.postExposure?.value??0),d=a.postExposure?.overrideState&&!t;e.renderer.toneMappingExposure=d?c:1,e.renderer.toneMapping||(e.renderer.toneMapping=gh)}}};y([_([o=>gx(o),$i])],mr.prototype,"components",2);var Zr=class extends M{sharedProfile;awake(){mc&&(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(){mc&&console.log("APPLY VOLUME",this),this.sharedProfile?.apply(this.context)}onDisable(){this.sharedProfile?.unapply(this.context)}};y([_(mr)],Zr.prototype,"sharedProfile",2);import{Vector3 as bx}from"three";var $r=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}},ss=class extends M{prefab=null;_grabModels=[];_grabModelsUpdateTime=[];_addOrUpdateSub=null;_endSub=null;_freeSub=null;_instances={};awake(){this.prefab&&(this.prefab.visible=!1)}onEnable(){this._addOrUpdateSub=this.context.connection.beginListen("xr-grab-visual-start-or-update",this.onRemoteGrabStartOrUpdate.bind(this)),this._endSub=this.context.connection.beginListen("xr-grab-visual-end",this.onRemoteGrabEnd.bind(this)),this._freeSub=pt.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),pt.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=R.instantiate(this.prefab);if(i.visible=!0,this._instances[e.guid]={instance:i,model:e},e.userId){let n=R.getComponentsInChildren(i,mt);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]&&(R.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<pt.Current.length;e++){let t=pt.Current[e];if(!t.controller||!t.selected)continue;this._grabModels.length<=e&&(this._grabModels.push(new $r),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 bx;updateRendering(){let e=this.context.time.deltaTime/.5;for(let t in this._instances){let{instance:i,model:n}=this._instances[t];if(!i||!n)continue;let{point:r}=n,s=B(i);this.temp.set(r.x,r.y,r.z),s.lerp(this.temp,e),ie(i,s)}}};import{Object3D as vx}from"three";var en=class extends M{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=R.getComponentInParent(this.gameObject,Ee)}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)}}};y([_(vx)],en.prototype,"eyes",2),y([_()],en.prototype,"lastBlinkTime",2),y([_()],en.prototype,"blinkLength",2),y([_()],en.prototype,"eyesOpen",2);import*as gc from"three";import{Object3D as bh}from"three";var vh=class extends M{head=null;eyes=null;target=null;brain=null;awake(){this.brain||(this.brain=R.getComponentInParent(this.gameObject,xn)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=R.addNewComponent(this.gameObject,xn)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new gc.Vector3;currentTargetPoint=new gc.Vector3;update(){let e=this.target;if(e&&this.head){let t=this.eyes;if(t){let i=B(e);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);let n=B(this.head),r=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(r.length()<.1)return;let s=vh.forward;if(s.set(0,0,1),s.applyQuaternion(fe(this.head)),s.dot(r)>.45)for(let c=0;c<t.length;c++)t[c].lookAt(this.currentTargetPoint)}}}},tn=vh;D(tn,"forward",new gc.Vector3(0,0,1)),y([_(bh)],tn.prototype,"head",2),y([_(bh)],tn.prototype,"eyes",2),y([_(bh)],tn.prototype,"target",2);import{Object3D as Gm}from"three";var yx=O("debugmouth"),vr=class extends M{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){setTimeout(()=>{this.voip=R.findObjectOfType(tt,this.context),this.marker||(this.marker=R.getComponentInParent(this.gameObject,le))},3e3)}update(){if(!this.voip||this.context.time.frameCount%10!==0)return;let e=this.marker?.connectionId??null;if(!e){yx&&(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)}}}};y([_(Gm)],vr.prototype,"idle",2),y([_(Gm)],vr.prototype,"talking",2);var as=class extends M{voip=null;marker=null;_startPosition=null;awake(){this.voip=R.findObjectOfType(tt,this.context),this.marker=R.getComponentInParent(this.gameObject,le)}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 Ch={};Gh(Ch,{AlignmentConstraint:()=>Kn,Animation:()=>Lt,AnimationCurve:()=>pi,AnimationTrackHandler:()=>yr,Animator:()=>Be,AnimatorController:()=>hi,AttachedObject:()=>pt,AudioListener:()=>fi,AudioSource:()=>se,AudioTrackHandler:()=>_r,AvatarBlink_Simple:()=>en,AvatarEyeLook_Rotation:()=>tn,AvatarLoader:()=>Jn,AvatarMarker:()=>le,AvatarModel:()=>Br,Avatar_Brain_LookAt:()=>xn,Avatar_MouthShapes:()=>vr,Avatar_MustacheShake:()=>as,Avatar_POI:()=>ve,AxesHelper:()=>yn,BaseUIComponent:()=>Ge,BasicIKConstraint:()=>Ao,BoxCollider:()=>er,BoxGizmo:()=>wi,BoxHelperComponent:()=>Ue,Button:()=>$t,CallInfo:()=>mi,Camera:()=>ee,Canvas:()=>We,CanvasGroup:()=>Fn,CapsuleCollider:()=>Bt,CharacterController:()=>Bi,CharacterControllerInput:()=>gi,Collider:()=>Ut,ColorAdjustments:()=>br,ColorBySpeedModule:()=>Ci,ColorOverLifetimeModule:()=>Pn,ControlTrackHandler:()=>Dn,Deletable:()=>jo,DeleteBox:()=>Wr,DeviceFlag:()=>Nr,DragControls:()=>Wi,DropListener:()=>or,Duplicatable:()=>Ni,EmissionModule:()=>ft,EventList:()=>ue,EventListEvent:()=>Gr,EventSystem:()=>Qe,EventTrigger:()=>Qr,FieldWithDefault:()=>Zo,FixedJoint:()=>Xo,FlyControls:()=>No,GltfExport:()=>Zt,GltfExportBox:()=>cs,Gradient:()=>Ti,Graphic:()=>kt,GraphicRaycaster:()=>ys,GridHelper:()=>Rn,GridLayoutGroup:()=>vs,GroundProjectedEnv:()=>Sn,HingeJoint:()=>sr,HorizontalLayoutGroup:()=>bs,Image:()=>Hn,InheritVelocityModule:()=>Yt,InputField:()=>Mt,Interactable:()=>Gt,Keyboard:()=>ms,LODGroup:()=>ar,LODModel:()=>Xi,LayoutGroup:()=>Bn,Light:()=>Ve,LimitVelocityOverLifetimeModule:()=>de,LogStats:()=>ls,LookAtConstraint:()=>wn,MainModule:()=>ye,MaskableGraphic:()=>jn,MeshCollider:()=>Vr,MeshRenderer:()=>Kr,MinMaxCurve:()=>U,MinMaxGradient:()=>Oe,NestedGltf:()=>qr,Networking:()=>Ei,NoiseModule:()=>Y,ObjectRaycaster:()=>so,OffsetConstraint:()=>Qi,OrbitControls:()=>it,ParticleBurst:()=>On,ParticleSubEmitter:()=>lr,ParticleSystem:()=>be,ParticleSystemRenderer:()=>qi,PlayableDirector:()=>Ln,PlayerColor:()=>mt,PointerEventData:()=>vi,RGBAColor:()=>Z,RawImage:()=>no,Raycaster:()=>oo,Rect:()=>io,RectTransform:()=>gt,ReflectionProbe:()=>Kt,RemoteSkybox:()=>Ri,Renderer:()=>ae,RendererLightmap:()=>kn,Rigidbody:()=>K,RotationBySpeedModule:()=>ze,RotationOverLifetimeModule:()=>qe,ScreenCapture:()=>ur,ShadowCatcher:()=>hr,ShapeModule:()=>ne,SignalAsset:()=>eo,SignalReceiver:()=>In,SignalReceiverEvent:()=>to,SignalTrackHandler:()=>An,Size:()=>ps,SizeBySpeedModule:()=>Pe,SizeOverLifetimeModule:()=>qt,SkinnedMeshRenderer:()=>$o,SmoothFollow:()=>Tt,SpatialHtml:()=>_s,SpatialTrigger:()=>Mn,SpatialTriggerReceiver:()=>Rt,SpectatorCamera:()=>ts,SphereCollider:()=>$n,Sprite:()=>Jt,SpriteRenderer:()=>Ji,SpriteSheet:()=>Zi,SubEmitterSystem:()=>cr,SyncedCamera:()=>fr,SyncedRoom:()=>Si,SyncedTransform:()=>wt,TeleportTarget:()=>Xr,TestRunner:()=>ns,TestSimulateUserData:()=>rs,Text:()=>ke,TextureSheetAnimationModule:()=>_e,ToneMapping:()=>gr,TrailModule:()=>te,TransformGizmo:()=>Jr,UIRaycastUtils:()=>_i,UIRootComponent:()=>En,UsageMarker:()=>Vt,VRUserState:()=>Xt,VelocityOverLifetimeModule:()=>je,VerticalLayoutGroup:()=>gs,VideoPlayer:()=>Ce,Voip:()=>tt,Volume:()=>Zr,VolumeComponent:()=>$i,VolumeParameter:()=>os,VolumeProfile:()=>mr,WebAR:()=>rr,WebARSessionRoot:()=>Wt,WebXR:()=>V,WebXRAvatar:()=>Nt,WebXRController:()=>J,WebXRSync:()=>Cn,XRFlag:()=>Ee,XRGrabModel:()=>$r,XRGrabRendering:()=>ss,XRRig:()=>nr,XRState:()=>Et,__Ignore:()=>ma});var _x=O("logstats"),ls=class extends M{onEnable(){console.log(this),_x&&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{GLTFExporter as Ex}from"three/examples/jsm/exporters/GLTFExporter.js";import{BufferAttribute as yh,Matrix4 as xx,Vector3 as Vm,Quaternion as wx}from"three";var ua=class{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;let i=this.writer,n=i.extensionsUsed,r={};t.extensions=t.extensions||{},t.extensions[this.name]=r;let s=new xx,a=new Array,c=new Array,d=new Array;for(let b=0;b<e.count;b++){e.getMatrixAt(b,s);let w=new Vm,v=new wx,x=new Vm;s.decompose(w,v,x),a.push(w.x,w.y,w.z),c.push(v.x,v.y,v.z,v.w),d.push(x.x,x.y,x.z)}let l=new Float32Array(a),u=new Float32Array(c),h=new Float32Array(d);r.attributes={TRANSLATION:i.processAccessor(new yh(l,3)),ROTATION:i.processAccessor(new yh(u,4)),SCALE:i.processAccessor(new yh(h,3))},n[this.name]=!0}};import{Object3D as Cx,Vector3 as Tx}from"three";var cs=class extends Ue{sceneRoot;start(){this.startCoroutine(this.updateGltfBox())}*updateGltfBox(){for(;;)for(let e=0;e<10;e++)yield}},Zt=class extends M{binary=!0;objects=[];exporter;ext;async exportNow(e){console.log("DO EXPORT",this.objects);let t={binary:this.binary,pivot:Zt.calculateCenter(this.objects)},i=await this.export(this.objects,t);this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?Zt.saveArrayBuffer(i,e):Zt.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 Ex,this.exporter.register(a=>new ua(a)),this.ext=new Io,this.ext.registerExport(this.exporter)),Zt.filterTopmostParent(e);let i={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:t?.binary??!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:Zt.collectAnimations(e)},n=new Cx;t?.pivot&&n.position.sub(t.pivot),console.log("EXPORT",e),e.forEach(a=>{a&&(n.children.push(a),a.matrixAutoUpdate=!1,a.matrix.copy(a.matrixWorld),R.getComponentsInChildren(a,ae).forEach(c=>{R.isActiveInHierarchy(c.gameObject)&&c.setInstancingEnabled(!1)}))});let r=new fo(n);return this.ext.context=r,new Promise((a,c)=>{try{this.exporter?.parse(n,d=>{s(),a(d)},d=>{s(),c(d)},i)}catch(d){console.error(d),c(d)}finally{console.log("FINALLY")}});function s(){e.forEach(a=>{!a||(a.matrixAutoUpdate=!0,R.getComponentsInChildren(a,ae).forEach(c=>{R.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 Tx;return i.set(0,0,0),e.forEach(n=>{i.add(B(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*as Nm from"three";var eo=class{guid},to=class{signal;reaction;$serializedTypes={signal:eo,reaction:ue}},In=class extends M{events;start(){console.log(this)}invoke(e){if(!this.events||!Array.isArray(this.events))return;let t=typeof e=="object"?e.guid:e;for(let i of this.events)if(i.signal.guid===t)try{if(i.reaction){if(!i.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",i,this);continue}}else{console.warn("Missing reaction for signal",i,this);continue}i.reaction.invoke()}catch(n){console.error(n)}}};y([_(to)],In.prototype,"events",2);import*as $ from"three";import{Quaternion as Rx,Vector3 as Sx}from"three";var ds=O("debugtimeline"),us=class{director;track;get muted(){return this.track.muted}set muted(e){e!==this.track.muted&&(this.track.muted=e,this.onMuteChanged?.call(this))}*forEachClip(e=!1){if(!!this.track?.clips)if(e)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(let t of this.track.clips)yield t}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,i,n=!0){if(t<0||t>=i.length)return 0;let r=i[t];if(n||e>=r.start&&e<=r.end){let s=1,a=!1;if(r.easeInDuration>0){let c=Math.min((e-r.start)/r.easeInDuration,1);s*=c}if(r.easeOutDuration>0&&!a){let c=Math.min((r.end-e)/r.easeOutDuration,1);s*=c}return s}return 0}},_h=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";ds&&console.log(t.name,t.tracks,n);for(let s of t.tracks)if(!(s.times.length<=0)){if(s.name.endsWith(n))this.rootStartPosition=new $.Vector3().fromArray(s.values,0),this.rootEndPosition=new $.Vector3().fromArray(s.values,s.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),ds&&console.log(this.rootPositionOffset);else if(s.name.endsWith(r)&&(this.rootStartQuaternion=new $.Quaternion().fromArray(s.values,0),this.rootEndQuaternion=new $.Quaternion().fromArray(s.values,s.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),ds)){let a=new $.Euler().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",a)}}}},yr=class extends us{models=[];trackOffset;target;mixer;clips=[];actions=[];_actionOffsets=[];_didBind=!1;createHooks(e,t){if(t.tracks?.length<=0){console.warn("No tracks in AnimationClip",t);return}let i=t.tracks[0].name.split("."),n=i[i.length-2],r=n+".position",s=n+".quaternion",a=!1,c=!1;for(let d of t.tracks)d.name.endsWith(r)?(a=!0,this.createPositionInterpolant(t,e,d)):d.name.endsWith(s)&&(c=!0,this.createRotationInterpolant(t,e,d));if(!a||!c){let d=this.mixer?.getRoot(),l=t.tracks[0],u=l.name.lastIndexOf("."),h=l.name.substring(0,u),b=h.substring(h.lastIndexOf(".")+1),w=d.getObjectByName(b);if(w)if(a){if(!c){let v=t.tracks[0].name.substring(0,u)+".quaternion";ds&&console.warn("Create quaternion track",b,w);let x=w.quaternion,m=new $.QuaternionKeyframeTrack(v,[0,t.duration],[x.x,x.y,x.z,x.w,x.x,x.y,x.z,x.w]);t.tracks.push(m),this.createRotationInterpolant(t,e,m)}}else{let v=h+".position";ds&&console.warn("Create position track",b,w);let x=w.position,m=new $.VectorKeyframeTrack(v,[0,t.duration],[x.x,x.y,x.z,x.x,x.y,x.z]);t.tracks.push(m),this.createPositionInterpolant(t,e,m)}}}bind(){if(!this._didBind){this._didBind=!0,ds&&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 _h(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 Sx(i.x,i.y,i.z)),n.isQuaternion||(t.rotation=new Rx(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 $.Vector3(e.x,e.y,e.z)));let t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new $.Quaternion(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new $.Vector3;_totalOffsetRotation=new $.Quaternion;_totalOffsetPosition2=new $.Vector3;_totalOffsetRotation2=new $.Quaternion;_summedPos=new $.Vector3;_tempPos=new $.Vector3;_summedRot=new $.Quaternion;_tempRot=new $.Quaternion;evaluate(e){if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let t=0,i=0,n=!1;for(let r=0;r<this.clips.length;r++){let s=this.models[r],a=this.actions[r],c=s.asset;a.weight=0;let d=e>=s.start&&e<=s.end,l=s.postExtrapolationMode,u=d;if(!u&&!n&&s.end<e&&s.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 b=this.getClipTime(e,s),w=0,v=c.duration;if(d){if(c.loop)for(w+=Math.floor(b/(v+1e-6));b>v;)b-=v}else if(!d)switch(l){case 2:b%=v;break;case 3:let f=Math.floor(b/v)%2!==0;b%=v,f&&(b=v-b);break}a.time=b,a.timeScale=0;let x=h*this.director.weight;if(a.weight=x,a.clampWhenFinished=!0,a.isRunning()||a.play(),this._useclipOffsets){let m=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,f=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-h),t+=1;let p=this._summedPos.set(0,0,0),g=this._tempPos.set(0,0,0),E=this._summedRot.identity(),C=this._tempRot.identity(),T=c.rotation,S=new $.Quaternion;S.slerp(T,h);let I=this._actionOffsets[r];if(I.hasOffsets)for(let A=0;A<w;A++)I.rootPositionOffset?g.copy(I.rootPositionOffset):g.set(0,0,0),g.applyQuaternion(E).applyQuaternion(S),I.rootQuaternionOffset&&(C.copy(I.rootQuaternionOffset),E.multiply(C)),p.add(g);f.multiply(S),f.multiply(E),p.add(c.position),m.add(p)}}}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 $.Quaternion;this.ensureTrackOffsets();let s=this.trackOffset?.rotation;i.createInterpolant=()=>{let a=n(),c=a.evaluate.bind(a);return a.evaluate=d=>{let l=c(d);return r.set(l[0],l[1],l[2],l[3]),r.premultiply(this._totalOffsetRotation),s&&r.premultiply(s),l[0]=r.x,l[1]=r.y,l[2]=r.z,l[3]=r.w,l},a}}createPositionInterpolant(e,t,i){let n=i.createInterpolant.bind(i),r=new $.Vector3;this.ensureTrackOffsets();let s=this.trackOffset?.rotation,a=this.trackOffset?.position,c;i.createInterpolant=()=>{let d=n(),l=d.evaluate.bind(d);return d.evaluate=u=>{let h=l(u);return r.set(h[0],h[1],h[2]),t.removeStartOffset&&(c===void 0?(c=null,c=this._actionOffsets.find(b=>b.clip===e)?.rootStartPosition?.clone()):c?.isVector3&&r.sub(c)),r.applyQuaternion(this._totalOffsetRotation),r.add(this._totalOffsetPosition),s&&r.applyQuaternion(s),a&&(r.x-=a.x,r.y+=a.y,r.z+=a.z),h[0]=r.x,h[1]=r.y,h[2]=r.z,h},d}}},_r=class extends us{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;getAudioFilePath(e){let t=this.director.sourceId;return Oi(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 $.Audio(this.listener);i.setVolume(e.asset.volume);let n=new $.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;if(i.easeInDuration>0){let s=Math.min((e-i.start)/i.easeInDuration,1);r*=s}if(i.easeOutDuration>0){let s=Math.min((i.end-e)/i.easeOutDuration,1);r*=s}n.setVolume(r*this.director.weight)}else n.isPlaying&&n.stop()}this.lastTime=e}}},An=class extends us{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 a of this.receivers)!a||a.invoke(i.asset)}}else i.emitOnce||(this.didTrigger[t]=!1)}}},ha=class extends us{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;ha.resolved[r]?n.sourceObject=ha.resolved[r]:(n.sourceObject=R.findByGuid(r,e.scene),ha.resolved[r]=n.sourceObject)}if(n.sourceObject){let r=R.getComponent(n.sourceObject,Ln);this.timelines.push(r),r&&n.updateDirector&&(r.playOnAwake=!1)}else{this.models.splice(t,1);continue}}}_previousActiveModel=null;evaluate(e){this._previousActiveModel=null;for(let t=0;t<this.models.length;t++){let i=this.models[t],n=i.asset;if(e>=i.start&&e<=i.end){this._previousActiveModel=i;let r=this.getClipTime(e,i);if(n.controlActivation){let s=n.sourceObject;s.visible=!0}if(n.updateDirector){let s=this.timelines[t];s&&(s.isPlaying&&s.pause(),s.time=r,s.evaluate())}}else{let r=this._previousActiveModel?.asset;if(n.controlActivation){let s=n.sourceObject;r?.sourceObject!==s&&(s.visible=!1)}}}}},Dn=ha;D(Dn,"resolved",{});var Wm=O("debugtimeline");var bc=class extends M{static registerCreateTrack(e,t){this.createTrackFunctions[e]=t}playableAsset;playOnAwake;extrapolationMode=1;get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(e){this._time=e}get duration(){return this._duration}set duration(e){this._duration=e}get weight(){return this._weight}set weight(e){this._weight=e}_visibilityChangeEvt;_clonedPlayableAsset=!1;awake(){Wm&&console.log(this,this.playableAsset?.tracks),this.rebuildGraph(),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.activeAndEnabled;)!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 a of t.clips)a.start<=e&&e<=a.end&&(r=!0);let s=n;s.visible!==void 0&&(s.visible=r)}}break}for(let t of this._animationTracks)t.evaluate(e);for(let t of this._audioTracks)t.evaluate(e);for(let t of this._signalTracks)t.evaluate(e);for(let t of this._controlTracks)t.evaluate(e);for(let t of this._customTracks)t.evaluate(e)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Ss(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=R.findByGuid(n,e);r===null||typeof r!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(Wm&&console.log("Resolved binding",n,"to",r),t.outputs[i]=r,r instanceof Be)}else if(n===null){if(t.outputs.splice(i,1),bc.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=bc.createTrackFunctions[i];if(n!=null){let r=n(this,t);if(typeof r.evaluate=="function"){r.director=this,r.track=t,this._customTracks.push(r);continue}}if(t.type==="AnimationTrack"){if(t.clips.length<=0)continue;for(let r=t.outputs.length-1;r>=0;r--){let s=t.outputs[r];typeof s.enabled=="boolean"&&(s.enabled=!1);let a=s?.gameObject?.animations;if(a){let c=new yr;c.trackOffset=t.trackOffset,c.director=this,c.track=t;for(let d=0;d<t.clips.length;d++){let l=t.clips[d],u=l.asset;if(!u){console.error("MISSING anim model?","clip#"+d,l,t,this.playableAsset,this.name);continue}let h=u.clip,b=h;if((typeof b=="string"||typeof b=="number")&&(b=a.find(v=>v.name===h)),!b){console.warn("Could not find animationClip for model",l,t.name,this.name,this.playableAsset?.name);continue}c.mixer||(c.mixer=new Nm.AnimationMixer(s.gameObject)),c.clips.push(b),c.mixer.uncacheAction(b),c.createHooks(l.asset,b);let w=c.mixer.clipAction(b);c.actions.push(w),c.models.push(l)}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 An;r.director=this,r.track=t;for(let s of t.markers)switch(s.type){case"SignalEmitter":r.models.push(s),r.didTrigger.push(!1);break}if(r!==null&&r.models.length>0){let s=R.getComponent(this.gameObject,In);s&&(r.receivers.push(s),this._signalTracks.push(r))}}else if(t.type==="SignalTrack"){let r=new An;r.director=this,r.track=t;for(let s of t.markers)r.models.push(s),r.didTrigger.push(!1);for(let s of t.outputs)r.receivers.push(s);this._signalTracks.push(r)}else if(t.type==="ControlTrack"){let r=new Dn;r.director=this,r.track=t;for(let s of t.clips)r.models.push(s);r.resolveSourceObjects(this.context),this._controlTracks.push(r)}}se.registerWaitForAllowAudio(()=>{let t=R.findObjectOfType(fi,this.context);if(!!t)for(let i of e){let n=new _r;n.director=this,n.track=i,n.listener=t.listener;for(let r=0;r<i.clips.length;r++){let s=i.clips[r];n.addModel(s)}this._audioTracks.push(n)}})}setAudioTracksAllowPlaying(e){for(let t of this._audioTracks)t.onAllowAudioChanged(e)}},Ln=bc;D(Ln,"createTrackFunctions",{});import{Color as Mx,Texture as Jm}from"three";import*as wh from"three-mesh-ui";import{Matrix4 as Ox,Object3D as kx,Vector2 as Ym,Vector3 as xh}from"three";import{FrontSide as Xm,DoubleSide as Qm}from"three";function hs(o,e){if(!o)return;let t=o.material;t?.isMaterial===!0&&(t.depthTest=!e.renderOnTop,t.side=e.doubleSided??!0?Qm:Xm,t.depthWrite=e.depthWrite??!1,t.shadowSide=e.doubleSided?Qm:Xm,o.castShadow=e.castShadows?e.castShadows:!1,o.receiveShadow=e.receiveShadows?e.receiveShadows:!1);for(let i of o.children)hs(i,e)}function vc(o,e,t){o[e]===void 0&&console.warn("Field",e,"is undefined on",o);let i=Proxy.revocable(o[e],{set(s,a,c,d){let l=s[a],u=Reflect.set(s,a,c,d);return t(c,l),u}}),n=i.revoke,r=o[e];return i.revoke=()=>{o[e]=r,n()},o[e]=i.proxy,i}function qm(o,e,t=3){let i=o.__scheduledActions;i||(i=o.__scheduledActions={});let n=e.name;i[t]||(i[t]={});let r=i[t];if(r[n])return;function*a(){e?.call(o),r[n]=null}let c=o.startCoroutine(a(),t);r[n]=c}var Km=O("debugui"),ps=class{width;height},io=class{x;y;width;height},gt=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 xh),this._anchoredPosition}rect;sizeDelta;anchoredPosition3D;pivot;lastMatrix;rectBlock;_transformNeedsUpdate=!1;awake(){super.awake(),this.lastMatrix=new Ox,this.rectBlock=new kx,this.rectBlock.position.z=.1,this.rectBlock.name=this.name,this._anchoredPosition||(this._anchoredPosition=new xh),vc(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)&&(Km&&console.log("updating",this.name),this.applyTransform()),Qe.ensureUpdateMeshUI(wh,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},Km&&console.log(this.name,e);let t=new wh.Block(e);return this._createdBlocks.push(t),t}};y([_(io)],gt.prototype,"rect",2),y([_(Ym)],gt.prototype,"sizeDelta",2),y([_(xh)],gt.prototype,"anchoredPosition3D",2),y([_(Ym)],gt.prototype,"pivot",2);var kt=class extends Ge{get isGraphic(){return!0}get color(){return this._color||(this._color=new Z(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 Z(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=R.getComponent(this.gameObject,gt)),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(),vc(this,"_color",()=>qm(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)}};y([_(Z)],kt.prototype,"color",1),y([_()],kt.prototype,"raycastTarget",2);var jn=class extends kt{onAfterCreated(){this.uiObject&&(this.uiObject.scale.y*=-1)}};var yc=class{texture;rect};y([_(Jm)],yc.prototype,"texture",2);var Hn=class extends jn{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 Mx(.4,.4,.4),e.borderOpacity=this.color.alpha,e.borderWidth=.3)}onAfterCreated(){super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture)}};y([_(yc)],Hn.prototype,"sprite",2);var no=class extends jn{mainTexture;onAfterCreated(){super.onAfterCreated(),this.setTexture(this.mainTexture)}};y([_(Jm)],no.prototype,"mainTexture",2);var fs=O("debugbutton");var $t=class extends M{onClick;_isHovered=!1;onPointerEnter(e){fs&&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"),this.context.input.setCursorPointer()}onPointerExit(){fs&&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"),this.context.input.setCursorNormal()}onPointerDown(e){fs&&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){fs&&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){fs&&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(),fs&&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=R.getComponent(this.gameObject,Hn),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){e.setInteractable(this.interactable);let t=this.getFinalColor(e.color,this.colors?.normalColor),i={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(i);let n=this.getFinalColor(e.color,this.colors?.highlightedColor),r={state:"hovered",attributes:{backgroundColor:n,backgroundOpacity:n.alpha}};e.setupState(r);let s=this.getFinalColor(e.color,this.colors?.pressedColor),a={state:"pressed",attributes:{backgroundColor:s,backgroundOpacity:s.alpha}};e.setupState(a);let c=this.getFinalColor(e.color,this.colors?.selectedColor),d={state:"selected",attributes:{backgroundColor:c,backgroundOpacity:c.alpha}};e.setupState(d);let l=this.getFinalColor(e.color,this.colors?.disabledColor),u={state:"disabled",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(u)}getFinalColor(e,t){return t?e.clone().multiply(t):e.clone()}};y([_(ue)],$t.prototype,"onClick",2),y([_()],$t.prototype,"colors",2),y([_()],$t.prototype,"transition",2),y([_()],$t.prototype,"animationTriggers",2),y([_(Be)],$t.prototype,"animator",2),y([_()],$t.prototype,"interactable",1);var Eh=class extends En{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 Eh||(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(),hs(this.shadowComponent,this);for(let e of R.getComponentsInChildren(this.gameObject,Ge))hs(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(H.toRadians(e.fieldOfView)*n)*(e.aspect*1.333333),s=r*(this.context.domHeight/this.context.domWidth);t.scale.x=-r,t.scale.y=s;break;case 2:break}}},We=Eh;y([_()],We.prototype,"renderOnTop",1),y([_()],We.prototype,"depthWrite",1),y([_()],We.prototype,"doubleSided",1),y([_()],We.prototype,"castShadows",1),y([_()],We.prototype,"receiveShadows",1),y([_()],We.prototype,"renderMode",1),y([_(We)],We.prototype,"rootCanvas",1),y([_()],We.prototype,"scaleFactor",1);var Fn=class extends M{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 R.getComponentsInChildren(this.gameObject,kt,this._buffer)){let t=e.color;t.alpha=this._alpha,e.color=t}}};y([_()],Fn.prototype,"alpha",1),y([_()],Fn.prototype,"interactable",2),y([_()],Fn.prototype,"blocksRaycasts",2);import*as Zm from"three-mesh-ui";import{Color as L}from"three";var Ix=O("debugtext");var ke=class extends kt{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){Ix&&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 s=e.createNewBlock(r);return i&&(Array.isArray(i)?s.add(...i):s.add(i)),s}getAlignment(e,t=!1){switch(t||(e.contentDirection="row"),this.alignment){default:case 0:case 1:case 2:e.justifyContent="start";break;case 3:case 4:case 5:e.justifyContent="center";break;case 6:case 7:case 8:e.justifyContent="end";break}switch(this.alignment){case 0:case 3:case 6:e.alignContent=t?"left":"top";break;case 1:case 4:case 7:e.alignContent="center";break;case 2:case 5:case 8:e.alignContent=t?"right":"bottom";break}return e}updateWidth(){this.horizontalOverflow===1&&setTimeout(()=>{if(!this._textMeshUi)return;let e=this._textMeshUi[0].parent;if(!!e&&e.lines){let t=e.lines.reduce((i,n)=>i+n.width,0);t+=e.getFontSize()*5,t+=e.padding*2||0,t+=this.fontSize*1.5,e.set({width:t}),this.ensureShadowComponentOwner()}},1)}ensureShadowComponentOwner(){this.shadowComponent&&this.shadowComponent.traverse(e=>{e[Ct]===void 0&&(e[Ct]=this)})}createText(e,t,i){if(!(!e||e.length<=0))if(this._textMeshUi||(this._textMeshUi=[]),i){let n=this.getNextTag(e);if(n)n.startIndex>0&&this.createText(e.substring(0,n.startIndex),t,!1);else return this.createText(e,t,!1);let r=[];for(;n;){let s=this.getNextTag(e,n.endIndex);if(s){let a=this.getText(e,n,s);this.handleTag(n,t,r),this.createText(a,t,!1)}else{let a=e.substring(n.endIndex);this.handleTag(n,t,r),this.createText(a,t,!1)}n=s}}else{let n={...t};n.content=e;let r=new Zm.Text(n);this._textMeshUi.push(r),this._textContainer&&this._textContainer.add(r)}}_didHandleTextRenderOnTop=!1;handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;let e=[],t=this.canvas,i={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let n=!1;if(this._textMeshUi)for(let r=0;r<this._textMeshUi.length;r++){if(e[r]===!0)continue;n=!0;let s=this._textMeshUi[r];!s.textContent||(hs(s,i),e[r]=!0)}if(!n)break;yield}}handleTag(e,t,i){if(e.isEndTag){if(i.length>0){let n=i.pop();if(n)for(let r in n.previousValues){let s=n.previousValues[r];t[r]=s}}}else if(e.type.includes("color")){let n=new pa(e,{fontColor:t.fontColor});if(i.push(n),e.type.length>6){let r=e.type.substring(6);t.fontColor=Dx(r)}else t.fontColor=new L(1,1,1)}else if(e.type=="b"){let n=new pa(e,{fontFamily:t.fontFamily,fontTexture:t.fontTexture});i.push(n),this.setFont(t,1)}else if(e.type=="i"){let n=new pa(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=Oi(this.sourceId,this.font),this.font):null}};y([_(We)],ke.prototype,"canvas",2),y([_()],ke.prototype,"alignment",2),y([_()],ke.prototype,"verticalOverflow",2),y([_()],ke.prototype,"horizontalOverflow",2),y([_()],ke.prototype,"lineSpacing",2),y([_()],ke.prototype,"supportRichText",2),y([_()],ke.prototype,"font",2),y([_()],ke.prototype,"fontStyle",2),y([_()],ke.prototype,"text",1),y([_()],ke.prototype,"fontSize",1);var pa=class{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}};function Dx(o){if(o.startsWith("#")){let t=o.substring(1);var e=parseInt(t,16);let i=e>>16&255,n=e>>8&255,r=e&255;return new L(i/255,n/255,r/255)}switch(o){case"black":return new L(0,0,0);case"white":return new L(1,1,1);case"red":return new L(1,0,0);case"lime":return new L(0,1,0);case"blue":return new L(0,0,1);case"yellow":return new L(1,1,0);case"cyan":return new L(0,1,1);case"magenta":return new L(1,0,1);case"silver":return new L(.75,.75,.75);case"gray":return new L(.5,.5,.5);case"maroon":return new L(.5,0,0);case"olive":return new L(.5,.5,0);case"green":return new L(0,.5,0);case"purple":return new L(.5,0,.5);case"teal":return new L(0,.5,.5);case"navy":return new L(0,0,.5);case"darkred":return new L(.54,0,0);case"brown":return new L(.55,.27,0);case"firebrick":return new L(.69,.13,.13);case"crimson":return new L(.86,.08,.24);case"tomato":return new L(1,.39,.28);case"coral":return new L(1,.49,.31);case"indianred":return new L(.6,.31,.51);case"lightcoral":return new L(.94,.5,.5);case"darkorange":return new L(1,.55,0);case"orange":return new L(1,.65,0);case"gold":return new L(1,.84,0);case"darkgoldenrod":return new L(.72,.53,.04);case"goldenrod":return new L(.85,.65,.13);case"palegoldenrod":return new L(.93,.87,.67);case"darkkhaki":return new L(.74,.7,.42);case"khaki":return new L(.94,.9,.55);case"yellowgreen":return new L(.6,.8,.19);case"darkolivegreen":return new L(.33,.42,.18);case"olivedrab":return new L(.42,.56,.14);case"lawngreen":return new L(.49,.99,0);case"chartreuse":return new L(.5,1,0);case"greenyellow":return new L(.68,1,.18);case"darkgreen":return new L(0,.39,0);case"forestgreen":return new L(.13,.55,.13);case"limegreen":return new L(.19,.8,.19);case"lightgreen":return new L(.56,.93,.56);case"palegreen":return new L(.59,.98,.59);case"darkseagreen":return new L(.56,.74,.56);case"mediumspringgreen":return new L(0,.98,.6);case"springgreen":return new L(0,1,.5);case"seagreen":return new L(.18,.31,.31);case"mediumaquamarine":return new L(.4,.8,.66);case"mediumseagreen":return new L(.24,.7,.44);case"lightseagreen":return new L(.13,.7,.67);case"darkslategray":return new L(.18,.31,.31);case"darkcyan":return new L(0,.55,.55);case"aqua":return new L(0,1,1);case"lightcyan":return new L(.8,1,1);case"darkturquoise":return new L(0,.81,.82);case"turquoise":return new L(0,.82,.82);case"mediumturquoise":return new L(.28,.82,.8);case"paleturquoise":return new L(.68,1,.93);case"aquamarine":return new L(.5,1,.83);case"powderblue":return new L(.69,.88,.9);case"cadetblue":return new L(.37,.62,.63);case"steelblue":return new L(.27,.51,.71);case"cornflowerblue":return new L(.39,.58,.93);case"deepskyblue":return new L(0,.7,1);case"dodgerblue":return new L(.12,.56,1);case"lightblue":return new L(.68,.85,.9);case"skyblue":return new L(.53,.81,.92);case"lightskyblue":return new L(.53,.81,.98);case"midnightblue":return new L(.18,.18,.31);case"darkblue":return new L(0,0,.55);case"mediumblue":return new L(0,0,.82);case"royalblue":return new L(.25,.41,.88);case"blueviolet":return new L(.54,.17,.89);case"indigo":return new L(.29,0,.51);case"darkslateblue":return new L(.28,.24,.55);case"slateblue":return new L(.42,.35,.8);case"mediumslateblue":return new L(.48,.41,.9);case"mediumpurple":return new L(.58,.44,.86);case"darkmagenta":return new L(.55,0,.55);case"darkviolet":return new L(.58,0,.83);case"darkorchid":return new L(.6,.2,.8);case"mediumorchid":return new L(.73,.33,.83);case"thistle":return new L(.84,.75,.85);case"plum":return new L(.87,.63,.87);case"violet":return new L(.93,.51,.93);case"fuchsia":return new L(1,0,1);case"orchid":return new L(.85,.44,.84);case"mediumvioletred":return new L(.78,.08,.52);case"palevioletred":return new L(.86,.44,.58);case"hotpink":return new L(1,.4,.71);case"deeppink":return new L(1,.08,.58);case"lightpink":return new L(1,.71,.76);case"pink":return new L(1,.75,.78);case"antiquewhite":return new L(.98,.92,.84);case"beige":return new L(.96,.96,.86);case"bisque":return new L(1,.89,.77);case"blanchedalmond":return new L(1,.92,.82);case"wheat":return new L(.96,.87,.87);case"cornsilk":return new L(1,.97,.86);case"lemonchiffon":return new L(1,.98,.8);case"lightgoldenrodyellow":return new L(.98,.98,.82);case"lightyellow":return new L(1,1,.8);case"saddlebrown":return new L(.55,.27,.07);case"sienna":return new L(.63,.32,.18);case"chocolate":return new L(.82,.41,.12);case"peru":return new L(.82,.52,.25);case"sandybrown":return new L(.96,.64,.38);case"burlywood":return new L(.87,.72,.53);case"tan":return new L(.82,.71,.55);case"rosybrown":return new L(.74,.56,.56);case"moccasin":return new L(1,.89,.71);case"navajowhite":return new L(1,.87,.68);case"peachpuff":return new L(1,.85,.73);case"mistyrose":return new L(1,.89,.88);case"lavenderblush":return new L(1,.94,.93);case"linen":return new L(.98,.94,.9);case"oldlace":return new L(.99,.96,.9);case"papayawhip":return new L(1,.94,.84);case"seashell":return new L(1,.96,.93);case"mintcream":return new L(.98,1,.98);case"slategray":return new L(.44,.5,.56);case"lightslategray":return new L(.47,.53,.6);case"lightsteelblue":return new L(.69,.77,.87);case"lavender":return new L(.9,.9,.98);case"floralwhite":return new L(1,.98,.98);case"aliceblue":return new L(.94,.97,1);case"ghostwhite":return new L(.97,.97,1);case"honeydew":return new L(.94,1,.94);case"ivory":return new L(1,1,.94);case"azure":return new L(.94,1,1);case"snow":return new L(1,.98,.98);case"dimgray":return new L(.4,.4,.4);case"darkgray":return new L(.66,.66,.66);case"lightgray":return new L(.83,.83,.83);case"gainsboro":return new L(.86,.86,.86);case"whitesmoke":return new L(.96,.96,.96)}return new L(1,1,1)}var ro=O("debuginputfield"),N=class extends M{get text(){return this.textComponent?.text??""}get isFocused(){return N.active===this}textComponent;placeholder;onValueChanged;onEndEdit;inputEventFn;start(){ro&&console.log(this.name,this)}onEnable(){N.htmlField||(N.htmlField=document.createElement("input"),N.htmlField.classList.add("ar"),document.body.appendChild(N.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),N.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&R.setActive(this.placeholder.gameObject,!1)}onDisable(){N.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected()}onPointerClick(e){ro&&console.log("CLICK",e,N.active),N.activeTime=this.context.time.time,N.active!==this&&this.startCoroutine(this.activeLoop(),2),this.selectInputField()}*activeLoop(){for(this.onSelected();N.active===this&&!(this.context.input.getPointerUp(0)&&this.context.time.time-N.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(N.active!==this&&(ro&&console.log("Select",this.name,this,N.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,N.htmlField?.value),N.active?.onDeselected(),N.active=this,this.placeholder&&R.setActive(this.placeholder.gameObject,!1),N.htmlField)){if(N.htmlField.value=this.textComponent?.text||"",ro&&console.log("set input field value",N.htmlField.value),this.context.isInXR){let e=this.context.arOverlayElement;e&&(N.htmlField.style.width="0px",N.htmlField.style.height="0px",e.append(N.htmlField))}this.selectInputField()}}onDeselected(){N.active===this&&(N.active=null,ro&&console.log("Deselect",this.name,this),N.htmlField&&(N.htmlField.blur(),document.body.append(N.htmlField),N.htmlField.style.width="",N.htmlField.style.height=""),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&R.setActive(this.placeholder.gameObject,!0),this.onEndEdit?.invoke())}onInput(e){if(N.active===this){if(ro&&console.log(e.code,e,N.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}N.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&R.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&N.htmlField){if(this.textComponent.text!==N.htmlField.value){ro&&console.log("VALUE CHANGED");let e=this.textComponent.text,t=N.htmlField.value;this.onValueChanged?.invoke(t,e)}this.textComponent.text=N.htmlField.value}}selectInputField(){N.htmlField&&(N.htmlField.setSelectionRange(N.htmlField.value.length,N.htmlField.value.length),N.htmlField.focus())}},Mt=N;D(Mt,"active",null),D(Mt,"activeTime",-1),D(Mt,"htmlField",null),y([_(ke)],Mt.prototype,"textComponent",2),y([_(ke)],Mt.prototype,"placeholder",2),y([_(ue)],Mt.prototype,"onValueChanged",2),y([_(ue)],Mt.prototype,"onEndEdit",2);import*as $m from"three-mesh-ui";import*as fa from"three";var eg=(a=>(a[a.fr=0]="fr",a[a.ru=1]="ru",a[a.de=2]="de",a[a.es=3]="es",a[a.el=4]="el",a[a.nord=5]="nord",a[a.eng=6]="eng",a))(eg||{}),ms=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=eg[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=R.getComponent(this.gameObject,gt);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:zo+"/"+t+"-msdf.json",fontTexture:zo+"/"+t+".png",fontSize:this.fontSize||6,backgroundColor:new fa.Color(this.colors.keyboardBack),backspaceTexture:zo+"/backspace.png",shiftTexture:zo+"/shift.png",enterTexture:zo+"/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 $m.Keyboard(n),this.gameObject.scale.set(1,1,1),this.keyboard.keys.forEach(s=>{s.setupState({state:"normal",attributes:{offset:.003,backgroundColor:new fa.Color(this.colors.button),backgroundOpacity:1}}),s.setState("normal"),s.setupState({state:"hovered",attributes:{offset:.3,backgroundColor:new fa.Color(this.colors.hovered),backgroundOpacity:1}}),s.setupState({state:"pressed",attributes:{offset:.1,backgroundColor:new fa.Color(this.colors.selected),backgroundOpacity:1},onSet:()=>{let a=s.info.input,c=s.info.command;if(this._lastKeyPressed!==a)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=a,c)switch(c){case"switch":this.keyboard.setNextPanel();break;case"switch-set":this.keyboard.setNextCharset();break;case"enter":this.tryAppend(`
308
+ `);break;case"space":this.tryAppend(" ");break;case"backspace":if(!this.text?.text?.length)break;this.text?.text&&(this.text.text=this.text.text.substring(0,this.text.text.length-1)||"");break;case"shift":this.keyboard.toggleCase();break}else s.info.input!==void 0&&this.tryAppend(s.info.input)}})})}tryAppend(e){this.text&&(this.text.text+=e,this.markDirty())}};var Bn=class extends M{reverseArrangement=!1},gs=class extends Bn{},bs=class extends Bn{},vs=class extends Bn{};var oo=class extends M{awake(){Qe.createIfNoneExists(this.context)}onEnable(){Qe.instance?.register(this)}onDisable(){Qe.instance?.unregister(this)}performRaycast(e=null){return null}},so=class extends oo{targets=null;raycastHits=[];start(){this.targets=[this.gameObject]}performRaycast(e=null){return this.targets?(e??=new ge,e.targets=this.targets,e.results=this.raycastHits,this.context.physics.raycast(e)):null}},ys=class extends so{};import*as tg from"three";import{HTMLMesh as Ax}from"three/examples/jsm/interactive/HTMLMesh.js";import{InteractiveGroup as Lx}from"three/examples/jsm/interactive/InteractiveGroup.js";var _s=class extends M{id=null;keepAspect=!1;start(){if(!this.id||!this.context.mainCamera)return;let e=document.getElementById(this.id);if(!e){console.warn('Could not find element with id "'+this.id+'"');return}e.style.display="block",e.style.visibility="hidden";let t=new Lx(this.context.renderer,this.context.mainCamera);this.gameObject.add(t);let i=new Ax(e);t.add(i),i.visible=!1,console.log(i);let n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;let r=La(this.gameObject).clone();ja(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();let s=new tg.Box3;s.setFromObject(t),this.setWorldRotation(r.x,r.y,r.z);let a=s.max.x-s.min.x,c=s.max.y-s.min.y;if(this.keepAspect){let l=a/c;a>c?i.scale.set(1/a,1/c/l,1):i.scale.set(1/a*l,1/c,1)}else i.scale.set(1/a,1/c,1);let d=this.gameObject.scale;i.scale.multiply(d)},1)}};var ma=class{};var _c=class extends M{toggleKey="p";update(){this.context.input.isKeyDown("p")&&this.context.domElement.classList.toggle("presentation-mode")}};import*as ig from"three";import{Raycaster as Fx,Vector3 as Bx}from"three";import*as xc from"three";import{MeshLine as jx,MeshLineMaterial as Hx}from"three.meshline";var Th=class{id=0;points=[];line=new jx;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 xc.Mesh(this.line,this.material),e.add(this.mesh)}appendPoint(e){let t=Th.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 Hx({color:10066329,lineWidth:.01})},xs=Th;D(xs,"wp",new xc.Vector3);var ao=class extends M{startLine(e,t){let i=Math.random()*Number.MAX_SAFE_INTEGER;return this.internalStartLine(e,i,!0,t)}updateLine(e,t){let i=this.inFlight[e.id];if(!i)return;t.point&&(t.point=i.appendPoint(t.point));let n=this.buffer[e.id];n&&(t.point&&n.push(t.point.x,t.point.y,t.point.z),n.length>5&&(this.sendLineUpdate(i,!1,void 0,n),n.length=0))}endLine(e,t=!0){let i=this.inFlight[e.id];if(!i)return;this.finished.push(i),delete this.inFlight[e.id],t&&this.sendLineUpdate(i,!0,0);let n=this.buffer[e.id];if(n){delete this.buffer[e.id];let r=n;r.length=0,this.freeBuffer.push(r)}return i}getLine(e){return this.inFlight[e.id]}finished=[];inFlight=[];buffer={};freeBuffer=new Array;awake(){this.context.connection.beginListen("line-start",e=>{this.onEnsureLine(e.id,e.parentGuid)}),this.context.connection.beginListen("line-update",e=>{let t=this.onEnsureLine(e.guid,e.parentGuid);t&&e.points&&(e.startIndex<=0?t.points=e.points:e.startIndex>=t.points.length&&t.points.push(...e.points),t.line.setPoints(t.points),t.material.lineWidth=e.width,t.material.color.fromArray(e.color),e.finished===!0&&this.endLine({id:t.id},!1))})}onEnsureLine(e,t){if(this.inFlight[e])return this.inFlight[e];let i=R.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 xs(e??this.context.scene,n);r.id=t,this.inFlight[t]=r,i&&this.sendLineStart(r);let s;return this.freeBuffer.length<=0?s=new Array:s=this.freeBuffer.pop(),this.buffer[t]=s,{id:t}}sendLineStart(e){let t=e.mesh.parent;this.context.connection.send("line-start",{id:e.id,parentGuid:t?t.guid:void 0})}sendLineUpdate(e,t,i,n){if(e){let r={parentGuid:e.mesh.parent.guid,guid:e.id,points:n?[...n]:e.points,width:e.material.lineWidth,color:e.material.color.toArray(),startIndex:i!==void 0?i:e.points.length,finished:t};this.context.connection.send("line-update",r)}}};import{MeshLineMaterial as Ux}from"three.meshline";var wc=class{isDrawing;lastHit;currentHandle;maxDistance;prevDistance;lastParent;constructor(){this.isDrawing=!1,this.lastHit=new Bx,this.currentHandle=null,this.maxDistance=0,this.prevDistance=0,this.lastParent=null}},Ec=class extends M{lines;colliders;alignToSurface=!0;addToPaintedObject=!0;orbit;start(){this.lines||(this.lines=R.getComponent(this.gameObject,ao),this.lines||(this.lines=R.addNewComponent(this.gameObject,ao))),this.orbit=R.findObjectOfType(it,this.context)??void 0,this._states.mouse=new wc;let e={};J.addEventListener("select-start",(t,i)=>{e[t.controller.uuid]=!0}),J.addEventListener("update",(t,i)=>{if(e[t.controller.uuid]===!0){let n=t.getRay();this.updateLine(t.controller.uuid,n,!0,!1,!1)}}),J.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);Ec._raycaster.setFromCamera(t,this.context.mainCamera);let i=Ec._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 s=this._states[e];if(s||(this._states[e]=new wc,s=this._states[e]),n)s.isDrawing=!1,s.currentHandle&&(this.lines.endLine(s.currentHandle),s.currentHandle=null);else if(i){if(r)return s;let a=this.getHit(t),c=null,d=s.prevDistance;if(a)s.currentHandle||(s.maxDistance=a.distance),c=a.point,c.add(a.face.normal.multiplyScalar(.01)),s.prevDistance=a.distance;else if(s.maxDistance>0){let l=s.maxDistance;if(!s.currentHandle&&s.lastHit){let u=B(this.context.mainCamera);l=s.lastHit.distanceTo(u)}c=t.origin.add(t.direction.multiplyScalar(s.maxDistance)),s.prevDistance=s.maxDistance}if(c){if(!s.currentHandle){let l=s.lastParent??this.gameObject;this.addToPaintedObject&&a&&(l=a.object),s.lastParent=l,s.currentHandle=this.lines.startLine(l,{material:this.createRandomMaterial()})}if(this.alignToSurface&&(s.prevDistance>s.maxDistance||Math.abs(d-s.prevDistance)>.2)){let l=s.maxDistance;c=t.origin.add(t.direction.multiplyScalar(l)),s.prevDistance=l}if(s.lastHit&&s.lastHit.distanceTo(c)<s.prevDistance*.01)return s;this.lines.updateLine(s.currentHandle,{point:c}),s.lastHit.copy(c)}s.isDrawing=s.currentHandle!==null}return s}_raycastOptions=new ge;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(!!R.isActiveInHierarchy(i.object))return i}return null}createRandomMaterial(){let e;return this.context.connection.connectionId?e=mt.colorFromHashCode(mt.hashCode(this.context.connection.connectionId)):e=new ig.Color("hsl("+(Math.random()*100).toFixed(0)+", 80%, 30%)"),new Ux({color:e,lineWidth:H.lerp(.005,.01,Math.random())})}},ga=Ec;D(ga,"_raycaster",new Fx);import{Object3D as Gx}from"three";var ba=class extends M{asset;joinedRoomFunction;awake(){this.watchTabVisible(),this.joinedRoomFunction=this.onUserJoined.bind(this)}onEnable(){this.context.connection.beginListen("joined-room",this.joinedRoomFunction)}onDisable(){this.context.connection.stopListening("joined-room",this.joinedRoomFunction)}async onUserJoined(e){let t=await this.asset?.instantiateSynced({parent:this.gameObject},!0);if(t){let i=R.getComponent(t,nn);i&&(i.owner=this.context.connection.connectionId)}}watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=nn.all.length-1;t>=0;t--){let i=nn.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};y([_($e)],ba.prototype,"asset",2);var ei=class extends M{static get all(){return ei._all}static get local(){return ei._local}static isLocalPlayer(e){return e instanceof Gx?R.getComponentInParent(e,ei)?.isLocalPlayer??!1:e instanceof xt?R.getComponentInParent(e.gameObject,ei)?.isLocalPlayer??!1:!1}owner;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}awake(){this.isLocalPlayer&&ei.local.push(this),ei.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(){bo(this.gameObject,this.context.connection)}onDestroy(){if(ei.all.splice(ei.all.indexOf(this),1),this.isLocalPlayer){let e=ei._local.indexOf(this);e>=0&&ei._local.splice(e,1)}}},nn=ei;D(nn,"_all",[]),D(nn,"_local",[]),y([lc(),_()],nn.prototype,"owner",2);P.add("AlignmentConstraint",Kn);P.add("Animation",Lt);P.add("AnimationCurve",pi);P.add("Animator",Be);P.add("AnimatorController",hi);P.add("AudioListener",fi);P.add("AudioSource",se);P.add("AvatarModel",Br);P.add("AvatarLoader",Jn);P.add("AxesHelper",yn);P.add("BasicIKConstraint",Ao);P.add("BoxHelperComponent",Ue);P.add("Camera",ee);P.add("CharacterController",Bi);P.add("CharacterControllerInput",gi);P.add("Collider",Ut);P.add("SphereCollider",$n);P.add("BoxCollider",er);P.add("MeshCollider",Vr);P.add("CapsuleCollider",Bt);P.add("DeleteBox",Wr);P.add("Deletable",jo);P.add("DeviceFlag",Nr);P.add("DragControls",Wi);P.add("DropListener",or);P.add("Duplicatable",Ni);P.add("CallInfo",mi);P.add("EventListEvent",Gr);P.add("EventList",ue);P.add("EventTrigger",Qr);P.add("FlyControls",No);P.add("BoxGizmo",wi);P.add("GridHelper",Rn);P.add("GroundProjectedEnv",Sn);P.add("Interactable",Gt);P.add("UsageMarker",Vt);P.add("FixedJoint",Xo);P.add("HingeJoint",sr);P.add("Light",Ve);P.add("LODModel",Xi);P.add("LODGroup",ar);P.add("LookAtConstraint",wn);P.add("NestedGltf",qr);P.add("Networking",Ei);P.add("OffsetConstraint",Qi);P.add("OrbitControls",it);P.add("SubEmitterSystem",cr);P.add("ParticleSystemRenderer",qi);P.add("ParticleSystem",be);P.add("Gradient",Ti);P.add("MinMaxCurve",U);P.add("MinMaxGradient",Oe);P.add("MainModule",ye);P.add("ParticleBurst",On);P.add("EmissionModule",ft);P.add("ColorOverLifetimeModule",Pn);P.add("SizeOverLifetimeModule",qt);P.add("ShapeModule",ne);P.add("NoiseModule",Y);P.add("TrailModule",te);P.add("VelocityOverLifetimeModule",je);P.add("TextureSheetAnimationModule",_e);P.add("RotationOverLifetimeModule",qe);P.add("RotationBySpeedModule",ze);P.add("LimitVelocityOverLifetimeModule",de);P.add("InheritVelocityModule",Yt);P.add("SizeBySpeedModule",Pe);P.add("ColorBySpeedModule",Ci);P.add("ParticleSubEmitter",lr);P.add("PlayerColor",mt);P.add("ReflectionProbe",Kt);P.add("FieldWithDefault",Zo);P.add("Renderer",ae);P.add("MeshRenderer",Kr);P.add("SkinnedMeshRenderer",$o);P.add("RendererLightmap",kn);P.add("Rigidbody",K);P.add("ScreenCapture",ur);P.add("ShadowCatcher",hr);P.add("RemoteSkybox",Ri);P.add("SmoothFollow",Tt);P.add("SpatialTriggerReceiver",Rt);P.add("SpatialTrigger",Mn);P.add("SpectatorCamera",ts);P.add("Sprite",Jt);P.add("SpriteSheet",Zi);P.add("SpriteRenderer",Ji);P.add("SyncedCamera",fr);P.add("SyncedRoom",Si);P.add("SyncedTransform",wt);P.add("TestRunner",ns);P.add("TestSimulateUserData",rs);P.add("TransformGizmo",Jr);P.add("VideoPlayer",Ce);P.add("Voip",tt);P.add("VolumeParameter",os);P.add("VolumeComponent",$i);P.add("ToneMapping",gr);P.add("ColorAdjustments",br);P.add("VolumeProfile",mr);P.add("Volume",Zr);P.add("WebARSessionRoot",Wt);P.add("WebXR",V);P.add("WebAR",rr);P.add("AvatarMarker",le);P.add("WebXRAvatar",Nt);P.add("TeleportTarget",Xr);P.add("WebXRController",J);P.add("AttachedObject",pt);P.add("XRGrabModel",$r);P.add("XRGrabRendering",ss);P.add("XRRig",nr);P.add("VRUserState",Xt);P.add("WebXRSync",Cn);P.add("XRState",Et);P.add("XRFlag",Ee);P.add("AvatarBlink_Simple",en);P.add("AvatarEyeLook_Rotation",tn);P.add("Avatar_POI",ve);P.add("Avatar_Brain_LookAt",xn);P.add("Avatar_MouthShapes",vr);P.add("Avatar_MustacheShake",as);P.add("__Ignore",ma);P.add("LogStats",ls);P.add("GltfExportBox",cs);P.add("GltfExport",Zt);P.add("RGBAColor",Z);P.add("PlayableDirector",Ln);P.add("SignalAsset",eo);P.add("SignalReceiverEvent",to);P.add("SignalReceiver",In);P.add("AnimationTrackHandler",yr);P.add("AudioTrackHandler",_r);P.add("SignalTrackHandler",An);P.add("ControlTrackHandler",Dn);P.add("BaseUIComponent",Ge);P.add("UIRootComponent",En);P.add("Button",$t);P.add("Canvas",We);P.add("CanvasGroup",Fn);P.add("EventSystem",Qe);P.add("Graphic",kt);P.add("MaskableGraphic",jn);P.add("Image",Hn);P.add("RawImage",no);P.add("InputField",Mt);P.add("Keyboard",ms);P.add("LayoutGroup",Bn);P.add("VerticalLayoutGroup",gs);P.add("HorizontalLayoutGroup",bs);P.add("GridLayoutGroup",vs);P.add("PointerEventData",vi);P.add("Raycaster",oo);P.add("ObjectRaycaster",so);P.add("GraphicRaycaster",ys);P.add("UIRaycastUtils",_i);P.add("Size",ps);P.add("Rect",io);P.add("RectTransform",gt);P.add("SpatialHtml",_s);P.add("Text",ke);P.add("PresentationMode",_c);P.add("LinesDrawer",ga);P.add("LineInstanceHandler",xs);P.add("LinesManager",ao);P.add("PlayerSync",ba);P.add("PlayerState",nn);var ng=Te,Vx=O("debugtypestore");Vx&&console.log(P);function rg(o,e){let i=qc(o,e);return i!==void 0?i:null}var zx=new Ma;async function og(o,e,t,i=null,n){if(!t)return;let r=[],s=i;typeof s=="number"&&(s=new Ie(i));let a=new fo(t.scene);a.gltfId=e,a.context=o,a.gltf=t,a.nodeToObject=n?.nodeToObjectMap,a.implementationInformation=zx;let c=[];if(t.scenes)for(let d of t.scenes)await Sh(a,d,c,r);if(t.children)for(let d of t.children)await Sh(a,d,c,r);o.new_scripts_pre_setup_callbacks.push(()=>{for(let d of c)Wx(d,a);if(s){Rh(t,s);for(let d of t.scenes)Rh(d,s)}})}function Rh(o,e){if(e!==null&&!!o){if(o.guid=e.generateUUID(),o&&o.userData&&o.userData.components)for(let t of o.userData.components)t!==null&&(t.guid=e.generateUUID());if(o.children)for(let t of o.children)Rh(t,e)}}var va=[];async function Sh(o,e,t,i){if(!e)return;let n=e.userData;if(n){let r=n.builtin_components;if(r&&r.length>0)for(let s of r)try{if(s===null)continue;let a=P.get(s.name);if(a!=null){let c=new a;c.sourceId=o.gltfId,It(c,s,o.implementationInformation),Vn(e,c,!1),t.push({instance:c,compData:s,obj:e})}else ng&&console.debug("unknown component: "+s.name),va.includes(s.name)||va.push(s.name)}catch(a){console.error(s.name+" - "+a.message,a)}if(va.length>0){let s=va.join(", ");console.warn("unknown components: "+s),va.length=0,ti()&&Ke(`<strong>Unknown components in scene</strong>:
310
309
 
311
310
  ${s}
312
311
 
313
312
  This could mean you forgot to add a npmdef to your ExportInfo
314
- <a href="https://engine.needle.tools/docs/project_structure.html#creating-and-installing-a-npmdef" target="_blank">documentation</a>`,1)}}if(e.children)for(let r of e.children)await _h(o,r,t,i)}function Dx(o,e){let{instance:t,compData:i,obj:n}=o;e.object=n,e.target=t;let r=!0;r=Ss(t,i,e)===!0,Ym&&console.debug("add "+i.name,i,t)}var fa=class{createBuiltinComponents(e,t,i,n,r){return Jm(e,t,i,n,r)}writeBuiltinComponentData(e,t){return Km(e,t)}parseSync(e,t,i,n){return jx(e,t,i,n)}loadSync(e,t,i,n,r){return Hx(e,t,i,n,r)}};nl(fa);var Lx=M("printGltf");var yr=class{context;loader;path;gltf;constructor(e,t,i,n){this.context=e,this.path=t,this.loader=i,this.gltf=n}},Zm={};function ys(o,e){if(Zm[o])for(let t of Zm[o])t(e)}async function eg(o,e,t,i,n){Lx&&console.log(t),await o.assets.registerGltf(t),await Ne().createBuiltinComponents(o,e,t,i,n)}function jx(o,e,t,i){typeof t!="string"&&console.warn("Parse gltf binary without path, this might lead to errors in resolving extensions. Please provide the source path of the gltf/glb file",t,typeof t);let n=new $m;Zd(n,o,t);let s=Jd(n);return new Promise((a,c)=>{try{hn(n,o),ys(0,new yr(o,t,n)),n.parse(e,t,async d=>{ys(1,new yr(o,t,n,d)),await eg(o,t,d,i,s),ys(10,new yr(o,t,n,d)),a(d)},d=>{console.error("failed loading "+t,d),a(void 0)})}catch(d){console.error(d),c(d)}})}function Hx(o,e,t,i=!1,n){let r=new $m;Zd(r,o,e);let a=Jd(r);return new Promise((c,d)=>{try{hn(r,o),ys(0,new yr(o,e,r)),r.load(e,async l=>{ys(1,new yr(o,e,r,l)),await eg(o,e,l,t,a),ys(10,new yr(o,e,r,l)),c(l)},l=>{n?.call(r,l)},l=>{console.error("failed loading "+e,l),c(void 0)})}catch(l){console.error(l),d(l)}})}nl(fa);var so=M("debugwebcomponent"),xh=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||R.destroySynced(this.previouslyAdded)),this.previouslyAdded=null,t||this.context.connection.send(this.networkEvent,e),this.previousSource=e,G.Current=this.context;let n=await Ne().loadSync(this.context,e,this.getHashFromString(e),!1);i||dn(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}},Fx="needle-engine",tg="vr",ig="desktop",Bx=[Ai,tg,ig],ma="ar-session-active",ga="desktop-session-active",wh=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=R;GameObject=R;_context=null;_overlay_ar;_loadingProgress01=0;_watcher;_loadingView;constructor(){super(),this._overlay_ar=new ml}async connectedCallback(){this.onSetupDesktop();var e=new MutationObserver(this.onElementsChanged.bind(this));e.observe(this,{childList:!0});let t=()=>{let a=this.getAttribute("src");return a?.endsWith(".glb")||a?.endsWith(".gltf")?a:null},i="loadScene",n=t();n&&(i=n);let r=this.getAttribute("alias"),s=this.getAttribute("hash");if(this._context=new G({name:i,domElement:this,alias:r,hash:s??void 0}),this._watcher=new xh(this.getAttribute("id")??r??"",this._context),i&&i.length>0){if(!n)for(;Object.keys(fl).length<=0;){if(!this.isConnected)return;await Gh(10)}let a=fl[i]??window[i],c=null;if((!a||n)&&(n&&(i=n),a=async d=>{let l=t();l&&this._watcher&&(c=l,await this._watcher.onSourceChanged(l,!0,!0))}),a){this.classList.add("loading"),console.log("Needle Engine: Begin loading",r??"");let d=!0,l=this.dispatchEvent(new CustomEvent("loadstart",{detail:{context:this._context,alias:r},cancelable:d}));!this._loadingView&&l&&(this._loadingView=new bl(this)),l&&this._loadingView?.onLoadingBegin("begin load");let u=(b,w)=>{this._loadingProgress01=Id(b),l&&this._loadingView?.onLoadingUpdate(b,w),this.dispatchEvent(new CustomEvent("progress",{detail:{context:this._context,name:b.name,progress:b.progress,index:b.index,count:b.count,totalProgress01:this._loadingProgress01}}))};this.onBeforeBeginLoading(),await this._context.onCreate(a,{progress:u});let h=t();h&&h!==c&&await this._watcher.onSourceChanged(h,!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',fl)}else console.error("Missing src attribute - please provide a function name",this)}disconnectedCallback(){this._context&&this._context.onDestroy()}static get observedAttributes(){return["hash","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&&(so&&console.log(e+" attribute changed",i),this.registerEventFromAttribute(e,i));break;case"dracoDecoderPath":so&&console.log("dracoDecoderPath",i),Dd(i);break;case"dracoDecoderType":i==="wasm"||i==="js"?(so&&console.log("dracoDecoderType",i),Ld(i)):console.error("Invalid dracoDecoderType",i,"expected js or wasm");break;case"ktx2DecoderPath":so&&console.log("ktx2DecoderPath",i),jd(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(ma),this.classList.remove(ga);let e=this.getAROverlayContainer();e&&(e.classList.add(ma),e.classList.remove(ga)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,Ai))}onSetupVR(){this.classList.remove(ma),this.classList.remove(ga),this.foreachHtmlElement(e=>this.setupElementsForMode(e,tg))}onSetupDesktop(){this.classList.remove(ma),this.classList.add(ga);let e=this.getAROverlayContainer();e&&(e.classList.remove(ma),e.classList.add(ga)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,ig))}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 Bx)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&&(so&&console.log("using custom draco decoder path",e),Dd(e));let t=this.getAttribute("dracoDecoderType");t&&(so&&console.log("using custom draco decoder type",t),Ld(t));let i=this.getAttribute("ktx2DecoderPath");i&&(so&&console.log("using custom ktx2 decoder path",i),jd(i))}};window.customElements.define(Fx,wh);import*as Ux from"three";xf();var Eh={Context:G};globalThis.Needle=Eh;function ng(o){for(let e in o)Eh[e]=o[e]}ng(Md);ng(bh);for(let o of Object.getOwnPropertyNames(R))switch(o){case"prototype":case"constructor":case"length":case"name":continue;default:Eh[o]=R[o];break}globalThis.THREE?console.warn("Threejs is already imported"):globalThis.THREE=Ux;export{qn as AlignmentConstraint,Lt as Animation,hi as AnimationCurve,br as AnimationTrackHandler,et as Animator,ui as AnimatorController,Ze as AssetReference,ht as AttachedObject,pi as AudioListener,oe as AudioSource,vr as AudioTrackHandler,Ki as AvatarBlink_Simple,Ji as AvatarEyeLook_Rotation,Yn as AvatarLoader,le as AvatarMarker,Hr as AvatarModel,bn as Avatar_Brain_LookAt,gr as Avatar_MouthShapes,rs as Avatar_MustacheShake,ve as Avatar_POI,mn as AxesHelper,Ue as BaseUIComponent,Mo as BasicIKConstraint,k as Behaviour,Zn as BoxCollider,wn as BoxGizmo,Be as BoxHelperComponent,Zt as Button,fi as CallInfo,se as Camera,ze as Canvas,jn as CanvasGroup,Bt as CapsuleCollider,ji as CharacterController,mi as CharacterControllerInput,Ut as Collider,Ms as Collision,mr as ColorAdjustments,wi as ColorBySpeedModule,Tn as ColorOverLifetimeModule,Mn as ControlTrackHandler,Ao as Deletable,Vr as DeleteBox,zr as DeviceFlag,Gi as DragControls,nr as DropListener,Vi as Duplicatable,pt as EmissionModule,be as EventList,Br as EventListEvent,Xe as EventSystem,Vo as EventTrigger,Ko as FieldWithDefault,Wo as FixedJoint,zo as FlyControls,Dt as FrameEvent,R as GameObject,Mr as Gizmos,Jt as GltfExport,ss as GltfExportBox,Ei as Gradient,Ot as Graphic,gs as GraphicRaycaster,En as GridHelper,ms as GridLayoutGroup,Cn as GroundProjectedEnv,Zg as HideFlags,rr as HingeJoint,fs as HorizontalLayoutGroup,Ln as Image,Yt as InheritVelocityModule,kt as InputField,re as InstancingUtil,Fe as InstantiateOptions,Gt as Interactable,hs as Keyboard,or as LODGroup,zi as LODModel,Hn as LayoutGroup,Ge as Light,de as LimitVelocityOverLifetimeModule,os as LogStats,Ts as LogType,vn as LookAtConstraint,ye as MainModule,Dn as MaskableGraphic,Ur as MeshCollider,Qr as MeshRenderer,U as MinMaxCurve,Oe as MinMaxGradient,Nr as NestedGltf,xi as Networking,Y as NoiseModule,ro as ObjectRaycaster,Wi as OffsetConstraint,it as OrbitControls,Rn as ParticleBurst,sr as ParticleSubEmitter,ge as ParticleSystem,Ni as ParticleSystemRenderer,An as PlayableDirector,ft as PlayerColor,bi as PointerEventData,Z as RGBAColor,to as RawImage,no as Raycaster,eo as Rect,mt as RectTransform,Kt as ReflectionProbe,qi as RemoteSkybox,ae as Renderer,Sn as RendererLightmap,K as Rigidbody,Ve as RotationBySpeedModule,Qe as RotationOverLifetimeModule,cr as ScreenCapture,dr as ShadowCatcher,ie as ShapeModule,Zr as SignalAsset,kn as SignalReceiver,$r as SignalReceiverEvent,In as SignalTrackHandler,ds as Size,Pe as SizeBySpeedModule,qt as SizeOverLifetimeModule,Jo as SkinnedMeshRenderer,Et as SmoothFollow,bs as SpatialHtml,Pn as SpatialTrigger,Ct as SpatialTriggerReceiver,$o as SpectatorCamera,Jn as SphereCollider,qr as Sprite,On as SpriteRenderer,ar as SubEmitterSystem,hr as SyncedCamera,Ci as SyncedRoom,_t as SyncedTransform,Wr as TeleportTarget,es as TestRunner,ts as TestSimulateUserData,ke as Text,_e as TextureSheetAnimationModule,fr as ToneMapping,ee as TrailModule,Yr as TransformGizmo,P as TypeStore,yi as UIRaycastUtils,yn as UIRootComponent,Vt as UsageMarker,Xt as VRUserState,je as VelocityOverLifetimeModule,ps as VerticalLayoutGroup,Ce as VideoPlayer,tt as Voip,Kr as Volume,Yi as VolumeComponent,is as VolumeParameter,pr as VolumeProfile,ir as WebAR,Wt as WebARSessionRoot,V as WebXR,Nt as WebXRAvatar,J as WebXRController,_n as WebXRSync,Ee as XRFlag,Jr as XRGrabModel,ns as XRGrabRendering,tr as XRRig,xt as XRState,da as __Ignore,Un as addNewComponent,yo as apply,ni as destroy,Pp as destroyComponentInstance,Tr as findByGuid,kp as findObjectOfType,Mp as findObjectsOfType,ri as foreachComponent,Sr as getComponent,Pr as getComponentInChildren,go as getComponentInParent,bo as getComponents,vo as getComponentsInChildren,Ds as getComponentsInParent,Ua as getOrAddComponent,Rr as instantiate,Ap as isActiveInHierarchy,cn as isActiveSelf,za as isUsingInstancing,Dp as markAsInstancedRendered,Sp as moveComponentInstance,Ba as removeComponent,y as serializable,Mf as serializeable,_o as setActive,Ye as showBalloonMessage,_a as showBalloonWarning,Lc as showDebugConsole,ai as validate};
313
+ <a href="https://engine.needle.tools/docs/project_structure.html#creating-and-installing-a-npmdef" target="_blank">documentation</a>`,1)}}if(e.children)for(let r of e.children)await Sh(o,r,t,i)}function Wx(o,e){let{instance:t,compData:i,obj:n}=o;e.object=n,e.target=t;let r=!0;r=ks(t,i,e)===!0,ng&&console.debug("add "+i.name,i,t)}var ya=class{createBuiltinComponents(e,t,i,n,r){return og(e,t,i,n,r)}writeBuiltinComponentData(e,t){return rg(e,t)}parseSync(e,t,i,n){return Xx(e,t,i,n)}loadSync(e,t,i,n,r){return Qx(e,t,i,n,r)}};ll(ya);var Nx=O("printGltf");var xr=class{context;loader;path;gltf;constructor(e,t,i,n){this.context=e,this.path=t,this.loader=i,this.gltf=n}},sg={};function ws(o,e){if(sg[o])for(let t of sg[o])t(e)}async function lg(o,e,t,i,n){Nx&&console.log(t),await o.assets.registerGltf(t),await Xe().createBuiltinComponents(o,e,t,i,n)}function Xx(o,e,t,i){typeof t!="string"&&console.warn("Parse gltf binary without path, this might lead to errors in resolving extensions. Please provide the source path of the gltf/glb file",t,typeof t);let n=new ag;nu(n,o,t);let s=iu(n);return new Promise((a,c)=>{try{gn(n,o),ws(0,new xr(o,t,n)),n.parse(e,t,async d=>{ws(1,new xr(o,t,n,d)),await lg(o,t,d,i,s),ws(10,new xr(o,t,n,d)),a(d)},d=>{console.error("failed loading "+t,d),a(void 0)})}catch(d){console.error(d),c(d)}})}function Qx(o,e,t,i=!1,n){let r=new ag;nu(r,o,e);let a=iu(r);return new Promise((c,d)=>{try{gn(r,o),ws(0,new xr(o,e,r)),r.load(e,async l=>{ws(1,new xr(o,e,r,l)),await lg(o,e,l,t,a),ws(10,new xr(o,e,r,l)),c(l)},l=>{n?.call(r,l)},l=>{console.error("failed loading "+e,l),c(void 0)})}catch(l){console.error(l),d(l)}})}ll(ya);var lo=O("debugwebcomponent"),Ph=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||R.destroySynced(this.previouslyAdded)),this.previouslyAdded=null,t||this.context.connection.send(this.networkEvent,e),this.previousSource=e,G.Current=this.context;let n=await Xe().loadSync(this.context,e,this.getHashFromString(e),!1);i||fn(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}},qx="needle-engine",cg="vr",dg="desktop",Yx=[ji,cg,dg],_a="ar-session-active",xa="desktop-session-active",Oh=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=R;GameObject=R;_context=null;_overlay_ar;_loadingProgress01=0;_watcher;_loadingView;constructor(){super(),this._overlay_ar=new _l}async connectedCallback(){this.onSetupDesktop();var e=new MutationObserver(this.onElementsChanged.bind(this));e.observe(this,{childList:!0});let t=()=>{let a=this.getAttribute("src");return a?.endsWith(".glb")||a?.endsWith(".gltf")?a:null},i="loadScene",n=t();n&&(i=n);let r=this.getAttribute("alias"),s=this.getAttribute("hash");if(this._context=new G({name:i,domElement:this,alias:r,hash:s??void 0}),this._watcher=new Ph(this.getAttribute("id")??r??"",this._context),i&&i.length>0){if(!n)for(;Object.keys(yl).length<=0;){if(!this.isConnected)return;await qh(10)}let a=yl[i]??window[i],c=null;if((!a||n)&&(n&&(i=n),a=async d=>{let l=t();l&&this._watcher&&(c=l,await this._watcher.onSourceChanged(l,!0,!0))}),a){this.classList.add("loading"),console.log("Needle Engine: Begin loading",r??"");let d=!0,l=this.dispatchEvent(new CustomEvent("loadstart",{detail:{context:this._context,alias:r},cancelable:d}));!this._loadingView&&l&&(this._loadingView=new wl(this)),l&&this._loadingView?.onLoadingBegin("begin load");let u=(b,w)=>{this._loadingProgress01=Hd(b),l&&this._loadingView?.onLoadingUpdate(b,w),this.dispatchEvent(new CustomEvent("progress",{detail:{context:this._context,name:b.name,progress:b.progress,index:b.index,count:b.count,totalProgress01:this._loadingProgress01}}))};this.onBeforeBeginLoading(),await this._context.onCreate(a,{progress:u});let h=t();h&&h!==c&&await this._watcher.onSourceChanged(h,!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',yl)}else console.error("Missing src attribute - please provide a function name",this)}disconnectedCallback(){this._context&&this._context.onDestroy()}static get observedAttributes(){return["hash","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&&(lo&&console.log(e+" attribute changed",i),this.registerEventFromAttribute(e,i));break;case"dracoDecoderPath":lo&&console.log("dracoDecoderPath",i),Bd(i);break;case"dracoDecoderType":i==="wasm"||i==="js"?(lo&&console.log("dracoDecoderType",i),Ud(i)):console.error("Invalid dracoDecoderType",i,"expected js or wasm");break;case"ktx2DecoderPath":lo&&console.log("ktx2DecoderPath",i),Gd(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(_a),this.classList.remove(xa);let e=this.getAROverlayContainer();e&&(e.classList.add(_a),e.classList.remove(xa)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,ji))}onSetupVR(){this.classList.remove(_a),this.classList.remove(xa),this.foreachHtmlElement(e=>this.setupElementsForMode(e,cg))}onSetupDesktop(){this.classList.remove(_a),this.classList.add(xa);let e=this.getAROverlayContainer();e&&(e.classList.remove(_a),e.classList.add(xa)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,dg))}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 Yx)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&&(lo&&console.log("using custom draco decoder path",e),Bd(e));let t=this.getAttribute("dracoDecoderType");t&&(lo&&console.log("using custom draco decoder type",t),Ud(t));let i=this.getAttribute("ktx2DecoderPath");i&&(lo&&console.log("using custom ktx2 decoder path",i),Gd(i))}};window.customElements.define(qx,Oh);import*as Kx from"three";Pf();var kh={Context:G};globalThis.Needle=kh;function ug(o){for(let e in o)kh[e]=o[e]}ug(jd);ug(Ch);for(let o of Object.getOwnPropertyNames(R))switch(o){case"prototype":case"constructor":case"length":case"name":continue;default:kh[o]=R[o];break}globalThis.THREE?console.warn("Threejs is already imported"):globalThis.THREE=Kx;export{Kn as AlignmentConstraint,Lt as Animation,pi as AnimationCurve,yr as AnimationTrackHandler,Be as Animator,hi as AnimatorController,$e as AssetReference,pt as AttachedObject,fi as AudioListener,se as AudioSource,_r as AudioTrackHandler,en as AvatarBlink_Simple,tn as AvatarEyeLook_Rotation,Jn as AvatarLoader,le as AvatarMarker,Br as AvatarModel,xn as Avatar_Brain_LookAt,vr as Avatar_MouthShapes,as as Avatar_MustacheShake,ve as Avatar_POI,yn as AxesHelper,Ge as BaseUIComponent,Ao as BasicIKConstraint,M as Behaviour,er as BoxCollider,wi as BoxGizmo,Ue as BoxHelperComponent,$t as Button,mi as CallInfo,ee as Camera,We as Canvas,Fn as CanvasGroup,Bt as CapsuleCollider,Bi as CharacterController,gi as CharacterControllerInput,Ut as Collider,As as Collision,br as ColorAdjustments,Ci as ColorBySpeedModule,Pn as ColorOverLifetimeModule,Dn as ControlTrackHandler,jo as Deletable,Wr as DeleteBox,Nr as DeviceFlag,Wi as DragControls,or as DropListener,Ni as Duplicatable,ft as EmissionModule,ue as EventList,Gr as EventListEvent,Qe as EventSystem,Qr as EventTrigger,Zo as FieldWithDefault,Xo as FixedJoint,No as FlyControls,_t as FrameEvent,R as GameObject,Dr as Gizmos,Zt as GltfExport,cs as GltfExportBox,Ti as Gradient,kt as Graphic,ys as GraphicRaycaster,Rn as GridHelper,vs as GridLayoutGroup,Sn as GroundProjectedEnv,sb as HideFlags,sr as HingeJoint,bs as HorizontalLayoutGroup,Hn as Image,Yt as InheritVelocityModule,Mt as InputField,oe as InstancingUtil,Fe as InstantiateOptions,Gt as Interactable,ms as Keyboard,ar as LODGroup,Xi as LODModel,Bn as LayoutGroup,Ve as Light,de as LimitVelocityOverLifetimeModule,ls as LogStats,Ps as LogType,wn as LookAtConstraint,ye as MainModule,jn as MaskableGraphic,Vr as MeshCollider,Kr as MeshRenderer,U as MinMaxCurve,Oe as MinMaxGradient,qr as NestedGltf,Ei as Networking,Y as NoiseModule,so as ObjectRaycaster,Qi as OffsetConstraint,it as OrbitControls,On as ParticleBurst,lr as ParticleSubEmitter,be as ParticleSystem,qi as ParticleSystemRenderer,Ln as PlayableDirector,mt as PlayerColor,vi as PointerEventData,Z as RGBAColor,no as RawImage,oo as Raycaster,io as Rect,gt as RectTransform,Kt as ReflectionProbe,Ri as RemoteSkybox,ae as Renderer,kn as RendererLightmap,K as Rigidbody,ze as RotationBySpeedModule,qe as RotationOverLifetimeModule,ur as ScreenCapture,hr as ShadowCatcher,ne as ShapeModule,eo as SignalAsset,In as SignalReceiver,to as SignalReceiverEvent,An as SignalTrackHandler,ps as Size,Pe as SizeBySpeedModule,qt as SizeOverLifetimeModule,$o as SkinnedMeshRenderer,Tt as SmoothFollow,_s as SpatialHtml,Mn as SpatialTrigger,Rt as SpatialTriggerReceiver,ts as SpectatorCamera,$n as SphereCollider,Jt as Sprite,Ji as SpriteRenderer,Zi as SpriteSheet,cr as SubEmitterSystem,fr as SyncedCamera,Si as SyncedRoom,wt as SyncedTransform,Xr as TeleportTarget,ns as TestRunner,rs as TestSimulateUserData,ke as Text,_e as TextureSheetAnimationModule,gr as ToneMapping,te as TrailModule,Jr as TransformGizmo,P as TypeStore,_i as UIRaycastUtils,En as UIRootComponent,Vt as UsageMarker,Xt as VRUserState,je as VelocityOverLifetimeModule,gs as VerticalLayoutGroup,Ce as VideoPlayer,tt as Voip,Zr as Volume,$i as VolumeComponent,os as VolumeParameter,mr as VolumeProfile,rr as WebAR,Wt as WebARSessionRoot,V as WebXR,Nt as WebXRAvatar,J as WebXRController,Cn as WebXRSync,Ee as XRFlag,$r as XRGrabModel,ss as XRGrabRendering,nr as XRRig,Et as XRState,ma as __Ignore,Vn as addNewComponent,xo as apply,ri as destroy,Lp as destroyComponentInstance,Sr as findByGuid,Hp as findObjectOfType,Fp as findObjectsOfType,oi as foreachComponent,Or as getComponent,kr as getComponentInChildren,vo as getComponentInParent,yo as getComponents,_o as getComponentsInChildren,Hs as getComponentsInParent,Na as getOrAddComponent,Pr as instantiate,Up as isActiveInHierarchy,pn as isActiveSelf,qa as isUsingInstancing,Gp as markAsInstancedRendered,Ap as moveComponentInstance,Wa as removeComponent,_ as serializable,ko as serializeable,wo as setActive,Ke as showBalloonMessage,Ta as showBalloonWarning,Uc as showDebugConsole,li as validate};
315
314
  /*!
316
315
  * Determine if an object is a Buffer
317
316
  *